diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/tests/org.bonitasoft.studio.diagram.test/src/org/bonitasoft/studio/diagram/test/TestBug1640.java b/tests/org.bonitasoft.studio.diagram.test/src/org/bonitasoft/studio/diagram/test/TestBug1640.java index 1973d6e0d0..a5f6f11223 100644 --- a/tests/org.bonitasoft.studio.diagram.test/src/org/bonitasoft/studio/diagram/test/TestBug1640.java +++ b/tests/org.bonitasoft.studio.diagram.test/src/org/bonitasoft/studio/diagram/test/TestBug1640.java @@ -1,113 +1,114 @@ /** * Copyright (C) 2010 BonitaSoft S.A. * BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.diagram.test; import org.bonitasoft.studio.model.process.MainProcess; import org.bonitasoft.studio.model.process.ProcessPackage; import org.bonitasoft.studio.model.process.diagram.part.ProcessDiagramEditor; import org.bonitasoft.studio.test.swtbot.util.SWTBotTestUtil; import org.eclipse.draw2d.geometry.Point; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.swt.widgets.Display; import org.eclipse.swtbot.eclipse.gef.finder.SWTBotGefTestCase; import org.eclipse.swtbot.eclipse.gef.finder.widgets.SWTBotGefEditor; import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Mickael Istria * */ @RunWith(SWTBotJunit4ClassRunner.class) public class TestBug1640 extends SWTBotGefTestCase { // @Override // @Before // public void setUp() { // Display.getDefault().syncExec(new Runnable() { // public void run() { // PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().saveAllEditors(false); // boolean closed = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().closeAllEditors(false); // assertTrue("all editors were not closed",closed); // PlatformUtil.closeIntro(); // } // }); // } @Test public void testBug1640() throws Exception { //close editors that were re-opened (for form closed editors) bot.saveAllEditors(); bot.closeAllEditors(); // Create first process SWTBotMenu saveMenu = bot.menu("Diagram").menu("Save"); SWTBotTestUtil.createNewDiagram(bot); + saveMenu.click(); SWTBotGefEditor editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); final ProcessDiagramEditor processEditor = (ProcessDiagramEditor) bot.editors().get(0).getReference().getEditor(false); editor.click(10, 10); // Rename it Display.getDefault().syncExec(new Runnable() { public void run() { MainProcess diagram = (MainProcess)processEditor.getDiagramEditPart().resolveSemanticElement(); processEditor.getEditingDomain().getCommandStack().execute(new SetCommand(processEditor.getEditingDomain(), diagram, ProcessPackage.Literals.ELEMENT__NAME, "TestBug1640_1)")); } }); assertTrue(editor.isDirty()); saveMenu.click(); int tries = 5; do { Thread.sleep(5000); tries --; } while (bot.editors().size() != 1 && tries > 0); bot.closeAllEditors(); assertFalse(editor.isActive()); // Create 2nd process SWTBotTestUtil.createNewDiagram(bot); editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); //TODO: use the avsolute coordinate Point center = ((IGraphicalEditPart)editor.getEditPart("Step1").part()).getFigure().getBounds().getCenter(); editor.drag(center.x+20, center.y+20, center.x + 200, center.y + 200); Assert.assertTrue(editor.isDirty()); saveMenu.click(); // Check that editor is not closed Assert.assertEquals(1, bot.editors().size()); } @Override @After public void tearDown() { bot.saveAllEditors(); bot.closeAllEditors(); } }
true
true
public void testBug1640() throws Exception { //close editors that were re-opened (for form closed editors) bot.saveAllEditors(); bot.closeAllEditors(); // Create first process SWTBotMenu saveMenu = bot.menu("Diagram").menu("Save"); SWTBotTestUtil.createNewDiagram(bot); SWTBotGefEditor editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); final ProcessDiagramEditor processEditor = (ProcessDiagramEditor) bot.editors().get(0).getReference().getEditor(false); editor.click(10, 10); // Rename it Display.getDefault().syncExec(new Runnable() { public void run() { MainProcess diagram = (MainProcess)processEditor.getDiagramEditPart().resolveSemanticElement(); processEditor.getEditingDomain().getCommandStack().execute(new SetCommand(processEditor.getEditingDomain(), diagram, ProcessPackage.Literals.ELEMENT__NAME, "TestBug1640_1)")); } }); assertTrue(editor.isDirty()); saveMenu.click(); int tries = 5; do { Thread.sleep(5000); tries --; } while (bot.editors().size() != 1 && tries > 0); bot.closeAllEditors(); assertFalse(editor.isActive()); // Create 2nd process SWTBotTestUtil.createNewDiagram(bot); editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); //TODO: use the avsolute coordinate Point center = ((IGraphicalEditPart)editor.getEditPart("Step1").part()).getFigure().getBounds().getCenter(); editor.drag(center.x+20, center.y+20, center.x + 200, center.y + 200); Assert.assertTrue(editor.isDirty()); saveMenu.click(); // Check that editor is not closed Assert.assertEquals(1, bot.editors().size()); }
public void testBug1640() throws Exception { //close editors that were re-opened (for form closed editors) bot.saveAllEditors(); bot.closeAllEditors(); // Create first process SWTBotMenu saveMenu = bot.menu("Diagram").menu("Save"); SWTBotTestUtil.createNewDiagram(bot); saveMenu.click(); SWTBotGefEditor editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); final ProcessDiagramEditor processEditor = (ProcessDiagramEditor) bot.editors().get(0).getReference().getEditor(false); editor.click(10, 10); // Rename it Display.getDefault().syncExec(new Runnable() { public void run() { MainProcess diagram = (MainProcess)processEditor.getDiagramEditPart().resolveSemanticElement(); processEditor.getEditingDomain().getCommandStack().execute(new SetCommand(processEditor.getEditingDomain(), diagram, ProcessPackage.Literals.ELEMENT__NAME, "TestBug1640_1)")); } }); assertTrue(editor.isDirty()); saveMenu.click(); int tries = 5; do { Thread.sleep(5000); tries --; } while (bot.editors().size() != 1 && tries > 0); bot.closeAllEditors(); assertFalse(editor.isActive()); // Create 2nd process SWTBotTestUtil.createNewDiagram(bot); editor = bot.gefEditor(bot.editors().get(0).getTitle()); assertTrue(!editor.isDirty()); //TODO: use the avsolute coordinate Point center = ((IGraphicalEditPart)editor.getEditPart("Step1").part()).getFigure().getBounds().getCenter(); editor.drag(center.x+20, center.y+20, center.x + 200, center.y + 200); Assert.assertTrue(editor.isDirty()); saveMenu.click(); // Check that editor is not closed Assert.assertEquals(1, bot.editors().size()); }
diff --git a/src/com/yad/harpseal/controller/GameControllerBase.java b/src/com/yad/harpseal/controller/GameControllerBase.java index 54c3013..679e7f4 100644 --- a/src/com/yad/harpseal/controller/GameControllerBase.java +++ b/src/com/yad/harpseal/controller/GameControllerBase.java @@ -1,291 +1,291 @@ package com.yad.harpseal.controller; import java.util.LinkedList; import java.util.Queue; import com.yad.harpseal.constant.Layer; import com.yad.harpseal.constant.Screen; import com.yad.harpseal.util.Communicable; import com.yad.harpseal.util.Controllable; import com.yad.harpseal.util.Func; import com.yad.harpseal.util.HarpEvent; import com.yad.harpseal.util.HarpLog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.view.MotionEvent; import android.view.SurfaceHolder; public abstract class GameControllerBase extends Thread implements Controllable,Communicable { // common private Context context; // thread private boolean isPaused; private boolean isEnded; // game play private int period; private final static int PERIOD_BASE=15; // motion event private Queue<HarpEvent> event; private boolean pressed; private float pressX,pressY; private int pressTime; private final static int CLICK_RANGE=50; private final static int CLICK_TIME=500; private final static int LONGCLICK_TIME=1000; // drawing private SurfaceHolder holder; private Paint paint; // sound private MediaPlayer mediaPlayer; private SoundPool soundPool; public GameControllerBase(Context context,SurfaceHolder holder) { this.context=context; this.isPaused=false; this.isEnded=false; this.period=PERIOD_BASE; this.event=new LinkedList<HarpEvent>(); this.pressed=false; this.pressTime=0; this.holder=holder; this.paint=new Paint(); this.mediaPlayer=new MediaPlayer(); this.soundPool=new SoundPool(7,AudioManager.STREAM_MUSIC,0); HarpLog.info("GameController created"); } @Override public final void start() { super.start(); HarpLog.info("Game thread started"); } @Override public final void run() { super.run(); HarpLog.info("Game thread is running"); // temp variable (Frequently changed) Canvas c=null; long fms,lms; float scaleRate; float transHeight; HarpEvent ev=null; while(!isEnded) { // do thread's work (including draw screen) while(!isPaused) { try { // timer start fms=System.currentTimeMillis(); // game play playGame(period); // check screen is available c=holder.lockCanvas(null); if(c!=null) { // calculate scale, trans scaleRate=(float)c.getWidth()/Screen.SCREEN_X; transHeight=(float)(c.getHeight()-Screen.SCREEN_Y*scaleRate)*0.5f; // long click check if(pressed) { pressTime+=period; if(pressTime>=LONGCLICK_TIME) { event.add(new HarpEvent(HarpEvent.MOTION_LONGCLICK,pressX,pressY)); HarpLog.debug("Action LongClick : "+ev.getX()+", "+ev.getY()); pressed=false; pressTime=0; } } // process events while(event.peek()!=null) { ev=event.poll(); ev.regulate(scaleRate, transHeight); if( (ev.getType()==HarpEvent.MOTION_DOWN || ev.getType()==HarpEvent.MOTION_CLICK) && (ev.getX()<0 || ev.getX()>Screen.SCREEN_X || ev.getY()<0 || ev.getY()>Screen.SCREEN_Y) ) continue; for(int i=Layer.LAYER_SIZE-1;(i>=0 && ev.isProcessed()==false);i--) { receiveMotion(ev,i); } } // drawing paint.reset(); paint.setColor(0xFF000000); c.drawRect(0,0,c.getWidth(),c.getHeight(),paint); c.translate(0,transHeight); c.scale(scaleRate,scaleRate); c.clipRect(0,0,Screen.SCREEN_X,Screen.SCREEN_Y); for(int i=0;i<Layer.LAYER_SIZE;i++) drawScreen(c,paint,i); // restore canvas holder.unlockCanvasAndPost(c); c=null; } // timer end lms=System.currentTimeMillis(); - if(fms+period<lms) Thread.sleep(lms-fms-period); + if(lms-fms<period) Thread.sleep(period-lms+fms); // time loss need to be processed } catch (InterruptedException e) { // print error e.printStackTrace(); // time loss need to be processed but.. I think this exception cannot be called HarpLog.danger("Interrupted Exception caught! It makes time loss!"); } } //// // wait HarpLog.debug("Game thread is waiting being restarted"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //// } // restore data HarpLog.info("Game thread ended"); restoreData(); mediaPlayer.release(); soundPool.release(); } public final void pause() { HarpLog.info("Game thread paused"); isPaused=true; mediaPlayer.pause(); } public final void restart() { HarpLog.info("Game thread restarted"); isPaused=false; mediaPlayer.start(); } public final void end() { HarpLog.info("Game thread will be ended"); isEnded=true; } public final void pushEvent(MotionEvent ev) { switch(ev.getAction()) { case MotionEvent.ACTION_DOWN: event.add(new HarpEvent(HarpEvent.MOTION_DOWN,ev.getX(),ev.getY())); HarpLog.debug("Action Down : "+ev.getX()+", "+ev.getY()); pressed=true; pressX=ev.getX(); pressY=ev.getY(); pressTime=0; break; case MotionEvent.ACTION_UP: event.add(new HarpEvent(HarpEvent.MOTION_UP,ev.getX(),ev.getY())); HarpLog.debug("Action Up : "+ev.getX()+", "+ev.getY()); if(pressed && pressTime<CLICK_TIME) { event.add(new HarpEvent(HarpEvent.MOTION_CLICK,ev.getX(),ev.getY())); HarpLog.debug("Action Click : "+ev.getX()+", "+ev.getY()); } pressed=false; pressTime=0; break; case MotionEvent.ACTION_MOVE: event.add(new HarpEvent(HarpEvent.MOTION_DRAG,ev.getX(),ev.getY())); HarpLog.debug("Action Move : "+ev.getX()+", "+ev.getY()); if( pressed && Func.distan(pressX,pressY,ev.getX(),ev.getY()) > CLICK_RANGE ) { HarpLog.debug("Click Range Out : "+(ev.getX()-pressX)+", "+(ev.getY()-pressY)); pressed=false; pressTime=0; } break; } } @Override public int send(String msg) { HarpLog.debug("Controller received message : "+msg); String[] msgs=msg.split("/"); if(msgs[0].equals("playSound")) { mediaPlayer.release(); mediaPlayer=MediaPlayer.create(context,Integer.parseInt(msgs[1])); if(mediaPlayer!=null) { mediaPlayer.setLooping(true); mediaPlayer.start(); return 1; } else return 0; } else if(msgs[0].equals("resetSound")) { mediaPlayer.reset(); return 1; } else if(msgs[0].equals("loadChunk")) { return soundPool.load(context,Integer.parseInt(msgs[1]),0); } else if(msgs[0].equals("unloadChunk")) { if(soundPool.unload(Integer.parseInt(msgs[1]))==true) return 1; else return 0; } else if(msgs[0].equals("playChunk")) { if( soundPool.play(Integer.parseInt(msgs[1]),1f,1f,0,0,1f) != 0 ) return 1; else return 0; } HarpLog.error("Controller couldn't understand message : "+msg); return 0; } @Override public Object get(String name) { if(name.equals("resources")) return context.getResources(); else if(name.equals("assetManager")) return context.getAssets(); else { HarpLog.error("Controller received invalid name of get() : "+name); return null; } } }
true
true
public final void run() { super.run(); HarpLog.info("Game thread is running"); // temp variable (Frequently changed) Canvas c=null; long fms,lms; float scaleRate; float transHeight; HarpEvent ev=null; while(!isEnded) { // do thread's work (including draw screen) while(!isPaused) { try { // timer start fms=System.currentTimeMillis(); // game play playGame(period); // check screen is available c=holder.lockCanvas(null); if(c!=null) { // calculate scale, trans scaleRate=(float)c.getWidth()/Screen.SCREEN_X; transHeight=(float)(c.getHeight()-Screen.SCREEN_Y*scaleRate)*0.5f; // long click check if(pressed) { pressTime+=period; if(pressTime>=LONGCLICK_TIME) { event.add(new HarpEvent(HarpEvent.MOTION_LONGCLICK,pressX,pressY)); HarpLog.debug("Action LongClick : "+ev.getX()+", "+ev.getY()); pressed=false; pressTime=0; } } // process events while(event.peek()!=null) { ev=event.poll(); ev.regulate(scaleRate, transHeight); if( (ev.getType()==HarpEvent.MOTION_DOWN || ev.getType()==HarpEvent.MOTION_CLICK) && (ev.getX()<0 || ev.getX()>Screen.SCREEN_X || ev.getY()<0 || ev.getY()>Screen.SCREEN_Y) ) continue; for(int i=Layer.LAYER_SIZE-1;(i>=0 && ev.isProcessed()==false);i--) { receiveMotion(ev,i); } } // drawing paint.reset(); paint.setColor(0xFF000000); c.drawRect(0,0,c.getWidth(),c.getHeight(),paint); c.translate(0,transHeight); c.scale(scaleRate,scaleRate); c.clipRect(0,0,Screen.SCREEN_X,Screen.SCREEN_Y); for(int i=0;i<Layer.LAYER_SIZE;i++) drawScreen(c,paint,i); // restore canvas holder.unlockCanvasAndPost(c); c=null; } // timer end lms=System.currentTimeMillis(); if(fms+period<lms) Thread.sleep(lms-fms-period); // time loss need to be processed } catch (InterruptedException e) { // print error e.printStackTrace(); // time loss need to be processed but.. I think this exception cannot be called HarpLog.danger("Interrupted Exception caught! It makes time loss!"); } } //// // wait HarpLog.debug("Game thread is waiting being restarted"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //// } // restore data HarpLog.info("Game thread ended"); restoreData(); mediaPlayer.release(); soundPool.release(); }
public final void run() { super.run(); HarpLog.info("Game thread is running"); // temp variable (Frequently changed) Canvas c=null; long fms,lms; float scaleRate; float transHeight; HarpEvent ev=null; while(!isEnded) { // do thread's work (including draw screen) while(!isPaused) { try { // timer start fms=System.currentTimeMillis(); // game play playGame(period); // check screen is available c=holder.lockCanvas(null); if(c!=null) { // calculate scale, trans scaleRate=(float)c.getWidth()/Screen.SCREEN_X; transHeight=(float)(c.getHeight()-Screen.SCREEN_Y*scaleRate)*0.5f; // long click check if(pressed) { pressTime+=period; if(pressTime>=LONGCLICK_TIME) { event.add(new HarpEvent(HarpEvent.MOTION_LONGCLICK,pressX,pressY)); HarpLog.debug("Action LongClick : "+ev.getX()+", "+ev.getY()); pressed=false; pressTime=0; } } // process events while(event.peek()!=null) { ev=event.poll(); ev.regulate(scaleRate, transHeight); if( (ev.getType()==HarpEvent.MOTION_DOWN || ev.getType()==HarpEvent.MOTION_CLICK) && (ev.getX()<0 || ev.getX()>Screen.SCREEN_X || ev.getY()<0 || ev.getY()>Screen.SCREEN_Y) ) continue; for(int i=Layer.LAYER_SIZE-1;(i>=0 && ev.isProcessed()==false);i--) { receiveMotion(ev,i); } } // drawing paint.reset(); paint.setColor(0xFF000000); c.drawRect(0,0,c.getWidth(),c.getHeight(),paint); c.translate(0,transHeight); c.scale(scaleRate,scaleRate); c.clipRect(0,0,Screen.SCREEN_X,Screen.SCREEN_Y); for(int i=0;i<Layer.LAYER_SIZE;i++) drawScreen(c,paint,i); // restore canvas holder.unlockCanvasAndPost(c); c=null; } // timer end lms=System.currentTimeMillis(); if(lms-fms<period) Thread.sleep(period-lms+fms); // time loss need to be processed } catch (InterruptedException e) { // print error e.printStackTrace(); // time loss need to be processed but.. I think this exception cannot be called HarpLog.danger("Interrupted Exception caught! It makes time loss!"); } } //// // wait HarpLog.debug("Game thread is waiting being restarted"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //// } // restore data HarpLog.info("Game thread ended"); restoreData(); mediaPlayer.release(); soundPool.release(); }
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java index 848a7364d..c6dbdd682 100644 --- a/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java +++ b/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java @@ -1,710 +1,710 @@ package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.lucene.codecs.Codec; import org.apache.lucene.codecs.PostingsFormat; import org.apache.lucene.codecs.lucene40.Lucene40Codec; import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CheckIndex; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.LogMergePolicy; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.MergeScheduler; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.index.TieredMergePolicy; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.junit.Assert; public class _TestUtil { /** Returns temp dir, based on String arg in its name; * does not create the directory. */ public static File getTempDir(String desc) { try { File f = createTempFile(desc, "tmp", LuceneTestCase.TEMP_DIR); f.delete(); LuceneTestCase.registerTempDir(f); return f; } catch (IOException e) { throw new RuntimeException(e); } } /** * Deletes a directory and everything underneath it. */ public static void rmDir(File dir) throws IOException { if (dir.exists()) { if (dir.isFile() && !dir.delete()) { throw new IOException("could not delete " + dir); } for (File f : dir.listFiles()) { if (f.isDirectory()) { rmDir(f); } else { if (!f.delete()) { throw new IOException("could not delete " + f); } } } if (!dir.delete()) { throw new IOException("could not delete " + dir); } } } /** * Convenience method: Unzip zipName + ".zip" under destDir, removing destDir first */ public static void unzip(File zipName, File destDir) throws IOException { ZipFile zipFile = new ZipFile(zipName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); rmDir(destDir); destDir.mkdir(); LuceneTestCase.registerTempDir(destDir); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); InputStream in = zipFile.getInputStream(entry); File targetFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { // allow unzipping with directory structure targetFile.mkdirs(); } else { if (targetFile.getParentFile()!=null) { // be on the safe side: do not rely on that directories are always extracted // before their children (although this makes sense, but is it guaranteed?) targetFile.getParentFile().mkdirs(); } OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[8192]; int len; while((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } zipFile.close(); } public static void syncConcurrentMerges(IndexWriter writer) { syncConcurrentMerges(writer.getConfig().getMergeScheduler()); } public static void syncConcurrentMerges(MergeScheduler ms) { if (ms instanceof ConcurrentMergeScheduler) ((ConcurrentMergeScheduler) ms).sync(); } /** This runs the CheckIndex tool on the index in. If any * issues are hit, a RuntimeException is thrown; else, * true is returned. */ public static CheckIndex.Status checkIndex(Directory dir) throws IOException { return checkIndex(dir, true); } public static CheckIndex.Status checkIndex(Directory dir, boolean crossCheckTermVectors) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); CheckIndex checker = new CheckIndex(dir); checker.setCrossCheckTermVectors(crossCheckTermVectors); checker.setInfoStream(new PrintStream(bos), false); CheckIndex.Status indexStatus = checker.checkIndex(null); if (indexStatus == null || indexStatus.clean == false) { System.out.println("CheckIndex failed"); System.out.println(bos.toString()); throw new RuntimeException("CheckIndex failed"); } else { if (LuceneTestCase.INFOSTREAM) { System.out.println(bos.toString()); } return indexStatus; } } // NOTE: only works for TMP and LMP!! public static void setUseCompoundFile(MergePolicy mp, boolean v) { if (mp instanceof TieredMergePolicy) { ((TieredMergePolicy) mp).setUseCompoundFile(v); } else if (mp instanceof LogMergePolicy) { ((LogMergePolicy) mp).setUseCompoundFile(v); } } /** start and end are BOTH inclusive */ public static int nextInt(Random r, int start, int end) { return start + r.nextInt(end-start+1); } public static String randomSimpleString(Random r) { final int end = r.nextInt(10); if (end == 0) { // allow 0 length return ""; } final char[] buffer = new char[end]; for (int i = 0; i < end; i++) { buffer[i] = (char) _TestUtil.nextInt(r, 97, 102); } return new String(buffer, 0, end); } /** Returns random string, including full unicode range. */ public static String randomUnicodeString(Random r) { return randomUnicodeString(r, 20); } /** * Returns a random string up to a certain length. */ public static String randomUnicodeString(Random r, int maxLength) { final int end = r.nextInt(maxLength); if (end == 0) { // allow 0 length return ""; } final char[] buffer = new char[end]; randomFixedLengthUnicodeString(r, buffer, 0, buffer.length); return new String(buffer, 0, end); } /** * Fills provided char[] with valid random unicode code * unit sequence. */ public static void randomFixedLengthUnicodeString(Random random, char[] chars, int offset, int length) { int i = offset; final int end = offset + length; while(i < end) { final int t = random.nextInt(5); if (0 == t && i < length - 1) { // Make a surrogate pair // High surrogate chars[i++] = (char) nextInt(random, 0xd800, 0xdbff); // Low surrogate chars[i++] = (char) nextInt(random, 0xdc00, 0xdfff); } else if (t <= 1) { chars[i++] = (char) random.nextInt(0x80); } else if (2 == t) { chars[i++] = (char) nextInt(random, 0x80, 0x7ff); } else if (3 == t) { chars[i++] = (char) nextInt(random, 0x800, 0xd7ff); } else if (4 == t) { chars[i++] = (char) nextInt(random, 0xe000, 0xffff); } } } private static final String[] HTML_CHAR_ENTITIES = { "AElig", "Aacute", "Acirc", "Agrave", "Alpha", "AMP", "Aring", "Atilde", "Auml", "Beta", "COPY", "Ccedil", "Chi", "Dagger", "Delta", "ETH", "Eacute", "Ecirc", "Egrave", "Epsilon", "Eta", "Euml", "Gamma", "GT", "Iacute", "Icirc", "Igrave", "Iota", "Iuml", "Kappa", "Lambda", "LT", "Mu", "Ntilde", "Nu", "OElig", "Oacute", "Ocirc", "Ograve", "Omega", "Omicron", "Oslash", "Otilde", "Ouml", "Phi", "Pi", "Prime", "Psi", "QUOT", "REG", "Rho", "Scaron", "Sigma", "THORN", "Tau", "Theta", "Uacute", "Ucirc", "Ugrave", "Upsilon", "Uuml", "Xi", "Yacute", "Yuml", "Zeta", "aacute", "acirc", "acute", "aelig", "agrave", "alefsym", "alpha", "amp", "and", "ang", "apos", "aring", "asymp", "atilde", "auml", "bdquo", "beta", "brvbar", "bull", "cap", "ccedil", "cedil", "cent", "chi", "circ", "clubs", "cong", "copy", "crarr", "cup", "curren", "dArr", "dagger", "darr", "deg", "delta", "diams", "divide", "eacute", "ecirc", "egrave", "empty", "emsp", "ensp", "epsilon", "equiv", "eta", "eth", "euml", "euro", "exist", "fnof", "forall", "frac12", "frac14", "frac34", "frasl", "gamma", "ge", "gt", "hArr", "harr", "hearts", "hellip", "iacute", "icirc", "iexcl", "igrave", "image", "infin", "int", "iota", "iquest", "isin", "iuml", "kappa", "lArr", "lambda", "lang", "laquo", "larr", "lceil", "ldquo", "le", "lfloor", "lowast", "loz", "lrm", "lsaquo", "lsquo", "lt", "macr", "mdash", "micro", "middot", "minus", "mu", "nabla", "nbsp", "ndash", "ne", "ni", "not", "notin", "nsub", "ntilde", "nu", "oacute", "ocirc", "oelig", "ograve", "oline", "omega", "omicron", "oplus", "or", "ordf", "ordm", "oslash", "otilde", "otimes", "ouml", "para", "part", "permil", "perp", "phi", "pi", "piv", "plusmn", "pound", "prime", "prod", "prop", "psi", "quot", "rArr", "radic", "rang", "raquo", "rarr", "rceil", "rdquo", "real", "reg", "rfloor", "rho", "rlm", "rsaquo", "rsquo", "sbquo", "scaron", "sdot", "sect", "shy", "sigma", "sigmaf", "sim", "spades", "sub", "sube", "sum", "sup", "sup1", "sup2", "sup3", "supe", "szlig", "tau", "there4", "theta", "thetasym", "thinsp", "thorn", "tilde", "times", "trade", "uArr", "uacute", "uarr", "ucirc", "ugrave", "uml", "upsih", "upsilon", "uuml", "weierp", "xi", "yacute", "yen", "yuml", "zeta", "zwj", "zwnj" }; public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; - case 21: sb.append("\n"); - case 22: sb.append(" ".substring(nextInt(random, 0, 10))); + case 21: sb.append("\n"); break; + case 22: sb.append(" ".substring(nextInt(random, 0, 10))); break; default: sb.append(randomSimpleString(random)); } } return sb.toString(); } private static final int[] blockStarts = { 0x0000, 0x0080, 0x0100, 0x0180, 0x0250, 0x02B0, 0x0300, 0x0370, 0x0400, 0x0500, 0x0530, 0x0590, 0x0600, 0x0700, 0x0750, 0x0780, 0x07C0, 0x0800, 0x0900, 0x0980, 0x0A00, 0x0A80, 0x0B00, 0x0B80, 0x0C00, 0x0C80, 0x0D00, 0x0D80, 0x0E00, 0x0E80, 0x0F00, 0x1000, 0x10A0, 0x1100, 0x1200, 0x1380, 0x13A0, 0x1400, 0x1680, 0x16A0, 0x1700, 0x1720, 0x1740, 0x1760, 0x1780, 0x1800, 0x18B0, 0x1900, 0x1950, 0x1980, 0x19E0, 0x1A00, 0x1A20, 0x1B00, 0x1B80, 0x1C00, 0x1C50, 0x1CD0, 0x1D00, 0x1D80, 0x1DC0, 0x1E00, 0x1F00, 0x2000, 0x2070, 0x20A0, 0x20D0, 0x2100, 0x2150, 0x2190, 0x2200, 0x2300, 0x2400, 0x2440, 0x2460, 0x2500, 0x2580, 0x25A0, 0x2600, 0x2700, 0x27C0, 0x27F0, 0x2800, 0x2900, 0x2980, 0x2A00, 0x2B00, 0x2C00, 0x2C60, 0x2C80, 0x2D00, 0x2D30, 0x2D80, 0x2DE0, 0x2E00, 0x2E80, 0x2F00, 0x2FF0, 0x3000, 0x3040, 0x30A0, 0x3100, 0x3130, 0x3190, 0x31A0, 0x31C0, 0x31F0, 0x3200, 0x3300, 0x3400, 0x4DC0, 0x4E00, 0xA000, 0xA490, 0xA4D0, 0xA500, 0xA640, 0xA6A0, 0xA700, 0xA720, 0xA800, 0xA830, 0xA840, 0xA880, 0xA8E0, 0xA900, 0xA930, 0xA960, 0xA980, 0xAA00, 0xAA60, 0xAA80, 0xABC0, 0xAC00, 0xD7B0, 0xE000, 0xF900, 0xFB00, 0xFB50, 0xFE00, 0xFE10, 0xFE20, 0xFE30, 0xFE50, 0xFE70, 0xFF00, 0xFFF0, 0x10000, 0x10080, 0x10100, 0x10140, 0x10190, 0x101D0, 0x10280, 0x102A0, 0x10300, 0x10330, 0x10380, 0x103A0, 0x10400, 0x10450, 0x10480, 0x10800, 0x10840, 0x10900, 0x10920, 0x10A00, 0x10A60, 0x10B00, 0x10B40, 0x10B60, 0x10C00, 0x10E60, 0x11080, 0x12000, 0x12400, 0x13000, 0x1D000, 0x1D100, 0x1D200, 0x1D300, 0x1D360, 0x1D400, 0x1F000, 0x1F030, 0x1F100, 0x1F200, 0x20000, 0x2A700, 0x2F800, 0xE0000, 0xE0100, 0xF0000, 0x100000 }; private static final int[] blockEnds = { 0x007F, 0x00FF, 0x017F, 0x024F, 0x02AF, 0x02FF, 0x036F, 0x03FF, 0x04FF, 0x052F, 0x058F, 0x05FF, 0x06FF, 0x074F, 0x077F, 0x07BF, 0x07FF, 0x083F, 0x097F, 0x09FF, 0x0A7F, 0x0AFF, 0x0B7F, 0x0BFF, 0x0C7F, 0x0CFF, 0x0D7F, 0x0DFF, 0x0E7F, 0x0EFF, 0x0FFF, 0x109F, 0x10FF, 0x11FF, 0x137F, 0x139F, 0x13FF, 0x167F, 0x169F, 0x16FF, 0x171F, 0x173F, 0x175F, 0x177F, 0x17FF, 0x18AF, 0x18FF, 0x194F, 0x197F, 0x19DF, 0x19FF, 0x1A1F, 0x1AAF, 0x1B7F, 0x1BBF, 0x1C4F, 0x1C7F, 0x1CFF, 0x1D7F, 0x1DBF, 0x1DFF, 0x1EFF, 0x1FFF, 0x206F, 0x209F, 0x20CF, 0x20FF, 0x214F, 0x218F, 0x21FF, 0x22FF, 0x23FF, 0x243F, 0x245F, 0x24FF, 0x257F, 0x259F, 0x25FF, 0x26FF, 0x27BF, 0x27EF, 0x27FF, 0x28FF, 0x297F, 0x29FF, 0x2AFF, 0x2BFF, 0x2C5F, 0x2C7F, 0x2CFF, 0x2D2F, 0x2D7F, 0x2DDF, 0x2DFF, 0x2E7F, 0x2EFF, 0x2FDF, 0x2FFF, 0x303F, 0x309F, 0x30FF, 0x312F, 0x318F, 0x319F, 0x31BF, 0x31EF, 0x31FF, 0x32FF, 0x33FF, 0x4DBF, 0x4DFF, 0x9FFF, 0xA48F, 0xA4CF, 0xA4FF, 0xA63F, 0xA69F, 0xA6FF, 0xA71F, 0xA7FF, 0xA82F, 0xA83F, 0xA87F, 0xA8DF, 0xA8FF, 0xA92F, 0xA95F, 0xA97F, 0xA9DF, 0xAA5F, 0xAA7F, 0xAADF, 0xABFF, 0xD7AF, 0xD7FF, 0xF8FF, 0xFAFF, 0xFB4F, 0xFDFF, 0xFE0F, 0xFE1F, 0xFE2F, 0xFE4F, 0xFE6F, 0xFEFF, 0xFFEF, 0xFFFF, 0x1007F, 0x100FF, 0x1013F, 0x1018F, 0x101CF, 0x101FF, 0x1029F, 0x102DF, 0x1032F, 0x1034F, 0x1039F, 0x103DF, 0x1044F, 0x1047F, 0x104AF, 0x1083F, 0x1085F, 0x1091F, 0x1093F, 0x10A5F, 0x10A7F, 0x10B3F, 0x10B5F, 0x10B7F, 0x10C4F, 0x10E7F, 0x110CF, 0x123FF, 0x1247F, 0x1342F, 0x1D0FF, 0x1D1FF, 0x1D24F, 0x1D35F, 0x1D37F, 0x1D7FF, 0x1F02F, 0x1F09F, 0x1F1FF, 0x1F2FF, 0x2A6DF, 0x2B73F, 0x2FA1F, 0xE007F, 0xE01EF, 0xFFFFF, 0x10FFFF }; /** Returns random string of length between 0-20 codepoints, all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r) { return randomRealisticUnicodeString(r, 20); } /** Returns random string of length up to maxLength codepoints , all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r, int maxLength) { return randomRealisticUnicodeString(r, 0, 20); } /** Returns random string of length between min and max codepoints, all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r, int minLength, int maxLength) { final int end = minLength + r.nextInt(maxLength); final int block = r.nextInt(blockStarts.length); StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) sb.appendCodePoint(nextInt(r, blockStarts[block], blockEnds[block])); return sb.toString(); } /** Returns random string, with a given UTF-8 byte length*/ public static String randomFixedByteLengthUnicodeString(Random r, int length) { final char[] buffer = new char[length*3]; int bytes = length; int i = 0; for (; i < buffer.length && bytes != 0; i++) { int t; if (bytes >= 4) { t = r.nextInt(5); } else if (bytes >= 3) { t = r.nextInt(4); } else if (bytes >= 2) { t = r.nextInt(2); } else { t = 0; } if (t == 0) { buffer[i] = (char) r.nextInt(0x80); bytes--; } else if (1 == t) { buffer[i] = (char) nextInt(r, 0x80, 0x7ff); bytes -= 2; } else if (2 == t) { buffer[i] = (char) nextInt(r, 0x800, 0xd7ff); bytes -= 3; } else if (3 == t) { buffer[i] = (char) nextInt(r, 0xe000, 0xffff); bytes -= 3; } else if (4 == t) { // Make a surrogate pair // High surrogate buffer[i++] = (char) nextInt(r, 0xd800, 0xdbff); // Low surrogate buffer[i] = (char) nextInt(r, 0xdc00, 0xdfff); bytes -= 4; } } return new String(buffer, 0, i); } /** Return a Codec that can read any of the * default codecs and formats, but always writes in the specified * format. */ public static Codec alwaysPostingsFormat(final PostingsFormat format) { return new Lucene40Codec() { @Override public PostingsFormat getPostingsFormatForField(String field) { return format; } }; } // TODO: generalize all 'test-checks-for-crazy-codecs' to // annotations (LUCENE-3489) public static String getPostingsFormat(String field) { PostingsFormat p = Codec.getDefault().postingsFormat(); if (p instanceof PerFieldPostingsFormat) { return ((PerFieldPostingsFormat)p).getPostingsFormatForField(field).getName(); } else { return p.getName(); } } public static boolean anyFilesExceptWriteLock(Directory dir) throws IOException { String[] files = dir.listAll(); if (files.length > 1 || (files.length == 1 && !files[0].equals("write.lock"))) { return true; } else { return false; } } /** just tries to configure things to keep the open file * count lowish */ public static void reduceOpenFiles(IndexWriter w) { // keep number of open files lowish MergePolicy mp = w.getConfig().getMergePolicy(); if (mp instanceof LogMergePolicy) { LogMergePolicy lmp = (LogMergePolicy) mp; lmp.setMergeFactor(Math.min(5, lmp.getMergeFactor())); } else if (mp instanceof TieredMergePolicy) { TieredMergePolicy tmp = (TieredMergePolicy) mp; tmp.setMaxMergeAtOnce(Math.min(5, tmp.getMaxMergeAtOnce())); tmp.setSegmentsPerTier(Math.min(5, tmp.getSegmentsPerTier())); } MergeScheduler ms = w.getConfig().getMergeScheduler(); if (ms instanceof ConcurrentMergeScheduler) { ((ConcurrentMergeScheduler) ms).setMaxThreadCount(2); ((ConcurrentMergeScheduler) ms).setMaxMergeCount(3); } } /** Checks some basic behaviour of an AttributeImpl * @param reflectedValues contains a map with "AttributeClass#key" as values */ public static <T> void assertAttributeReflection(final AttributeImpl att, Map<String,T> reflectedValues) { final Map<String,Object> map = new HashMap<String,Object>(); att.reflectWith(new AttributeReflector() { public void reflect(Class<? extends Attribute> attClass, String key, Object value) { map.put(attClass.getName() + '#' + key, value); } }); Assert.assertEquals("Reflection does not produce same map", reflectedValues, map); } public static void keepFullyDeletedSegments(IndexWriter w) { try { // Carefully invoke what is a package-private (test // only, internal) method on IndexWriter: Method m = IndexWriter.class.getDeclaredMethod("keepFullyDeletedSegments"); m.setAccessible(true); m.invoke(w); } catch (Exception e) { // Should not happen? throw new RuntimeException(e); } } /** Adds field info for a Document. */ public static void add(Document doc, FieldInfos fieldInfos) { for (IndexableField field : doc) { fieldInfos.addOrUpdate(field.name(), field.fieldType()); } } /** * insecure, fast version of File.createTempFile * uses Random instead of SecureRandom. */ public static File createTempFile(String prefix, String suffix, File directory) throws IOException { // Force a prefix null check first if (prefix.length() < 3) { throw new IllegalArgumentException("prefix must be 3"); } String newSuffix = suffix == null ? ".tmp" : suffix; File result; do { result = genTempFile(prefix, newSuffix, directory); } while (!result.createNewFile()); return result; } /* Temp file counter */ private static int counter = 0; /* identify for differnt VM processes */ private static int counterBase = 0; private static class TempFileLocker {}; private static TempFileLocker tempFileLocker = new TempFileLocker(); private static File genTempFile(String prefix, String suffix, File directory) { int identify = 0; synchronized (tempFileLocker) { if (counter == 0) { int newInt = new Random().nextInt(); counter = ((newInt / 65535) & 0xFFFF) + 0x2710; counterBase = counter; } identify = counter++; } StringBuilder newName = new StringBuilder(); newName.append(prefix); newName.append(counterBase); newName.append(identify); newName.append(suffix); return new File(directory, newName.toString()); } public static void assertEquals(TopDocs expected, TopDocs actual) { Assert.assertEquals("wrong total hits", expected.totalHits, actual.totalHits); Assert.assertEquals("wrong maxScore", expected.getMaxScore(), actual.getMaxScore(), 0.0); Assert.assertEquals("wrong hit count", expected.scoreDocs.length, actual.scoreDocs.length); for(int hitIDX=0;hitIDX<expected.scoreDocs.length;hitIDX++) { final ScoreDoc expectedSD = expected.scoreDocs[hitIDX]; final ScoreDoc actualSD = actual.scoreDocs[hitIDX]; Assert.assertEquals("wrong hit docID", expectedSD.doc, actualSD.doc); Assert.assertEquals("wrong hit score", expectedSD.score, actualSD.score, 0.0); if (expectedSD instanceof FieldDoc) { Assert.assertTrue(actualSD instanceof FieldDoc); Assert.assertArrayEquals("wrong sort field values", ((FieldDoc) expectedSD).fields, ((FieldDoc) actualSD).fields); } else { Assert.assertFalse(actualSD instanceof FieldDoc); } } } // NOTE: this is likely buggy, and cannot clone fields // with tokenStreamValues, etc. Use at your own risk!! // TODO: is there a pre-existing way to do this!!! public static Document cloneDocument(Document doc1) { final Document doc2 = new Document(); for(IndexableField f : doc1) { Field field1 = (Field) f; Field field2 = new Field(field1.name(), field1.stringValue(), field1.fieldType()); doc2.add(field2); } return doc2; } // Returns a DocsEnum, but randomly sometimes uses a // DocsAndFreqsEnum, DocsAndPositionsEnum. Returns null // if field/term doesn't exist: public static DocsEnum docs(Random random, IndexReader r, String field, BytesRef term, Bits liveDocs, DocsEnum reuse, boolean needsFreqs) throws IOException { final Terms terms = MultiFields.getTerms(r, field); if (terms == null) { return null; } final TermsEnum termsEnum = terms.iterator(null); if (!termsEnum.seekExact(term, random.nextBoolean())) { return null; } if (random.nextBoolean()) { if (random.nextBoolean()) { // TODO: cast re-use to D&PE if we can...? DocsAndPositionsEnum docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, true); if (docsAndPositions == null) { docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, false); } if (docsAndPositions != null) { return docsAndPositions; } } final DocsEnum docsAndFreqs = termsEnum.docs(liveDocs, reuse, true); if (docsAndFreqs != null) { return docsAndFreqs; } } return termsEnum.docs(liveDocs, reuse, needsFreqs); } // Returns a DocsEnum from a positioned TermsEnum, but // randomly sometimes uses a DocsAndFreqsEnum, DocsAndPositionsEnum. public static DocsEnum docs(Random random, TermsEnum termsEnum, Bits liveDocs, DocsEnum reuse, boolean needsFreqs) throws IOException { if (random.nextBoolean()) { if (random.nextBoolean()) { // TODO: cast re-use to D&PE if we can...? DocsAndPositionsEnum docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, true); if (docsAndPositions == null) { docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, false); } if (docsAndPositions != null) { return docsAndPositions; } } final DocsEnum docsAndFreqs = termsEnum.docs(liveDocs, null, true); if (docsAndFreqs != null) { return docsAndFreqs; } } return termsEnum.docs(liveDocs, null, needsFreqs); } }
true
true
public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; case 21: sb.append("\n"); case 22: sb.append(" ".substring(nextInt(random, 0, 10))); default: sb.append(randomSimpleString(random)); } } return sb.toString(); }
public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; case 21: sb.append("\n"); break; case 22: sb.append(" ".substring(nextInt(random, 0, 10))); break; default: sb.append(randomSimpleString(random)); } } return sb.toString(); }
diff --git a/src/main/java/com/github/xgameenginee/codec/GameDecoder.java b/src/main/java/com/github/xgameenginee/codec/GameDecoder.java index cbd8122..1953b53 100644 --- a/src/main/java/com/github/xgameenginee/codec/GameDecoder.java +++ b/src/main/java/com/github/xgameenginee/codec/GameDecoder.java @@ -1,29 +1,29 @@ package com.github.xgameenginee.codec; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import com.github.xgameenginee.GameBoss; import com.github.xgameenginee.core.ProtocolCoder; public class GameDecoder extends LengthFieldBasedFrameDecoder { public GameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) { super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, true); } @Override protected Object decode(ChannelHandlerContext ctx, Channel ch, ChannelBuffer cb) throws Exception { ChannelBuffer buffer = (ChannelBuffer)super.decode(ctx, ch, cb); ProtocolCoder coder = GameBoss.getInstance().getProtocolCoder(); - if (coder != null) { + if (coder != null && buffer != null) { byte[] decodebytes = coder.decode(buffer.array()); return ChannelBuffers.wrappedBuffer(decodebytes); } return buffer; } }
true
true
protected Object decode(ChannelHandlerContext ctx, Channel ch, ChannelBuffer cb) throws Exception { ChannelBuffer buffer = (ChannelBuffer)super.decode(ctx, ch, cb); ProtocolCoder coder = GameBoss.getInstance().getProtocolCoder(); if (coder != null) { byte[] decodebytes = coder.decode(buffer.array()); return ChannelBuffers.wrappedBuffer(decodebytes); } return buffer; }
protected Object decode(ChannelHandlerContext ctx, Channel ch, ChannelBuffer cb) throws Exception { ChannelBuffer buffer = (ChannelBuffer)super.decode(ctx, ch, cb); ProtocolCoder coder = GameBoss.getInstance().getProtocolCoder(); if (coder != null && buffer != null) { byte[] decodebytes = coder.decode(buffer.array()); return ChannelBuffers.wrappedBuffer(decodebytes); } return buffer; }
diff --git a/src/LL1Parser.java b/src/LL1Parser.java index b011e4e..606e162 100644 --- a/src/LL1Parser.java +++ b/src/LL1Parser.java @@ -1,123 +1,123 @@ import java.io.File; import java.io.FileNotFoundException; import java.util.List; import java.util.Scanner; import java.util.Stack; /** * LL1 Parser that determines whether or not an example file is valid with a given grammar. */ public class LL1Parser { private LL1Grammar grammar; private LL1ParsingTable parsingTable; private LL1Lexer lexer; private Scanner lexerOutputScanner; public static boolean VERBOSE = false; /** * Main method which requires two CLI arguments - grammar file and file to parse. An optional third "-v" argument turns on verbose mode. * @param args CLI arguments */ public static void main(String[] args) { if (args.length >= 2 && args.length <= 3) { File grammarFile = new File(args[0]); File fileToParse = new File(args[1]); if (args.length >= 3 && args[2].equals("-v")) { VERBOSE = true; } LL1Parser parser = new LL1Parser(grammarFile, fileToParse); try { parser.parse(); } catch (LL1ParseException e) { e.printStackTrace(); } } else { System.err.println("Incorrect usage. Required arguments: [grammar file] [file to parse]\nOptional third argument \"-v\" available for verbose."); } } /** * Constructs a new LL1 Parser. Creates the grammar, parsing table, and the lexer. * @param grammarFile Grammar file * @param fileToParse Sample file of the language */ public LL1Parser(File grammarFile, File fileToParse) { try { grammar = new LL1Grammar(grammarFile); } catch (LL1GrammarException e) { e.printStackTrace(); } if (VERBOSE) { System.out.println(grammar); } parsingTable = new LL1ParsingTable(grammar); lexer = new LL1Lexer(fileToParse); try { lexerOutputScanner = new Scanner(lexer.getOutputFile()); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Parse the sample file. * @return Boolean of success * @throws LL1ParseException */ public boolean parse() throws LL1ParseException { Stack<RuleElement> parsingStack = new Stack<RuleElement>(); parsingStack.push(grammar.getStartVariable()); TokenType tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); while (!parsingStack.isEmpty()) { if (VERBOSE) { System.out.println(parsingStack); } RuleElement re = parsingStack.pop(); if (VERBOSE) { System.out.println("Popped " + re); } if (re instanceof Variable) { Variable v = (Variable)re; List<RuleElement> newRuleElements = parsingTable.getRuleElements(v, tokenType); if (newRuleElements != null) { for (int i = newRuleElements.size() - 1; i >= 0; i--) { parsingStack.push(newRuleElements.get(i)); } } else { throw new LL1ParseException("Parsing failed with token of type " + tokenType + " and stack: " + parsingStack); } } else if (re instanceof Terminal && !(((Terminal)re).isEmptyString())) { Terminal terminal = (Terminal)re; TokenType parsingStackTokenType = TokenType.tokenWithIdentifier(terminal.toString()); if (parsingStackTokenType.equals(tokenType)) { if (parsingStack.isEmpty()) { // if token is matched and parsing stack is empty, no need to go further break; } if (VERBOSE) { System.out.println("Parsed " + tokenType); } tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); } else { - throw new LL1ParseException("Unexpected " + tokenType + " (expected "+ tokenType + ")"); + throw new LL1ParseException("Unexpected " + tokenType + " (expected "+ parsingStackTokenType + ")"); } } } if (lexerOutputScanner.hasNext()) { throw new LL1ParseException("Parsing ended with input remaining"); } System.out.println("Successful parse!"); return true; } }
true
true
public boolean parse() throws LL1ParseException { Stack<RuleElement> parsingStack = new Stack<RuleElement>(); parsingStack.push(grammar.getStartVariable()); TokenType tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); while (!parsingStack.isEmpty()) { if (VERBOSE) { System.out.println(parsingStack); } RuleElement re = parsingStack.pop(); if (VERBOSE) { System.out.println("Popped " + re); } if (re instanceof Variable) { Variable v = (Variable)re; List<RuleElement> newRuleElements = parsingTable.getRuleElements(v, tokenType); if (newRuleElements != null) { for (int i = newRuleElements.size() - 1; i >= 0; i--) { parsingStack.push(newRuleElements.get(i)); } } else { throw new LL1ParseException("Parsing failed with token of type " + tokenType + " and stack: " + parsingStack); } } else if (re instanceof Terminal && !(((Terminal)re).isEmptyString())) { Terminal terminal = (Terminal)re; TokenType parsingStackTokenType = TokenType.tokenWithIdentifier(terminal.toString()); if (parsingStackTokenType.equals(tokenType)) { if (parsingStack.isEmpty()) { // if token is matched and parsing stack is empty, no need to go further break; } if (VERBOSE) { System.out.println("Parsed " + tokenType); } tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); } else { throw new LL1ParseException("Unexpected " + tokenType + " (expected "+ tokenType + ")"); } } } if (lexerOutputScanner.hasNext()) { throw new LL1ParseException("Parsing ended with input remaining"); } System.out.println("Successful parse!"); return true; }
public boolean parse() throws LL1ParseException { Stack<RuleElement> parsingStack = new Stack<RuleElement>(); parsingStack.push(grammar.getStartVariable()); TokenType tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); while (!parsingStack.isEmpty()) { if (VERBOSE) { System.out.println(parsingStack); } RuleElement re = parsingStack.pop(); if (VERBOSE) { System.out.println("Popped " + re); } if (re instanceof Variable) { Variable v = (Variable)re; List<RuleElement> newRuleElements = parsingTable.getRuleElements(v, tokenType); if (newRuleElements != null) { for (int i = newRuleElements.size() - 1; i >= 0; i--) { parsingStack.push(newRuleElements.get(i)); } } else { throw new LL1ParseException("Parsing failed with token of type " + tokenType + " and stack: " + parsingStack); } } else if (re instanceof Terminal && !(((Terminal)re).isEmptyString())) { Terminal terminal = (Terminal)re; TokenType parsingStackTokenType = TokenType.tokenWithIdentifier(terminal.toString()); if (parsingStackTokenType.equals(tokenType)) { if (parsingStack.isEmpty()) { // if token is matched and parsing stack is empty, no need to go further break; } if (VERBOSE) { System.out.println("Parsed " + tokenType); } tokenType = TokenType.tokenWithIdentifier(lexerOutputScanner.next()); } else { throw new LL1ParseException("Unexpected " + tokenType + " (expected "+ parsingStackTokenType + ")"); } } } if (lexerOutputScanner.hasNext()) { throw new LL1ParseException("Parsing ended with input remaining"); } System.out.println("Successful parse!"); return true; }
diff --git a/src/com/vorsk/crossfitr/WorkoutProfileActivity.java b/src/com/vorsk/crossfitr/WorkoutProfileActivity.java index b8f4714..d2096f3 100644 --- a/src/com/vorsk/crossfitr/WorkoutProfileActivity.java +++ b/src/com/vorsk/crossfitr/WorkoutProfileActivity.java @@ -1,223 +1,225 @@ package com.vorsk.crossfitr; import com.vorsk.crossfitr.models.WorkoutModel; import com.vorsk.crossfitr.models.WorkoutRow; import com.vorsk.crossfitr.models.WorkoutSessionModel; import android.app.Activity; import android.app.AlertDialog; import android.opengl.Visibility; import android.os.Bundle; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Typeface; import android.text.Editable; import android.text.InputType; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; public class WorkoutProfileActivity extends Activity implements OnClickListener { //initialize variables private WorkoutRow workout; private int ACT_TIMER = 1; private Typeface font; TextView screenName, tvname, tvdesc, tvbestRecord; //Its dynamic! android should use this by default private String TAG = this.getClass().getName(); public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //create model object WorkoutModel model = new WorkoutModel(this); //get the id passed from previous activity (workout lists) long id = getIntent().getLongExtra("ID", -1); //if ID is invalid, go back to home screen if(id < 0) { finish(); } //set view setContentView(R.layout.workout_profile); //create a WorkoutRow, to retrieve data from database model.open(); workout = model.getByID(id); //TextView objects font = Typeface.createFromAsset(this.getAssets(), "fonts/Roboto-Thin.ttf"); screenName = (TextView) findViewById(R.id.screenTitle); screenName.setTypeface(font); tvname = (TextView) findViewById(R.id.workout_profile_nameDB); tvname.setTypeface(font); tvbestRecord = (TextView) findViewById(R.id.workout_profile_best_recordDB); tvbestRecord.setTypeface(font); tvdesc = (TextView) findViewById(R.id.workout_profile_descDB); tvdesc.setTypeface(font); //set the text of the TextView objects from the data retrieved from the DB Resources res = getResources(); tvname.setText(workout.name); - if (model.getTypeName(workout.workout_type_id).equals("WOD")) + if (model.getTypeName(workout.workout_type_id).equals("WOD")){ + tvname.setText("WOD"); tvname.setTextColor(res.getColor(R.color.wod)); + } else if (model.getTypeName(workout.workout_type_id).equals("Hero")) tvname.setTextColor(res.getColor(R.color.heroes)); else if (model.getTypeName(workout.workout_type_id).equals("Girl")) tvname.setTextColor(res.getColor(R.color.girls)); else if(model.getTypeName(workout.workout_type_id).equals("Custom")) tvname.setTextColor(res.getColor(R.color.custom)); tvdesc.setText(workout.description); //tvrecordType.setText(model.getTypeName(workout.workout_type_id)); model.close(); // begin workout button View beginButton = findViewById(R.id.button_begin_workout); ((TextView) beginButton).setTypeface(font); if (workout.description.indexOf("Rest Day") == -1){ //It is not a rest day tvbestRecord.setText("Personal Record: "+StopwatchActivity.formatElapsedTime(Long.parseLong(String.valueOf(workout.record)))); beginButton.setOnClickListener(this); }else{ //it is a rest day beginButton.setVisibility(View.GONE); tvbestRecord.setVisibility(View.GONE); } } public void onClick(View v) { switch (v.getId()) { // if user presses begin button, user will now go into the timer page. case R.id.button_begin_workout: if(workout.record_type_id == WorkoutModel.SCORE_WEIGHT){ weightPopup(); } else if(workout.record_type_id == WorkoutModel.SCORE_REPS){ repsPopup(); } else{ Intent i = new Intent(this, TimeTabWidget.class); i.putExtra("workout_id", workout._id); //i.putExtra("workout_score", //Integer.parseInt(etextra.getText().toString())); startActivityForResult(i, ACT_TIMER); } break; } } private void repsPopup() { // TODO Auto-generated method stub final Intent i = new Intent(this, TimeTabWidget.class); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Enter Number of Reps:"); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setView(input); alert.setPositiveButton("Begin", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); i.putExtra("workout_id", workout._id); i.putExtra("workout_score", Integer.parseInt(value.toString())); startActivityForResult(i, ACT_TIMER); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. Do nothing } }); alert.show(); } private void weightPopup() { // TODO Auto-generated method stub AlertDialog.Builder alert = new AlertDialog.Builder(this); final Intent i = new Intent(this, TimeTabWidget.class); alert.setTitle("Input Weight For Workout (lbs):"); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setView(input); alert.setPositiveButton("Begin", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Editable value = input.getText(); i.putExtra("workout_id", workout._id); i.putExtra("workout_score", Integer.parseInt(value.toString())); startActivityForResult(i, ACT_TIMER); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }); alert.show(); } protected void onActivityResult(int request, int result, Intent data) { if (request == ACT_TIMER) { if (result != RESULT_CANCELED) { // Session was completed long score; WorkoutSessionModel model = new WorkoutSessionModel(this); model.open(); // Get the score returned if (workout.record_type_id == WorkoutModel.SCORE_TIME) { score = data.getLongExtra("time", WorkoutModel.NOT_SCORED); } else if (workout.record_type_id == WorkoutModel.SCORE_REPS) { score = data.getIntExtra("score", WorkoutModel.NOT_SCORED); } else if (workout.record_type_id == WorkoutModel.SCORE_WEIGHT) { score = data.getIntExtra("score", WorkoutModel.NOT_SCORED); } else { score = WorkoutModel.NOT_SCORED; } //Test debugging! //Log.d(TAG,"workoutID: "+workout._id+" score: "+score+" recotdTypeID: "+workout.record_type_id); // Save as a new session long id = model.insert(workout._id, score, workout.record_type_id); model.close(); // Show the results page Intent res = new Intent(this, ResultsActivity.class); res.putExtra("session_id", id); startActivity(res); } } } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //create model object WorkoutModel model = new WorkoutModel(this); //get the id passed from previous activity (workout lists) long id = getIntent().getLongExtra("ID", -1); //if ID is invalid, go back to home screen if(id < 0) { finish(); } //set view setContentView(R.layout.workout_profile); //create a WorkoutRow, to retrieve data from database model.open(); workout = model.getByID(id); //TextView objects font = Typeface.createFromAsset(this.getAssets(), "fonts/Roboto-Thin.ttf"); screenName = (TextView) findViewById(R.id.screenTitle); screenName.setTypeface(font); tvname = (TextView) findViewById(R.id.workout_profile_nameDB); tvname.setTypeface(font); tvbestRecord = (TextView) findViewById(R.id.workout_profile_best_recordDB); tvbestRecord.setTypeface(font); tvdesc = (TextView) findViewById(R.id.workout_profile_descDB); tvdesc.setTypeface(font); //set the text of the TextView objects from the data retrieved from the DB Resources res = getResources(); tvname.setText(workout.name); if (model.getTypeName(workout.workout_type_id).equals("WOD")) tvname.setTextColor(res.getColor(R.color.wod)); else if (model.getTypeName(workout.workout_type_id).equals("Hero")) tvname.setTextColor(res.getColor(R.color.heroes)); else if (model.getTypeName(workout.workout_type_id).equals("Girl")) tvname.setTextColor(res.getColor(R.color.girls)); else if(model.getTypeName(workout.workout_type_id).equals("Custom")) tvname.setTextColor(res.getColor(R.color.custom)); tvdesc.setText(workout.description); //tvrecordType.setText(model.getTypeName(workout.workout_type_id)); model.close(); // begin workout button View beginButton = findViewById(R.id.button_begin_workout); ((TextView) beginButton).setTypeface(font); if (workout.description.indexOf("Rest Day") == -1){ //It is not a rest day tvbestRecord.setText("Personal Record: "+StopwatchActivity.formatElapsedTime(Long.parseLong(String.valueOf(workout.record)))); beginButton.setOnClickListener(this); }else{ //it is a rest day beginButton.setVisibility(View.GONE); tvbestRecord.setVisibility(View.GONE); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //create model object WorkoutModel model = new WorkoutModel(this); //get the id passed from previous activity (workout lists) long id = getIntent().getLongExtra("ID", -1); //if ID is invalid, go back to home screen if(id < 0) { finish(); } //set view setContentView(R.layout.workout_profile); //create a WorkoutRow, to retrieve data from database model.open(); workout = model.getByID(id); //TextView objects font = Typeface.createFromAsset(this.getAssets(), "fonts/Roboto-Thin.ttf"); screenName = (TextView) findViewById(R.id.screenTitle); screenName.setTypeface(font); tvname = (TextView) findViewById(R.id.workout_profile_nameDB); tvname.setTypeface(font); tvbestRecord = (TextView) findViewById(R.id.workout_profile_best_recordDB); tvbestRecord.setTypeface(font); tvdesc = (TextView) findViewById(R.id.workout_profile_descDB); tvdesc.setTypeface(font); //set the text of the TextView objects from the data retrieved from the DB Resources res = getResources(); tvname.setText(workout.name); if (model.getTypeName(workout.workout_type_id).equals("WOD")){ tvname.setText("WOD"); tvname.setTextColor(res.getColor(R.color.wod)); } else if (model.getTypeName(workout.workout_type_id).equals("Hero")) tvname.setTextColor(res.getColor(R.color.heroes)); else if (model.getTypeName(workout.workout_type_id).equals("Girl")) tvname.setTextColor(res.getColor(R.color.girls)); else if(model.getTypeName(workout.workout_type_id).equals("Custom")) tvname.setTextColor(res.getColor(R.color.custom)); tvdesc.setText(workout.description); //tvrecordType.setText(model.getTypeName(workout.workout_type_id)); model.close(); // begin workout button View beginButton = findViewById(R.id.button_begin_workout); ((TextView) beginButton).setTypeface(font); if (workout.description.indexOf("Rest Day") == -1){ //It is not a rest day tvbestRecord.setText("Personal Record: "+StopwatchActivity.formatElapsedTime(Long.parseLong(String.valueOf(workout.record)))); beginButton.setOnClickListener(this); }else{ //it is a rest day beginButton.setVisibility(View.GONE); tvbestRecord.setVisibility(View.GONE); } }
diff --git a/OpenGLEN/src/com/super2k/openglen/animation/Animation3D.java b/OpenGLEN/src/com/super2k/openglen/animation/Animation3D.java index 4d901d8..d26fbcc 100644 --- a/OpenGLEN/src/com/super2k/openglen/animation/Animation3D.java +++ b/OpenGLEN/src/com/super2k/openglen/animation/Animation3D.java @@ -1,509 +1,510 @@ /* Copyright 2012 Richard Sahlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.super2k.openglen.animation; import com.super2k.openglen.objects.PooledObject; /** * Base class for animations. * @author Richard Sahlin * */ public abstract class Animation3D implements PooledObject { protected final static String INVALID_PARAMETER_STR = "Invalid parameter, null parameter, or sizes do not match."; /** * Value to specify that animation should loop forever. */ public final static int LOOP_INFINITE = -1; /** * Value to specify that animation should not play. */ public final static int DISABLED = 0; /** * Value to specify that animation should play once. * For other loop counts use the number of times the animation should loop, * eg 4 to play 4 times. */ public final static int ONCE = 1; protected final static float DEFAULT_TIMEFACTOR = 1f; /** * User defined animation type. Is preserved when exporting animations. */ protected int mAnimationType; /** * The key for pooled animation, or NOT_POOLED_OBJECT if not pooled. */ protected int mKey = NOT_POOLED_OBJECT; /** * Type of class, can be used to determine what class animation is for pooled objects. */ protected int mType; /** * Keypoints in the time domain */ protected float[] mInput; /** * Keypoints in the target domain. */ protected float[] mOutput; /** * The target array, this is normally a reference. */ protected float[] mTarget; protected int mOutputIndex = 0; protected int mOutputStride = 0; protected int mOutputStartIndex = 0; protected int mTargetIndex = 0; /** * Number of targets */ protected int mTargets; /** * May be used by subclasses to keep track of z axis rotation. */ protected float mZAxisRotation; /** * Max number of times an animation shall loop. * If != LOOP_INFINITE then this value limits number of times the animation can loop. * When this loop count is reached the animation shall not animate further * and report true when isFinished is called. */ protected int mLoopCount = LOOP_INFINITE; /** * Controls if animation values are absolute or added to existing values. * Set to true to make values be added to existing values. */ protected boolean mRelative[]; /** * Set to true to ping-pong animation */ protected boolean mPingPong[]; /** * Array that may be used to copy the contents of the target */ protected float[] mResetArray; /** * Factor for time, this can be used for slowmotion of speedup of animation. */ protected float mTimeFactor = DEFAULT_TIMEFACTOR; /* * -------------------------------- * Runtime variables. * -------------------------------- */ protected float[] mCurrentTime; protected int mInputIndex = 0; protected boolean mFinished = false; protected int mCurrentLoop = 0; protected boolean mTempLoop; /** * Set to true when looping and pingpong is set, this will go backwards. */ protected boolean[] mReverse; protected float mTempMaxtime; protected int mTempMaxIndex; /** * Return the time in seconds when this animation starts. * @return */ public float getAnimationStart() { return mInput[0]; } /** * Return the time in seconds when this animation ends. * @return */ public float getAnimationEnd() { return mInput[mInput.length-1]; } /** * Return true of the animation is finished. * Note that the animation will not be considered as finished while loop is true. * @return True if the animation has finished (ie loop is not true and animation has reached end) */ public boolean isFinished() { return mFinished; } /** * Checks wether the animation has looped or not, returns number of times the animation * has looped. * This value is reset when calling resetAnimation() * @return Number of times the animation has looped, 0 or more. */ public int getCurrentLoop() { return mCurrentLoop; } /** * Set the time of the animation, * this will perform a resetAnimation followed by a call to animate() with the specified time. * This means that the animation will be affected by the timefactor value. * @param time */ public void setTime(float time) { resetAnimation(); animate(time); } /** * Inits the animation with the specified number of targets and flags. * @param targets Number of target values (axes) * @param relative Array with target number of boolean values for relative flag. * @param pingPong Array with target number of boolean values for pingpong flag. */ public void init(int targets, boolean[] relative, boolean[] pingPong) { mTargets = targets; if (mRelative == null || mRelative.length < targets) { mRelative = new boolean[targets]; mPingPong = new boolean[targets]; mReverse = new boolean[targets]; mCurrentTime = new float[targets]; } for (int i = 0; i < targets; i++) { mRelative[i] = relative[i]; mPingPong[i] = pingPong[i]; mReverse[i] = false; mCurrentTime[i] = 0; } } /** * Sets the timefactor, this can be use for slowmotion of speedup of animations. * Note that this field should be used in the animate() method to alter the incoming delta value. * @param factor Timefactor for animation speed, 1.0 is normal speed - lower values means slower animation. */ public void setTimeFactor(float factor) { mTimeFactor = factor; } /** * Set the way values are considered when writing back, * if relative set to true then animation values are added to existing transform values. * If false the values from the animation is set in the transform. * @param relative * @param index Index to the axis to set */ public void setRelative(boolean relative, int index) { mRelative[index] = relative; } /** * Return the type of animation, * this is something that is understood by the client. The animation type is simply a way for clients * to mark tag animations with a specific type that can later be retrieved. * The animation type is preserved when exporting the animation. * @return The type of this animation or -1 if not set. */ public int getAnimationType() { return mAnimationType; } /** * Returns the target index, this can for instance be used when copying one animation. * @return Index into target array where output values are written. */ public int getTargetIndex() { return mTargetIndex; } /** * Sets a (new) target for the animation, only call this if you know what you are doing. * This will discard the previous target and replace it with the new, may not be called * on a released object. * If the target array length is not sufficient an exception will occur when animating. * Caller must make sure target size matches that of the animation. * This method is intended to be used when switching target to a different sprite object, eg * swapping the position target in one SpriteObject with the position target of another * SpriteObject. * @param target The new target array - must contain enough values for existing animation. * @param index Index into target where values are set. * @throws IllegalArgumentException If index < 0 */ public void setTarget(float[] target, int index) { if (index < 0) { throw new IllegalArgumentException("Invalid target index: " + index); } if (target == null) { throw new IllegalArgumentException("Invalid target null."); } mTarget = target; mTargetIndex = index; } /** * Set the (user defined) animation type for this animation. * This is client specific data that can be used to group animations together. * The animation type is saved when exporting the animation. * @param type */ public void setAnimationType(int type) { mAnimationType = type; } /** * Sets the max number of times the animation may loop, if looping is enabled. * @param count LOOP_INFINITE to loop forever, LOOP_DISABLED to disable looping, or * number of times animation shall loop. */ public void setLoopCount(int count) { mLoopCount = count; } /** * Sets the ping-pong flag, if enabled, and looping is enabled, the animation will go backwards when end is reached. * Each turn at beginning or end will count up loopcount. * @param flag True to enable ping-pong, remember to set loopcount as well. * @param index Index to axis to set. */ public void setPingPong(boolean flag, int index) { mPingPong[index] = flag; } /** * Fetches the max number of times this animation shall loop. * @return LOOP_INFINITE to loop forever, LOOP_DISABLED to disable looping, or * number of times animation shall loop. */ public int getLoopCount() { return mLoopCount; } /** * Internal method to update the time, temp time and temp index * @param deltaTime */ protected void updateTime(float deltaTime, int index) { if (mReverse[index]) { mCurrentTime[index] -= deltaTime * mTimeFactor; mTempMaxtime = mInput[0]; mTempMaxIndex = 0; } else { mCurrentTime[index] += deltaTime * mTimeFactor; mTempMaxtime = mInput[mInput.length-1]; mTempMaxIndex = mInput.length - 2; } } /** * Internal method * Prepares animation for looping. * Checks pingpong flag, updates reverse flag according. * Call this method when animation shall loop, current time will be correct after calling this. * @param index Index to animation elements, 0 and upwards */ protected void loopAnimation(int index) { //Check for pingpong if (!mFinished) { if (mPingPong[index]) { if (!mReverse[index]) { mCurrentTime[index] -= mCurrentTime[index] - mTempMaxtime; } else { mCurrentTime[index] = Math.abs(mCurrentTime[index]); //Count one ping-pong from begin-end-begin as one loop. mCurrentLoop++; } mReverse[index] = !mReverse[index]; } else { while (mCurrentTime[index] > mTempMaxtime ) mCurrentTime[index] -= mTempMaxtime; mCurrentLoop++; } } } /** * Calculate the currentTime and currentIndex values. * @param timeDelta * @param index index of the axis (value) to animate * @return True if animation reached end */ boolean calcCurrentIndex(float timeDelta, int index) { mTempLoop = false; updateTime(timeDelta, 0); if ((!mReverse[index] && mCurrentTime[index] > mTempMaxtime) || (mReverse[index] && mCurrentTime[index] < mTempMaxtime)) { //Reached end of animation if (mLoopCount == DISABLED) { mFinished = true; mInputIndex = mTempMaxIndex; mCurrentTime[index] = mTempMaxtime; return true; } else { //Looping is enabled mInputIndex = mTempMaxIndex; if (mLoopCount != LOOP_INFINITE) { if (mCurrentLoop >= mLoopCount -1) { //End of animation. mFinished = true; mCurrentTime[index] = mTempMaxtime; } } loopAnimation(index); } mTempLoop = true; } - while (mCurrentTime[index] > mInput[mInputIndex + 1]) + int inputlimit = mInput.length - 1; + while ((mInputIndex < inputlimit) && mCurrentTime[index] > mInput[mInputIndex + 1]) mInputIndex++; mOutputIndex = mInputIndex * mOutputStride + mOutputStartIndex; return mTempLoop; } /** * Restore target values. This is normally done at end of animation if reset flag is set. * If no target has been saved this method does nothing. */ public void restoreTarget() { if (mResetArray != null) { System.arraycopy(mResetArray, 0, mTarget, mTargetIndex, mTargets); } } /** * Saves the target values, may not work on all animations. */ public void saveTarget() { if (mResetArray == null || mResetArray.length < mTargets) { mResetArray = new float[mTargets]; } System.arraycopy(mTarget, mTargetIndex, mResetArray, 0, mTargets); } /** * This resets the animation, resets the internal current time value. * The animate() method can be called after this to produce the animation from start. */ public void resetAnimation() { mCurrentTime[0] = 0; mInputIndex = 0; mFinished = false; mCurrentLoop = 0; } public void reset() { for (int i = 0; i < mOutputStride; i++) { mCurrentTime[i] = 0; mReverse[i] = false; } mInputIndex = 0; mFinished = false; mOutputIndex = 0; mOutputStride = 0; mOutputStartIndex = 0; mTimeFactor = DEFAULT_TIMEFACTOR; } /** * Animate the target axis, current time will be updated with the timeDelta. * The timeDelta will be multiplied by the timeFactor. * @param timeDelta The time delta from last call to this method (or to resetAnimation()). * @return True if this animation reached the end of the animation, regardless of looping. * use isFinished() to determine if the animation has stopped. */ public abstract boolean animate(float timeDelta); /** * Returns true if this is a relative animation, * if relative then values are added/subtracted from previous values. * @index Index to axis to query * @return True if animation is relative, false for absolute values. */ public boolean isRelative(int index) { return mRelative[index]; } /** * Rotates the animation on the Z axis, note that not all animations support rotation. * Animations that do support z axis rotation will only rotate 3 values, animation is * setup for more than 3 values (eg RGBA) the result is undefined. * @param angle Rotation on Z axis * @throws IllegalArgumentException If animation does not support rotation along z axis. */ public void rotateZ(float angle) { mZAxisRotation = angle; } @Override public void setKey(int key) { mKey = key; } @Override public int getKey() { return mKey; } @Override public void setType(int type) { mType = type; } @Override public int getType() { return mType; } @Override public void releaseObject() { mTarget = null; mResetArray = null; mInput = null; mOutput = null; mZAxisRotation = 0; // mReverse = false; } @Override public void createObject(Object obj) { // TODO Auto-generated method stub } @Override public void destroyObject(Object obj) { // TODO Auto-generated method stub } }
true
true
boolean calcCurrentIndex(float timeDelta, int index) { mTempLoop = false; updateTime(timeDelta, 0); if ((!mReverse[index] && mCurrentTime[index] > mTempMaxtime) || (mReverse[index] && mCurrentTime[index] < mTempMaxtime)) { //Reached end of animation if (mLoopCount == DISABLED) { mFinished = true; mInputIndex = mTempMaxIndex; mCurrentTime[index] = mTempMaxtime; return true; } else { //Looping is enabled mInputIndex = mTempMaxIndex; if (mLoopCount != LOOP_INFINITE) { if (mCurrentLoop >= mLoopCount -1) { //End of animation. mFinished = true; mCurrentTime[index] = mTempMaxtime; } } loopAnimation(index); } mTempLoop = true; } while (mCurrentTime[index] > mInput[mInputIndex + 1]) mInputIndex++; mOutputIndex = mInputIndex * mOutputStride + mOutputStartIndex; return mTempLoop; }
boolean calcCurrentIndex(float timeDelta, int index) { mTempLoop = false; updateTime(timeDelta, 0); if ((!mReverse[index] && mCurrentTime[index] > mTempMaxtime) || (mReverse[index] && mCurrentTime[index] < mTempMaxtime)) { //Reached end of animation if (mLoopCount == DISABLED) { mFinished = true; mInputIndex = mTempMaxIndex; mCurrentTime[index] = mTempMaxtime; return true; } else { //Looping is enabled mInputIndex = mTempMaxIndex; if (mLoopCount != LOOP_INFINITE) { if (mCurrentLoop >= mLoopCount -1) { //End of animation. mFinished = true; mCurrentTime[index] = mTempMaxtime; } } loopAnimation(index); } mTempLoop = true; } int inputlimit = mInput.length - 1; while ((mInputIndex < inputlimit) && mCurrentTime[index] > mInput[mInputIndex + 1]) mInputIndex++; mOutputIndex = mInputIndex * mOutputStride + mOutputStartIndex; return mTempLoop; }
diff --git a/src/main/java/eu/wisebed/wisedb/controller/VirtualNodeDescriptionControllerImpl.java b/src/main/java/eu/wisebed/wisedb/controller/VirtualNodeDescriptionControllerImpl.java index 090dc05..6e20c6d 100644 --- a/src/main/java/eu/wisebed/wisedb/controller/VirtualNodeDescriptionControllerImpl.java +++ b/src/main/java/eu/wisebed/wisedb/controller/VirtualNodeDescriptionControllerImpl.java @@ -1,180 +1,187 @@ package eu.wisebed.wisedb.controller; import eu.wisebed.wisedb.exception.UnknownTestbedException; import eu.wisebed.wisedb.model.*; import org.apache.log4j.Logger; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.*; /** * CRUD operations for NodeCapabilities entities. */ @SuppressWarnings("unchecked") public class VirtualNodeDescriptionControllerImpl extends AbstractController<VirtualNodeDescription> implements VirtualNodeDescriptionController { /** * static instance(ourInstance) initialized as null. */ private static VirtualNodeDescriptionController ourInstance = null; private static final String USERNAME = "user"; /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(VirtualNodeDescriptionControllerImpl.class); private Random rand; /** * Public constructor . */ public VirtualNodeDescriptionControllerImpl() { // Does nothing super(); } /** * NodeCapabilityController is loaded on the first execution of * NodeCapabilityController.getInstance() or the first access to * NodeCapabilityController.ourInstance, not before. * * @return ourInstance */ public static VirtualNodeDescriptionController getInstance() { synchronized (VirtualNodeDescriptionControllerImpl.class) { if (ourInstance == null) { ourInstance = new VirtualNodeDescriptionControllerImpl(); } } return ourInstance; } @Override public void delete(int id) { LOGGER.info("delete(" + id + ")"); super.delete(new VirtualNodeDescription(), id); } public List<VirtualNodeDescription> list() { LOGGER.info("list()"); final Session session = getSessionFactory().getCurrentSession(); final Criteria criteria = session.createCriteria(VirtualNodeDescription.class); return criteria.list(); } @Override public String rebuild(int testbedId) { StringBuilder response = new StringBuilder("+---------------------------------------------------------------+\n"); List<VirtualNodeDescription> virtualNodes = list(); for (VirtualNodeDescription virtualNode : virtualNodes) { response.append("VirtualNode:" + virtualNode.getNode().getName()).append("\n"); Set<Node> nodesFound = null; try { JSONArray conditionsJSON = new JSONArray(virtualNode.getDescription()); response.append("Conditions:").append("\n"); for (int i = 0; i < conditionsJSON.length(); i++) { JSONObject curCondition = new JSONObject(conditionsJSON.get(i).toString()); HashSet<Node> curNodesFound = new HashSet<Node>(); try { response.append(curCondition.toString()).append("\n"); String capabilityName = curCondition.getString("capability"); Capability capability = CapabilityControllerImpl.getInstance().getByID(capabilityName); String capabilityValue = curCondition.getString("value"); final List<NodeCapability> nodeCapabilities = NodeCapabilityControllerImpl.getInstance().list(virtualNode.getNode().getSetup(), capability); if ("*".equals(capabilityValue)) { for (NodeCapability nodeCapability : nodeCapabilities) { curNodesFound.add(nodeCapability.getNode()); } } else { for (NodeCapability nodeCapability : nodeCapabilities) { try { - if (nodeCapability.getLastNodeReading().getStringReading().equals(capabilityValue)) { + if ( nodeCapability.getLastNodeReading().getStringReading().contains(",")) { + for (String aCapabilityValue : nodeCapability.getLastNodeReading().getStringReading().split(",")) { + if (aCapabilityValue.equals(capabilityValue)) { + curNodesFound.add(nodeCapability.getNode()); + break; + } + } + } else if (nodeCapability.getLastNodeReading().getStringReading().equals(capabilityValue)) { curNodesFound.add(nodeCapability.getNode()); } } catch (Exception e) { LOGGER.error(nodeCapability.toString(), e); } } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } if (nodesFound == null) { nodesFound = curNodesFound; } else { nodesFound.retainAll(curNodesFound); } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } response.append("Should Include : ").append("\n"); Capability virtual = CapabilityControllerImpl.getInstance().getByID("virtual"); for (Node node : nodesFound) { response.append(node.getName()); final Link link = LinkControllerImpl.getInstance().getByID(virtualNode.getNode().getName(), node.getName()); if (link != null) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability != null) { if (linkCapability.getLastLinkReading().getReading() != 1.0) { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } response.append("\n"); } List<Link> links = LinkControllerImpl.getInstance().getBySource(virtualNode.getNode()); response.append("Should Disconnect: ").append("\n"); for (Link link : links) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability.getLastLinkReading().getReading() != 0.0 && !nodesFound.contains(link.getTarget())) { addLinkReading(virtualNode.getNode().getName(), link.getTarget().getName(), 0.0); response.append(link.getTarget().getName()).append("\n"); } } response.append("+---------------------------------------------------------------+\n"); } return response.toString(); } void addLinkReading(String source, String dest, Double value) { try { LinkReadingControllerImpl.getInstance().insertReading(source, dest, "virtual", value, null, new Date()); } catch (UnknownTestbedException e) { LOGGER.error(e, e); } } public VirtualNodeDescription getByID(int entityId) { LOGGER.info("getByID(" + entityId + ")"); return super.getByID(new VirtualNodeDescription(), entityId); } @Override public VirtualNodeDescription getByUsername(String username) { LOGGER.info("list()"); final Session session = getSessionFactory().getCurrentSession(); final Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.eq(USERNAME, username)); return (VirtualNodeDescription) criteria.uniqueResult(); } }
true
true
public String rebuild(int testbedId) { StringBuilder response = new StringBuilder("+---------------------------------------------------------------+\n"); List<VirtualNodeDescription> virtualNodes = list(); for (VirtualNodeDescription virtualNode : virtualNodes) { response.append("VirtualNode:" + virtualNode.getNode().getName()).append("\n"); Set<Node> nodesFound = null; try { JSONArray conditionsJSON = new JSONArray(virtualNode.getDescription()); response.append("Conditions:").append("\n"); for (int i = 0; i < conditionsJSON.length(); i++) { JSONObject curCondition = new JSONObject(conditionsJSON.get(i).toString()); HashSet<Node> curNodesFound = new HashSet<Node>(); try { response.append(curCondition.toString()).append("\n"); String capabilityName = curCondition.getString("capability"); Capability capability = CapabilityControllerImpl.getInstance().getByID(capabilityName); String capabilityValue = curCondition.getString("value"); final List<NodeCapability> nodeCapabilities = NodeCapabilityControllerImpl.getInstance().list(virtualNode.getNode().getSetup(), capability); if ("*".equals(capabilityValue)) { for (NodeCapability nodeCapability : nodeCapabilities) { curNodesFound.add(nodeCapability.getNode()); } } else { for (NodeCapability nodeCapability : nodeCapabilities) { try { if (nodeCapability.getLastNodeReading().getStringReading().equals(capabilityValue)) { curNodesFound.add(nodeCapability.getNode()); } } catch (Exception e) { LOGGER.error(nodeCapability.toString(), e); } } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } if (nodesFound == null) { nodesFound = curNodesFound; } else { nodesFound.retainAll(curNodesFound); } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } response.append("Should Include : ").append("\n"); Capability virtual = CapabilityControllerImpl.getInstance().getByID("virtual"); for (Node node : nodesFound) { response.append(node.getName()); final Link link = LinkControllerImpl.getInstance().getByID(virtualNode.getNode().getName(), node.getName()); if (link != null) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability != null) { if (linkCapability.getLastLinkReading().getReading() != 1.0) { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } response.append("\n"); } List<Link> links = LinkControllerImpl.getInstance().getBySource(virtualNode.getNode()); response.append("Should Disconnect: ").append("\n"); for (Link link : links) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability.getLastLinkReading().getReading() != 0.0 && !nodesFound.contains(link.getTarget())) { addLinkReading(virtualNode.getNode().getName(), link.getTarget().getName(), 0.0); response.append(link.getTarget().getName()).append("\n"); } } response.append("+---------------------------------------------------------------+\n"); } return response.toString(); }
public String rebuild(int testbedId) { StringBuilder response = new StringBuilder("+---------------------------------------------------------------+\n"); List<VirtualNodeDescription> virtualNodes = list(); for (VirtualNodeDescription virtualNode : virtualNodes) { response.append("VirtualNode:" + virtualNode.getNode().getName()).append("\n"); Set<Node> nodesFound = null; try { JSONArray conditionsJSON = new JSONArray(virtualNode.getDescription()); response.append("Conditions:").append("\n"); for (int i = 0; i < conditionsJSON.length(); i++) { JSONObject curCondition = new JSONObject(conditionsJSON.get(i).toString()); HashSet<Node> curNodesFound = new HashSet<Node>(); try { response.append(curCondition.toString()).append("\n"); String capabilityName = curCondition.getString("capability"); Capability capability = CapabilityControllerImpl.getInstance().getByID(capabilityName); String capabilityValue = curCondition.getString("value"); final List<NodeCapability> nodeCapabilities = NodeCapabilityControllerImpl.getInstance().list(virtualNode.getNode().getSetup(), capability); if ("*".equals(capabilityValue)) { for (NodeCapability nodeCapability : nodeCapabilities) { curNodesFound.add(nodeCapability.getNode()); } } else { for (NodeCapability nodeCapability : nodeCapabilities) { try { if ( nodeCapability.getLastNodeReading().getStringReading().contains(",")) { for (String aCapabilityValue : nodeCapability.getLastNodeReading().getStringReading().split(",")) { if (aCapabilityValue.equals(capabilityValue)) { curNodesFound.add(nodeCapability.getNode()); break; } } } else if (nodeCapability.getLastNodeReading().getStringReading().equals(capabilityValue)) { curNodesFound.add(nodeCapability.getNode()); } } catch (Exception e) { LOGGER.error(nodeCapability.toString(), e); } } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } if (nodesFound == null) { nodesFound = curNodesFound; } else { nodesFound.retainAll(curNodesFound); } } } catch (JSONException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } response.append("Should Include : ").append("\n"); Capability virtual = CapabilityControllerImpl.getInstance().getByID("virtual"); for (Node node : nodesFound) { response.append(node.getName()); final Link link = LinkControllerImpl.getInstance().getByID(virtualNode.getNode().getName(), node.getName()); if (link != null) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability != null) { if (linkCapability.getLastLinkReading().getReading() != 1.0) { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } } else { addLinkReading(virtualNode.getNode().getName(), node.getName(), 1.0); response.append("<--"); } response.append("\n"); } List<Link> links = LinkControllerImpl.getInstance().getBySource(virtualNode.getNode()); response.append("Should Disconnect: ").append("\n"); for (Link link : links) { final LinkCapability linkCapability = LinkCapabilityControllerImpl.getInstance().getByID(link, virtual); if (linkCapability.getLastLinkReading().getReading() != 0.0 && !nodesFound.contains(link.getTarget())) { addLinkReading(virtualNode.getNode().getName(), link.getTarget().getName(), 0.0); response.append(link.getTarget().getName()).append("\n"); } } response.append("+---------------------------------------------------------------+\n"); } return response.toString(); }
diff --git a/Allocator/src/main/java/com/em/allocator/AllocatorOutput.java b/Allocator/src/main/java/com/em/allocator/AllocatorOutput.java index 5c3098a..c5a4b2d 100644 --- a/Allocator/src/main/java/com/em/allocator/AllocatorOutput.java +++ b/Allocator/src/main/java/com/em/allocator/AllocatorOutput.java @@ -1,456 +1,456 @@ package com.em.allocator; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Furnace; import org.bukkit.entity.Item; import org.bukkit.event.Event; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import com.em.allocator.item.ItemAllocatable; public class AllocatorOutput { /** * Just output items as dropped item * * @param inputItems * @param world * @param outputLocation * @param al * @param thePlugin */ public static void outputItemToDropped(List<ItemAllocatable> inputItems, World world, Location outputLocation, AllocatorBlock al, Allocator thePlugin) { // System.out.println("+++ " + inputItems); // for (Iterator iterator = inputItems.iterator(); iterator.hasNext();) { // ItemAllocatable itemAllocatable = (ItemAllocatable) iterator.next(); // System.out.println("+++ " + // itemAllocatable.getType()+" "+itemAllocatable.getAmount()); // } // the counter to limit dropped List<ItemStack> stackDropped = new ArrayList<ItemStack>(); boolean isOneItemAllocated = false; List<ItemStack> stacks = new ArrayList<ItemStack>(); for (ItemAllocatable itemAllocatable : inputItems) { // for each item in the Stack int itemAllocatableAmount = itemAllocatable.getAmount(); for (int i = 0; i < itemAllocatableAmount; i++) { // System.out.println("=== " + itemAllocatable); // try to stack or add boolean stacked = false; for (ItemStack is : stacks) { // if there is a not full stack add it if (is.getType().equals(itemAllocatable.getType()) && (is.getAmount() < is.getMaxStackSize())) { // limit to count (via config) boolean canBeDropped = limitDropCount(is, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; int newSize = is.getAmount() + 1; is.setAmount(newSize); if (newSize == is.getAmount()) { // Bukkit.getLogger().info(" Item dropped " + is); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not dropped " + is); } } stacked = true; break; } } // not existing stack... create a new if (!stacked) { ItemStack item = itemAllocatable.getTheItemStack().clone(); item.setAmount(1); // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; Item droppedItem = world.dropItem(outputLocation, item); if (droppedItem != null) { stacks.add(droppedItem.getItemStack()); // Bukkit.getLogger().info(" Item dropped " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not dropped " + item); } } } } } if (isOneItemAllocated) { // Smoke world.playEffect(outputLocation, Effect.SMOKE, 0); al.getLocation().getWorld().playEffect(al.getLocation(), Effect.CLICK1, 0); } } /** * Just add Item to inventory * * @param inputItems * @param outputContainer * @param thePlugin */ public static void outputItemToContainer(List<ItemAllocatable> inputItems, InventoryHolder outputContainer, InventoryHolder inputContainer, AllocatorBlock al, Allocator thePlugin) { // the counter to limit dropped List<ItemStack> stackDropped = new ArrayList<ItemStack>(); // List to get already refused material (to go faster) List<Material> materialAlreadyRefused = new ArrayList<Material>(); boolean isOneItemAllocated = false; for (ItemAllocatable itemAllocatable : inputItems) { // for each item in the Stack int itemAllocatableAmount = itemAllocatable.getAmount(); for (int j = 0; j < itemAllocatableAmount; j++) { // try to stack or add boolean stacked = false; ItemStack[] stacks = outputContainer.getInventory().getContents(); for (int i = 0; i < stacks.length; i++) { ItemStack is = stacks[i]; if (is == null) { continue; } // if there is a not full stack add it if (is.getType().equals(itemAllocatable.getType()) && (is.getAmount() < is.getMaxStackSize())) { // limit to count (via config) boolean canBeDropped = limitDropCount(is, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; int newSize = is.getAmount() + 1; is.setAmount(newSize); if (newSize == is.getAmount()) { // Bukkit.getLogger().info(" Item added " + is); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + is); } } stacked = true; break; } } // not existing stack... create a new if (!stacked) { // check if there is empty stack to prepare for other filter if (checkIfMaterialRefused(itemAllocatable, outputContainer, al, materialAlreadyRefused)) { continue; } // add the stack ItemStack item = itemAllocatable.getTheItemStack().clone(); item.setAmount(1); int firstEmpty = outputContainer.getInventory().firstEmpty(); if (firstEmpty >= 0) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setItem(firstEmpty, item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else { // Bukkit.getLogger().info(" Item not added " + item); } } } } if (isOneItemAllocated) { sendInventoryEvent(outputContainer, inputContainer, thePlugin); al.getLocation().getWorld().playEffect(al.getLocation(), Effect.CLICK1, 0); } } /** * Check if there is enough place foreach filtered item * * @param itemAllocatable * @param outputContainer * @param al * @param materialAlreadyRefused * @return */ private static boolean checkIfMaterialRefused(ItemAllocatable itemAllocatable, InventoryHolder outputContainer, AllocatorBlock al, List<Material> materialAlreadyRefused) { // check if there is empty stack to prepare for other filter // if already refused, refuse it if (materialAlreadyRefused.contains(itemAllocatable.getType())) { return true; } // System.out.println("----" + al.hasNoFilter()+" "+ // al.getFilters().size()); if (!al.hasNoFilter() && (al.getFilters().size() != 1)) { List<Material> filters = new ArrayList<Material>(); for (Material material : al.getFilters()) { filters.add(material); } int empty = 0; // System.out.println(filters); // Search for each stack in the directories (a filter or an empty // stack) for (int i = 0; (i < outputContainer.getInventory().getContents().length) && (empty <= filters.size()); i++) { // System.out.println(empty +" "+filters); ItemStack anItemStack = outputContainer.getInventory().getContents()[i]; if (anItemStack == null) { empty++; } else { if (filters.contains(anItemStack.getType())) { filters.remove(anItemStack.getType()); } } } // System.out.println("##"+empty +" "+filters); // If there is no enough empty stack, do not transfer if ((empty < filters.size()) || ((empty == filters.size()) && !filters.contains(itemAllocatable.getType()))) { materialAlreadyRefused.add(itemAllocatable.getType()); return true; } } return false; } /** * Just add Item to inventory * * @param inputItems * @param outputContainer */ public static void outputItemToFurnace(List<ItemAllocatable> inputItems, Furnace outputContainer, InventoryHolder inputContainer, AllocatorBlock al, Allocator thePlugin) { // the counter to limit dropped List<ItemStack> stackDropped = new ArrayList<ItemStack>(); boolean isOneItemAllocated = false; for (ItemAllocatable itemAllocatable : inputItems) { // for each item in the Stack int itemAllocatableAmount = itemAllocatable.getAmount(); for (int j = 0; j < itemAllocatableAmount; j++) { // try to stack or add boolean stacked = false; ItemStack[] stacks = outputContainer.getInventory().getContents(); for (int i = 0; i < stacks.length; i++) { ItemStack is = stacks[i]; if (is == null) { continue; } // if there is a not full stack add it if (is.getType().equals(itemAllocatable.getType()) && (is.getAmount() < is.getMaxStackSize())) { // limit to count (via config) boolean canBeDropped = limitDropCount(is, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; int newSize = is.getAmount() + 1; is.setAmount(newSize); if (newSize == is.getAmount()) { // Bukkit.getLogger().info(" Item added " + is); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + is); } } stacked = true; break; } } // not existing stack... create a new if (!stacked) { ItemStack item = itemAllocatable.getTheItemStack().clone(); item.setAmount(1); - // if it's fuel + // if it's fuel set it in the fuel if (isFuel(itemAllocatable.getTheItemStack()) && (outputContainer.getInventory().getFuel() == null)) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setFuel(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } - } else if (outputContainer.getInventory().getSmelting() == null) { + } else if (!isFuel(itemAllocatable.getTheItemStack()) && (outputContainer.getInventory().getSmelting() == null)) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setSmelting(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else { // Bukkit.getLogger().info(" Item not added " + item); } } } } if (isOneItemAllocated) { sendInventoryEvent(outputContainer, inputContainer, thePlugin); al.getLocation().getWorld().playEffect(al.getLocation(), Effect.CLICK1, 0); } } /** * Can this item be dropped (du to count limits in config) * * @param is * @param stackDropped * @param thePlugin * @return */ private static boolean limitDropCount(ItemStack is, List<ItemStack> stackDropped, Allocator thePlugin) { boolean dropped = false; // Count sent items if (!thePlugin.quantityIsStack) { // System.out.println("--- Items " + stackDropped.size()); // In case of item filter, just count down if (stackDropped.size() < thePlugin.quantityDropped) { stackDropped.add(is); dropped = true; } else { dropped = false; } // System.out.println("--- Items " + stackDropped.size() + "->" + // dropped); } else { // System.out.println("--- Stack " + stackDropped.size()); // In case of stack filter, try to add it in stackDropped count for (ItemStack droppedItemStack : stackDropped) { // try to add it into the dropped stack // System.out.println(droppedItemStack.getAmount()+" "+is.getMaxStackSize()); if (is.getType().equals(droppedItemStack.getType()) && (droppedItemStack.getAmount() < is.getMaxStackSize())) { droppedItemStack.setAmount(droppedItemStack.getAmount() + 1); dropped = true; } } // Not added try to create a new stack if (!dropped && (stackDropped.size() < thePlugin.quantityDropped)) { stackDropped.add(new ItemStack(is.getType(), 1)); dropped = true; } // System.out.println("--- Stack " + stackDropped.size() + "->" + // dropped); } return dropped; } private static void sendInventoryEvent(InventoryHolder outputContainer, InventoryHolder inputContainer, Allocator thePlugin) { final InventoryHolder inputContainerf = inputContainer; final InventoryHolder outputContainerf = outputContainer; thePlugin.getServer().getScheduler().scheduleSyncDelayedTask(thePlugin, new Runnable() { public void run() { if (inputContainerf != null) { sendChestTrapEventIfExist(inputContainerf.getInventory()); } if (outputContainerf != null) { sendChestTrapEventIfExist(outputContainerf.getInventory()); } } }, 1L); } /** * Method inspired from net.minecraft.server.TileEntityFurnace */ public static boolean isFuel(ItemStack itemstack) { return burning.contains(itemstack.getType()); } static List<Material> burning = new ArrayList<Material>(); static { burning.add(Material.WOOD); burning.add(Material.STICK); burning.add(Material.COAL); burning.add(Material.LAVA_BUCKET); burning.add(Material.SAPLING); burning.add(Material.BLAZE_ROD); } private static Constructor<Event> enventConstructor = null; private static Boolean eventSearched = false; private static void sendChestTrapEventIfExist(Inventory inventory) { synchronized (eventSearched) { if (!eventSearched) { try { @SuppressWarnings("unchecked") Class<Event> cls = (Class<Event>) Class.forName("com.em.chesttrap.MyInventoryModifiedEvent"); enventConstructor = cls.getConstructor(Inventory.class); } catch (ClassNotFoundException e) { } catch (ClassCastException e) { } catch (SecurityException e) { } catch (NoSuchMethodException e) { } eventSearched = true; } } if (enventConstructor != null) { try { Event event = enventConstructor.newInstance(inventory); Bukkit.getServer().getPluginManager().callEvent(event); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
false
true
public static void outputItemToFurnace(List<ItemAllocatable> inputItems, Furnace outputContainer, InventoryHolder inputContainer, AllocatorBlock al, Allocator thePlugin) { // the counter to limit dropped List<ItemStack> stackDropped = new ArrayList<ItemStack>(); boolean isOneItemAllocated = false; for (ItemAllocatable itemAllocatable : inputItems) { // for each item in the Stack int itemAllocatableAmount = itemAllocatable.getAmount(); for (int j = 0; j < itemAllocatableAmount; j++) { // try to stack or add boolean stacked = false; ItemStack[] stacks = outputContainer.getInventory().getContents(); for (int i = 0; i < stacks.length; i++) { ItemStack is = stacks[i]; if (is == null) { continue; } // if there is a not full stack add it if (is.getType().equals(itemAllocatable.getType()) && (is.getAmount() < is.getMaxStackSize())) { // limit to count (via config) boolean canBeDropped = limitDropCount(is, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; int newSize = is.getAmount() + 1; is.setAmount(newSize); if (newSize == is.getAmount()) { // Bukkit.getLogger().info(" Item added " + is); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + is); } } stacked = true; break; } } // not existing stack... create a new if (!stacked) { ItemStack item = itemAllocatable.getTheItemStack().clone(); item.setAmount(1); // if it's fuel if (isFuel(itemAllocatable.getTheItemStack()) && (outputContainer.getInventory().getFuel() == null)) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setFuel(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else if (outputContainer.getInventory().getSmelting() == null) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setSmelting(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else { // Bukkit.getLogger().info(" Item not added " + item); } } } } if (isOneItemAllocated) { sendInventoryEvent(outputContainer, inputContainer, thePlugin); al.getLocation().getWorld().playEffect(al.getLocation(), Effect.CLICK1, 0); } }
public static void outputItemToFurnace(List<ItemAllocatable> inputItems, Furnace outputContainer, InventoryHolder inputContainer, AllocatorBlock al, Allocator thePlugin) { // the counter to limit dropped List<ItemStack> stackDropped = new ArrayList<ItemStack>(); boolean isOneItemAllocated = false; for (ItemAllocatable itemAllocatable : inputItems) { // for each item in the Stack int itemAllocatableAmount = itemAllocatable.getAmount(); for (int j = 0; j < itemAllocatableAmount; j++) { // try to stack or add boolean stacked = false; ItemStack[] stacks = outputContainer.getInventory().getContents(); for (int i = 0; i < stacks.length; i++) { ItemStack is = stacks[i]; if (is == null) { continue; } // if there is a not full stack add it if (is.getType().equals(itemAllocatable.getType()) && (is.getAmount() < is.getMaxStackSize())) { // limit to count (via config) boolean canBeDropped = limitDropCount(is, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; int newSize = is.getAmount() + 1; is.setAmount(newSize); if (newSize == is.getAmount()) { // Bukkit.getLogger().info(" Item added " + is); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + is); } } stacked = true; break; } } // not existing stack... create a new if (!stacked) { ItemStack item = itemAllocatable.getTheItemStack().clone(); item.setAmount(1); // if it's fuel set it in the fuel if (isFuel(itemAllocatable.getTheItemStack()) && (outputContainer.getInventory().getFuel() == null)) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setFuel(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else if (!isFuel(itemAllocatable.getTheItemStack()) && (outputContainer.getInventory().getSmelting() == null)) { // limit to count (via config) boolean canBeDropped = limitDropCount(item, stackDropped, thePlugin); if (canBeDropped) { // really added it to the target (and remove it from the input) isOneItemAllocated = true; outputContainer.getInventory().setSmelting(item); if (outputContainer.getInventory().contains(item)) { // Bukkit.getLogger().info(" Item added " + item); itemAllocatable.remove(); } else { // Bukkit.getLogger().info(" Item not added " + item); } } } else { // Bukkit.getLogger().info(" Item not added " + item); } } } } if (isOneItemAllocated) { sendInventoryEvent(outputContainer, inputContainer, thePlugin); al.getLocation().getWorld().playEffect(al.getLocation(), Effect.CLICK1, 0); } }
diff --git a/lttng/org.eclipse.linuxtools.lttng.ui/src/org/eclipse/linuxtools/lttng/ui/tracecontrol/wizards/TraceConfigurationPage.java b/lttng/org.eclipse.linuxtools.lttng.ui/src/org/eclipse/linuxtools/lttng/ui/tracecontrol/wizards/TraceConfigurationPage.java index d0432a504..e89e94350 100644 --- a/lttng/org.eclipse.linuxtools.lttng.ui/src/org/eclipse/linuxtools/lttng/ui/tracecontrol/wizards/TraceConfigurationPage.java +++ b/lttng/org.eclipse.linuxtools.lttng.ui/src/org/eclipse/linuxtools/lttng/ui/tracecontrol/wizards/TraceConfigurationPage.java @@ -1,592 +1,595 @@ /******************************************************************************* * Copyright (c) 2011 Ericsson * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bernd Hufmann - Initial API and implementation * *******************************************************************************/ package org.eclipse.linuxtools.lttng.ui.tracecontrol.wizards; import java.io.File; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.linuxtools.lttng.tracecontrol.model.TraceResource; import org.eclipse.linuxtools.lttng.tracecontrol.model.TraceResource.TraceState; import org.eclipse.linuxtools.lttng.tracecontrol.model.config.TraceConfig; import org.eclipse.linuxtools.lttng.ui.tracecontrol.TraceControlConstants; import org.eclipse.linuxtools.lttng.ui.tracecontrol.Messages; import org.eclipse.linuxtools.lttng.ui.tracecontrol.subsystems.TraceSubSystem; import org.eclipse.rse.services.clientserver.messages.SystemMessageException; import org.eclipse.rse.ui.SystemBasePlugin; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; /** * <b><u>UstTraceChannelConfigurationPage</u></b> * <p> * Wizard page implementation to configure a trace (Kernel and UST). * </p> */ public class TraceConfigurationPage extends WizardPage { // ------------------------------------------------------------------------ // Attributes // ------------------------------------------------------------------------ private ConfigureTraceWizard fWizard; private String fTraceName; private String fTraceTransport; private String fTracePath; private int fMode; private int fNumChannel; private Boolean fIsAppend; private Boolean fIsLocal = false; private Text fNameText; private Text fTransportText; private Text fPathText; private Text fNumChannelText; private Button fLocalButton; private Button fRemoteButton; private Button fIsAppendButton; private Button fNoneButton; private Button fFlightRecorderButton; private Button fNormalButton; private Display fDisplay; private String fTraceNameError; private String fTracePathError; private Button fBrowseButton; private TraceResource fTraceResource; private TraceConfig fOldTraceConfig; private TraceSubSystem fSubSystem; // ------------------------------------------------------------------------ // Constructors // ------------------------------------------------------------------------ /** * Constructore * * @param wizard */ public TraceConfigurationPage(ConfigureTraceWizard wizard) { super("TraceConfigurationPage"); //$NON-NLS-1$ setTitle(Messages.ConfigureTraceDialog_Title); // setDescription("set description..."); this.fWizard = wizard; setPageComplete(false); fTraceNameError = ""; //$NON-NLS-1$ fTracePathError = ""; //$NON-NLS-1$ fTraceResource = this.fWizard.getSelectedTrace(); fOldTraceConfig = fTraceResource.getTraceConfig(); fSubSystem = (TraceSubSystem)this.fWizard.getSelectedTrace().getSubSystem(); } // ------------------------------------------------------------------------ // Operations // ------------------------------------------------------------------------ /* * (non-Javadoc) * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ @Override public void createControl(Composite parent) { GridData griddata = new GridData(); griddata = new GridData(); Composite composite1 = new Composite(parent, SWT.NONE); GridLayout compositeLayout1 = new GridLayout(4, false); composite1.setSize(520, 300); composite1.setLayout(compositeLayout1); griddata.horizontalSpan = 3; griddata.widthHint = 520; griddata.minimumWidth = 520; composite1.setLayoutData(griddata); fDisplay = this.getShell().getDisplay(); setControl(composite1); Label nameLabel = new Label(composite1, SWT.NULL); nameLabel.setText(Messages.NewTraceDialog_TraceName + ":"); //$NON-NLS-1$ griddata = new GridData(); griddata.verticalIndent = 20; nameLabel.setLayoutData(griddata); fNameText = new Text(composite1, SWT.SINGLE | SWT.BORDER); if (fTraceResource.isUst()) { fNameText.setText(TraceControlConstants.Lttng_Ust_TraceName); fNameText.setEnabled(false); } griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 20; griddata.horizontalSpan = 3; fNameText.setLayoutData(griddata); fNameText.setSize(500, 50); fNameText.setText(fTraceResource.getName()); fNameText.setEnabled(false); Label transportLabel = new Label(composite1, SWT.NULL); transportLabel.setText(Messages.ConfigureTraceDialog_Trace_Transport + ":"); //$NON-NLS-1$ griddata = new GridData(); transportLabel.setLayoutData(griddata); fTransportText = new Text(composite1, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.horizontalSpan = 3; fTransportText.setLayoutData(griddata); fTransportText.setSize(500, 50); fTransportText.setText(TraceControlConstants.Lttng_Trace_Transport_Relay); fTransportText.setEnabled(false); // relay is the only allowed value if (fOldTraceConfig != null) { fTransportText.setText(fOldTraceConfig.getTraceTransport()); } griddata = new GridData(); Group composite21 = new Group(composite1, SWT.SHADOW_OUT); composite21.setSize(300, 300); composite21.setText(Messages.ConfigureTraceDialog_Trace_Location); griddata.horizontalAlignment = SWT.FILL; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; griddata.widthHint = 300; griddata.minimumWidth = 300; composite21.setLayoutData(griddata); GridLayout compositeLayout21 = new GridLayout(4, false); composite21.setLayout(compositeLayout21); fRemoteButton = new Button(composite21, SWT.RADIO); fRemoteButton.setText(Messages.ConfigureTraceDialog_Remote); fRemoteButton.setSelection(true); fLocalButton = new Button(composite21, SWT.RADIO); fLocalButton.setText(Messages.ConfigureTraceDialog_Local); griddata = new GridData(); griddata.horizontalSpan = 3; fLocalButton.setLayoutData(griddata); fIsLocal = false; fLocalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fLocalButton.getSelection()) { fIsLocal = true; fBrowseButton.setEnabled(true); } else { fIsLocal = false; fBrowseButton.setEnabled(false); } validatePathName(fPathText.getText()); validate(); } }); Label pathLabel = new Label(composite21, SWT.NULL); pathLabel.setText(Messages.ConfigureTraceDialog_Trace_Path); griddata = new GridData(); griddata.verticalIndent = 10; pathLabel.setLayoutData(griddata); fPathText = new Text(composite21, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 10; fPathText.setLayoutData(griddata); fPathText.setData(""); //$NON-NLS-1$ fBrowseButton = new Button(composite21, SWT.PUSH); fBrowseButton.setText(Messages.ConfigureTraceDialog_Browse + "..."); //$NON-NLS-1$ griddata = new GridData(); griddata.grabExcessHorizontalSpace = false; griddata.widthHint = 100; griddata.verticalIndent = 10; fBrowseButton.setLayoutData(griddata); fBrowseButton.setEnabled(false); fBrowseButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { DirectoryDialog dialog = new DirectoryDialog(fDisplay.getActiveShell()); String newPath = dialog.open(); if (newPath != null) { fPathText.setText(newPath); } } }); fNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateTraceName(fNameText.getText()); validate(); } }); fTransportText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fPathText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { if (!fPathText.isEnabled()) { return; } validatePathName(fPathText.getText()); validate(); } }); griddata = new GridData(); Composite composite2 = new Composite(composite1, SWT.NONE); GridLayout compositeLayout2 = new GridLayout(2, false); composite2.setLayout(compositeLayout2); griddata.horizontalSpan = 4; griddata.widthHint = 500; griddata.minimumWidth = 500; composite2.setLayoutData(griddata); Label numChannelLabel = new Label(composite2, SWT.NULL); numChannelLabel.setText(Messages.ConfigureTraceDialog_Num_Channels + ":"); //$NON-NLS-1$); griddata = new GridData(); griddata.verticalIndent = 10; numChannelLabel.setLayoutData(griddata); fNumChannelText = new Text(composite2, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.verticalIndent = 10; griddata.widthHint = 50; griddata.minimumWidth = 50; fNumChannelText.setLayoutData(griddata); if (fTraceResource.isUst()) { fNumChannelText.setText("1"); //$NON-NLS-1$ fNumChannelText.setEnabled(false); } else { fNumChannelText.setText("2"); //$NON-NLS-1$ } fNumChannelText.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { e.doit = e.text.matches("[0-9]*"); //$NON-NLS-1$ } }); fNumChannelText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fIsAppendButton = new Button(composite1, SWT.CHECK); fIsAppendButton.setText(Messages.ConfigureTraceDialog_Append); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; fIsAppendButton.setLayoutData(griddata); fIsAppend = Boolean.valueOf(false); fIsAppendButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fIsAppendButton.getSelection()) { fIsAppend = true; } else { fIsAppend = false; } } }); if (fTraceResource.isUst()) { fIsAppendButton.setEnabled(false); } griddata = new GridData(); Group composite22 = new Group(composite1, SWT.SHADOW_OUT); composite22.setText(Messages.ConfigureTraceDialog_Trace_Mode); griddata.horizontalSpan = 4; griddata.verticalIndent = 10; composite22.setLayoutData(griddata); GridLayout compositeLayout22 = new GridLayout(3, false); composite22.setLayout(compositeLayout22); fNoneButton = new Button(composite22, SWT.RADIO); fNoneButton.setText(Messages.ConfigureTraceDialog_Mode_None); fNoneButton.setSelection(true); fFlightRecorderButton = new Button(composite22, SWT.RADIO); fFlightRecorderButton.setText(Messages.ConfigureTraceDialog_Mode_Flight_Recorder); fNormalButton = new Button(composite22, SWT.RADIO); fNormalButton.setText(Messages.ConfigureTraceDialog_Mode_Normal); fMode = 0; fNoneButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNoneButton.getSelection()) { fMode = TraceConfig.NONE_MODE; } } }); fFlightRecorderButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fFlightRecorderButton.getSelection()) { fMode = TraceConfig.FLIGHT_RECORDER_MODE; } } }); fNormalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNormalButton.getSelection()) { fMode = TraceConfig.NORMAL_MODE; } } }); if (fTraceResource.isUst()) { fNoneButton.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); } if(fOldTraceConfig != null) { fPathText.setText(fOldTraceConfig.getTracePath()); fIsLocal = fOldTraceConfig.isNetworkTrace(); + fLocalButton.setSelection(fIsLocal); + fRemoteButton.setSelection(!fIsLocal); fBrowseButton.setEnabled(true); fIsAppend = fOldTraceConfig.getIsAppend(); + fIsAppendButton.setSelection(fIsAppend); fNumChannelText.setText(String.valueOf(fOldTraceConfig.getNumChannel())); fFlightRecorderButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.FLIGHT_RECORDER_MODE); fNormalButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NORMAL_MODE); fNoneButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NONE_MODE); } // Depending on the state disable fields, it's only informational then if ((fTraceResource.getTraceState() == TraceState.STARTED) || (fTraceResource.getTraceState() == TraceState.PAUSED)) { fPathText.setEnabled(false); fBrowseButton.setEnabled(false); fRemoteButton.setEnabled(false); fLocalButton.setEnabled(false); fIsAppendButton.setEnabled(false); fNumChannelText.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); fNoneButton.setEnabled(false); } validate(); fDisplay.getActiveShell().addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_ESCAPE) { event.doit = false; } } }); } /* * (non-Javadoc) * @see org.eclipse.jface.dialogs.DialogPage#dispose() */ @Override public void dispose() { super.dispose(); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean) */ @Override public void setVisible(boolean visible) { if (visible) { validate(); } super.setVisible(visible); } /* * Validates the trace name which has to be unique. */ protected boolean validateTraceName(String name) { if (name.length() > 0) { TraceResource[] traces = new TraceResource[0]; try { traces = fSubSystem.getAllTraces(); } catch (SystemMessageException e) { SystemBasePlugin.logError("TraceConfigurationPage ", e); //$NON-NLS-1$ } for (int i = 0; i < traces.length; i++) { if (traces[i].getName().compareTo(name) == 0) { fTraceNameError = Messages.NewTraceDialog_Error_Already_Exists; setErrorMessage(fTraceNameError); return false; } } final char[] chars = name.toCharArray(); for (int x = 0; x < chars.length; x++) { final char c = chars[x]; if ((x == 0) && !(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')))) { fTraceNameError = Messages.NewTraceDialog_Error_Invalid_First_Char; setErrorMessage(fTraceNameError); return false; } else if (x != 0) { if (!((c >= 'a') && (c <= 'z')) && !((c >= 'A') && (c <= 'Z')) && !((c >= '0') && (c <= '9'))) { fTraceNameError = Messages.NewTraceDialog_Error_Invalid_Name; setErrorMessage(fTraceNameError); return false; } } } } if (fTracePathError.length() > 0) { setErrorMessage(fTracePathError); } else { setErrorMessage(null); } fTraceNameError = ""; //$NON-NLS-1$ return true; } /* * Validates the trace path. */ private boolean validatePathName(String path) { if (path.length() > 0) { final char c0 = path.charAt(0); if (c0 != '/') { fTracePathError = Messages.ConfigureTraceDialog_Error_Invalid_Path; setErrorMessage(fTracePathError); return false; } else { String[] folders = path.split("/"); //$NON-NLS-1$ for (int i = 0; i < folders.length; i++) { final char[] chars = folders[i].toCharArray(); for (int x = 0; x < chars.length; x++) { final char c = chars[x]; if ((c >= 'a') && (c <= 'z')) { continue; // lowercase } if ((c >= 'A') && (c <= 'Z')) { continue; // uppercase } if ((c >= '0') && (c <= '9')) { continue; // numeric } fTracePathError = Messages.ConfigureTraceDialog_Error_Invalid_Folder; setErrorMessage(fTracePathError); return false; } } if (path.length() > 1) { for (int i = 0; i < path.length() - 1; i++) { if ((path.charAt(i) == '/') && (path.charAt(i + 1) == '/')) { fTracePathError = Messages.ConfigureTraceDialog_Error_Multiple_Seps; setErrorMessage(fTracePathError); return false; } } } } if (fIsLocal) { File file = new File(path); if (file.isFile()) { fTracePathError = Messages.ConfigureTraceDialog_Error_File_Exists; setErrorMessage(fTracePathError); return false; } if (path.length() > 1 && !file.getParentFile().canWrite()) { fTracePathError = Messages.ConfigureTraceDialog_Error_Can_Not_Write; setErrorMessage(fTracePathError); return false; } } } if (fTraceNameError.length() > 0) { setErrorMessage(fTraceNameError); } else { setErrorMessage(null); } fTracePathError = ""; //$NON-NLS-1$ return true; } /* * Validates all input values. */ private void validate() { if ((fNameText.getText() == null) || (fTransportText.getText() == null) || (fTransportText.getText().length() == 0) || (fNameText.getText().length() == 0) || (fNumChannelText.getText().length() == 0) || (fNumChannelText.getText().length() == 0)) { setPageComplete(false); return; } if (fPathText.getText().length() == 0) { setPageComplete(false); return; } if ((fTracePathError.length() > 0) || (fTraceNameError.length() > 0)) { setPageComplete(false); return; } fTraceName = fNameText.getText(); fTraceTransport = fTransportText.getText(); fTracePath = fPathText.getText(); fNumChannel = Integer.parseInt(fNumChannelText.getText()); if (fTraceNameError.length() == 0) { setErrorMessage(null); setPageComplete(true); } else { setErrorMessage(fTraceNameError); setPageComplete(false); } } /** * Gets the trace configuration. * * @return trace configuration */ public TraceConfig getTraceConfig() { TraceConfig newTraceConfig = new TraceConfig(); newTraceConfig.setTraceName(fTraceName); newTraceConfig.setTraceTransport(fTraceTransport); newTraceConfig.setTracePath(fTracePath); newTraceConfig.setNetworkTrace(fIsLocal); newTraceConfig.setIsAppend(fIsAppend); newTraceConfig.setMode(fMode); newTraceConfig.setNumChannel(fNumChannel); return newTraceConfig; } /** * Gets if trace is a local trace (i.e. if trace output is stored on host * where client is running) * * @return isLocalTrace */ public boolean isLocalTrace() { return fIsLocal; } }
false
true
public void createControl(Composite parent) { GridData griddata = new GridData(); griddata = new GridData(); Composite composite1 = new Composite(parent, SWT.NONE); GridLayout compositeLayout1 = new GridLayout(4, false); composite1.setSize(520, 300); composite1.setLayout(compositeLayout1); griddata.horizontalSpan = 3; griddata.widthHint = 520; griddata.minimumWidth = 520; composite1.setLayoutData(griddata); fDisplay = this.getShell().getDisplay(); setControl(composite1); Label nameLabel = new Label(composite1, SWT.NULL); nameLabel.setText(Messages.NewTraceDialog_TraceName + ":"); //$NON-NLS-1$ griddata = new GridData(); griddata.verticalIndent = 20; nameLabel.setLayoutData(griddata); fNameText = new Text(composite1, SWT.SINGLE | SWT.BORDER); if (fTraceResource.isUst()) { fNameText.setText(TraceControlConstants.Lttng_Ust_TraceName); fNameText.setEnabled(false); } griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 20; griddata.horizontalSpan = 3; fNameText.setLayoutData(griddata); fNameText.setSize(500, 50); fNameText.setText(fTraceResource.getName()); fNameText.setEnabled(false); Label transportLabel = new Label(composite1, SWT.NULL); transportLabel.setText(Messages.ConfigureTraceDialog_Trace_Transport + ":"); //$NON-NLS-1$ griddata = new GridData(); transportLabel.setLayoutData(griddata); fTransportText = new Text(composite1, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.horizontalSpan = 3; fTransportText.setLayoutData(griddata); fTransportText.setSize(500, 50); fTransportText.setText(TraceControlConstants.Lttng_Trace_Transport_Relay); fTransportText.setEnabled(false); // relay is the only allowed value if (fOldTraceConfig != null) { fTransportText.setText(fOldTraceConfig.getTraceTransport()); } griddata = new GridData(); Group composite21 = new Group(composite1, SWT.SHADOW_OUT); composite21.setSize(300, 300); composite21.setText(Messages.ConfigureTraceDialog_Trace_Location); griddata.horizontalAlignment = SWT.FILL; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; griddata.widthHint = 300; griddata.minimumWidth = 300; composite21.setLayoutData(griddata); GridLayout compositeLayout21 = new GridLayout(4, false); composite21.setLayout(compositeLayout21); fRemoteButton = new Button(composite21, SWT.RADIO); fRemoteButton.setText(Messages.ConfigureTraceDialog_Remote); fRemoteButton.setSelection(true); fLocalButton = new Button(composite21, SWT.RADIO); fLocalButton.setText(Messages.ConfigureTraceDialog_Local); griddata = new GridData(); griddata.horizontalSpan = 3; fLocalButton.setLayoutData(griddata); fIsLocal = false; fLocalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fLocalButton.getSelection()) { fIsLocal = true; fBrowseButton.setEnabled(true); } else { fIsLocal = false; fBrowseButton.setEnabled(false); } validatePathName(fPathText.getText()); validate(); } }); Label pathLabel = new Label(composite21, SWT.NULL); pathLabel.setText(Messages.ConfigureTraceDialog_Trace_Path); griddata = new GridData(); griddata.verticalIndent = 10; pathLabel.setLayoutData(griddata); fPathText = new Text(composite21, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 10; fPathText.setLayoutData(griddata); fPathText.setData(""); //$NON-NLS-1$ fBrowseButton = new Button(composite21, SWT.PUSH); fBrowseButton.setText(Messages.ConfigureTraceDialog_Browse + "..."); //$NON-NLS-1$ griddata = new GridData(); griddata.grabExcessHorizontalSpace = false; griddata.widthHint = 100; griddata.verticalIndent = 10; fBrowseButton.setLayoutData(griddata); fBrowseButton.setEnabled(false); fBrowseButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { DirectoryDialog dialog = new DirectoryDialog(fDisplay.getActiveShell()); String newPath = dialog.open(); if (newPath != null) { fPathText.setText(newPath); } } }); fNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateTraceName(fNameText.getText()); validate(); } }); fTransportText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fPathText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { if (!fPathText.isEnabled()) { return; } validatePathName(fPathText.getText()); validate(); } }); griddata = new GridData(); Composite composite2 = new Composite(composite1, SWT.NONE); GridLayout compositeLayout2 = new GridLayout(2, false); composite2.setLayout(compositeLayout2); griddata.horizontalSpan = 4; griddata.widthHint = 500; griddata.minimumWidth = 500; composite2.setLayoutData(griddata); Label numChannelLabel = new Label(composite2, SWT.NULL); numChannelLabel.setText(Messages.ConfigureTraceDialog_Num_Channels + ":"); //$NON-NLS-1$); griddata = new GridData(); griddata.verticalIndent = 10; numChannelLabel.setLayoutData(griddata); fNumChannelText = new Text(composite2, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.verticalIndent = 10; griddata.widthHint = 50; griddata.minimumWidth = 50; fNumChannelText.setLayoutData(griddata); if (fTraceResource.isUst()) { fNumChannelText.setText("1"); //$NON-NLS-1$ fNumChannelText.setEnabled(false); } else { fNumChannelText.setText("2"); //$NON-NLS-1$ } fNumChannelText.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { e.doit = e.text.matches("[0-9]*"); //$NON-NLS-1$ } }); fNumChannelText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fIsAppendButton = new Button(composite1, SWT.CHECK); fIsAppendButton.setText(Messages.ConfigureTraceDialog_Append); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; fIsAppendButton.setLayoutData(griddata); fIsAppend = Boolean.valueOf(false); fIsAppendButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fIsAppendButton.getSelection()) { fIsAppend = true; } else { fIsAppend = false; } } }); if (fTraceResource.isUst()) { fIsAppendButton.setEnabled(false); } griddata = new GridData(); Group composite22 = new Group(composite1, SWT.SHADOW_OUT); composite22.setText(Messages.ConfigureTraceDialog_Trace_Mode); griddata.horizontalSpan = 4; griddata.verticalIndent = 10; composite22.setLayoutData(griddata); GridLayout compositeLayout22 = new GridLayout(3, false); composite22.setLayout(compositeLayout22); fNoneButton = new Button(composite22, SWT.RADIO); fNoneButton.setText(Messages.ConfigureTraceDialog_Mode_None); fNoneButton.setSelection(true); fFlightRecorderButton = new Button(composite22, SWT.RADIO); fFlightRecorderButton.setText(Messages.ConfigureTraceDialog_Mode_Flight_Recorder); fNormalButton = new Button(composite22, SWT.RADIO); fNormalButton.setText(Messages.ConfigureTraceDialog_Mode_Normal); fMode = 0; fNoneButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNoneButton.getSelection()) { fMode = TraceConfig.NONE_MODE; } } }); fFlightRecorderButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fFlightRecorderButton.getSelection()) { fMode = TraceConfig.FLIGHT_RECORDER_MODE; } } }); fNormalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNormalButton.getSelection()) { fMode = TraceConfig.NORMAL_MODE; } } }); if (fTraceResource.isUst()) { fNoneButton.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); } if(fOldTraceConfig != null) { fPathText.setText(fOldTraceConfig.getTracePath()); fIsLocal = fOldTraceConfig.isNetworkTrace(); fBrowseButton.setEnabled(true); fIsAppend = fOldTraceConfig.getIsAppend(); fNumChannelText.setText(String.valueOf(fOldTraceConfig.getNumChannel())); fFlightRecorderButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.FLIGHT_RECORDER_MODE); fNormalButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NORMAL_MODE); fNoneButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NONE_MODE); } // Depending on the state disable fields, it's only informational then if ((fTraceResource.getTraceState() == TraceState.STARTED) || (fTraceResource.getTraceState() == TraceState.PAUSED)) { fPathText.setEnabled(false); fBrowseButton.setEnabled(false); fRemoteButton.setEnabled(false); fLocalButton.setEnabled(false); fIsAppendButton.setEnabled(false); fNumChannelText.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); fNoneButton.setEnabled(false); } validate(); fDisplay.getActiveShell().addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_ESCAPE) { event.doit = false; } } }); }
public void createControl(Composite parent) { GridData griddata = new GridData(); griddata = new GridData(); Composite composite1 = new Composite(parent, SWT.NONE); GridLayout compositeLayout1 = new GridLayout(4, false); composite1.setSize(520, 300); composite1.setLayout(compositeLayout1); griddata.horizontalSpan = 3; griddata.widthHint = 520; griddata.minimumWidth = 520; composite1.setLayoutData(griddata); fDisplay = this.getShell().getDisplay(); setControl(composite1); Label nameLabel = new Label(composite1, SWT.NULL); nameLabel.setText(Messages.NewTraceDialog_TraceName + ":"); //$NON-NLS-1$ griddata = new GridData(); griddata.verticalIndent = 20; nameLabel.setLayoutData(griddata); fNameText = new Text(composite1, SWT.SINGLE | SWT.BORDER); if (fTraceResource.isUst()) { fNameText.setText(TraceControlConstants.Lttng_Ust_TraceName); fNameText.setEnabled(false); } griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 20; griddata.horizontalSpan = 3; fNameText.setLayoutData(griddata); fNameText.setSize(500, 50); fNameText.setText(fTraceResource.getName()); fNameText.setEnabled(false); Label transportLabel = new Label(composite1, SWT.NULL); transportLabel.setText(Messages.ConfigureTraceDialog_Trace_Transport + ":"); //$NON-NLS-1$ griddata = new GridData(); transportLabel.setLayoutData(griddata); fTransportText = new Text(composite1, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.horizontalSpan = 3; fTransportText.setLayoutData(griddata); fTransportText.setSize(500, 50); fTransportText.setText(TraceControlConstants.Lttng_Trace_Transport_Relay); fTransportText.setEnabled(false); // relay is the only allowed value if (fOldTraceConfig != null) { fTransportText.setText(fOldTraceConfig.getTraceTransport()); } griddata = new GridData(); Group composite21 = new Group(composite1, SWT.SHADOW_OUT); composite21.setSize(300, 300); composite21.setText(Messages.ConfigureTraceDialog_Trace_Location); griddata.horizontalAlignment = SWT.FILL; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; griddata.widthHint = 300; griddata.minimumWidth = 300; composite21.setLayoutData(griddata); GridLayout compositeLayout21 = new GridLayout(4, false); composite21.setLayout(compositeLayout21); fRemoteButton = new Button(composite21, SWT.RADIO); fRemoteButton.setText(Messages.ConfigureTraceDialog_Remote); fRemoteButton.setSelection(true); fLocalButton = new Button(composite21, SWT.RADIO); fLocalButton.setText(Messages.ConfigureTraceDialog_Local); griddata = new GridData(); griddata.horizontalSpan = 3; fLocalButton.setLayoutData(griddata); fIsLocal = false; fLocalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fLocalButton.getSelection()) { fIsLocal = true; fBrowseButton.setEnabled(true); } else { fIsLocal = false; fBrowseButton.setEnabled(false); } validatePathName(fPathText.getText()); validate(); } }); Label pathLabel = new Label(composite21, SWT.NULL); pathLabel.setText(Messages.ConfigureTraceDialog_Trace_Path); griddata = new GridData(); griddata.verticalIndent = 10; pathLabel.setLayoutData(griddata); fPathText = new Text(composite21, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.FILL; griddata.grabExcessHorizontalSpace = true; griddata.verticalIndent = 10; fPathText.setLayoutData(griddata); fPathText.setData(""); //$NON-NLS-1$ fBrowseButton = new Button(composite21, SWT.PUSH); fBrowseButton.setText(Messages.ConfigureTraceDialog_Browse + "..."); //$NON-NLS-1$ griddata = new GridData(); griddata.grabExcessHorizontalSpace = false; griddata.widthHint = 100; griddata.verticalIndent = 10; fBrowseButton.setLayoutData(griddata); fBrowseButton.setEnabled(false); fBrowseButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { DirectoryDialog dialog = new DirectoryDialog(fDisplay.getActiveShell()); String newPath = dialog.open(); if (newPath != null) { fPathText.setText(newPath); } } }); fNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateTraceName(fNameText.getText()); validate(); } }); fTransportText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fPathText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { if (!fPathText.isEnabled()) { return; } validatePathName(fPathText.getText()); validate(); } }); griddata = new GridData(); Composite composite2 = new Composite(composite1, SWT.NONE); GridLayout compositeLayout2 = new GridLayout(2, false); composite2.setLayout(compositeLayout2); griddata.horizontalSpan = 4; griddata.widthHint = 500; griddata.minimumWidth = 500; composite2.setLayoutData(griddata); Label numChannelLabel = new Label(composite2, SWT.NULL); numChannelLabel.setText(Messages.ConfigureTraceDialog_Num_Channels + ":"); //$NON-NLS-1$); griddata = new GridData(); griddata.verticalIndent = 10; numChannelLabel.setLayoutData(griddata); fNumChannelText = new Text(composite2, SWT.SINGLE | SWT.BORDER); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.verticalIndent = 10; griddata.widthHint = 50; griddata.minimumWidth = 50; fNumChannelText.setLayoutData(griddata); if (fTraceResource.isUst()) { fNumChannelText.setText("1"); //$NON-NLS-1$ fNumChannelText.setEnabled(false); } else { fNumChannelText.setText("2"); //$NON-NLS-1$ } fNumChannelText.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { e.doit = e.text.matches("[0-9]*"); //$NON-NLS-1$ } }); fNumChannelText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validate(); } }); fIsAppendButton = new Button(composite1, SWT.CHECK); fIsAppendButton.setText(Messages.ConfigureTraceDialog_Append); griddata = new GridData(); griddata.horizontalAlignment = SWT.BEGINNING; griddata.horizontalSpan = 4; griddata.verticalIndent = 10; fIsAppendButton.setLayoutData(griddata); fIsAppend = Boolean.valueOf(false); fIsAppendButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fIsAppendButton.getSelection()) { fIsAppend = true; } else { fIsAppend = false; } } }); if (fTraceResource.isUst()) { fIsAppendButton.setEnabled(false); } griddata = new GridData(); Group composite22 = new Group(composite1, SWT.SHADOW_OUT); composite22.setText(Messages.ConfigureTraceDialog_Trace_Mode); griddata.horizontalSpan = 4; griddata.verticalIndent = 10; composite22.setLayoutData(griddata); GridLayout compositeLayout22 = new GridLayout(3, false); composite22.setLayout(compositeLayout22); fNoneButton = new Button(composite22, SWT.RADIO); fNoneButton.setText(Messages.ConfigureTraceDialog_Mode_None); fNoneButton.setSelection(true); fFlightRecorderButton = new Button(composite22, SWT.RADIO); fFlightRecorderButton.setText(Messages.ConfigureTraceDialog_Mode_Flight_Recorder); fNormalButton = new Button(composite22, SWT.RADIO); fNormalButton.setText(Messages.ConfigureTraceDialog_Mode_Normal); fMode = 0; fNoneButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNoneButton.getSelection()) { fMode = TraceConfig.NONE_MODE; } } }); fFlightRecorderButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fFlightRecorderButton.getSelection()) { fMode = TraceConfig.FLIGHT_RECORDER_MODE; } } }); fNormalButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event e) { if (fNormalButton.getSelection()) { fMode = TraceConfig.NORMAL_MODE; } } }); if (fTraceResource.isUst()) { fNoneButton.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); } if(fOldTraceConfig != null) { fPathText.setText(fOldTraceConfig.getTracePath()); fIsLocal = fOldTraceConfig.isNetworkTrace(); fLocalButton.setSelection(fIsLocal); fRemoteButton.setSelection(!fIsLocal); fBrowseButton.setEnabled(true); fIsAppend = fOldTraceConfig.getIsAppend(); fIsAppendButton.setSelection(fIsAppend); fNumChannelText.setText(String.valueOf(fOldTraceConfig.getNumChannel())); fFlightRecorderButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.FLIGHT_RECORDER_MODE); fNormalButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NORMAL_MODE); fNoneButton.setSelection(fOldTraceConfig.getMode() == TraceConfig.NONE_MODE); } // Depending on the state disable fields, it's only informational then if ((fTraceResource.getTraceState() == TraceState.STARTED) || (fTraceResource.getTraceState() == TraceState.PAUSED)) { fPathText.setEnabled(false); fBrowseButton.setEnabled(false); fRemoteButton.setEnabled(false); fLocalButton.setEnabled(false); fIsAppendButton.setEnabled(false); fNumChannelText.setEnabled(false); fFlightRecorderButton.setEnabled(false); fNormalButton.setEnabled(false); fNoneButton.setEnabled(false); } validate(); fDisplay.getActiveShell().addListener(SWT.Traverse, new Listener() { @Override public void handleEvent(Event event) { if (event.detail == SWT.TRAVERSE_ESCAPE) { event.doit = false; } } }); }
diff --git a/plugins/org.eclipse.viatra2.emf.incquery.validation.runtime/src/org/eclipse/viatra2/emf/incquery/validation/runtime/ModelEditorPartListener.java b/plugins/org.eclipse.viatra2.emf.incquery.validation.runtime/src/org/eclipse/viatra2/emf/incquery/validation/runtime/ModelEditorPartListener.java index a25dd33b..ad89d1d3 100644 --- a/plugins/org.eclipse.viatra2.emf.incquery.validation.runtime/src/org/eclipse/viatra2/emf/incquery/validation/runtime/ModelEditorPartListener.java +++ b/plugins/org.eclipse.viatra2.emf.incquery.validation.runtime/src/org/eclipse/viatra2/emf/incquery/validation/runtime/ModelEditorPartListener.java @@ -1,65 +1,65 @@ /******************************************************************************* * Copyright (c) 2010-2012, Zoltan Ujhelyi, Abel Hegedus, Tamas Szabo, Istvan Rath and Daniel Varro * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Zoltan Ujhelyi, Abel Hegedus, Tamas Szabo - initial API and implementation *******************************************************************************/ package org.eclipse.viatra2.emf.incquery.validation.runtime; import java.util.Set; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.viatra2.emf.incquery.runtime.api.IPatternMatch; /** * The PartListener is used to observe EditorPart close actions. * * @author Tamas Szabo * */ public class ModelEditorPartListener implements IPartListener { @Override public void partActivated(IWorkbenchPart part) { } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { if (part instanceof IEditorPart) { IEditorPart closedEditor = (IEditorPart) part; - Set<ConstraintAdapter<IPatternMatch>> adapters = ValidationUtil.getAdapterMap().get(closedEditor); + Set<ConstraintAdapter<IPatternMatch>> adapters = ValidationUtil.getAdapterMap().remove(closedEditor); if (adapters != null) { for (ConstraintAdapter<IPatternMatch> adapter : adapters) { adapter.dispose(); } } closedEditor.getEditorSite().getPage().removePartListener(ValidationUtil.editorPartListener); } } @Override public void partDeactivated(IWorkbenchPart part) { } @Override public void partOpened(IWorkbenchPart part) { } }
true
true
public void partClosed(IWorkbenchPart part) { if (part instanceof IEditorPart) { IEditorPart closedEditor = (IEditorPart) part; Set<ConstraintAdapter<IPatternMatch>> adapters = ValidationUtil.getAdapterMap().get(closedEditor); if (adapters != null) { for (ConstraintAdapter<IPatternMatch> adapter : adapters) { adapter.dispose(); } } closedEditor.getEditorSite().getPage().removePartListener(ValidationUtil.editorPartListener); } }
public void partClosed(IWorkbenchPart part) { if (part instanceof IEditorPart) { IEditorPart closedEditor = (IEditorPart) part; Set<ConstraintAdapter<IPatternMatch>> adapters = ValidationUtil.getAdapterMap().remove(closedEditor); if (adapters != null) { for (ConstraintAdapter<IPatternMatch> adapter : adapters) { adapter.dispose(); } } closedEditor.getEditorSite().getPage().removePartListener(ValidationUtil.editorPartListener); } }
diff --git a/src/org/eclipse/core/internal/localstore/UnifiedTree.java b/src/org/eclipse/core/internal/localstore/UnifiedTree.java index fbc9aaf1..e5d91377 100644 --- a/src/org/eclipse/core/internal/localstore/UnifiedTree.java +++ b/src/org/eclipse/core/internal/localstore/UnifiedTree.java @@ -1,432 +1,433 @@ /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.localstore; import java.util.*; import org.eclipse.core.internal.resources.*; import org.eclipse.core.internal.resources.Resource; import org.eclipse.core.internal.resources.Workspace; import org.eclipse.core.internal.utils.*; //import "queue" explicitly here to prevent ambiguity when running against 1.5. import org.eclipse.core.internal.utils.Queue; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; /** * Represents the workspace's tree merged with the file system's tree. */ public class UnifiedTree { /** tree's root */ protected IResource root; /** cache root's location (may be null) */ protected IPath rootLocalLocation; /** tree's actual level */ protected int level; /** * True if the level of the children of the current node are valid according * to the requested refresh depth, false otherwise */ protected boolean childLevelValid = false; /** our queue */ protected Queue queue; /** Spare node objects available for reuse */ protected ArrayList freeNodes = new ArrayList(); /** special node to mark the beginning of a level in the tree */ protected static final UnifiedTreeNode levelMarker = new UnifiedTreeNode(null, null, 0, null, null, false); /** special node to mark the separation of a node's children */ protected static final UnifiedTreeNode childrenMarker = new UnifiedTreeNode(null, null, 0, null, null, false); /** Singleton to indicate no local children */ private static final Object[] NO_CHILDREN = new Object[0]; /** * The root must only be a file or a folder. */ public UnifiedTree(IResource root) { setRoot(root); } public void accept(IUnifiedTreeVisitor visitor) throws CoreException { accept(visitor, IResource.DEPTH_INFINITE); } public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException { Assert.isNotNull(root); initializeQueue(); setLevel(0, depth); while (!queue.isEmpty()) { UnifiedTreeNode node = (UnifiedTreeNode) queue.remove(); if (isChildrenMarker(node)) continue; if (isLevelMarker(node)) { if (!setLevel(getLevel()+1, depth)) break; continue; } if (visitor.visit(node)) addNodeChildrenToQueue(node); else removeNodeChildrenFromQueue(node); //allow reuse of the node freeNodes.add(node); } } protected void addChildren(UnifiedTreeNode node) throws CoreException { Resource parent = (Resource)node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && node.isFile()) return; // get the list of resources in the file system String parentLocalLocation = node.getLocalLocation(); // don't ask for local children if we know it doesn't exist locally Object[] list = node.existsInFileSystem() ? getLocalList(node, parentLocalLocation) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); String localName = (list != null && localIndex < list.length) ? (String) list[localIndex] : null; int comp = localName != null ? name.compareTo(localName) : -1; //special handling for linked resources if (parentType == IResource.PROJECT && target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); localIndex++; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, localIndex); /* Mark the children as now known */ if (unknown) { - resourceInfo = parent.getResourceInfo(false, true); + // Don't open the info - we might not be inside a workspace-modifying operation + resourceInfo = parent.getResourceInfo(false, false); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); } /** * Creates a tree node for a resource that is linked in a different file system location. */ protected UnifiedTreeNode createChildForLinkedResource(IResource target) { IPath location = target.getLocation(); long stat = 0; String locationString = null; String name = null; if (location != null) { locationString = location.toOSString(); name = location.lastSegment(); stat = CoreFileSystemLibrary.getStat(locationString); } return createNode(target, stat, locationString, name, true); } protected void addChildrenFromFileSystem(UnifiedTreeNode node, String parentLocalLocation, Object[] list, int index) { if (list == null) return; for (int i = index; i < list.length; i++) { String localName = (String) list[i]; UnifiedTreeNode child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); if (child != null) addChildToTree(node, child); } } protected void addChildrenMarker() { addElementToQueue(childrenMarker); } protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) { if (node.getFirstChild() == null) node.setFirstChild(child); addElementToQueue(child); } protected void addElementToQueue(UnifiedTreeNode target) { queue.add(target); } /** * Creates a string representing the OS path for the given parent and child name. */ protected String createChildLocation(String parentLocation, String childLocation) { if (parentLocation == null) return null; StringBuffer buffer = new StringBuffer(parentLocation.length() + childLocation.length() + 1); buffer.append(parentLocation); buffer.append(java.io.File.separatorChar); buffer.append(childLocation); return buffer.toString(); } protected void addNodeChildrenToQueue(UnifiedTreeNode node) throws CoreException { /* if the first child is not null we already added the children */ /* If the children won't be at a valid level for the refresh depth, don't bother adding them */ if (!childLevelValid || node.getFirstChild() != null) return; addChildren(node); if (queue.isEmpty()) return; //if we're about to change levels, then the children just added //are the last nodes for their level, so add a level marker to the queue UnifiedTreeNode nextNode = (UnifiedTreeNode) queue.peek(); if (isChildrenMarker(nextNode)) queue.remove(); nextNode = (UnifiedTreeNode) queue.peek(); if (isLevelMarker(nextNode)) addElementToQueue(levelMarker); } protected void addRootToQueue() { long stat = 0; String rootLocationString = null; String name = null; if (rootLocalLocation != null) { rootLocationString = rootLocalLocation.toOSString(); name = rootLocalLocation.lastSegment(); stat = CoreFileSystemLibrary.getStat(rootLocationString); } UnifiedTreeNode node = createNode(root, stat, rootLocationString, name, root.exists()); if (!node.existsInFileSystem() && !node.existsInWorkspace()) return; addElementToQueue(node); } /** * Creates a child node for a location in the file system. Does nothing and returns null if the location does not correspond to a valid file/folder. */ protected UnifiedTreeNode createChildNodeFromFileSystem(UnifiedTreeNode parent, String parentLocalLocation, String childName) { IPath childPath = parent.getResource().getFullPath().append(childName); String location = createChildLocation(parentLocalLocation, childName); long stat = CoreFileSystemLibrary.getStat(location); int type = CoreFileSystemLibrary.isFile(stat) ? IResource.FILE : (CoreFileSystemLibrary.isFolder(stat) ? IResource.FOLDER : 0); // if it is not a valid file or folder if (type == 0) return null; IResource target = getWorkspace().newResource(childPath, type); return createNode(target, stat, location, childName, false); } /** * Factory method for creating a node for this tree. */ protected UnifiedTreeNode createNode(IResource resource, long stat, String localLocation, String localName, boolean existsWorkspace) { //first check for reusable objects UnifiedTreeNode node = null; int size = freeNodes.size(); if (size > 0) { node = (UnifiedTreeNode) freeNodes.remove(size - 1); node.reuse(this, resource, stat, localLocation, localName, existsWorkspace); return node; } //none available, so create a new one return new UnifiedTreeNode(this, resource, stat, localLocation, localName, existsWorkspace); } protected Enumeration getChildren(UnifiedTreeNode node) throws CoreException { /* if first child is null we need to add node's children to queue */ if (node.getFirstChild() == null) addNodeChildrenToQueue(node); /* if the first child is still null, the node does not have any children */ if (node.getFirstChild() == null) return EmptyEnumeration.getEnumeration(); /* get the index of the first child */ int index = queue.indexOf(node.getFirstChild()); /* if we do not have children, just return an empty enumeration */ if (index == -1) return EmptyEnumeration.getEnumeration(); /* create an enumeration with node's children */ List result = new ArrayList(10); while (true) { UnifiedTreeNode child = (UnifiedTreeNode) queue.elementAt(index); if (isChildrenMarker(child)) break; result.add(child); index = queue.increment(index); } return Collections.enumeration(result); } protected String getLocalLocation(IResource target) { if (rootLocalLocation == null) return null; int segments = target.getFullPath().matchingFirstSegments(root.getFullPath()); return rootLocalLocation.append(target.getFullPath().removeFirstSegments(segments)).toOSString(); } protected int getLevel() { return level; } protected Object[] getLocalList(UnifiedTreeNode node, String location) { if (node.isFile() || location == null) return null; String[] list = new java.io.File(location).list(); if (list == null) return list; int size = list.length; if (size > 1) quickSort(list, 0, size - 1); return list; } protected Workspace getWorkspace() { return (Workspace) root.getWorkspace(); } /** * Increases the current tree level by one. Returns true if the new * level is still valid for the given depth */ protected boolean setLevel(int newLevel, int depth) { level = newLevel; childLevelValid = isValidLevel(level+1, depth); return isValidLevel(level, depth); } protected void initializeQueue() { //init the queue if (queue == null) queue = new Queue(100, false); else queue.reset(); //init the free nodes list if (freeNodes == null) freeNodes = new ArrayList(100); else freeNodes.clear(); addRootToQueue(); addElementToQueue(levelMarker); } protected boolean isChildrenMarker(UnifiedTreeNode node) { return node == childrenMarker; } protected boolean isLevelMarker(UnifiedTreeNode node) { return node == levelMarker; } protected boolean isValidLevel(int currentLevel, int depth) { switch (depth) { case IResource.DEPTH_INFINITE : return true; case IResource.DEPTH_ONE : return currentLevel <= 1; case IResource.DEPTH_ZERO : return currentLevel == 0; default : return currentLevel + 1000 <= depth; } } /** * Remove from the last element of the queue to the first child of the * given node. */ protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) { UnifiedTreeNode first = node.getFirstChild(); if (first == null) return; while (true) { if (first.equals(queue.removeTail())) break; } node.setFirstChild(null); } public void setRoot(IResource root) { this.root = root; this.rootLocalLocation = root.getLocation(); } /** * Sorts the given array of strings in place. This is * not using the sorting framework to avoid casting overhead. */ protected void quickSort(String[] strings, int left, int right) { int originalLeft = left; int originalRight = right; String mid = strings[(left + right) / 2]; do { while (mid.compareTo(strings[left]) > 0) left++; while (strings[right].compareTo(mid) > 0) right--; if (left <= right) { String tmp = strings[left]; strings[left] = strings[right]; strings[right] = tmp; left++; right--; } } while (left <= right); if (originalLeft < right) quickSort(strings, originalLeft, right); if (left < originalRight) quickSort(strings, left, originalRight); return; } }
true
true
protected void addChildren(UnifiedTreeNode node) throws CoreException { Resource parent = (Resource)node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && node.isFile()) return; // get the list of resources in the file system String parentLocalLocation = node.getLocalLocation(); // don't ask for local children if we know it doesn't exist locally Object[] list = node.existsInFileSystem() ? getLocalList(node, parentLocalLocation) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); String localName = (list != null && localIndex < list.length) ? (String) list[localIndex] : null; int comp = localName != null ? name.compareTo(localName) : -1; //special handling for linked resources if (parentType == IResource.PROJECT && target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); localIndex++; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, localIndex); /* Mark the children as now known */ if (unknown) { resourceInfo = parent.getResourceInfo(false, true); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
protected void addChildren(UnifiedTreeNode node) throws CoreException { Resource parent = (Resource)node.getResource(); // is there a possibility to have children? int parentType = parent.getType(); if (parentType == IResource.FILE && node.isFile()) return; // get the list of resources in the file system String parentLocalLocation = node.getLocalLocation(); // don't ask for local children if we know it doesn't exist locally Object[] list = node.existsInFileSystem() ? getLocalList(node, parentLocalLocation) : NO_CHILDREN; int localIndex = 0; // See if the children of this resource have been computed before ResourceInfo resourceInfo = parent.getResourceInfo(false, false); int flags = parent.getFlags(resourceInfo); boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN); // get the list of resources in the workspace if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) { IResource target = null; UnifiedTreeNode child = null; IResource[] members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); int workspaceIndex = 0; //iterate simultaneously over file system and workspace members while (workspaceIndex < members.length) { target = members[workspaceIndex]; String name = target.getName(); String localName = (list != null && localIndex < list.length) ? (String) list[localIndex] : null; int comp = localName != null ? name.compareTo(localName) : -1; //special handling for linked resources if (parentType == IResource.PROJECT && target.isLinked()) { //child will be null if location is undefined child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource if (comp == 0) localIndex++; } else if (comp == 0) { // resource exists in workspace and file system String localLocation = createChildLocation(parentLocalLocation, localName); long stat = CoreFileSystemLibrary.getStat(localLocation); child = createNode(target, stat, localLocation, localName, true); localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system child = createChildNodeFromFileSystem(node, parentLocalLocation, localName); localIndex++; } else { // resource exists only in the workspace child = createNode(target, 0, null, null, true); workspaceIndex++; } if (child != null) addChildToTree(node, child); } } /* process any remaining resource from the file system */ addChildrenFromFileSystem(node, parentLocalLocation, list, localIndex); /* Mark the children as now known */ if (unknown) { // Don't open the info - we might not be inside a workspace-modifying operation resourceInfo = parent.getResourceInfo(false, false); if (resourceInfo != null) resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); } /* if we added children, add the childMarker separator */ if (node.getFirstChild() != null) addChildrenMarker(); }
diff --git a/BOLT/src/entity/util/EntityLoader.java b/BOLT/src/entity/util/EntityLoader.java index 9102d5d..edf70d1 100644 --- a/BOLT/src/entity/util/EntityLoader.java +++ b/BOLT/src/entity/util/EntityLoader.java @@ -1,201 +1,202 @@ package entity.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.lwjgl.util.vector.Vector3f; import entity.EntityBuilder; import entity.EntityRegistry; public class EntityLoader { public static HashMap<String, EntityFound> entitiesFound = new HashMap<>(); /** * * @param path The path of the .entity file * @param secondParsing Is this the second parsing? * @return Returns an instance of EntityBuilder if successful and null if not * @throws IOException */ public static EntityBuilder loadEntity(String name) throws IOException { String path = ""; if(doesEntityExist(name)) { if(isParentValid(entitiesFound.get(name).getParent())) path = entitiesFound.get(name).getPath(); else return null; } else return null; File OBJFile = new File(path); BufferedReader reader = new BufferedReader(new FileReader(OBJFile)); EntityBuilder e = new EntityBuilder(); String line; boolean parentFound = false; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) ; else if (line.startsWith("parent ")) { String parent = line.split(" ")[1]; if(parent.equals("null"))parentFound = true; else if (EntityLoader.doesEntityExist(parent)) { + EntityRegistry.registerEntityBuilder(EntityLoader.loadEntity(parent)); e = EntityRegistry.entries.get(parent).clone(); e.parent = parent; parentFound = true; } } else if (!parentFound) { reader.close(); return null; } else if (line.startsWith("name ")) { e.name = line.split(" ")[1]; } else if (line.startsWith("fullName ")) { e.fullName = line.split(" ")[1]; } else if (line.startsWith("physicsType ")) { e.physicsType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("collisionType ")) { e.collisionType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("invisible ")) { e.invisible = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("gravity ")) { e.gravity = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("class ")) { e.classPath = line.split(" ")[1]; } else if (line.startsWith("model ")) { e.model = line.split(" ")[1]; } else if (line.startsWith("collisionModel ")) { e.collisionModel = line.split(" ")[1]; } else if (line.startsWith("weight ")) { e.weight = Float.valueOf(line.split(" ")[1]); } else if (line.startsWith("balancePoint ")) { e.balancePoint = new Vector3f(Float.valueOf(line.split(" ")[1]), Float.valueOf(line.split(" ")[2]), Float.valueOf(line.split(" ")[3])); } else { if (line.startsWith("byte ")) { e.customValues.put(line.split(" ")[1], Byte.valueOf(line.split(" ")[2])); } else if (line.startsWith("float ")) { e.customValues.put(line.split(" ")[1], Float.valueOf(line.split(" ")[2])); } else if (line.startsWith("integer ")) { e.customValues.put(line.split(" ")[1], Integer.valueOf(line.split(" ")[2])); } else if (line.startsWith("boolean ")) { e.customValues.put(line.split(" ")[1], Boolean.valueOf(line.split(" ")[2])); } else if (line.startsWith("string ")) { e.customValues.put(line.split(" ")[1], line.substring(line.indexOf(" ", 8)).trim()); } } } reader.close(); return e; } private static boolean isParentValid(String parent) { if(parent.equals("null")) return true; else if(doesEntityExist(parent))return isParentValid(entitiesFound.get(parent).getParent()); return false; } private static boolean doesEntityExist(String name) { return entitiesFound.containsKey(name); } public static void findEntities(String path) throws IOException { File entFile = new File(path); BufferedReader reader = new BufferedReader(new FileReader(entFile)); String line; List<String> filesToParse = new ArrayList<>(); while ((line = reader.readLine()) != null) { filesToParse.add(line); } reader.close(); for (String s : filesToParse) { File file = new File(s); reader = new BufferedReader(new FileReader(file)); String name = "", parent = ""; while((line = reader.readLine()) != null) { if(line.startsWith("#")); else if(line.startsWith("parent ")) parent = line.split(" ")[1]; else if(line.startsWith("name ")) name = line.split(" ")[1]; } if(name != "" && parent != "")entitiesFound.put(name, new EntityFound(parent, name, s)); else System.err.println(s +" could not be read properly"); } } public static class EntityFound { private final String parent, name, path; public EntityFound(String parent, String name, String path) { super(); this.parent = parent; this.name = name; this.path = path; } public String getParent() { return parent; } public String getName() { return name; } public String getPath() { return path; } } }
true
true
public static EntityBuilder loadEntity(String name) throws IOException { String path = ""; if(doesEntityExist(name)) { if(isParentValid(entitiesFound.get(name).getParent())) path = entitiesFound.get(name).getPath(); else return null; } else return null; File OBJFile = new File(path); BufferedReader reader = new BufferedReader(new FileReader(OBJFile)); EntityBuilder e = new EntityBuilder(); String line; boolean parentFound = false; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) ; else if (line.startsWith("parent ")) { String parent = line.split(" ")[1]; if(parent.equals("null"))parentFound = true; else if (EntityLoader.doesEntityExist(parent)) { e = EntityRegistry.entries.get(parent).clone(); e.parent = parent; parentFound = true; } } else if (!parentFound) { reader.close(); return null; } else if (line.startsWith("name ")) { e.name = line.split(" ")[1]; } else if (line.startsWith("fullName ")) { e.fullName = line.split(" ")[1]; } else if (line.startsWith("physicsType ")) { e.physicsType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("collisionType ")) { e.collisionType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("invisible ")) { e.invisible = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("gravity ")) { e.gravity = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("class ")) { e.classPath = line.split(" ")[1]; } else if (line.startsWith("model ")) { e.model = line.split(" ")[1]; } else if (line.startsWith("collisionModel ")) { e.collisionModel = line.split(" ")[1]; } else if (line.startsWith("weight ")) { e.weight = Float.valueOf(line.split(" ")[1]); } else if (line.startsWith("balancePoint ")) { e.balancePoint = new Vector3f(Float.valueOf(line.split(" ")[1]), Float.valueOf(line.split(" ")[2]), Float.valueOf(line.split(" ")[3])); } else { if (line.startsWith("byte ")) { e.customValues.put(line.split(" ")[1], Byte.valueOf(line.split(" ")[2])); } else if (line.startsWith("float ")) { e.customValues.put(line.split(" ")[1], Float.valueOf(line.split(" ")[2])); } else if (line.startsWith("integer ")) { e.customValues.put(line.split(" ")[1], Integer.valueOf(line.split(" ")[2])); } else if (line.startsWith("boolean ")) { e.customValues.put(line.split(" ")[1], Boolean.valueOf(line.split(" ")[2])); } else if (line.startsWith("string ")) { e.customValues.put(line.split(" ")[1], line.substring(line.indexOf(" ", 8)).trim()); } } } reader.close(); return e; }
public static EntityBuilder loadEntity(String name) throws IOException { String path = ""; if(doesEntityExist(name)) { if(isParentValid(entitiesFound.get(name).getParent())) path = entitiesFound.get(name).getPath(); else return null; } else return null; File OBJFile = new File(path); BufferedReader reader = new BufferedReader(new FileReader(OBJFile)); EntityBuilder e = new EntityBuilder(); String line; boolean parentFound = false; while ((line = reader.readLine()) != null) { if (line.startsWith("#")) ; else if (line.startsWith("parent ")) { String parent = line.split(" ")[1]; if(parent.equals("null"))parentFound = true; else if (EntityLoader.doesEntityExist(parent)) { EntityRegistry.registerEntityBuilder(EntityLoader.loadEntity(parent)); e = EntityRegistry.entries.get(parent).clone(); e.parent = parent; parentFound = true; } } else if (!parentFound) { reader.close(); return null; } else if (line.startsWith("name ")) { e.name = line.split(" ")[1]; } else if (line.startsWith("fullName ")) { e.fullName = line.split(" ")[1]; } else if (line.startsWith("physicsType ")) { e.physicsType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("collisionType ")) { e.collisionType = Integer.valueOf(line.split(" ")[1]); } else if (line.startsWith("invisible ")) { e.invisible = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("gravity ")) { e.gravity = Boolean.valueOf(line.split(" ")[1]); } else if (line.startsWith("class ")) { e.classPath = line.split(" ")[1]; } else if (line.startsWith("model ")) { e.model = line.split(" ")[1]; } else if (line.startsWith("collisionModel ")) { e.collisionModel = line.split(" ")[1]; } else if (line.startsWith("weight ")) { e.weight = Float.valueOf(line.split(" ")[1]); } else if (line.startsWith("balancePoint ")) { e.balancePoint = new Vector3f(Float.valueOf(line.split(" ")[1]), Float.valueOf(line.split(" ")[2]), Float.valueOf(line.split(" ")[3])); } else { if (line.startsWith("byte ")) { e.customValues.put(line.split(" ")[1], Byte.valueOf(line.split(" ")[2])); } else if (line.startsWith("float ")) { e.customValues.put(line.split(" ")[1], Float.valueOf(line.split(" ")[2])); } else if (line.startsWith("integer ")) { e.customValues.put(line.split(" ")[1], Integer.valueOf(line.split(" ")[2])); } else if (line.startsWith("boolean ")) { e.customValues.put(line.split(" ")[1], Boolean.valueOf(line.split(" ")[2])); } else if (line.startsWith("string ")) { e.customValues.put(line.split(" ")[1], line.substring(line.indexOf(" ", 8)).trim()); } } } reader.close(); return e; }
diff --git a/server/jetty/src/test/java/org/mortbay/jetty/servlet/AbstractSessionTest.java b/server/jetty/src/test/java/org/mortbay/jetty/servlet/AbstractSessionTest.java index a3176b144..2f8a909f8 100644 --- a/server/jetty/src/test/java/org/mortbay/jetty/servlet/AbstractSessionTest.java +++ b/server/jetty/src/test/java/org/mortbay/jetty/servlet/AbstractSessionTest.java @@ -1,97 +1,97 @@ // ======================================================================== // Copyright 2008 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package org.mortbay.jetty.servlet; import junit.framework.TestCase; public abstract class AbstractSessionTest extends TestCase { public static final String __host1 = "localhost"; public static final String __host2 = __host1; public static final String __port1 = "8010"; public static final String __port2 = "8011"; SessionTestServer _server1; SessionTestServer _server2; public abstract SessionTestServer newServer1 (); public abstract SessionTestServer newServer2(); public void setUp () throws Exception { _server1 = newServer1(); _server2 = newServer2(); _server1.start(); _server2.start(); } public void tearDown () throws Exception { if (_server1 != null) _server1.stop(); if (_server2 != null) _server2.stop(); _server1=null; _server2=null; } public void testSessions () throws Exception { SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1); SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2); // confirm that user has no session assertFalse(client1.send("/contextA", null)); String cookie1 = client1.newSession("/contextA"); assertNotNull(cookie1); System.err.println("cookie1: " + cookie1); // confirm that client2 has the same session attributes as client1 assertTrue(client1.setAttribute("/contextA", cookie1, "foo", "bar")); assertTrue(client2.hasAttribute("/contextA", cookie1, "foo", "bar")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client1.send("/contextB", cookie1)); // verify that session attributes on /contextA is different from /contextB assertFalse(client1.hasAttribute("/contextB/action", cookie1, "foo", "bar")); // add new session attributes on /contextB client1.setAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy"); assertTrue(client1.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); // verify that client2 has same sessionAttributes on /contextB // client1's newly added attribute "zzzzz" needs to be flushed to the database first - // saveInterval is configured at 10ms... to test, uncomment the 2 lines below. + // saveInterval is configured at 10s... to test, uncomment the 2 lines below. //Thread.sleep(10000); //assertTrue(client2.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); String cookie2 = client2.newSession("/contextA"); assertNotNull(cookie2); System.err.println("cookie2: " + cookie2); // confirm that client1 has same session attributes as client2 assertTrue(client2.setAttribute("/contextA", cookie2, "hello", "world")); assertTrue(client1.hasAttribute("/contextA", cookie2, "hello", "world")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client1.send("/contextB", cookie2)); } }
true
true
public void testSessions () throws Exception { SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1); SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2); // confirm that user has no session assertFalse(client1.send("/contextA", null)); String cookie1 = client1.newSession("/contextA"); assertNotNull(cookie1); System.err.println("cookie1: " + cookie1); // confirm that client2 has the same session attributes as client1 assertTrue(client1.setAttribute("/contextA", cookie1, "foo", "bar")); assertTrue(client2.hasAttribute("/contextA", cookie1, "foo", "bar")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client1.send("/contextB", cookie1)); // verify that session attributes on /contextA is different from /contextB assertFalse(client1.hasAttribute("/contextB/action", cookie1, "foo", "bar")); // add new session attributes on /contextB client1.setAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy"); assertTrue(client1.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); // verify that client2 has same sessionAttributes on /contextB // client1's newly added attribute "zzzzz" needs to be flushed to the database first // saveInterval is configured at 10ms... to test, uncomment the 2 lines below. //Thread.sleep(10000); //assertTrue(client2.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); String cookie2 = client2.newSession("/contextA"); assertNotNull(cookie2); System.err.println("cookie2: " + cookie2); // confirm that client1 has same session attributes as client2 assertTrue(client2.setAttribute("/contextA", cookie2, "hello", "world")); assertTrue(client1.hasAttribute("/contextA", cookie2, "hello", "world")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client1.send("/contextB", cookie2)); }
public void testSessions () throws Exception { SessionTestClient client1 = new SessionTestClient("http://"+__host1+":"+__port1); SessionTestClient client2 = new SessionTestClient("http://"+__host2+":"+__port2); // confirm that user has no session assertFalse(client1.send("/contextA", null)); String cookie1 = client1.newSession("/contextA"); assertNotNull(cookie1); System.err.println("cookie1: " + cookie1); // confirm that client2 has the same session attributes as client1 assertTrue(client1.setAttribute("/contextA", cookie1, "foo", "bar")); assertTrue(client2.hasAttribute("/contextA", cookie1, "foo", "bar")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie1)); assertTrue(client1.send("/contextB", cookie1)); // verify that session attributes on /contextA is different from /contextB assertFalse(client1.hasAttribute("/contextB/action", cookie1, "foo", "bar")); // add new session attributes on /contextB client1.setAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy"); assertTrue(client1.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); // verify that client2 has same sessionAttributes on /contextB // client1's newly added attribute "zzzzz" needs to be flushed to the database first // saveInterval is configured at 10s... to test, uncomment the 2 lines below. //Thread.sleep(10000); //assertTrue(client2.hasAttribute("/contextB/action", cookie1, "zzzzz", "yyyyy")); String cookie2 = client2.newSession("/contextA"); assertNotNull(cookie2); System.err.println("cookie2: " + cookie2); // confirm that client1 has same session attributes as client2 assertTrue(client2.setAttribute("/contextA", cookie2, "hello", "world")); assertTrue(client1.hasAttribute("/contextA", cookie2, "hello", "world")); // confirm that /contextA would share same sessionId as /contextB assertTrue(client1.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client2.send("/contextA/dispatch/forward/contextB", cookie2)); assertTrue(client1.send("/contextB", cookie2)); }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java index 86f88f88..3f52e8e0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -1,76 +1,77 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpaccept extends EssentialsCommand { public Commandtpaccept() { super("tpaccept"); } @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || !target.isOnline()) { throw new Exception(_("noPendingRequest")); } if (user.isTpRequestHere() && ((!target.isAuthorized("essentials.tpahere") && !target.isAuthorized("essentials.tpaall")) || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (!user.isTpRequestHere() && (!target.isAuthorized("essentials.tpa") || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + target.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTpRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTpRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); + throw new NoChargeException(); } }
true
true
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || !target.isOnline()) { throw new Exception(_("noPendingRequest")); } if (user.isTpRequestHere() && ((!target.isAuthorized("essentials.tpahere") && !target.isAuthorized("essentials.tpaall")) || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (!user.isTpRequestHere() && (!target.isAuthorized("essentials.tpa") || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + target.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTpRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTpRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); }
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || !target.isOnline()) { throw new Exception(_("noPendingRequest")); } if (user.isTpRequestHere() && ((!target.isAuthorized("essentials.tpahere") && !target.isAuthorized("essentials.tpaall")) || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (!user.isTpRequestHere() && (!target.isAuthorized("essentials.tpa") || (user.getWorld() != target.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + target.getWorld().getName())))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTpRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTpRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); throw new NoChargeException(); }
diff --git a/src/com/android/mms/data/Contact.java b/src/com/android/mms/data/Contact.java index f1c6bc1..2d725f0 100644 --- a/src/com/android/mms/data/Contact.java +++ b/src/com/android/mms/data/Contact.java @@ -1,488 +1,490 @@ package com.android.mms.data; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.ContentUris; import android.content.Context; import android.database.ContentObserver; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Presence; import android.provider.Telephony.Mms; import android.telephony.PhoneNumberUtils; import android.text.TextUtils; import android.util.Log; import com.android.mms.ui.MessageUtils; import com.android.mms.util.ContactInfoCache; import com.android.mms.util.TaskStack; import com.android.mms.LogTag; public class Contact { private static final String TAG = "Contact"; private static final boolean V = false; private static final TaskStack sTaskStack = new TaskStack(); // private static final ContentObserver sContactsObserver = new ContentObserver(new Handler()) { // @Override // public void onChange(boolean selfUpdate) { // if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { // log("contact changed, invalidate cache"); // } // invalidateCache(); // } // }; private static final ContentObserver sPresenceObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfUpdate) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("presence changed, invalidate cache"); } invalidateCache(); } }; private final HashSet<UpdateListener> mListeners = new HashSet<UpdateListener>(); private String mNumber; private String mName; private String mNameAndNumber; // for display, e.g. Fred Flintstone <670-782-1123> private boolean mNumberIsModified; // true if the number is modified private long mRecipientId; // used to find the Recipient cache entry private String mLabel; private long mPersonId; private int mPresenceResId; // TODO: make this a state instead of a res ID private String mPresenceText; private BitmapDrawable mAvatar; private boolean mIsStale; @Override public synchronized String toString() { return String.format("{ number=%s, name=%s, nameAndNumber=%s, label=%s, person_id=%d }", mNumber, mName, mNameAndNumber, mLabel, mPersonId); } public interface UpdateListener { public void onUpdate(Contact updated); } private Contact(String number) { mName = ""; setNumber(number); mNumberIsModified = false; mLabel = ""; mPersonId = 0; mPresenceResId = 0; mIsStale = true; } private static void logWithTrace(String msg, Object... format) { Thread current = Thread.currentThread(); StackTraceElement[] stack = current.getStackTrace(); StringBuilder sb = new StringBuilder(); sb.append("["); sb.append(current.getId()); sb.append("] "); sb.append(String.format(msg, format)); sb.append(" <- "); int stop = stack.length > 7 ? 7 : stack.length; for (int i = 3; i < stop; i++) { String methodName = stack[i].getMethodName(); sb.append(methodName); if ((i+1) != stop) { sb.append(" <- "); } } Log.d(TAG, sb.toString()); } public static Contact get(String number, boolean canBlock) { if (V) logWithTrace("get(%s, %s)", number, canBlock); if (TextUtils.isEmpty(number)) { throw new IllegalArgumentException("Contact.get called with null or empty number"); } Contact contact = Cache.get(number); if (contact == null) { contact = new Contact(number); Cache.put(contact); } if (contact.mIsStale) { asyncUpdateContact(contact, canBlock); } return contact; } public static void invalidateCache() { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("invalidateCache"); } // force invalidate the contact info cache, so we will query for fresh info again. // This is so we can get fresh presence info again on the screen, since the presence // info changes pretty quickly, and we can't get change notifications when presence is // updated in the ContactsProvider. ContactInfoCache.getInstance().invalidateCache(); // While invalidating our local Cache doesn't remove the contacts, it will mark them // stale so the next time we're asked for a particular contact, we'll return that // stale contact and at the same time, fire off an asyncUpdateContact to update // that contact's info in the background. UI elements using the contact typically // call addListener() so they immediately get notified when the contact has been // updated with the latest info. They redraw themselves when we call the // listener's onUpdate(). Cache.invalidate(); } private static String emptyIfNull(String s) { return (s != null ? s : ""); } private static boolean contactChanged(Contact orig, ContactInfoCache.CacheEntry newEntry) { // The phone number should never change, so don't bother checking. // TODO: Maybe update it if it has gotten longer, i.e. 650-234-5678 -> +16502345678? String oldName = emptyIfNull(orig.mName); String newName = emptyIfNull(newEntry.name); if (!oldName.equals(newName)) { if (V) Log.d(TAG, String.format("name changed: %s -> %s", oldName, newName)); return true; } String oldLabel = emptyIfNull(orig.mLabel); String newLabel = emptyIfNull(newEntry.phoneLabel); if (!oldLabel.equals(newLabel)) { if (V) Log.d(TAG, String.format("label changed: %s -> %s", oldLabel, newLabel)); return true; } if (orig.mPersonId != newEntry.person_id) { if (V) Log.d(TAG, "person id changed"); return true; } if (orig.mPresenceResId != newEntry.presenceResId) { if (V) Log.d(TAG, "presence changed"); return true; } return false; } /** * Handles the special case where the local ("Me") number is being looked up. * Updates the contact with the "me" name and returns true if it is the * local number, no-ops and returns false if it is not. */ private static boolean handleLocalNumber(Contact c) { if (MessageUtils.isLocalNumber(c.mNumber)) { c.mName = Cache.getContext().getString(com.android.internal.R.string.me); c.updateNameAndNumber(); return true; } return false; } private static void asyncUpdateContact(final Contact c, boolean canBlock) { if (c == null) { return; } if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("asyncUpdateContact for " + c.toString() + " canBlock: " + canBlock + " isStale: " + c.mIsStale); } Runnable r = new Runnable() { public void run() { updateContact(c); } }; if (canBlock) { r.run(); } else { sTaskStack.push(r); } } private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } + } else { + c.mIsStale = false; } } } public static String formatNameAndNumber(String name, String number) { // Format like this: Mike Cleron <(650) 555-1234> // Erick Tseng <(650) 555-1212> // Tutankhamun <[email protected]> // (408) 555-1289 String formattedNumber = number; if (!Mms.isEmailAddress(number)) { formattedNumber = PhoneNumberUtils.formatNumber(number); } if (!TextUtils.isEmpty(name) && !name.equals(number)) { return name + " <" + formattedNumber + ">"; } else { return formattedNumber; } } public synchronized String getNumber() { return mNumber; } public synchronized void setNumber(String number) { mNumber = number; updateNameAndNumber(); mNumberIsModified = true; } public boolean isNumberModified() { return mNumberIsModified; } public void setIsNumberModified(boolean flag) { mNumberIsModified = flag; } public synchronized String getName() { if (TextUtils.isEmpty(mName)) { return mNumber; } else { return mName; } } public synchronized String getNameAndNumber() { return mNameAndNumber; } private void updateNameAndNumber() { mNameAndNumber = formatNameAndNumber(mName, mNumber); } public synchronized long getRecipientId() { return mRecipientId; } public synchronized void setRecipientId(long id) { mRecipientId = id; } public synchronized String getLabel() { return mLabel; } public synchronized Uri getUri() { return ContentUris.withAppendedId(Contacts.CONTENT_URI, mPersonId); } public long getPersonId() { return mPersonId; } public synchronized int getPresenceResId() { return mPresenceResId; } public synchronized boolean existsInDatabase() { return (mPersonId > 0); } public synchronized void addListener(UpdateListener l) { boolean added = mListeners.add(l); if (V && added) dumpListeners(); } public synchronized void removeListener(UpdateListener l) { boolean removed = mListeners.remove(l); if (V && removed) dumpListeners(); } public synchronized void dumpListeners() { int i=0; Log.i(TAG, "[Contact] dumpListeners(" + mNumber + ") size=" + mListeners.size()); for (UpdateListener listener : mListeners) { Log.i(TAG, "["+ (i++) + "]" + listener); } } public synchronized boolean isEmail() { return Mms.isEmailAddress(mNumber); } public String getPresenceText() { return mPresenceText; } public Drawable getAvatar(Drawable defaultValue) { return mAvatar != null ? mAvatar : defaultValue; } public static void init(final Context context) { Cache.init(context); RecipientIdCache.init(context); // it maybe too aggressive to listen for *any* contact changes, and rebuild MMS contact // cache each time that occurs. Unless we can get targeted updates for the contacts we // care about(which probably won't happen for a long time), we probably should just // invalidate cache peoridically, or surgically. /* context.getContentResolver().registerContentObserver( Contacts.CONTENT_URI, true, sContactsObserver); */ } public static void dump() { Cache.dump(); } public static void startPresenceObserver() { Cache.getContext().getContentResolver().registerContentObserver( Presence.CONTENT_URI, true, sPresenceObserver); } public static void stopPresenceObserver() { Cache.getContext().getContentResolver().unregisterContentObserver(sPresenceObserver); } private static class Cache { private static Cache sInstance; static Cache getInstance() { return sInstance; } private final List<Contact> mCache; private final Context mContext; private Cache(Context context) { mCache = new ArrayList<Contact>(); mContext = context; } static void init(Context context) { sInstance = new Cache(context); } static Context getContext() { return sInstance.mContext; } static void dump() { synchronized (sInstance) { Log.d(TAG, "**** Contact cache dump ****"); for (Contact c : sInstance.mCache) { Log.d(TAG, c.toString()); } } } private static Contact getEmail(String number) { synchronized (sInstance) { for (Contact c : sInstance.mCache) { if (number.equalsIgnoreCase(c.mNumber)) { return c; } } return null; } } static Contact get(String number) { if (Mms.isEmailAddress(number)) return getEmail(number); synchronized (sInstance) { for (Contact c : sInstance.mCache) { // if the numbers are an exact match (i.e. Google SMS), or if the phone // number comparison returns a match, return the contact. if (number.equals(c.mNumber) || PhoneNumberUtils.compare(number, c.mNumber)) { return c; } } return null; } } static void put(Contact c) { synchronized (sInstance) { // We update cache entries in place so people with long- // held references get updated. if (get(c.mNumber) != null) { throw new IllegalStateException("cache already contains " + c); } sInstance.mCache.add(c); } } static String[] getNumbers() { synchronized (sInstance) { String[] numbers = new String[sInstance.mCache.size()]; int i = 0; for (Contact c : sInstance.mCache) { numbers[i++] = c.getNumber(); } return numbers; } } static List<Contact> getContacts() { synchronized (sInstance) { return new ArrayList<Contact>(sInstance.mCache); } } static void invalidate() { // Don't remove the contacts. Just mark them stale so we'll update their // info, particularly their presence. synchronized (sInstance) { for (Contact c : sInstance.mCache) { c.mIsStale = true; } } } } private static void log(String msg) { Log.d(TAG, msg); } }
true
true
private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } } } }
private static void updateContact(final Contact c) { if (c == null) { return; } ContactInfoCache cache = ContactInfoCache.getInstance(); ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber); synchronized (Cache.getInstance()) { if (contactChanged(c, entry)) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { log("updateContact: contact changed for " + entry.name); } //c.mNumber = entry.phoneNumber; c.mName = entry.name; c.updateNameAndNumber(); c.mLabel = entry.phoneLabel; c.mPersonId = entry.person_id; c.mPresenceResId = entry.presenceResId; c.mPresenceText = entry.presenceText; c.mAvatar = entry.mAvatar; c.mIsStale = false; // Check to see if this is the local ("me") number and update the name. handleLocalNumber(c); for (UpdateListener l : c.mListeners) { if (V) Log.d(TAG, "updating " + l); l.onUpdate(c); } } else { c.mIsStale = false; } } }
diff --git a/freeplane/src/org/freeplane/view/swing/map/NodeViewLayoutAdapter.java b/freeplane/src/org/freeplane/view/swing/map/NodeViewLayoutAdapter.java index 801fa8ff6..e997790ef 100644 --- a/freeplane/src/org/freeplane/view/swing/map/NodeViewLayoutAdapter.java +++ b/freeplane/src/org/freeplane/view/swing/map/NodeViewLayoutAdapter.java @@ -1,442 +1,443 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Dimitry Polivaev * * This file author is Dimitry Polivaev * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.view.swing.map; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import javax.swing.JComponent; import org.freeplane.features.cloud.CloudModel; import org.freeplane.features.map.NodeModel; import org.freeplane.view.swing.map.cloud.CloudView; abstract public class NodeViewLayoutAdapter implements INodeViewLayout { protected static class LayoutData{ final int[] lx; final int[] ly; int left; int childContentHeight; int top; boolean rightDataSet; boolean leftDataSet; public LayoutData(int childCount) { super(); this.lx = new int[childCount]; this.ly = new int[childCount]; this.left = 0; this.childContentHeight = 0; this.top = 0; rightDataSet = false; leftDataSet = false; } } private static Dimension minDimension; private int childCount; private JComponent content; protected final int LISTENER_VIEW_WIDTH = 10; protected Point location = new Point(); private NodeModel model; private int spaceAround; private int vGap; private NodeView view; private Dimension contentPreferredSize; private int contentWidth; public void addLayoutComponent(final String arg0, final Component arg1) { } /** * @return Returns the childCount. */ protected int getChildCount() { return childCount; } /** * @return Returns the content. */ protected JComponent getContent() { return content; } /** * @return Returns the model. */ protected NodeModel getModel() { return model; } /** * @return Returns the spaceAround. */ int getSpaceAround() { return spaceAround; } /** * @return Returns the vGap. */ int getVGap() { return vGap; } /** * @return Returns the view. */ protected NodeView getView() { return view; } abstract protected void layout(); public void layoutContainer(final Container c) { setUp(c); layout(); shutDown(); } /* * (non-Javadoc) * @see java.awt.LayoutManager#minimumLayoutSize(java.awt.Container) */ public Dimension minimumLayoutSize(final Container arg0) { if (NodeViewLayoutAdapter.minDimension == null) { NodeViewLayoutAdapter.minDimension = new Dimension(0, 0); } return NodeViewLayoutAdapter.minDimension; } /* * (non-Javadoc) * @see java.awt.LayoutManager#preferredLayoutSize(java.awt.Container) */ public Dimension preferredLayoutSize(final Container c) { if (!c.isValid()) { c.validate(); } return c.getSize(); } /* * (non-Javadoc) * @see java.awt.LayoutManager#removeLayoutComponent(java.awt.Component) */ public void removeLayoutComponent(final Component arg0) { } protected void setUp(final Container c) { final NodeView localView = (NodeView) c; final int localChildCount = localView.getComponentCount() - 1; for (int i = 0; i < localChildCount; i++) { final Component component = localView.getComponent(i); if (component instanceof NodeView) { ((NodeView) component).validateTree(); } else { component.validate(); } } view = localView; model = localView.getModel(); childCount = localChildCount; content = localView.getContent(); if (getModel().isVisible()) { setVGap(getView().getVGap()); } else { setVGap(getView().getVisibleParentView().getVGap()); } spaceAround = view.getSpaceAround(); if (view.isContentVisible()) { contentPreferredSize = getContent().getPreferredSize(); contentWidth = contentPreferredSize.width; } else { contentWidth = 0; } } protected void shutDown() { view = null; model = null; content = null; childCount = 0; setVGap(0); spaceAround = 0; } public void setVGap(final int vGap) { this.vGap = vGap; } /** * Calculates the tree height increment because of the clouds. */ public int getAdditionalCloudHeigth(final NodeView node) { if (!node.isContentVisible()) { return 0; } final CloudModel cloud = node.getCloudModel(); if (cloud != null) { return CloudView.getAdditionalHeigth(cloud, node); } else { return 0; } } protected void calcLayout(final boolean isLeft, final LayoutData data) { int highestSummaryLevel = 1; int level = 1; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } if(child.isSummary()){ level++; highestSummaryLevel = Math.max(highestSummaryLevel, level); } else{ level = 1; } } int left = 0; int y = 0; int childContentHeightSum = 0; int visibleChildCounter = 0; int top = 0; final int[] groupStart = new int[highestSummaryLevel]; final int[] groupStartContentHeightSum = new int[highestSummaryLevel]; final int[] groupStartVisibleChildCounter = new int[highestSummaryLevel]; final int[] groupStartY = new int[highestSummaryLevel]; final int[] groupEndY = new int[highestSummaryLevel]; final int summaryBaseX[] = new int[highestSummaryLevel]; level = highestSummaryLevel; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } final boolean isSummary = child.isSummary(); final boolean isItem = ! (isSummary && visibleChildCounter > 0); final int oldLevel = level; if(isItem){ level = 0; } else{ level++; } final int childCloudHeigth = getAdditionalCloudHeigth(child); final int childContentHeight = child.getContent().getHeight(); final int childShiftY = child.getShift(); final int childContentShift = child.getContent().getY() - getSpaceAround(); final int childHGap = child.getContent().isVisible() ? child.getHGap() : 0; final int childHeight = child.getHeight() - 2 * getSpaceAround(); if(isItem){ if (childShiftY < 0 || visibleChildCounter == 0) { top += childShiftY; } top -= childContentShift; y += childCloudHeigth/2; if (childShiftY < 0) { data.ly[i] = y; y -= childShiftY; } else { if(visibleChildCounter > 0) y += childShiftY; data.ly[i] = y; } if (childHeight != 0) { y += childHeight + getVGap() + childCloudHeigth/2; } childContentHeightSum += childContentHeight + childCloudHeigth; if (child.getHeight() - 2 * getSpaceAround() != 0) { if (visibleChildCounter > 0) childContentHeightSum += getVGap(); visibleChildCounter++; } if(oldLevel > 0){ summaryBaseX[0] = 0; for(int j = 0; j < oldLevel; j++){ groupStart[j] = i; groupStartY[j] = Integer.MAX_VALUE; groupEndY[j] = Integer.MIN_VALUE; groupStartContentHeightSum[j] = childContentHeightSum; groupStartVisibleChildCounter[j] = visibleChildCounter; } } else if(child.isFirstGroupNode()){ groupStartContentHeightSum[0] = childContentHeightSum; groupStartVisibleChildCounter[0] = visibleChildCounter; summaryBaseX[0] = 0; groupStart[0] = i; } } else{ final int itemLevel = level - 1; if(child.isFirstGroupNode()){ groupStartContentHeightSum[level] = groupStartContentHeightSum[itemLevel]; groupStartVisibleChildCounter[level] = groupStartVisibleChildCounter[itemLevel]; summaryBaseX[level] = 0; groupStart[level] = groupStart[itemLevel]; } int summaryY = (groupStartY[itemLevel] + groupEndY[itemLevel] ) / 2 - childContentHeight / 2 + childShiftY - (child.getContent().getY() - getSpaceAround()); data.ly[i] = summaryY; final int deltaY = summaryY -childCloudHeigth/2 - groupStartY[itemLevel]; if(deltaY < 0){ top += deltaY; y -= deltaY; + summaryY -= deltaY; for(int j = groupStart[itemLevel]; j <= i; j++){ NodeView groupItem = (NodeView) getView().getComponent(j); if(groupItem.isLeft() == isLeft) data.ly[j]-=deltaY; } } if (childHeight != 0) { summaryY += childHeight + getVGap() + childCloudHeigth/2; } y = Math.max(y, summaryY); final int summaryContentHeight = groupStartContentHeightSum[itemLevel] + childContentHeight; if(childContentHeightSum < summaryContentHeight){ childContentHeightSum = summaryContentHeight; } } if(child.isFirstGroupNode()){ groupStartY[level] = data.ly[i]-childCloudHeigth/2; groupEndY[level] = data.ly[i] + childHeight+childCloudHeigth/2; } else{ groupStartY[level] = Math.min(groupStartY[level],data.ly[i]-childCloudHeigth/2); groupEndY[level] = Math.max(data.ly[i] + childHeight+childCloudHeigth/2, groupEndY[level]); } final int x; final int baseX; if(level > 0) baseX = summaryBaseX[level - 1]; else{ if(child.isLeft()){ baseX = 0; } else{ baseX = contentWidth; } } if(child.isLeft()){ x = baseX - childHGap - child.getContent().getX() - child.getContent().getWidth(); summaryBaseX[level] = Math.min(summaryBaseX[level], x + getSpaceAround()); } else{ x = baseX + childHGap - child.getContent().getX(); summaryBaseX[level] = Math.max(summaryBaseX[level], x + child.getWidth() - getSpaceAround()); } left = Math.min(left, x); data.lx[i] = x; } if (getView().isContentVisible()) { final Dimension contentPreferredSize = getContent().getPreferredSize(); final int contentVerticalShift = (contentPreferredSize.height - childContentHeightSum) / 2; top += contentVerticalShift; } setData(data, isLeft, left, childContentHeightSum, top); } private void setData(final LayoutData data, boolean isLeft, int left, int childContentHeight, int top) { if(!isLeft && data.leftDataSet || isLeft && data.rightDataSet){ data.left = Math.min(data.left, left); data.childContentHeight = Math.max(data.childContentHeight, childContentHeight); int deltaTop = top - data.top; final boolean changeLeft; if(deltaTop < 0){ data.top = top; changeLeft = !isLeft; deltaTop = - deltaTop; } else{ changeLeft = isLeft; } for(int i = 0; i < getChildCount(); i++){ NodeView child = (NodeView) getView().getComponent(i); if(child.isLeft() == changeLeft){ data.ly[i] += deltaTop; } } } else{ data.left = left; data.childContentHeight = childContentHeight; data.top = top; } if(isLeft) data.leftDataSet = true; else data.rightDataSet = true; } protected void placeChildren(final LayoutData data) { final int contentHeight; final NodeView view = getView(); final int contentX = Math.max(getSpaceAround(), -data.left); final int contentY = getSpaceAround() + Math.max(0, -data.top); if (view.isContentVisible()) { contentHeight = contentPreferredSize.height; } else { contentHeight = data.childContentHeight; } if (getView().isContentVisible()) { getContent().setVisible(true); } else { getContent().setVisible(false); } getContent().setBounds(contentX, contentY, contentWidth, contentHeight); final int baseY = contentY - getSpaceAround() + data.top; int width = contentX + contentWidth + getSpaceAround(); int height = contentY + contentHeight + getSpaceAround(); for (int i = 0; i < getChildCount(); i++) { NodeView child = (NodeView) getView().getComponent(i); child.setLocation(contentX + data.lx[i], baseY + data.ly[i]); width = Math.max(width, child.getX() + child.getWidth()); height = Math.max(height, child.getY() + child.getHeight()+ getAdditionalCloudHeigth(child) / 2); } getView().setSize(width, height); } }
true
true
protected void calcLayout(final boolean isLeft, final LayoutData data) { int highestSummaryLevel = 1; int level = 1; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } if(child.isSummary()){ level++; highestSummaryLevel = Math.max(highestSummaryLevel, level); } else{ level = 1; } } int left = 0; int y = 0; int childContentHeightSum = 0; int visibleChildCounter = 0; int top = 0; final int[] groupStart = new int[highestSummaryLevel]; final int[] groupStartContentHeightSum = new int[highestSummaryLevel]; final int[] groupStartVisibleChildCounter = new int[highestSummaryLevel]; final int[] groupStartY = new int[highestSummaryLevel]; final int[] groupEndY = new int[highestSummaryLevel]; final int summaryBaseX[] = new int[highestSummaryLevel]; level = highestSummaryLevel; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } final boolean isSummary = child.isSummary(); final boolean isItem = ! (isSummary && visibleChildCounter > 0); final int oldLevel = level; if(isItem){ level = 0; } else{ level++; } final int childCloudHeigth = getAdditionalCloudHeigth(child); final int childContentHeight = child.getContent().getHeight(); final int childShiftY = child.getShift(); final int childContentShift = child.getContent().getY() - getSpaceAround(); final int childHGap = child.getContent().isVisible() ? child.getHGap() : 0; final int childHeight = child.getHeight() - 2 * getSpaceAround(); if(isItem){ if (childShiftY < 0 || visibleChildCounter == 0) { top += childShiftY; } top -= childContentShift; y += childCloudHeigth/2; if (childShiftY < 0) { data.ly[i] = y; y -= childShiftY; } else { if(visibleChildCounter > 0) y += childShiftY; data.ly[i] = y; } if (childHeight != 0) { y += childHeight + getVGap() + childCloudHeigth/2; } childContentHeightSum += childContentHeight + childCloudHeigth; if (child.getHeight() - 2 * getSpaceAround() != 0) { if (visibleChildCounter > 0) childContentHeightSum += getVGap(); visibleChildCounter++; } if(oldLevel > 0){ summaryBaseX[0] = 0; for(int j = 0; j < oldLevel; j++){ groupStart[j] = i; groupStartY[j] = Integer.MAX_VALUE; groupEndY[j] = Integer.MIN_VALUE; groupStartContentHeightSum[j] = childContentHeightSum; groupStartVisibleChildCounter[j] = visibleChildCounter; } } else if(child.isFirstGroupNode()){ groupStartContentHeightSum[0] = childContentHeightSum; groupStartVisibleChildCounter[0] = visibleChildCounter; summaryBaseX[0] = 0; groupStart[0] = i; } } else{ final int itemLevel = level - 1; if(child.isFirstGroupNode()){ groupStartContentHeightSum[level] = groupStartContentHeightSum[itemLevel]; groupStartVisibleChildCounter[level] = groupStartVisibleChildCounter[itemLevel]; summaryBaseX[level] = 0; groupStart[level] = groupStart[itemLevel]; } int summaryY = (groupStartY[itemLevel] + groupEndY[itemLevel] ) / 2 - childContentHeight / 2 + childShiftY - (child.getContent().getY() - getSpaceAround()); data.ly[i] = summaryY; final int deltaY = summaryY -childCloudHeigth/2 - groupStartY[itemLevel]; if(deltaY < 0){ top += deltaY; y -= deltaY; for(int j = groupStart[itemLevel]; j <= i; j++){ NodeView groupItem = (NodeView) getView().getComponent(j); if(groupItem.isLeft() == isLeft) data.ly[j]-=deltaY; } } if (childHeight != 0) { summaryY += childHeight + getVGap() + childCloudHeigth/2; } y = Math.max(y, summaryY); final int summaryContentHeight = groupStartContentHeightSum[itemLevel] + childContentHeight; if(childContentHeightSum < summaryContentHeight){ childContentHeightSum = summaryContentHeight; } } if(child.isFirstGroupNode()){ groupStartY[level] = data.ly[i]-childCloudHeigth/2; groupEndY[level] = data.ly[i] + childHeight+childCloudHeigth/2; } else{ groupStartY[level] = Math.min(groupStartY[level],data.ly[i]-childCloudHeigth/2); groupEndY[level] = Math.max(data.ly[i] + childHeight+childCloudHeigth/2, groupEndY[level]); } final int x; final int baseX; if(level > 0) baseX = summaryBaseX[level - 1]; else{ if(child.isLeft()){ baseX = 0; } else{ baseX = contentWidth; } } if(child.isLeft()){ x = baseX - childHGap - child.getContent().getX() - child.getContent().getWidth(); summaryBaseX[level] = Math.min(summaryBaseX[level], x + getSpaceAround()); } else{ x = baseX + childHGap - child.getContent().getX(); summaryBaseX[level] = Math.max(summaryBaseX[level], x + child.getWidth() - getSpaceAround()); } left = Math.min(left, x); data.lx[i] = x; } if (getView().isContentVisible()) { final Dimension contentPreferredSize = getContent().getPreferredSize(); final int contentVerticalShift = (contentPreferredSize.height - childContentHeightSum) / 2; top += contentVerticalShift; } setData(data, isLeft, left, childContentHeightSum, top); }
protected void calcLayout(final boolean isLeft, final LayoutData data) { int highestSummaryLevel = 1; int level = 1; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } if(child.isSummary()){ level++; highestSummaryLevel = Math.max(highestSummaryLevel, level); } else{ level = 1; } } int left = 0; int y = 0; int childContentHeightSum = 0; int visibleChildCounter = 0; int top = 0; final int[] groupStart = new int[highestSummaryLevel]; final int[] groupStartContentHeightSum = new int[highestSummaryLevel]; final int[] groupStartVisibleChildCounter = new int[highestSummaryLevel]; final int[] groupStartY = new int[highestSummaryLevel]; final int[] groupEndY = new int[highestSummaryLevel]; final int summaryBaseX[] = new int[highestSummaryLevel]; level = highestSummaryLevel; for (int i = 0; i < getChildCount(); i++) { final NodeView child = (NodeView) getView().getComponent(i); if (child.isLeft() != isLeft) { continue; } final boolean isSummary = child.isSummary(); final boolean isItem = ! (isSummary && visibleChildCounter > 0); final int oldLevel = level; if(isItem){ level = 0; } else{ level++; } final int childCloudHeigth = getAdditionalCloudHeigth(child); final int childContentHeight = child.getContent().getHeight(); final int childShiftY = child.getShift(); final int childContentShift = child.getContent().getY() - getSpaceAround(); final int childHGap = child.getContent().isVisible() ? child.getHGap() : 0; final int childHeight = child.getHeight() - 2 * getSpaceAround(); if(isItem){ if (childShiftY < 0 || visibleChildCounter == 0) { top += childShiftY; } top -= childContentShift; y += childCloudHeigth/2; if (childShiftY < 0) { data.ly[i] = y; y -= childShiftY; } else { if(visibleChildCounter > 0) y += childShiftY; data.ly[i] = y; } if (childHeight != 0) { y += childHeight + getVGap() + childCloudHeigth/2; } childContentHeightSum += childContentHeight + childCloudHeigth; if (child.getHeight() - 2 * getSpaceAround() != 0) { if (visibleChildCounter > 0) childContentHeightSum += getVGap(); visibleChildCounter++; } if(oldLevel > 0){ summaryBaseX[0] = 0; for(int j = 0; j < oldLevel; j++){ groupStart[j] = i; groupStartY[j] = Integer.MAX_VALUE; groupEndY[j] = Integer.MIN_VALUE; groupStartContentHeightSum[j] = childContentHeightSum; groupStartVisibleChildCounter[j] = visibleChildCounter; } } else if(child.isFirstGroupNode()){ groupStartContentHeightSum[0] = childContentHeightSum; groupStartVisibleChildCounter[0] = visibleChildCounter; summaryBaseX[0] = 0; groupStart[0] = i; } } else{ final int itemLevel = level - 1; if(child.isFirstGroupNode()){ groupStartContentHeightSum[level] = groupStartContentHeightSum[itemLevel]; groupStartVisibleChildCounter[level] = groupStartVisibleChildCounter[itemLevel]; summaryBaseX[level] = 0; groupStart[level] = groupStart[itemLevel]; } int summaryY = (groupStartY[itemLevel] + groupEndY[itemLevel] ) / 2 - childContentHeight / 2 + childShiftY - (child.getContent().getY() - getSpaceAround()); data.ly[i] = summaryY; final int deltaY = summaryY -childCloudHeigth/2 - groupStartY[itemLevel]; if(deltaY < 0){ top += deltaY; y -= deltaY; summaryY -= deltaY; for(int j = groupStart[itemLevel]; j <= i; j++){ NodeView groupItem = (NodeView) getView().getComponent(j); if(groupItem.isLeft() == isLeft) data.ly[j]-=deltaY; } } if (childHeight != 0) { summaryY += childHeight + getVGap() + childCloudHeigth/2; } y = Math.max(y, summaryY); final int summaryContentHeight = groupStartContentHeightSum[itemLevel] + childContentHeight; if(childContentHeightSum < summaryContentHeight){ childContentHeightSum = summaryContentHeight; } } if(child.isFirstGroupNode()){ groupStartY[level] = data.ly[i]-childCloudHeigth/2; groupEndY[level] = data.ly[i] + childHeight+childCloudHeigth/2; } else{ groupStartY[level] = Math.min(groupStartY[level],data.ly[i]-childCloudHeigth/2); groupEndY[level] = Math.max(data.ly[i] + childHeight+childCloudHeigth/2, groupEndY[level]); } final int x; final int baseX; if(level > 0) baseX = summaryBaseX[level - 1]; else{ if(child.isLeft()){ baseX = 0; } else{ baseX = contentWidth; } } if(child.isLeft()){ x = baseX - childHGap - child.getContent().getX() - child.getContent().getWidth(); summaryBaseX[level] = Math.min(summaryBaseX[level], x + getSpaceAround()); } else{ x = baseX + childHGap - child.getContent().getX(); summaryBaseX[level] = Math.max(summaryBaseX[level], x + child.getWidth() - getSpaceAround()); } left = Math.min(left, x); data.lx[i] = x; } if (getView().isContentVisible()) { final Dimension contentPreferredSize = getContent().getPreferredSize(); final int contentVerticalShift = (contentPreferredSize.height - childContentHeightSum) / 2; top += contentVerticalShift; } setData(data, isLeft, left, childContentHeightSum, top); }
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/RpcStatus.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/RpcStatus.java index 713df5a08..6f18da3a2 100644 --- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/RpcStatus.java +++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/RpcStatus.java @@ -1,70 +1,70 @@ // Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwtjsonrpc.client.event.RpcCompleteEvent; import com.google.gwtjsonrpc.client.event.RpcCompleteHandler; import com.google.gwtjsonrpc.client.event.RpcStartEvent; import com.google.gwtjsonrpc.client.event.RpcStartHandler; public class RpcStatus implements RpcStartHandler, RpcCompleteHandler { private static int hideDepth; /** Execute code, hiding the RPCs they execute from being shown visually. */ public static void hide(final Runnable run) { try { hideDepth++; run.run(); } finally { hideDepth--; } } private final Label loading; private int activeCalls; RpcStatus(final Panel p) { final FlowPanel r = new FlowPanel(); r.setStyleName(Gerrit.RESOURCES.css().rpcStatusPanel()); p.add(r); loading = new InlineLabel(); loading.setText(Gerrit.C.rpcStatusLoading()); loading.setStyleName(Gerrit.RESOURCES.css().rpcStatus()); - loading.addStyleDependentName("Loading"); + loading.addStyleName(Gerrit.RESOURCES.css().rpcStatusLoading()); loading.setVisible(false); r.add(loading); } @Override public void onRpcStart(final RpcStartEvent event) { if (++activeCalls == 1) { if (hideDepth == 0) { loading.setVisible(true); } } } @Override public void onRpcComplete(final RpcCompleteEvent event) { if (--activeCalls == 0) { loading.setVisible(false); } } }
true
true
RpcStatus(final Panel p) { final FlowPanel r = new FlowPanel(); r.setStyleName(Gerrit.RESOURCES.css().rpcStatusPanel()); p.add(r); loading = new InlineLabel(); loading.setText(Gerrit.C.rpcStatusLoading()); loading.setStyleName(Gerrit.RESOURCES.css().rpcStatus()); loading.addStyleDependentName("Loading"); loading.setVisible(false); r.add(loading); }
RpcStatus(final Panel p) { final FlowPanel r = new FlowPanel(); r.setStyleName(Gerrit.RESOURCES.css().rpcStatusPanel()); p.add(r); loading = new InlineLabel(); loading.setText(Gerrit.C.rpcStatusLoading()); loading.setStyleName(Gerrit.RESOURCES.css().rpcStatus()); loading.addStyleName(Gerrit.RESOURCES.css().rpcStatusLoading()); loading.setVisible(false); r.add(loading); }
diff --git a/geogebra/geogebra3D/euclidian3D/opengl/Renderer.java b/geogebra/geogebra3D/euclidian3D/opengl/Renderer.java index 6c95519f6..935b84372 100644 --- a/geogebra/geogebra3D/euclidian3D/opengl/Renderer.java +++ b/geogebra/geogebra3D/euclidian3D/opengl/Renderer.java @@ -1,2051 +1,2053 @@ package geogebra3D.euclidian3D.opengl; import geogebra.euclidian.EuclidianView; import geogebra.main.Application; import geogebra3D.Matrix.Ggb3DMatrix; import geogebra3D.Matrix.Ggb3DMatrix4x4; import geogebra3D.Matrix.Ggb3DVector; import geogebra3D.euclidian3D.DrawList3D; import geogebra3D.euclidian3D.Drawable3D; import geogebra3D.euclidian3D.EuclidianController3D; import geogebra3D.euclidian3D.EuclidianView3D; import geogebra3D.euclidian3D.Hits3D; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.nio.ByteBuffer; import java.nio.IntBuffer; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import javax.media.opengl.glu.GLUtessellator; import com.sun.opengl.util.BufferUtil; import com.sun.opengl.util.FPSAnimator; import com.sun.opengl.util.j2d.TextRenderer; /** * * Used for openGL display. * <p> * It provides: * <ul> * <li> methods for displaying {@link Drawable3D}, with painting parameters </li> * <li> methods for picking object </li> * </ul> * * @author ggb3D * * * */ public class Renderer implements GLEventListener { // openGL variables private GLU glu= new GLU(); //private GLUT glut = new GLUT(); private TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.BOLD, 16)); /** default text scale factor */ private static final float DEFAULT_TEXT_SCALE_FACTOR = 0.8f; /** matrix changing Y-direction to Z-direction */ //private double[] matrixYtoZ = {1,0,0,0, 0,0,1,0, 0,1,0,0, 0,0,0,1}; /** canvas usable for a JPanel */ public GLCanvas canvas; //public GLJPanel canvas; private GLCapabilities caps; private GL gl; private GLUquadric quadric; private FPSAnimator animator; /** for polygon tesselation */ private GLUtessellator tobj; private IntBuffer selectBuffer; private int BUFSIZE = 512; private static int MOUSE_PICK_WIDTH = 3; Drawable3D[] drawHits; int pickingLoop; // other private DrawList3D drawList3D; private EuclidianView3D view3D; // for drawing private Ggb3DMatrix4x4 m_drawingMatrix; //matrix for drawing /////////////////// //primitives //private RendererPrimitives primitives; /////////////////// //geometries private Manager geometryManager; /////////////////// //dash /** opengl organization of the dash textures */ private int[] texturesDash; /** number of dash styles */ private int DASH_NUMBER = 3; /** no dash. */ static public int DASH_NONE = -1; /** simple dash: 1-(1), ... */ static public int DASH_SIMPLE = 0; /** dotted dash: 1-(3), ... */ static public int DASH_DOTTED = 1; /** dotted/dashed dash: 7-(4)-1-(4), ... */ static public int DASH_DOTTED_DASHED = 2; /** description of the dash styles */ static private boolean[][] DASH_DESCRIPTION = { {true, false}, // DASH_SIMPLE {true, false, false, false}, // DASH_DOTTED {true,true,true,true, true,true,true,false, false,false,false,true, false,false,false,false} // DASH_DOTTED_DASHED }; /** # of the dash */ private int dash = DASH_NONE; /** scale factor for dash */ private float dashScale = 1f; ///////////////////// // spencil attributes /** current drawing color {r,g,b} */ private Color color; /** current alpha blending */ private double alpha; /** current text color {r,g,b} */ private Color textColor; private double thickness; /////////////////// // arrows /** no arrows */ static final public int ARROW_TYPE_NONE=0; /** simple arrows */ static final public int ARROW_TYPE_SIMPLE=1; private int m_arrowType=ARROW_TYPE_NONE; private double m_arrowLength, m_arrowWidth; /////////////////// // dilation private static final int DILATION_NONE = 0; private static final int DILATION_HIGHLITED = 1; private int dilation = DILATION_NONE; private double[] dilationValues = { 1, // DILATION_NONE 1.3 // DILATION_HIGHLITED }; /////////////////// // for picking private int mouseX, mouseY; private boolean waitForPick = false; private boolean doPick = false; public static final int PICKING_MODE_OBJECTS = 0; public static final int PICKING_MODE_LABELS = 1; private int pickingMode = PICKING_MODE_OBJECTS; /** * creates a renderer linked to an {@link EuclidianView3D} * @param view the {@link EuclidianView3D} linked to */ public Renderer(EuclidianView3D view){ super(); caps = new GLCapabilities(); //anti-aliasing caps.setSampleBuffers(true);caps.setNumSamples(4); //caps.setSampleBuffers(false); //avoid flickering caps.setDoubleBuffered(true); //canvas canvas = new GLCanvas(caps); //canvas = new GLJPanel(caps); canvas.addGLEventListener(this); //animator : 60 frames per second animator = new FPSAnimator( canvas, 60 ); animator.setRunAsFastAsPossible(true); //animator.setRunAsFastAsPossible(false); animator.start(); //link to 3D view this.view3D=view; } /** * set the list of {@link Drawable3D} to be drawn * @param dl list of {@link Drawable3D} */ public void setDrawList3D(DrawList3D dl){ drawList3D = dl; } /** * re-calc the display immediately */ public void display(){ canvas.display(); } /** sets if openGL culling is done or not * @param flag */ public void setCulling(boolean flag){ if (flag) gl.glEnable(GL.GL_CULL_FACE); else gl.glDisable(GL.GL_CULL_FACE); } /** * * openGL method called when the display is to be computed. * <p> * First, it calls {@link #doPick()} if a picking is to be done. * Then, for each {@link Drawable3D}, it calls: * <ul> * <li> {@link Drawable3D#drawHidden(EuclidianRenderer3D)} to draw hidden parts (dashed segments, lines, ...) </li> * <li> {@link Drawable3D#drawHighlightingPointsAndCurves(EuclidianRenderer3D)} to show objects that are picked (highlighted) </li> * <li> {@link Drawable3D#drawTransp(EuclidianRenderer3D)} to draw transparent objects (planes, spheres, ...) </li> * <li> {@link Drawable3D#drawSurfacesForHiding(EuclidianRenderer3D)} to draw in the z-buffer objects that hides others (planes, spheres, ...) </li> * <li> {@link Drawable3D#drawTransp(EuclidianRenderer3D)} to re-draw transparent objects for a better alpha-blending </li> * <li> {@link Drawable3D#draw(EuclidianRenderer3D)} to draw not hidden parts (dash-less segments, lines, ...) </li> * </ul> */ public void display(GLAutoDrawable gLDrawable) { //Application.debug("display"); //double displayTime = System.currentTimeMillis(); gl = gLDrawable.getGL(); //picking if(waitForPick){ doPick(); //Application.debug("doPick"); //return; } gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glClear(GL.GL_DEPTH_BUFFER_BIT); //start drawing viewOrtho(); //update 3D controller ((EuclidianController3D) view3D.getEuclidianController()).processMouseMoved(); // update 3D view view3D.update(); view3D.updateDrawablesNow(); // update 3D drawables drawList3D.updateAll(); //init drawing matrix to view3D toScreen matrix gl.glLoadMatrixd(view3D.getToScreenMatrix().get(),0); //drawing the cursor view3D.drawCursor(this); //primitives.enableVBO(gl); //drawing hidden part gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts //gl.glDisable(GL.GL_BLEND); drawList3D.drawHidden(this); gl.glDisable(GL.GL_ALPHA_TEST); //drawing highlighted parts -- points and curves - gl.glDepthMask(false); + //gl.glDepthMask(false); //setMaterial(new Color(0f,0f,0f),0.75f); dilation = DILATION_HIGHLITED; gl.glCullFace(GL.GL_FRONT); //draws inside parts - gl.glEnable(GL.GL_BLEND); + //gl.glEnable(GL.GL_BLEND); drawList3D.drawHighlightingPointsAndCurves(this); dilation = DILATION_NONE; //drawing highlighted parts -- surfaces + gl.glDepthMask(false); + gl.glEnable(GL.GL_BLEND); gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawHighlightingSurfaces(this); //drawing transparents parts gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing labels gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_BLEND); drawList3D.drawLabel(this); gl.glEnable(GL.GL_LIGHTING); gl.glDisable(GL.GL_ALPHA_TEST); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glCullFace(GL.GL_FRONT); //draws inside parts drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces back-faces gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawSurfacesForHiding(this); //non closed surfaces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glDisable(GL.GL_BLEND); gl.glCullFace(GL.GL_BACK); //draws inside parts gl.glEnable(GL.GL_CULL_FACE); drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces front-faces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing not hidden parts gl.glEnable(GL.GL_CULL_FACE); gl.glDisable(GL.GL_BLEND); drawList3D.draw(this); //primitives.disableVBO(gl); //FPS /* gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_DEPTH_TEST); drawFPS(); gl.glEnable(GL.GL_DEPTH_TEST); gl.glEnable(GL.GL_LIGHTING); */ gLDrawable.swapBuffers(); //TODO //Application.debug("display : "+((int) (System.currentTimeMillis()-displayTime))); } /** * openGL method called when the canvas is reshaped. */ public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { GL gl = drawable.getGL(); //Application.debug("reshape\n x = "+x+"\n y = "+y+"\n w = "+w+"\n h = "+h); viewOrtho(x,y,w,h); view3D.setWaitForUpdate(); } /** * openGL method called when the display change. * empty method */ public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } /////////////////////////////////////////////////// // // pencil methods // ///////////////////////////////////////////////////// /** sets the color of the text * @param c color of the text */ public void setTextColor(Color c){ textColor = c; } /** * sets the material used by the pencil * * @param c the color of the pencil * @param alpha the alpha value for blending */ public void setColor(Color c, double alpha){ color = c; this.alpha = alpha; gl.glColor4f(((float) c.getRed())/256f, ((float) c.getGreen())/256f, ((float) c.getBlue())/256f, (float) alpha); /* gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, new float[] {((float) c.getRed())/256f, ((float) c.getGreen())/256f, ((float) c.getBlue())/256f, (float) alpha}, 0); */ } /** return (r,g,b) current color * @return (r,g,b) current color */ public Color getColor(){ return color; } /** return current alpha * @return current alpha */ public double getAlpha(){ return alpha; } /** * sets the thickness used by the pencil. * * @param a_thickness the thickness */ public void setThickness(double a_thickness){ this.thickness = a_thickness; } /** * gets the current thickness of the pencil. * * @return the thickness */ public double getThickness(){ return thickness; } //arrows /** * sets the type of arrow used by the pencil. * * @param a_arrowType type of arrow, see {@link #ARROW_TYPE_NONE}, {@link #ARROW_TYPE_SIMPLE}, ... */ public void setArrowType(int a_arrowType){ m_arrowType = a_arrowType; } /** * sets the width of the arrows painted by the pencil. * * @param a_arrowWidth the width of the arrows */ public void setArrowWidth(double a_arrowWidth){ m_arrowWidth = a_arrowWidth; } /** * sets the length of the arrows painted by the pencil. * * @param a_arrowLength the length of the arrows */ public void setArrowLength(double a_arrowLength){ m_arrowLength = a_arrowLength; } //layer /** * sets the layer to l. Use gl.glPolygonOffset( ). * @param l the layer */ public void setLayer(float l){ // 0<=l<10 // l2-l1>=1 to see something gl.glPolygonOffset(-l*0.05f, -l*10); } //drawing matrix /** * sets the matrix in which coord sys the pencil draws. * * @param a_matrix the matrix */ public void setMatrix(Ggb3DMatrix4x4 a_matrix){ m_drawingMatrix=a_matrix; } /** * gets the matrix describing the coord sys used by the pencil. * * @return the matrix */ public Ggb3DMatrix4x4 getMatrix(){ return m_drawingMatrix; } /** * sets the drawing matrix to openGL. * same as initMatrix(m_drawingMatrix) */ public void initMatrix(){ initMatrix(m_drawingMatrix); } /** * sets a_drawingMatrix to openGL. * @param a_drawingMatrix the matrix */ private void initMatrix(Ggb3DMatrix a_drawingMatrix){ initMatrix(a_drawingMatrix.get()); } /** * sets a_drawingMatrix to openGL. * @param a_drawingMatrix the matrix */ private void initMatrix(double[] a_drawingMatrix){ gl.glPushMatrix(); gl.glMultMatrixd(a_drawingMatrix,0); } /** * turn off the last drawing matrix set in openGL. */ public void resetMatrix(){ gl.glPopMatrix(); } //////////////////////////////////////////// // // TEXTURES // //////////////////////////////////////////// private void initTextures(){ gl.glEnable(GL.GL_TEXTURE_2D); // dash textures texturesDash = new int[DASH_NUMBER]; gl.glGenTextures(DASH_NUMBER, texturesDash, 0); for(int i=0; i<DASH_NUMBER; i++) initDashTexture(texturesDash[i],DASH_DESCRIPTION[i]); gl.glDisable(GL.GL_TEXTURE_2D); } // dash private void initDashTexture(int n, boolean[] description){ //int sizeX = 1; //int sizeY = description.length; int sizeX = description.length; int sizeY = 1; byte[] bytes = new byte[4*sizeX*sizeY]; // if description[i]==true, then texture is white opaque, else is transparent for (int i=0; i<sizeX; i++) if (description[i]) bytes[4*i+0]= bytes[4*i+1]= bytes[4*i+2]= bytes[4*i+3]= (byte) 255; ByteBuffer buf = ByteBuffer.wrap(bytes); gl.glBindTexture(GL.GL_TEXTURE_2D, n); gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MAG_FILTER,GL.GL_NEAREST); gl.glTexParameteri(GL.GL_TEXTURE_2D,GL.GL_TEXTURE_MIN_FILTER,GL.GL_NEAREST); //TODO use gl.glTexImage1D gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, 4, sizeX, sizeY, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buf); } /** * sets the dash used by the pencil. * * @param dash # of the dash, see EuclidianView, ... */ public void setDash(int dash){ switch (dash) { case EuclidianView.LINE_TYPE_DOTTED: this.dash=DASH_DOTTED; dashScale = 0.08f; break; case EuclidianView.LINE_TYPE_DASHED_SHORT: this.dash=DASH_SIMPLE; dashScale = 0.08f; break; case EuclidianView.LINE_TYPE_DASHED_LONG: this.dash=DASH_SIMPLE; dashScale = 0.04f; break; case EuclidianView.LINE_TYPE_DASHED_DOTTED: this.dash=DASH_DOTTED_DASHED; dashScale = 0.04f; break; default: // EuclidianView.LINE_TYPE_FULL this.dash = DASH_NONE; } } /////////////////////////////////////////////////////////// //drawing geometries public Manager getGeometryManager(){ return geometryManager; } /** * draws a segment from x=x1 to x=x2 according to drawing matrix * * @param a_x1 start of the segment * @param a_x2 end of the segment * */ public void drawSegment(double a_x1, double a_x2){ switch(m_arrowType){ case ARROW_TYPE_NONE: default: drawSegment(a_x1, a_x2, dash!=DASH_NONE); break; case ARROW_TYPE_SIMPLE: double x3=a_x2-m_arrowLength/(m_drawingMatrix.getUnit(Ggb3DMatrix4x4.X_AXIS)*view3D.getScale()); double thickness = getThickness(); setThickness(m_arrowWidth); drawCone(x3,a_x2); setThickness(thickness); if (x3>a_x1) drawSegment(a_x1, x3, dash!=DASH_NONE); break; } } private void drawSegment(double a_x1, double a_x2, boolean dashed){ initMatrix(m_drawingMatrix.segmentX(a_x1, a_x2)); if (dashed){ gl.glEnable(GL.GL_TEXTURE_2D); //TODO use object properties gl.glBindTexture(GL.GL_TEXTURE_2D, texturesDash[dash]); gl.glMatrixMode(GL.GL_TEXTURE); gl.glLoadIdentity(); float b = (float) (dashScale*(a_x2-a_x1)*m_drawingMatrix.getUnit(Ggb3DMatrix4x4.X_AXIS)*view3D.getScale()); float a = 0.75f/b-0.5f; gl.glScalef(b,1f,1f); gl.glTranslatef(a,0f,0f); gl.glMatrixMode(GL.GL_MODELVIEW); } double s = thickness*dilationValues[dilation]/view3D.getScale(); gl.glScaled(1,s,s); // primitives.segment(gl, (int) thickness); geometryManager.cylinder.draw(); if (dashed) gl.glDisable(GL.GL_TEXTURE_2D); resetMatrix(); } /** * draws a segment from x=0 to x=1 according to current drawing matrix. */ public void drawSegment(){ drawSegment(0,1); } /** * draws "coordinates segments" from the point origin of the drawing matrix to the axes * @param axisX color of the x axis * @param axisY color of the y axis * @param axisZ color of the z axis */ public void drawCoordSegments(Color axisX, Color axisY, Color axisZ){ Ggb3DMatrix4x4 drawingMatrixOld = m_drawingMatrix; Color colorOld = getColor(); double alphaOld = getAlpha(); Ggb3DMatrix4x4 matrix = new Ggb3DMatrix4x4(); matrix.setOrigin(m_drawingMatrix.getOrigin()); matrix.set(3,4,0); //sets the origin's altitude to 0 // z-segment double altitude = m_drawingMatrix.getOrigin().get(3);//altitude du point matrix.setVx((Ggb3DVector) EuclidianView3D.vz.mul(altitude)); if(altitude>0){ matrix.setVy(EuclidianView3D.vx); matrix.setVz(EuclidianView3D.vy); }else{ matrix.setVy(EuclidianView3D.vy); matrix.setVz(EuclidianView3D.vx); } setColor(axisZ, 1); setMatrix(matrix); drawSegment(); resetMatrix(); // x-segment double x = m_drawingMatrix.getOrigin().get(1);//x-coord of the point matrix.setVx((Ggb3DVector) EuclidianView3D.vx.mul(-x)); if(x>0){ matrix.setVy(EuclidianView3D.vz); matrix.setVz(EuclidianView3D.vy); }else{ matrix.setVy(EuclidianView3D.vy); matrix.setVz(EuclidianView3D.vz); } setColor(axisX, 1); setMatrix(matrix); drawSegment(); resetMatrix(); // y-segment double y = m_drawingMatrix.getOrigin().get(2);//y-coord of the point matrix.setVx((Ggb3DVector) EuclidianView3D.vy.mul(-y)); if(y>0){ matrix.setVy(EuclidianView3D.vx); matrix.setVz(EuclidianView3D.vz); }else{ matrix.setVy(EuclidianView3D.vz); matrix.setVz(EuclidianView3D.vx); } setColor(axisY, 1); setMatrix(matrix); drawSegment(); resetMatrix(); // reset the drawing matrix and color setMatrix(drawingMatrixOld); setColor(colorOld, alphaOld); } /** * draws a ray (half-line) according drawing matrix. */ /* public void drawRay(){ //TODO use frustum drawSegment(0,21); } */ /** draws a cone from x=x1 to x=x2 according to current drawing matrix. * @param a_x1 x-coordinate of the basis * @param a_x2 x-coordinate of the top */ public void drawCone(double a_x1, double a_x2){ initMatrix(m_drawingMatrix.segmentX(a_x1, a_x2)); double s = thickness*dilationValues[dilation]/view3D.getScale(); gl.glScaled(1,s,s); geometryManager.cone.draw(); resetMatrix(); } /** draws a quad according to current drawing matrix. * @param a_x1 x-coordinate of the top-left corner * @param a_y1 y-coordinate of the top-left corner * @param a_x2 x-coordinate of the bottom-right corner * @param a_y2 y-coordinate of the bottom-right corner */ public void drawQuad(double a_x1, double a_y1, double a_x2, double a_y2){ initMatrix(m_drawingMatrix.quad(a_x1, a_y1, a_x2, a_y2)); drawQuad(); resetMatrix(); } /** * draws a plane */ public void drawPlane(){ initMatrix(); geometryManager.plane.draw(); resetMatrix(); } /** draws a grid according to current drawing matrix. * @param a_x1 x-coordinate of the top-left corner * @param a_y1 y-coordinate of the top-left corner * @param a_x2 x-coordinate of the bottom-right corner * @param a_y2 y-coordinate of the bottom-right corner * @param a_dx distance between two x-lines * @param a_dy distance between two y-lines */ public void drawGrid(double a_x1, double a_y1, double a_x2, double a_y2, double a_dx, double a_dy){ double xmin, xmax; if (a_x1<a_x2){ xmin=a_x1; xmax=a_x2; }else{ xmin=a_x2; xmax=a_x1; } double ymin, ymax; if (a_y1<a_y2){ ymin=a_y1; ymax=a_y2; }else{ ymin=a_y2; ymax=a_y1; } int nXmin= (int) Math.ceil(xmin/a_dx); int nXmax= (int) Math.floor(xmax/a_dx); int nYmin= (int) Math.ceil(ymin/a_dy); int nYmax= (int) Math.floor(ymax/a_dy); //Application.debug("n = "+nXmin+","+nXmax+","+nYmin+","+nYmax); Ggb3DMatrix4x4 matrix = new Ggb3DMatrix4x4(); matrix.set(getMatrix()); for (int i=nYmin; i<=nYmax; i++){ setMatrix(matrix.translateY(i*a_dy)); drawSegment(xmin, xmax); } setMatrix(matrix); matrix.set(getMatrix()); Ggb3DMatrix4x4 matrix2 = matrix.mirrorXY(); for (int i=nXmin; i<=nXmax; i++){ setMatrix(matrix2.translateY(i*a_dx)); drawSegment(ymin, ymax); } setMatrix(matrix); } /** * draws a sphere according to current drawing matrix. * * @param radius radius of the sphere */ public void drawSphere(float radius){ initMatrix(); double s = radius/view3D.getScale(); gl.glScaled(s,s,s); //primitives.point(gl,size); geometryManager.point.draw(); //primitives.drawSphere(gl,radius/view3D.getScale(),16,16); resetMatrix(); } /** * draws a point according to current drawing matrix. * * @param radius radius of the point */ public void drawPoint(int size){ initMatrix(); double s = size*dilationValues[dilation]/view3D.getScale(); gl.glScaled(s,s,s); geometryManager.point.draw(); resetMatrix(); } /** draws a 2D cross cursor */ public void drawCursorCross2D(){ gl.glDisable(GL.GL_LIGHTING); initMatrix(); geometryManager.cursor.draw(); resetMatrix(); gl.glEnable(GL.GL_LIGHTING); } /** draws a 3D cross cursor */ public void drawCursorCross3D(){ gl.glDisable(GL.GL_LIGHTING); initMatrix(); //gl.glScalef(10f, 10f, 10f); geometryManager.cursor.draw(GeometryCursor.TYPE_CROSS3D); resetMatrix(); gl.glEnable(GL.GL_LIGHTING); } /** draws a cylinder cursor */ public void drawCursorCylinder(){ gl.glDisable(GL.GL_LIGHTING); initMatrix(); geometryManager.cursor.draw(GeometryCursor.TYPE_CYLINDER); resetMatrix(); gl.glEnable(GL.GL_LIGHTING); } /** draws a diamond cursor * */ public void drawCursorDiamond(){ gl.glDisable(GL.GL_LIGHTING); initMatrix(); geometryManager.cursor.draw(GeometryCursor.TYPE_DIAMOND); resetMatrix(); gl.glEnable(GL.GL_LIGHTING); } /** * set the tesselator to start drawing a new polygon * @param cullFace says if the faces have to be culled */ public int startPolygon(float nx, float ny, float nz){ return geometryManager.startPolygon(nx,ny,nz); } /** add the (x,y) point as a new vertex for the current polygon * @param x x-coordinate * @param y y-coordinate */ public void addToPolygon(double x, double y){ addToPolygon(x, y, 0); } //TODO remove this /** add the (x,y,z) point as a new vertex for the current polygon * @param x x-coordinate * @param y y-coordinate * @param z z-coordinate */ public void addToPolygon(double x, double y, double z){ geometryManager.addVertexToPolygon(x, y, z); } /** * end of the current polygon * @param cullFace says if the faces have been culled */ public void endPolygon(){ geometryManager.endPolygon(); } public void removePolygon(int index){ if (geometryManager!=null) geometryManager.remove(index); } public void drawPolygon(int index){ geometryManager.draw(index); } /** * draw a circle with center (x,y) and radius R * @param x x coord of the center * @param y y coord of the center * @param R radius */ public void drawCircle(double x, double y, double R){ initMatrix(); drawCircleArcDashedOrNot((float) x, (float) y, (float) R, 0, 2f * (float) Math.PI, dash!=0); resetMatrix(); } /** * draw a circle with center (x,y) and radius R * @param x x coord of the center * @param y y coord of the center * @param R radius * @param startAngle starting angle for the arc * @param endAngle ending angle for the arc * @param dash says if the circle is dashed */ private void drawCircleArcDashedOrNot(float x, float y, float R, float startAngle, float endAngle, boolean dash){ if (!dash) drawCircleArcNotDashed(x, y, R, startAngle, endAngle); else drawCircleArcNotDashed(x,y,R, startAngle, endAngle); } /** * draw a dashed circle with center (x,y) and radius R * @param x x coord of the center * @param y y coord of the center * @param R radius * @param startAngle starting angle for the arc * @param endAngle ending angle for the arc */ /* private void drawCircleArcDashed(float x, float y, float R, float startAngle, float endAngle){ m_dash_factor = 1/(R*m_drawingMatrix.getUnit(Ggb3DMatrix4x4.X_AXIS)); for(double l1=startAngle; l1<endAngle;){ double l2=l1; for(int i=0; (i<m_dash.length)&&(l1<endAngle); i++){ l2=l1+m_dash_factor*m_dash[i][0]; if (l2>endAngle) l2=endAngle; //Application.debug("l1,l2="+l1+","+l2); drawCircleArcNotDashed(x,y,R,(float) l1, (float) l2); l1=l2+m_dash_factor*m_dash[i][1]; } } } */ /** * draw a dashed circle with center (x,y) and radius R * @param x x coord of the center * @param y y coord of the center * @param R radius * @param startAngle starting angle for the arc * @param endAngle ending angle for the arc */ private void drawCircleArcNotDashed(float x, float y, float R, float startAngle, float endAngle){ int nsides = 16; //TODO use thickness int rings = (int) (60*(endAngle-startAngle)) +2; drawTorusArc(x, y, R, startAngle, endAngle, nsides, rings); } /** * draw a torus arc (using getThickness() for thickness) * @param x x coord of the center of the torus * @param y y coord of the center of the torus * @param R radius of the torus * @param startAngle starting angle for the arc * @param endAngle ending angle for the arc * @param nsides number of sides in a ring * @param rings number of rings */ private void drawTorusArc(float x, float y, float R, float startAngle, float endAngle, int nsides, int rings) { float r = (float) getThickness(); float ringDelta = (endAngle-startAngle) / rings; float sideDelta = 2.0f * (float) Math.PI / nsides; float theta = startAngle; float cosTheta = (float) Math.cos(theta); float sinTheta = (float) Math.sin(theta); for (int i = rings - 1; i >= 0; i--) { float theta1 = theta + ringDelta; float cosTheta1 = (float) Math.cos(theta1); float sinTheta1 = (float) Math.sin(theta1); gl.glBegin(GL.GL_QUAD_STRIP); float phi = 0.0f; for (int j = nsides; j >= 0; j--) { phi += sideDelta; float cosPhi = (float) Math.cos(phi); float sinPhi = (float) Math.sin(phi); float dist = R + r * cosPhi; gl.glNormal3f(cosTheta1 * cosPhi, sinTheta1 * cosPhi, -sinPhi); gl.glVertex3f(x+cosTheta1 * dist, y+sinTheta1 * dist, r * -sinPhi); gl.glNormal3f(cosTheta * cosPhi, sinTheta * cosPhi, -sinPhi); gl.glVertex3f(x+cosTheta * dist, y+sinTheta * dist, r * -sinPhi); } gl.glEnd(); theta = theta1; cosTheta = cosTheta1; sinTheta = sinTheta1; } } /////////////////////////////////////////////////////////// //drawing primitives TODO use VBO private void drawCylinder(double radius, int latitude){ gl.glScaled(1, radius, radius); float dt = (float) 1/latitude; float da = (float) (2*Math.PI *dt) ; gl.glBegin(GL.GL_QUADS); for( int i = 0; i < latitude + 1 ; i++ ) { float y0 = (float) Math.sin ( i * da ); float z0 = (float) Math.cos ( i * da ); float y1 = (float) Math.sin ( (i+1) * da ); float z1 = (float) Math.cos ( (i+1) * da ); gl.glTexCoord2f(0,i*dt); gl.glNormal3f(0,y0,z0); gl.glVertex3f(0,y0,z0); gl.glTexCoord2f(1,i*dt); gl.glNormal3f(1,y0,z0); gl.glVertex3f(1,y0,z0); gl.glTexCoord2f(1,(i+1)*dt); gl.glNormal3f(1,y1,z1); gl.glVertex3f(1,y1,z1); gl.glTexCoord2f(0,(i+1)*dt); gl.glNormal3f(0,y1,z1); gl.glVertex3f(0,y1,z1); } gl.glEnd(); } public void drawTriangle(){ initMatrix(); gl.glBegin(GL.GL_TRIANGLES); gl.glNormal3f(0.0f, 0.0f, 1.0f); gl.glVertex3f(0.0f, 0.0f, 0.0f); gl.glVertex3f(1.0f, 0.0f, 0.0f); gl.glVertex3f(0.0f, 1.0f, 0.0f); gl.glNormal3f(0.0f, 0.0f, -1.0f); gl.glVertex3f(0.0f, 0.0f, 0.0f); gl.glVertex3f(0.0f, 1.0f, 0.0f); gl.glVertex3f(1.0f, 0.0f, 0.0f); gl.glEnd(); resetMatrix(); } private void drawQuad(){ gl.glDisable(GL.GL_CULL_FACE); gl.glBegin(GL.GL_QUADS); gl.glNormal3f(0.0f, 0.0f, 1.0f); gl.glVertex3f(0.0f, 0.0f, 0.0f); gl.glVertex3f(1.0f, 0.0f, 0.0f); gl.glVertex3f(1.0f, 1.0f, 0.0f); gl.glVertex3f(0.0f, 1.0f, 0.0f); gl.glEnd(); gl.glEnable(GL.GL_CULL_FACE); } /** draws the text s * @param x x-coord * @param y y-coord * @param s text * @param colored says if the text has to be colored */ public void drawText(float x, float y, String s, boolean colored){ gl.glMatrixMode(GL.GL_TEXTURE); gl.glLoadIdentity(); gl.glMatrixMode(GL.GL_MODELVIEW); initMatrix(); initMatrix(view3D.getUndoRotationMatrix()); textRenderer.begin3DRendering(); if (colored) textRenderer.setColor(textColor); /* Rectangle2D bounds = textRenderer.getBounds(s); float w = (float) bounds.getWidth(); float h = (float) bounds.getHeight(); */ float textScaleFactor = DEFAULT_TEXT_SCALE_FACTOR/((float) view3D.getScale()); textRenderer.draw3D(s, x*textScaleFactor,//w / -2.0f * textScaleFactor, y*textScaleFactor,//h / -2.0f * textScaleFactor, 0, textScaleFactor); textRenderer.end3DRendering(); resetMatrix(); //initMatrix(m_view3D.getUndoRotationMatrix()); resetMatrix(); //initMatrix(); } ///////////////////////// // FPS double displayTime = 0; int nbFrame = 0; double fps = 0; private void drawFPS(){ if (displayTime==0) displayTime = System.currentTimeMillis(); nbFrame++; double newDisplayTime = System.currentTimeMillis(); //Application.debug("delay = "+ (newDisplayTime-displayTime)); //displayTime = System.currentTimeMillis(); if (newDisplayTime > displayTime+1000){ //Application.debug("nbFrame = "+nbFrame); /* fps = 0.9*fps + 0.1*1000/(displayTime-displayTimeOld); if (fps>100) fps=100; */ fps = 1000*nbFrame/(newDisplayTime - displayTime); displayTime = newDisplayTime; nbFrame = 0; } gl.glMatrixMode(GL.GL_TEXTURE); gl.glLoadIdentity(); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); textRenderer.begin3DRendering(); textRenderer.setColor(Color.BLACK); textRenderer.draw3D("FPS="+ ((int) fps),left,bottom,0,1); textRenderer.end3DRendering(); gl.glPopMatrix(); } ////////////////////////////////////// // picking /** * sets the mouse locations to (x,y) and asks for picking. * * @param x x-coordinate of the mouse * @param y y-coordinate of the mouse */ public void setMouseLoc(int x, int y, int pickingMode){ mouseX = x; mouseY = y; this.pickingMode = pickingMode; // on next rending, a picking will be done : see doPick() waitForPick = true; //thread = new Thread(picking); //thread.setPriority(Thread.MIN_PRIORITY); //thread.start(); //return thread; } /** * does the picking to sets which objects are under the mouse coordinates. */ public void doPick(){ //double pickTime = System.currentTimeMillis(); BUFSIZE = (drawList3D.size()+EuclidianView3D.DRAWABLES_NB)*2+1; selectBuffer = BufferUtil.newIntBuffer(BUFSIZE); // Set Up A Selection Buffer int hits; // The Number Of Objects That We Selected gl.glSelectBuffer(BUFSIZE, selectBuffer); // Tell OpenGL To Use Our Array For Selection // The Size Of The Viewport. [0] Is <x>, [1] Is <y>, [2] Is <length>, [3] Is <width> int[] viewport = new int[4]; gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0); //System.out.println("viewport= "+viewport[0]+","+viewport[1]+","+viewport[2]+","+viewport[3]); Dimension dim = canvas.getSize(); //System.out.println("dimension= "+dim.width +","+dim.height); // Puts OpenGL In Selection Mode. Nothing Will Be Drawn. Object ID's and Extents Are Stored In The Buffer. gl.glRenderMode(GL.GL_SELECT); gl.glInitNames(); // Initializes The Name Stack gl.glPushName(0); // Push 0 (At Least One Entry) Onto The Stack // This Creates A Matrix That Will Zoom Up To A Small Portion Of The Screen, Where The Mouse Is. gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); /* create MOUSE_PICK_WIDTH x MOUSE_PICK_WIDTH pixel picking region near cursor location */ //glu.gluPickMatrix((double) mouseX, (double) (470 - mouseY), 5.0, 5.0, viewport, 0); //mouseY+=30; //TODO understand this offset //glu.gluPickMatrix((double) mouseX, (double) (viewport[3] - mouseY), 5.0, 5.0, viewport, 0); glu.gluPickMatrix((double) mouseX, (double) (dim.height - mouseY), MOUSE_PICK_WIDTH, MOUSE_PICK_WIDTH, viewport, 0); gl.glOrtho(left,right,bottom,top,front,back); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glDisable(GL.GL_ALPHA_TEST); gl.glDisable(GL.GL_BLEND); gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_TEXTURE); //gl.glDisable(GL.GL_DEPTH_TEST); //gl.glColorMask(false,false,false,false); //gl.glDisable(GL.GL_NORMALIZE); drawHits = new Drawable3D[BUFSIZE]; //primitives.enableVBO(gl); // picking objects pickingLoop = 0; drawList3D.drawForPicking(this); int labelLoop = pickingLoop; if (pickingMode == PICKING_MODE_LABELS){ // picking labels drawList3D.drawLabelForPicking(this); } //primitives.disableVBO(gl); hits = gl.glRenderMode(GL.GL_RENDER); // Switch To Render Mode, Find Out How Many //hits are stored Hits3D hits3D = new Hits3D(); hits3D.init(); //view3D.getHits().init(); //String s="doPick (labelLoop = "+labelLoop+")"; int names, ptr = 0; float zMax, zMin; int num; for (int i = 0; i < hits; i++) { names = selectBuffer.get(ptr); ptr++; // min z zMin = getDepth(ptr); ptr++; // max z zMax = getDepth(ptr); ptr++; for (int j = 0; j < names; j++){ num = selectBuffer.get(ptr); //((Hits3D) view3D.getHits()).addDrawable3D(drawHits[num],num>labelLoop); hits3D.addDrawable3D(drawHits[num],num>labelLoop); //s+="\n("+num+") "+drawHits[num].getGeoElement().getLabel(); drawHits[num].zPickMin = zMin; drawHits[num].zPickMax = zMax; ptr++; } } //Application.debug(s); // sets the GeoElements in view3D //((Hits3D) view3D.getHits()).sort(); hits3D.sort(); view3D.setHits(hits3D); //Application.debug(hits3D.toString()); waitForPick = false; //Application.debug("pick : "+((int) (System.currentTimeMillis()-pickTime))); gl.glEnable(GL.GL_LIGHTING); } public void glLoadName(int loop){ gl.glLoadName(loop); } public void pick(Drawable3D d){ pickingLoop++; gl.glLoadName(pickingLoop); d.drawForPicking(this); drawHits[pickingLoop] = d; } public void pickLabel(Drawable3D d){ pickingLoop++; gl.glLoadName(pickingLoop); d.drawLabelForPicking(this); drawHits[pickingLoop] = d; } /** returns the depth between 0 and 2, in double format, from an integer offset * lowest is depth, nearest is the object * * @param ptr the integer offset * */ private float getDepth(int ptr){ float depth = (float) selectBuffer.get(ptr)/0x7fffffff; if (depth<0) depth+=2; return depth; } ////////////////////////////////// // initializations /** Called by the drawable immediately after the OpenGL context is * initialized for the first time. Can be used to perform one-time OpenGL * initialization such as setup of lights and display lists. * @param gLDrawable The GLAutoDrawable object. */ public void init(GLAutoDrawable drawable) { gl = drawable.getGL(); // Check For VBO support final boolean VBOsupported = gl.isFunctionAvailable("glGenBuffersARB") && gl.isFunctionAvailable("glBindBufferARB") && gl.isFunctionAvailable("glBufferDataARB") && gl.isFunctionAvailable("glDeleteBuffersARB"); Application.debug("vbo supported : "+VBOsupported); //TODO use gl lists / VBOs //geometryManager = new GeometryManager(gl,GeometryManager.TYPE_DIRECT); geometryManager = new ManagerGLList(gl,glu); //light /* float pos[] = { 1.0f, 1.0f, 1.0f, 0.0f }; //float pos[] = { 0.0f, 0.0f, 1.0f, 0.0f }; gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, pos, 0); gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_LIGHT0); */ float[] lightAmbient0 = {0.1f, 0.1f, 0.1f, 1.0f}; float[] lightDiffuse0 = {1.0f, 1.0f, 1.0f, 1.0f}; float[] lightPosition0 = {1.0f, 1.0f, 1.0f, 0.0f}; float[] lightSpecular0 = {0f, 0f, 0f, 1f}; gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, lightAmbient0, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, lightDiffuse0, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, lightPosition0, 0); gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, lightSpecular0, 0); gl.glEnable(GL.GL_LIGHT0); /* float[] lightAmbient1 = {0.1f, 0.1f, 0.1f, 1.0f}; float[] lightDiffuse1 = {1.0f, 1.0f, 1.0f, 1.0f}; float[] lightPosition1 = {-1.0f, -1.0f, -1.0f, 0.0f}; float[] lightSpecular1 = {0f, 0f, 0f, 1f}; gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, lightAmbient1, 0); gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, lightDiffuse1, 0); gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, lightPosition1, 0); gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, lightSpecular1, 0); gl.glEnable(GL.GL_LIGHT1); */ gl.glLightModelf(GL.GL_LIGHT_MODEL_TWO_SIDE,GL.GL_TRUE); gl.glShadeModel(GL.GL_SMOOTH); gl.glEnable(GL.GL_LIGHTING); //common enabling gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); gl.glEnable(GL.GL_POLYGON_OFFSET_FILL); //gl.glPolygonOffset(1.0f, 2f); gl.glEnable(GL.GL_CULL_FACE); //blending gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(GL.GL_BLEND); //gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_DST_ALPHA); gl.glClearColor(1.0f, 1.0f, 1.0f, 0.0f); gl.glAlphaFunc(GL.GL_NOTEQUAL, 0);//pixels with alpha=0 are not drawn //using glu quadrics quadric = glu.gluNewQuadric();// Create A Pointer To The Quadric Object (Return 0 If No Memory) (NEW) glu.gluQuadricNormals(quadric, GLU.GLU_SMOOTH); // Create Smooth Normals (NEW) glu.gluQuadricTexture(quadric, true); // Create Texture Coords (NEW) //projection type //viewOrtho(gl); //normal anti-scaling gl.glEnable(GL.GL_NORMALIZE); //gl.glEnable(GL.GL_RESCALE_NORMAL); //material gl.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE); gl.glEnable(GL.GL_COLOR_MATERIAL); //textures initTextures(); } //projection mode int left = 0; int right = 640; int bottom = 0; int top = 480; int front = -1000; int back = 1000; public int getLeft(){ return left; } public int getRight(){ return right; } public int getBottom(){ return bottom; } public int getTop(){ return top; } public int getFront(){ return front; } public int getBack(){ return back; } /** for a line described by (o,v), return the min and max parameters to draw the line * @param minmax initial interval * @param o origin of the line * @param v direction of the line * @return interval to draw the line */ public double[] getIntervalInFrustum(double[] minmax, Ggb3DVector o, Ggb3DVector v){ double left = (getLeft() - o.get(1))/v.get(1); double right = (getRight() - o.get(1))/v.get(1); updateIntervalInFrustum(minmax, left, right); double top = (getTop() - o.get(2))/v.get(2); double bottom = (getBottom() - o.get(2))/v.get(2); updateIntervalInFrustum(minmax, top, bottom); double front = (getFront() - o.get(3))/v.get(3); double back = (getBack() - o.get(3))/v.get(3); updateIntervalInFrustum(minmax, front, back); /* Application.debug("intersection = ("+left+","+right+ ")/("+top+","+bottom+")/("+front+","+back+")"+ "\ninterval = ("+minmax[0]+","+minmax[1]+")"); */ return minmax; } /** return the intersection of intervals [minmax] and [v1,v2] * @param minmax initial interval * @param v1 first value * @param v2 second value * @return intersection interval */ private double[] updateIntervalInFrustum(double[] minmax, double v1, double v2){ if (v1>v2){ double v = v1; v1 = v2; v2 = v; } if (v1>minmax[0]) minmax[0] = v1; if (v2<minmax[1]) minmax[1] = v2; return minmax; } /** * Set Up An Ortho View regarding left, right, bottom, front values * */ private void viewOrtho() { gl.glViewport(0,0,right-left,top-bottom); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(left,right,bottom,top,front,back); gl.glMatrixMode(GL.GL_MODELVIEW); } /** * Set Up An Ortho View after setting left, right, bottom, front values * @param x left * @param y bottom * @param w width * @param h height * */ private void viewOrtho(int x, int y, int w, int h){ left=x-w/2; bottom=y-h/2; right=left+w; top = bottom+h; /* Application.debug("viewOrtho:"+ "\n left="+left+"\n right="+right+ "\n top="+top+"\n bottom="+bottom+ "\n front="+front+"\n back="+back ); */ viewOrtho(); } private void viewPerspective(GL gl) // Set Up A Perspective View { gl.glMatrixMode(GL.GL_PROJECTION); // Select Projection gl.glPopMatrix(); // Pop The Matrix gl.glMatrixMode(GL.GL_MODELVIEW); // Select Modelview gl.glPopMatrix(); // Pop The Matrix } }
false
true
public void display(GLAutoDrawable gLDrawable) { //Application.debug("display"); //double displayTime = System.currentTimeMillis(); gl = gLDrawable.getGL(); //picking if(waitForPick){ doPick(); //Application.debug("doPick"); //return; } gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glClear(GL.GL_DEPTH_BUFFER_BIT); //start drawing viewOrtho(); //update 3D controller ((EuclidianController3D) view3D.getEuclidianController()).processMouseMoved(); // update 3D view view3D.update(); view3D.updateDrawablesNow(); // update 3D drawables drawList3D.updateAll(); //init drawing matrix to view3D toScreen matrix gl.glLoadMatrixd(view3D.getToScreenMatrix().get(),0); //drawing the cursor view3D.drawCursor(this); //primitives.enableVBO(gl); //drawing hidden part gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts //gl.glDisable(GL.GL_BLEND); drawList3D.drawHidden(this); gl.glDisable(GL.GL_ALPHA_TEST); //drawing highlighted parts -- points and curves gl.glDepthMask(false); //setMaterial(new Color(0f,0f,0f),0.75f); dilation = DILATION_HIGHLITED; gl.glCullFace(GL.GL_FRONT); //draws inside parts gl.glEnable(GL.GL_BLEND); drawList3D.drawHighlightingPointsAndCurves(this); dilation = DILATION_NONE; //drawing highlighted parts -- surfaces gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawHighlightingSurfaces(this); //drawing transparents parts gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing labels gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_BLEND); drawList3D.drawLabel(this); gl.glEnable(GL.GL_LIGHTING); gl.glDisable(GL.GL_ALPHA_TEST); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glCullFace(GL.GL_FRONT); //draws inside parts drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces back-faces gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawSurfacesForHiding(this); //non closed surfaces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glDisable(GL.GL_BLEND); gl.glCullFace(GL.GL_BACK); //draws inside parts gl.glEnable(GL.GL_CULL_FACE); drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces front-faces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing not hidden parts gl.glEnable(GL.GL_CULL_FACE); gl.glDisable(GL.GL_BLEND); drawList3D.draw(this); //primitives.disableVBO(gl); //FPS /* gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_DEPTH_TEST); drawFPS(); gl.glEnable(GL.GL_DEPTH_TEST); gl.glEnable(GL.GL_LIGHTING); */ gLDrawable.swapBuffers(); //TODO //Application.debug("display : "+((int) (System.currentTimeMillis()-displayTime))); }
public void display(GLAutoDrawable gLDrawable) { //Application.debug("display"); //double displayTime = System.currentTimeMillis(); gl = gLDrawable.getGL(); //picking if(waitForPick){ doPick(); //Application.debug("doPick"); //return; } gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glClear(GL.GL_DEPTH_BUFFER_BIT); //start drawing viewOrtho(); //update 3D controller ((EuclidianController3D) view3D.getEuclidianController()).processMouseMoved(); // update 3D view view3D.update(); view3D.updateDrawablesNow(); // update 3D drawables drawList3D.updateAll(); //init drawing matrix to view3D toScreen matrix gl.glLoadMatrixd(view3D.getToScreenMatrix().get(),0); //drawing the cursor view3D.drawCursor(this); //primitives.enableVBO(gl); //drawing hidden part gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts //gl.glDisable(GL.GL_BLEND); drawList3D.drawHidden(this); gl.glDisable(GL.GL_ALPHA_TEST); //drawing highlighted parts -- points and curves //gl.glDepthMask(false); //setMaterial(new Color(0f,0f,0f),0.75f); dilation = DILATION_HIGHLITED; gl.glCullFace(GL.GL_FRONT); //draws inside parts //gl.glEnable(GL.GL_BLEND); drawList3D.drawHighlightingPointsAndCurves(this); dilation = DILATION_NONE; //drawing highlighted parts -- surfaces gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawHighlightingSurfaces(this); //drawing transparents parts gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing labels gl.glEnable(GL.GL_CULL_FACE); gl.glCullFace(GL.GL_BACK); gl.glEnable(GL.GL_ALPHA_TEST); //avoid z-buffer writing for transparent parts gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_BLEND); drawList3D.drawLabel(this); gl.glEnable(GL.GL_LIGHTING); gl.glDisable(GL.GL_ALPHA_TEST); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glCullFace(GL.GL_FRONT); //draws inside parts drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces back-faces gl.glDisable(GL.GL_CULL_FACE); drawList3D.drawSurfacesForHiding(this); //non closed surfaces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing hiding parts gl.glColorMask(false,false,false,false); //no writing in color buffer gl.glDisable(GL.GL_BLEND); gl.glCullFace(GL.GL_BACK); //draws inside parts gl.glEnable(GL.GL_CULL_FACE); drawList3D.drawClosedSurfacesForHiding(this); //closed surfaces front-faces gl.glColorMask(true,true,true,true); //re-drawing transparents parts for better transparent effect //TODO improve it ! gl.glDisable(GL.GL_CULL_FACE); gl.glDepthMask(false); gl.glEnable(GL.GL_BLEND); drawList3D.drawTransp(this); gl.glDepthMask(true); //drawing not hidden parts gl.glEnable(GL.GL_CULL_FACE); gl.glDisable(GL.GL_BLEND); drawList3D.draw(this); //primitives.disableVBO(gl); //FPS /* gl.glDisable(GL.GL_LIGHTING); gl.glDisable(GL.GL_DEPTH_TEST); drawFPS(); gl.glEnable(GL.GL_DEPTH_TEST); gl.glEnable(GL.GL_LIGHTING); */ gLDrawable.swapBuffers(); //TODO //Application.debug("display : "+((int) (System.currentTimeMillis()-displayTime))); }
diff --git a/poo/file/NaturalMergeSort.java b/poo/file/NaturalMergeSort.java index fe3d2aa..2798ae8 100644 --- a/poo/file/NaturalMergeSort.java +++ b/poo/file/NaturalMergeSort.java @@ -1,98 +1,97 @@ package poo.file; import java.io.*; import java.util.*; public class NaturalMergeSort { public static void main(String[]args) { Scanner sc = new Scanner(System.in); System.out.print("Nome file di interi da ordinare: "); String nomeFile = sc.nextLine(); while (!(new File(nomeFile)).exists()) { System.out.print(nomeFile + " non esiste! Ridare nome file: "); nomeFile = sc.nextLine(); } risolvi(nomeFile); } // main static void risolvi(String nomeFile) { ObjectFile<Integer> f = null, tmp1 = null, tmp2 = null; try { f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); int n = 0, x = 0, y = 0; while ((n = numeroSegmenti(f)) > 1) { f.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); for (int i = 0; i < n; i++) copiaSegmento(f, (i % 2 == 0 ? tmp1 : tmp2)); f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.SCRITTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.LETTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.LETTURA); for (int i = 0; i < n / 2 + 1; i++) fondiSegmenti(f, tmp1, tmp2); - //while (!tmp1.eof()) { f.put(tmp1.peek()); tmp1.get(); } f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); } (new File("tmp1")).delete(); (new File("tmp2")).delete(); } catch (Exception e) { System.out.println("Errore di lettura/scrittura!"); e.printStackTrace(); } finally { try { if (f != null) f.close(); if (tmp1 != null) tmp1.close(); if (tmp2 != null) tmp2.close(); } catch (IOException e) { System.out.println("Errore di lettura/scrittura!"); } } } // risolvi private static int numeroSegmenti(ObjectFile<Integer> f) throws IOException { if (f.eof()) return 0; int n = 1, prev = f.peek(), next = 0; f.get(); while (!f.eof()) { next = f.peek(); if (next < prev) n++; prev = next; f.get(); } return n; } // numeroSegmenti private static void copiaSegmento(ObjectFile<Integer> f, ObjectFile<Integer> tmp) throws IOException { int prev = f.peek(), next = 0; tmp.put(prev); f.get(); while (!f.eof()) { next = f.peek(); if (prev <= next) { tmp.put(next); prev = next; } else break; f.get(); } } // copiaSegmento private static void fondiSegmenti(ObjectFile<Integer> f, ObjectFile<Integer> tmp1, ObjectFile<Integer> tmp2) throws IOException { int x1 = 0, x2 = 0; if (!tmp1.eof() && !tmp2.eof()) { for (;;) { x1 = tmp1.peek(); x2 = tmp2.peek(); if (x1 < x2) { f.put(x1); tmp1.get(); if (tmp1.eof() || tmp1.peek() < x1) break; } else { f.put(x2); tmp2.get(); if (tmp2.eof() || tmp2.peek() < x2) break; } } } else if (!tmp1.eof()) x1 = tmp1.peek(); else if (!tmp2.eof()) x2 = tmp2.peek(); while (!tmp1.eof() && tmp1.peek() >= x1) { f.put(x1 = tmp1.peek()); tmp1.get(); } while (!tmp2.eof() && tmp2.peek() >= x2) { f.put(x2 = tmp2.peek()); tmp2.get(); } } // fondiSegmenti } // NaturalMergeSort
true
true
static void risolvi(String nomeFile) { ObjectFile<Integer> f = null, tmp1 = null, tmp2 = null; try { f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); int n = 0, x = 0, y = 0; while ((n = numeroSegmenti(f)) > 1) { f.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); for (int i = 0; i < n; i++) copiaSegmento(f, (i % 2 == 0 ? tmp1 : tmp2)); f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.SCRITTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.LETTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.LETTURA); for (int i = 0; i < n / 2 + 1; i++) fondiSegmenti(f, tmp1, tmp2); //while (!tmp1.eof()) { f.put(tmp1.peek()); tmp1.get(); } f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); } (new File("tmp1")).delete(); (new File("tmp2")).delete(); } catch (Exception e) { System.out.println("Errore di lettura/scrittura!"); e.printStackTrace(); } finally { try { if (f != null) f.close(); if (tmp1 != null) tmp1.close(); if (tmp2 != null) tmp2.close(); } catch (IOException e) { System.out.println("Errore di lettura/scrittura!"); } } } // risolvi
static void risolvi(String nomeFile) { ObjectFile<Integer> f = null, tmp1 = null, tmp2 = null; try { f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); int n = 0, x = 0, y = 0; while ((n = numeroSegmenti(f)) > 1) { f.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); for (int i = 0; i < n; i++) copiaSegmento(f, (i % 2 == 0 ? tmp1 : tmp2)); f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.SCRITTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.LETTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.LETTURA); for (int i = 0; i < n / 2 + 1; i++) fondiSegmenti(f, tmp1, tmp2); f.close(); tmp1.close(); tmp2.close(); f = new ObjectFile<Integer>(nomeFile, ObjectFile.Modo.LETTURA); tmp1 = new ObjectFile<Integer>("tmp1", ObjectFile.Modo.SCRITTURA); tmp2 = new ObjectFile<Integer>("tmp2", ObjectFile.Modo.SCRITTURA); } (new File("tmp1")).delete(); (new File("tmp2")).delete(); } catch (Exception e) { System.out.println("Errore di lettura/scrittura!"); e.printStackTrace(); } finally { try { if (f != null) f.close(); if (tmp1 != null) tmp1.close(); if (tmp2 != null) tmp2.close(); } catch (IOException e) { System.out.println("Errore di lettura/scrittura!"); } } } // risolvi
diff --git a/src/main/java/org/mozilla/gecko/sync/net/HMACAuthHeaderProvider.java b/src/main/java/org/mozilla/gecko/sync/net/HMACAuthHeaderProvider.java index 9fd0fb0c2..643417a1f 100644 --- a/src/main/java/org/mozilla/gecko/sync/net/HMACAuthHeaderProvider.java +++ b/src/main/java/org/mozilla/gecko/sync/net/HMACAuthHeaderProvider.java @@ -1,257 +1,261 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.sync.net; import java.io.UnsupportedEncodingException; import java.net.URI; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.mozilla.apache.commons.codec.binary.Base64; import org.mozilla.gecko.sync.Logger; import org.mozilla.gecko.sync.Utils; import ch.boye.httpclientandroidlib.Header; import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase; import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.message.BasicHeader; import ch.boye.httpclientandroidlib.protocol.BasicHttpContext; /** * An <code>AuthHeaderProvider</code> that returns an Authorization header for * HMAC-SHA1-signed requests in the format expected by Mozilla Services * identity-attached services and specified by the MAC Authentication spec, available at * <a href="https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac">https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac</a>. * <p> * See <a href="https://wiki.mozilla.org/Services/Sagrada/ServiceClientFlow#Access">https://wiki.mozilla.org/Services/Sagrada/ServiceClientFlow#Access</a>. */ public class HMACAuthHeaderProvider implements AuthHeaderProvider { public static final String LOG_TAG = "HMACAuthHeaderProvider"; public static final int NONCE_LENGTH_IN_BYTES = 8; public static final String HMAC_SHA1_ALGORITHM = "hmacSHA1"; public final String identifier; public final String key; public HMACAuthHeaderProvider(String identifier, String key) { // Validate identifier string. From the MAC Authentication spec: // id = "id" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the id string, so input identifier must be a plain-string. if (identifier == null) { throw new IllegalArgumentException("identifier must not be null."); } if (!isPlainString(identifier)) { throw new IllegalArgumentException("identifier must be a plain-string."); } if (key == null) { throw new IllegalArgumentException("key must not be null."); } this.identifier = identifier; this.key = key; } @Override public Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client) throws GeneralSecurityException { long timestamp = System.currentTimeMillis() / 1000; String nonce = Base64.encodeBase64String(Utils.generateRandomBytes(NONCE_LENGTH_IN_BYTES)); String extra = ""; try { return getAuthHeader(request, context, client, timestamp, nonce, extra); } catch (InvalidKeyException e) { // We lie a little and make every exception a GeneralSecurityException. throw new GeneralSecurityException(e); } catch (UnsupportedEncodingException e) { throw new GeneralSecurityException(e); } catch (NoSuchAlgorithmException e) { throw new GeneralSecurityException(e); } } /** * Test if input is a <code>plain-string</code>. * <p> * A plain-string is defined by the MAC Authentication spec as * <code>plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E )</code>. * * @param input * as a String of "US-ASCII" bytes. * @return true if input is a <code>plain-string</code>; false otherwise. * @throws UnsupportedEncodingException */ protected static boolean isPlainString(String input) { if (input == null || input.length() == 0) { return false; } byte[] bytes; try { bytes = input.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { // Should never happen. Logger.warn(LOG_TAG, "Got exception in isPlainString; returning false.", e); return false; } for (byte b : bytes) { if ((0x20 <= b && b <= 0x21) || (0x23 <= b && b <= 0x5B) || (0x5D <= b && b <= 0x7E)) { continue; } return false; } return true; } /** * Helper function that generates an HTTP Authorization header given * additional MAC Authentication specific data. * * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ protected Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client, long timestamp, String nonce, String extra) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { // Validate timestamp. From the MAC Authentication spec: // timestamp = 1*DIGIT // This is equivalent to timestamp >= 0. if (timestamp < 0) { throw new IllegalArgumentException("timestamp must contain only [0-9]."); } // Validate nonce string. From the MAC Authentication spec: // nonce = "nonce" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the nonce string, so input nonce must be a plain-string. if (nonce == null) { throw new IllegalArgumentException("nonce must not be null."); } + if (nonce.length() == 0) { + throw new IllegalArgumentException("nonce must not be empty."); + } if (!isPlainString(nonce)) { throw new IllegalArgumentException("nonce must be a plain-string."); } // Validate extra string. From the MAC Authentication spec: // ext = "ext" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the extra string, so input extra must be a plain-string. + // We break the spec by allowing ext to be an empty string, i.e. to match 0*(...). if (extra == null) { throw new IllegalArgumentException("extra must not be null."); } - if (!isPlainString(extra)) { + if (extra.length() > 0 && !isPlainString(extra)) { throw new IllegalArgumentException("extra must be a plain-string."); } String requestString = getRequestString(request, timestamp, nonce, extra); String macString = getSignature(requestString, this.key); String h = "MAC id=\"" + this.identifier + "\", " + "ts=\"" + timestamp + "\", " + "nonce=\"" + nonce + "\", " + "mac=\"" + macString + "\""; if (extra != null) { h += ", ext=\"" + extra + "\""; } Header header = new BasicHeader("Authorization", h); return header; } protected static byte[] sha1(byte[] message, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec keySpec = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM); Mac hasher = Mac.getInstance(HMAC_SHA1_ALGORITHM); hasher.init(keySpec); hasher.update(message); byte[] hmac = hasher.doFinal(); return hmac; } /** * Sign an HMAC request string. * * @param requestString to sign. * @param key as <code>String</code>. * @return signature as base-64 encoded string. * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ protected static String getSignature(String requestString, String key) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { String macString = Base64.encodeBase64String(sha1(requestString.getBytes("UTF-8"), key.getBytes("UTF-8"))); return macString; } /** * Generate an HMAC request string. * <p> * This method trusts its inputs to be valid as per the MAC Authentication spec. * * @param request HTTP request. * @param timestamp to use. * @param nonce to use. * @param extra to use. * @return request string. */ protected static String getRequestString(HttpUriRequest request, long timestamp, String nonce, String extra) { String method = request.getMethod().toUpperCase(); URI uri = request.getURI(); String host = uri.getHost(); String path = uri.getRawPath(); if (uri.getRawQuery() != null) { path += "?"; path += uri.getRawQuery(); } if (uri.getRawFragment() != null) { path += "#"; path += uri.getRawFragment(); } int port = uri.getPort(); String scheme = uri.getScheme(); if (port != -1) { } else if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } else { throw new IllegalArgumentException("Unsupported URI scheme: " + scheme + "."); } String requestString = timestamp + "\n" + nonce + "\n" + method + "\n" + path + "\n" + host + "\n" + port + "\n" + extra + "\n"; return requestString; } }
false
true
protected Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client, long timestamp, String nonce, String extra) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { // Validate timestamp. From the MAC Authentication spec: // timestamp = 1*DIGIT // This is equivalent to timestamp >= 0. if (timestamp < 0) { throw new IllegalArgumentException("timestamp must contain only [0-9]."); } // Validate nonce string. From the MAC Authentication spec: // nonce = "nonce" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the nonce string, so input nonce must be a plain-string. if (nonce == null) { throw new IllegalArgumentException("nonce must not be null."); } if (!isPlainString(nonce)) { throw new IllegalArgumentException("nonce must be a plain-string."); } // Validate extra string. From the MAC Authentication spec: // ext = "ext" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the extra string, so input extra must be a plain-string. if (extra == null) { throw new IllegalArgumentException("extra must not be null."); } if (!isPlainString(extra)) { throw new IllegalArgumentException("extra must be a plain-string."); } String requestString = getRequestString(request, timestamp, nonce, extra); String macString = getSignature(requestString, this.key); String h = "MAC id=\"" + this.identifier + "\", " + "ts=\"" + timestamp + "\", " + "nonce=\"" + nonce + "\", " + "mac=\"" + macString + "\""; if (extra != null) { h += ", ext=\"" + extra + "\""; } Header header = new BasicHeader("Authorization", h); return header; }
protected Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client, long timestamp, String nonce, String extra) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException { // Validate timestamp. From the MAC Authentication spec: // timestamp = 1*DIGIT // This is equivalent to timestamp >= 0. if (timestamp < 0) { throw new IllegalArgumentException("timestamp must contain only [0-9]."); } // Validate nonce string. From the MAC Authentication spec: // nonce = "nonce" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the nonce string, so input nonce must be a plain-string. if (nonce == null) { throw new IllegalArgumentException("nonce must not be null."); } if (nonce.length() == 0) { throw new IllegalArgumentException("nonce must not be empty."); } if (!isPlainString(nonce)) { throw new IllegalArgumentException("nonce must be a plain-string."); } // Validate extra string. From the MAC Authentication spec: // ext = "ext" "=" string-value // string-value = ( <"> plain-string <"> ) / plain-string // plain-string = 1*( %x20-21 / %x23-5B / %x5D-7E ) // We add quotes around the extra string, so input extra must be a plain-string. // We break the spec by allowing ext to be an empty string, i.e. to match 0*(...). if (extra == null) { throw new IllegalArgumentException("extra must not be null."); } if (extra.length() > 0 && !isPlainString(extra)) { throw new IllegalArgumentException("extra must be a plain-string."); } String requestString = getRequestString(request, timestamp, nonce, extra); String macString = getSignature(requestString, this.key); String h = "MAC id=\"" + this.identifier + "\", " + "ts=\"" + timestamp + "\", " + "nonce=\"" + nonce + "\", " + "mac=\"" + macString + "\""; if (extra != null) { h += ", ext=\"" + extra + "\""; } Header header = new BasicHeader("Authorization", h); return header; }
diff --git a/ZMainProject/Trunk/MainProject/src/servlets/FormD.java b/ZMainProject/Trunk/MainProject/src/servlets/FormD.java index 2fdbf9db..44b74dc1 100644 --- a/ZMainProject/Trunk/MainProject/src/servlets/FormD.java +++ b/ZMainProject/Trunk/MainProject/src/servlets/FormD.java @@ -1,72 +1,72 @@ package servlets; import java.io.IOException; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.*; import javax.servlet.http.*; import forms.Form; import people.User; import serverLogic.DatabaseUtil; import time.Date; import time.Time; public class FormD extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter("Submit") != null) { String Email = req.getParameter("Email"); String AmountWorked = req.getParameter("AmountWorked"); String Details = req.getParameter("Details"); if (Email != null && AmountWorked != null && Details != null) { - Date date = new Date(Integer.parseInt(req.getParameter("Year")), Integer.parseInt(req.getParameter("Month")), - Integer.parseInt(req.getParameter("Day"))); + Date date = new Date(Integer.parseInt(req.getParameter("StartYear")), Integer.parseInt(req.getParameter("StartMonth")), + Integer.parseInt(req.getParameter("StartDay"))); Time time = new Time(0, 0, date); User guy = DatabaseUtil.getUser(""+req.getSession().getAttribute("user")); Form form = new Form(guy.getNetID(), Details, time, time, "FormD"); DatabaseUtil.addForm(form); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "..."; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(Email)); msg.setSubject(guy.getFirstName() + " " + guy.getLastName() + " requests approval of work time."); msg.setText((msgBody)); Transport.send(msg); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } resp.sendRedirect("/JSPPages/Student_Page.jsp"); } else { //TODO now you fucked up } } } }
true
true
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter("Submit") != null) { String Email = req.getParameter("Email"); String AmountWorked = req.getParameter("AmountWorked"); String Details = req.getParameter("Details"); if (Email != null && AmountWorked != null && Details != null) { Date date = new Date(Integer.parseInt(req.getParameter("Year")), Integer.parseInt(req.getParameter("Month")), Integer.parseInt(req.getParameter("Day"))); Time time = new Time(0, 0, date); User guy = DatabaseUtil.getUser(""+req.getSession().getAttribute("user")); Form form = new Form(guy.getNetID(), Details, time, time, "FormD"); DatabaseUtil.addForm(form); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "..."; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(Email)); msg.setSubject(guy.getFirstName() + " " + guy.getLastName() + " requests approval of work time."); msg.setText((msgBody)); Transport.send(msg); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } resp.sendRedirect("/JSPPages/Student_Page.jsp"); } else { //TODO now you fucked up } } }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getParameter("Submit") != null) { String Email = req.getParameter("Email"); String AmountWorked = req.getParameter("AmountWorked"); String Details = req.getParameter("Details"); if (Email != null && AmountWorked != null && Details != null) { Date date = new Date(Integer.parseInt(req.getParameter("StartYear")), Integer.parseInt(req.getParameter("StartMonth")), Integer.parseInt(req.getParameter("StartDay"))); Time time = new Time(0, 0, date); User guy = DatabaseUtil.getUser(""+req.getSession().getAttribute("user")); Form form = new Form(guy.getNetID(), Details, time, time, "FormD"); DatabaseUtil.addForm(form); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); String msgBody = "..."; try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("[email protected]")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(Email)); msg.setSubject(guy.getFirstName() + " " + guy.getLastName() + " requests approval of work time."); msg.setText((msgBody)); Transport.send(msg); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } resp.sendRedirect("/JSPPages/Student_Page.jsp"); } else { //TODO now you fucked up } } }
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java index f405a278d..f55da881d 100644 --- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java +++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/script/JSResultSetRow.java @@ -1,245 +1,245 @@ /******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.script; import java.util.HashMap; import java.util.Map; import org.eclipse.birt.core.data.DataTypeUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.core.script.JavascriptEvalUtil; import org.eclipse.birt.core.script.ScriptContext; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.expression.ExprEvaluateUtil; import org.eclipse.birt.data.engine.i18n.DataResourceHandle; import org.eclipse.birt.data.engine.i18n.ResourceConstants; import org.eclipse.birt.data.engine.impl.ExprManager; import org.eclipse.birt.data.engine.impl.IExecutorHelper; import org.eclipse.birt.data.engine.odi.IResultIterator; import org.eclipse.birt.data.engine.odi.IResultObject; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; /** * This JS object serves for the row of binding columns. */ public class JSResultSetRow extends ScriptableObject { private IResultIterator odiResult; private ExprManager exprManager; private Scriptable scope; private IExecutorHelper helper; private ScriptContext cx; private int currRowIndex; private Map valueCacheMap; /** */ private static final long serialVersionUID = 649424371394281464L; /** * @param odiResult * @param exprManager * @param scope * @param helper */ public JSResultSetRow( IResultIterator odiResult, ExprManager exprManager, Scriptable scope, IExecutorHelper helper, ScriptContext cx ) { this.odiResult = odiResult; this.exprManager = exprManager; this.scope = scope; this.helper = helper; this.cx = cx; this.currRowIndex = -1; this.valueCacheMap = new HashMap( ); } /* * @see org.mozilla.javascript.ScriptableObject#getClassName() */ public String getClassName( ) { return "ResultSetRow"; } /* * @see org.mozilla.javascript.ScriptableObject#has(int, * org.mozilla.javascript.Scriptable) */ public boolean has( int index, Scriptable start ) { return this.has( String.valueOf( index ), start ); } /* * @see org.mozilla.javascript.ScriptableObject#has(java.lang.String, * org.mozilla.javascript.Scriptable) */ public boolean has( String name, Scriptable start ) { try { return exprManager.getExpr( name ) != null; } catch ( DataException e ) { return false; } } /* * @see org.mozilla.javascript.ScriptableObject#get(int, * org.mozilla.javascript.Scriptable) */ public Object get( int index, Scriptable start ) { return this.get( String.valueOf( index ), start ); } /* * @see org.mozilla.javascript.ScriptableObject#get(java.lang.String, * org.mozilla.javascript.Scriptable) */ public Object get( String name, Scriptable start ) { if( ScriptConstants.OUTER_RESULT_KEYWORD.equalsIgnoreCase( name )) { if( this.helper.getParent( )!= null) return helper.getParent( ).getScriptable( ); else throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.NO_OUTER_RESULTS_EXIST ) ); } int rowIndex = -1; try { rowIndex = odiResult.getCurrentResultIndex( ); } catch ( BirtException e1 ) { // impossible, ignore } if( ScriptConstants.ROW_NUM_KEYWORD.equalsIgnoreCase( name )||"0".equalsIgnoreCase( name )) { return new Integer( rowIndex ); } if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) ) { return valueCacheMap.get( name ); } else { Object value = null; try { IBinding binding = this.exprManager.getBinding( name ); if ( binding == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } if ( binding.getAggrFunction( )!= null ) return this.odiResult.getAggrValue( name ); IBaseExpression dataExpr = this.exprManager.getExpr( name ); if ( dataExpr == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } value = ExprEvaluateUtil.evaluateValue( dataExpr, this.odiResult.getCurrentResultIndex( ), this.odiResult.getCurrentResult( ), this.scope, this.cx); value = JavascriptEvalUtil.convertToJavascriptValue( DataTypeUtil.convert( value, binding.getDataType( ) ), this.scope ); } catch ( BirtException e ) { - value = null; + throw Context.reportRuntimeError( e.getLocalizedMessage( ) ); } if ( this.currRowIndex != rowIndex ) { this.valueCacheMap.clear( ); this.currRowIndex = rowIndex; } valueCacheMap.put( name, value ); return value; } } /** * @param rsObject * @param index * @param name * @return value * @throws DataException */ public Object getValue( IResultObject rsObject, int index, String name ) throws DataException { Object value = null; if ( name.startsWith( "_{" ) ) { try { value = rsObject.getFieldValue( name ); } catch ( DataException e ) { // ignore } } else { IBaseExpression dataExpr = this.exprManager.getExpr( name ); try { value = ExprEvaluateUtil.evaluateValue( dataExpr, -1, rsObject, this.scope, this.cx); //value = JavascriptEvalUtil.convertJavascriptValue( value ); } catch ( BirtException e ) { } } return value; } /* * @see org.mozilla.javascript.ScriptableObject#put(int, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( int index, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } /* * @see org.mozilla.javascript.ScriptableObject#put(java.lang.String, * org.mozilla.javascript.Scriptable, java.lang.Object) */ public void put( String name, Scriptable scope, Object value ) { throw new IllegalArgumentException( "Put value on result set row is not supported." ); } }
true
true
public Object get( String name, Scriptable start ) { if( ScriptConstants.OUTER_RESULT_KEYWORD.equalsIgnoreCase( name )) { if( this.helper.getParent( )!= null) return helper.getParent( ).getScriptable( ); else throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.NO_OUTER_RESULTS_EXIST ) ); } int rowIndex = -1; try { rowIndex = odiResult.getCurrentResultIndex( ); } catch ( BirtException e1 ) { // impossible, ignore } if( ScriptConstants.ROW_NUM_KEYWORD.equalsIgnoreCase( name )||"0".equalsIgnoreCase( name )) { return new Integer( rowIndex ); } if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) ) { return valueCacheMap.get( name ); } else { Object value = null; try { IBinding binding = this.exprManager.getBinding( name ); if ( binding == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } if ( binding.getAggrFunction( )!= null ) return this.odiResult.getAggrValue( name ); IBaseExpression dataExpr = this.exprManager.getExpr( name ); if ( dataExpr == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } value = ExprEvaluateUtil.evaluateValue( dataExpr, this.odiResult.getCurrentResultIndex( ), this.odiResult.getCurrentResult( ), this.scope, this.cx); value = JavascriptEvalUtil.convertToJavascriptValue( DataTypeUtil.convert( value, binding.getDataType( ) ), this.scope ); } catch ( BirtException e ) { value = null; } if ( this.currRowIndex != rowIndex ) { this.valueCacheMap.clear( ); this.currRowIndex = rowIndex; } valueCacheMap.put( name, value ); return value; } }
public Object get( String name, Scriptable start ) { if( ScriptConstants.OUTER_RESULT_KEYWORD.equalsIgnoreCase( name )) { if( this.helper.getParent( )!= null) return helper.getParent( ).getScriptable( ); else throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.NO_OUTER_RESULTS_EXIST ) ); } int rowIndex = -1; try { rowIndex = odiResult.getCurrentResultIndex( ); } catch ( BirtException e1 ) { // impossible, ignore } if( ScriptConstants.ROW_NUM_KEYWORD.equalsIgnoreCase( name )||"0".equalsIgnoreCase( name )) { return new Integer( rowIndex ); } if ( rowIndex == currRowIndex && valueCacheMap.containsKey( name ) ) { return valueCacheMap.get( name ); } else { Object value = null; try { IBinding binding = this.exprManager.getBinding( name ); if ( binding == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } if ( binding.getAggrFunction( )!= null ) return this.odiResult.getAggrValue( name ); IBaseExpression dataExpr = this.exprManager.getExpr( name ); if ( dataExpr == null ) { throw Context.reportRuntimeError( DataResourceHandle.getInstance( ).getMessage( ResourceConstants.INVALID_BOUND_COLUMN_NAME, new String[]{name} ) ); } value = ExprEvaluateUtil.evaluateValue( dataExpr, this.odiResult.getCurrentResultIndex( ), this.odiResult.getCurrentResult( ), this.scope, this.cx); value = JavascriptEvalUtil.convertToJavascriptValue( DataTypeUtil.convert( value, binding.getDataType( ) ), this.scope ); } catch ( BirtException e ) { throw Context.reportRuntimeError( e.getLocalizedMessage( ) ); } if ( this.currRowIndex != rowIndex ) { this.valueCacheMap.clear( ); this.currRowIndex = rowIndex; } valueCacheMap.put( name, value ); return value; } }
diff --git a/src/contrib/raid/src/test/org/apache/hadoop/raid/TestCodec.java b/src/contrib/raid/src/test/org/apache/hadoop/raid/TestCodec.java index 7885a9f..82eb9e9 100644 --- a/src/contrib/raid/src/test/org/apache/hadoop/raid/TestCodec.java +++ b/src/contrib/raid/src/test/org/apache/hadoop/raid/TestCodec.java @@ -1,108 +1,107 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.raid; import java.util.List; import junit.framework.TestCase; import org.apache.hadoop.conf.Configuration; public class TestCodec extends TestCase { public void testCreation() throws Exception { Configuration conf = new Configuration(); String jsonStr = " [\n" + " { \n" + " \"id\" : \"rs\",\n" + " \"parity_dir\" : \"/raidrs\",\n" + " \"stripe_length\" : 10,\n" + " \"parity_length\" : 4,\n" + " \"priority\" : 300,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.ReedSolomonCode\",\n" + " \"description\" : \"ReedSolomonCode code\",\n" + " \"simulate_block_fix\" : true,\n" + " }, \n" + " { \n" + " \"id\" : \"xor\",\n" + " \"parity_dir\" : \"/raid\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 1,\n" + " \"priority\" : 100,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.XORCode\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " { \n" + " \"id\" : \"sr\",\n" + " \"parity_dir\" : \"/raidsr\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 5, \n" + " \"degree\" : 2,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.SimpleRegeneratingCode\",\n" + " \"priority\" : 200,\n" + " \"description\" : \"SimpleRegeneratingCode code\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " ]\n"; conf.set("raid.codecs.json", jsonStr); Codec.initializeCodecs(conf); assertEquals("xor", Codec.getCodec("xor").id); assertEquals("rs", Codec.getCodec("rs").id); assertEquals("sr", Codec.getCodec("sr").id); List<Codec> codecs = Codec.getCodecs(); assertEquals(3, codecs.size()); assertEquals("rs", codecs.get(0).id); assertEquals(10, codecs.get(0).stripeLength); assertEquals(4, codecs.get(0).parityLength); assertEquals(300, codecs.get(0).priority); assertEquals("/raidrs", codecs.get(0).parityDirectory); assertEquals("/tmp/raidrs", codecs.get(0).tmpParityDirectory); assertEquals("/tmp/raidrs_har", codecs.get(0).tmpHarDirectory); assertEquals("ReedSolomonCode code", codecs.get(0).description); assertEquals(true, codecs.get(0).simulateBlockFix); assertEquals("sr", codecs.get(1).id); assertEquals(10, codecs.get(1).stripeLength); assertEquals(5, codecs.get(1).parityLength); assertEquals(200, codecs.get(1).priority); assertEquals("/raidsr", codecs.get(1).parityDirectory); assertEquals("/tmp/raidsr", codecs.get(1).tmpParityDirectory); assertEquals("/tmp/raidsr_har", codecs.get(1).tmpHarDirectory); - assertEquals(2, codecs.get(1).json.getInt("degree")); assertEquals("SimpleRegeneratingCode code", codecs.get(1).description); assertEquals(false, codecs.get(1).simulateBlockFix); assertEquals("xor", codecs.get(2).id); assertEquals(10, codecs.get(2).stripeLength); assertEquals(1, codecs.get(2).parityLength); assertEquals(100, codecs.get(2).priority); assertEquals("/raid", codecs.get(2).parityDirectory); assertEquals("/tmp/raid", codecs.get(2).tmpParityDirectory); assertEquals("/tmp/raid_har", codecs.get(2).tmpHarDirectory); assertEquals("", codecs.get(2).description); assertEquals(false, codecs.get(2).simulateBlockFix); assertTrue(codecs.get(0).createErasureCode(conf) instanceof ReedSolomonCode); assertTrue(codecs.get(2).createErasureCode(conf) instanceof XORCode); } }
true
true
public void testCreation() throws Exception { Configuration conf = new Configuration(); String jsonStr = " [\n" + " { \n" + " \"id\" : \"rs\",\n" + " \"parity_dir\" : \"/raidrs\",\n" + " \"stripe_length\" : 10,\n" + " \"parity_length\" : 4,\n" + " \"priority\" : 300,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.ReedSolomonCode\",\n" + " \"description\" : \"ReedSolomonCode code\",\n" + " \"simulate_block_fix\" : true,\n" + " }, \n" + " { \n" + " \"id\" : \"xor\",\n" + " \"parity_dir\" : \"/raid\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 1,\n" + " \"priority\" : 100,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.XORCode\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " { \n" + " \"id\" : \"sr\",\n" + " \"parity_dir\" : \"/raidsr\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 5, \n" + " \"degree\" : 2,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.SimpleRegeneratingCode\",\n" + " \"priority\" : 200,\n" + " \"description\" : \"SimpleRegeneratingCode code\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " ]\n"; conf.set("raid.codecs.json", jsonStr); Codec.initializeCodecs(conf); assertEquals("xor", Codec.getCodec("xor").id); assertEquals("rs", Codec.getCodec("rs").id); assertEquals("sr", Codec.getCodec("sr").id); List<Codec> codecs = Codec.getCodecs(); assertEquals(3, codecs.size()); assertEquals("rs", codecs.get(0).id); assertEquals(10, codecs.get(0).stripeLength); assertEquals(4, codecs.get(0).parityLength); assertEquals(300, codecs.get(0).priority); assertEquals("/raidrs", codecs.get(0).parityDirectory); assertEquals("/tmp/raidrs", codecs.get(0).tmpParityDirectory); assertEquals("/tmp/raidrs_har", codecs.get(0).tmpHarDirectory); assertEquals("ReedSolomonCode code", codecs.get(0).description); assertEquals(true, codecs.get(0).simulateBlockFix); assertEquals("sr", codecs.get(1).id); assertEquals(10, codecs.get(1).stripeLength); assertEquals(5, codecs.get(1).parityLength); assertEquals(200, codecs.get(1).priority); assertEquals("/raidsr", codecs.get(1).parityDirectory); assertEquals("/tmp/raidsr", codecs.get(1).tmpParityDirectory); assertEquals("/tmp/raidsr_har", codecs.get(1).tmpHarDirectory); assertEquals(2, codecs.get(1).json.getInt("degree")); assertEquals("SimpleRegeneratingCode code", codecs.get(1).description); assertEquals(false, codecs.get(1).simulateBlockFix); assertEquals("xor", codecs.get(2).id); assertEquals(10, codecs.get(2).stripeLength); assertEquals(1, codecs.get(2).parityLength); assertEquals(100, codecs.get(2).priority); assertEquals("/raid", codecs.get(2).parityDirectory); assertEquals("/tmp/raid", codecs.get(2).tmpParityDirectory); assertEquals("/tmp/raid_har", codecs.get(2).tmpHarDirectory); assertEquals("", codecs.get(2).description); assertEquals(false, codecs.get(2).simulateBlockFix); assertTrue(codecs.get(0).createErasureCode(conf) instanceof ReedSolomonCode); assertTrue(codecs.get(2).createErasureCode(conf) instanceof XORCode); }
public void testCreation() throws Exception { Configuration conf = new Configuration(); String jsonStr = " [\n" + " { \n" + " \"id\" : \"rs\",\n" + " \"parity_dir\" : \"/raidrs\",\n" + " \"stripe_length\" : 10,\n" + " \"parity_length\" : 4,\n" + " \"priority\" : 300,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.ReedSolomonCode\",\n" + " \"description\" : \"ReedSolomonCode code\",\n" + " \"simulate_block_fix\" : true,\n" + " }, \n" + " { \n" + " \"id\" : \"xor\",\n" + " \"parity_dir\" : \"/raid\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 1,\n" + " \"priority\" : 100,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.XORCode\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " { \n" + " \"id\" : \"sr\",\n" + " \"parity_dir\" : \"/raidsr\",\n" + " \"stripe_length\" : 10, \n" + " \"parity_length\" : 5, \n" + " \"degree\" : 2,\n" + " \"erasure_code\" : \"org.apache.hadoop.raid.SimpleRegeneratingCode\",\n" + " \"priority\" : 200,\n" + " \"description\" : \"SimpleRegeneratingCode code\",\n" + " \"simulate_block_fix\" : false,\n" + " }, \n" + " ]\n"; conf.set("raid.codecs.json", jsonStr); Codec.initializeCodecs(conf); assertEquals("xor", Codec.getCodec("xor").id); assertEquals("rs", Codec.getCodec("rs").id); assertEquals("sr", Codec.getCodec("sr").id); List<Codec> codecs = Codec.getCodecs(); assertEquals(3, codecs.size()); assertEquals("rs", codecs.get(0).id); assertEquals(10, codecs.get(0).stripeLength); assertEquals(4, codecs.get(0).parityLength); assertEquals(300, codecs.get(0).priority); assertEquals("/raidrs", codecs.get(0).parityDirectory); assertEquals("/tmp/raidrs", codecs.get(0).tmpParityDirectory); assertEquals("/tmp/raidrs_har", codecs.get(0).tmpHarDirectory); assertEquals("ReedSolomonCode code", codecs.get(0).description); assertEquals(true, codecs.get(0).simulateBlockFix); assertEquals("sr", codecs.get(1).id); assertEquals(10, codecs.get(1).stripeLength); assertEquals(5, codecs.get(1).parityLength); assertEquals(200, codecs.get(1).priority); assertEquals("/raidsr", codecs.get(1).parityDirectory); assertEquals("/tmp/raidsr", codecs.get(1).tmpParityDirectory); assertEquals("/tmp/raidsr_har", codecs.get(1).tmpHarDirectory); assertEquals("SimpleRegeneratingCode code", codecs.get(1).description); assertEquals(false, codecs.get(1).simulateBlockFix); assertEquals("xor", codecs.get(2).id); assertEquals(10, codecs.get(2).stripeLength); assertEquals(1, codecs.get(2).parityLength); assertEquals(100, codecs.get(2).priority); assertEquals("/raid", codecs.get(2).parityDirectory); assertEquals("/tmp/raid", codecs.get(2).tmpParityDirectory); assertEquals("/tmp/raid_har", codecs.get(2).tmpHarDirectory); assertEquals("", codecs.get(2).description); assertEquals(false, codecs.get(2).simulateBlockFix); assertTrue(codecs.get(0).createErasureCode(conf) instanceof ReedSolomonCode); assertTrue(codecs.get(2).createErasureCode(conf) instanceof XORCode); }
diff --git a/flexodesktop/model/flexoxmlcode/src/main/java/org/openflexo/xmlcode/StringEncoder.java b/flexodesktop/model/flexoxmlcode/src/main/java/org/openflexo/xmlcode/StringEncoder.java index 8aafa8cd2..31f020b17 100644 --- a/flexodesktop/model/flexoxmlcode/src/main/java/org/openflexo/xmlcode/StringEncoder.java +++ b/flexodesktop/model/flexoxmlcode/src/main/java/org/openflexo/xmlcode/StringEncoder.java @@ -1,1030 +1,1033 @@ /* * (c) Copyright 2010-2011 AgileBirds * * This file is part of OpenFlexo. * * OpenFlexo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenFlexo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>. * */ package org.openflexo.xmlcode; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.awt.Rectangle; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; /** * Utility class used to encode objects * * @author sguerin */ public class StringEncoder { private static StringEncoder defaultInstance = new StringEncoder(); public static String encodeBoolean(boolean aBoolean) { return aBoolean ? "true" : "false"; } public static String encodeByte(byte aByte) { return "" + aByte; } public static String encodeCharacter(char aChar) { return "" + aChar; } public static String encodeDouble(double aDouble) { return "" + aDouble; } public static String encodeFloat(float aFloat) { return "" + aFloat; } public static String encodeInteger(int anInt) { return "" + anInt; } public static String encodeLong(long aLong) { return "" + aLong; } public static String encodeShort(short aShort) { return "" + aShort; } public static boolean decodeAsBoolean(String value) { return value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes"); } public static byte decodeAsByte(String value) { return Byte.parseByte(value); } public static char decodeAsCharacter(String value) { return value.charAt(0); } public static double decodeAsDouble(String value) { try { return Double.parseDouble(value); } catch (NumberFormatException e) { return 0; } } public static float decodeAsFloat(String value) { return Float.parseFloat(value); } public static int decodeAsInteger(String value) { if (value == null) { return -1; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { return (int) decodeAsDouble(value); } } public static long decodeAsLong(String value) { return Long.parseLong(value); } public static short decodeAsShort(String value) { return Short.parseShort(value); } /** * * @param value * @param objectType * @return * @deprecated use the non static method {@link #_decodeObject(String, Class)} */ @Deprecated public static <T> T decodeObject(String value, Class<T> objectType) { return defaultInstance._decodeObject(value, objectType); } /** * * @param object * @return * @deprecated use the non static method {@link #_encodeObject(Object)} */ @Deprecated public static <T> String encodeObject(T object) { return defaultInstance._encodeObject(object); } /** * * @param objectType * @return * @deprecated use the non static method {@link #_converterForClass(Class)} */ @Deprecated public static <T> Converter<T> converterForClass(Class<T> objectType) { return defaultInstance._converterForClass(objectType); } /** * * @param objectType * @return * @deprecated use the non static method {@link #_isConvertable(Class)} */ @Deprecated public static <T> boolean isConvertable(Class<T> objectType) { return defaultInstance._isConvertable(objectType); } /** * Sets date format, under the form <code>"yyyy.MM.dd G 'at' HH:mm:ss a zzz"</code> * * @deprecated use the non static method {@link #_setDateFormat(String)} */ @Deprecated public static void setDateFormat(String aFormat) { defaultInstance._setDateFormat(aFormat); } /** * * @return * @deprecated use the non static method {@link #_getDateFormat()} */ @Deprecated public static String getDateFormat() { return defaultInstance._getDateFormat(); } /** * Return a string representation of a date, according to valid date format * * @deprecated use the non-static method {@link #_getDateRepresentation(Date)} */ @Deprecated public static String getDateRepresentation(Date aDate) { return defaultInstance._getDateRepresentation(aDate); } /** * * @param converter * @return * @deprecated use the non-static method {@link #_addConverter(org.openflexo.xmlcode.StringEncoder.Converter)} */ @Deprecated public static <T> Converter<T> addConverter(Converter<T> converter) { return defaultInstance._addConverter(converter); } /** * @param converter */ public static <T> void removeConverter(Converter<T> converter) { defaultInstance._removeConverter(converter); } public static void initialize() { defaultInstance._initialize(); } public static void reset() { defaultInstance = new StringEncoder(); defaultInstance._initialize(); } /** * Abstract class defining a converter to and from a String for a given class * * @author sguerin */ public static abstract class Converter<T> { protected Class<T> converterClass; public Converter(Class<T> aClass) { super(); converterClass = aClass; } public Class<T> getConverterClass() { return converterClass; } public abstract T convertFromString(String value); public abstract String convertToString(T value); } public static class EnumerationConverter<T> extends Converter<T> { private String _stringRepresationMethodName; public EnumerationConverter(Class<T> enumeration, String stringRepresentationMethodName) { super(enumeration); _stringRepresationMethodName = stringRepresentationMethodName; } @Override public T convertFromString(String value) { if (value == null) { return null; } for (int i = 0; i < converterClass.getEnumConstants().length; i++) { if (value.equals(convertToString(converterClass.getEnumConstants()[i]))) { return converterClass.getEnumConstants()[i]; } } return null; } @Override public String convertToString(T value) { if (value == null) { return null; } try { Method m = value.getClass().getDeclaredMethod(_stringRepresationMethodName, (Class[]) null); return (String) m.invoke(value, (Object[]) null); } catch (NoSuchMethodException e) { System.err.println(_stringRepresationMethodName + " doesn't exist on enum :" + value.getClass().getName()); } catch (InvocationTargetException e) { System.err.println("Invocation of " + _stringRepresationMethodName + " on enum :" + value.getClass().getName() + " caused the following error : " + e.getMessage()); e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } /** * Class defining how to convert Boolean from/to String * * @author sguerin */ public static class BooleanConverter extends Converter<Boolean> { protected BooleanConverter() { super(Boolean.class); } @Override public Boolean convertFromString(String value) { return Boolean.valueOf(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes")); } @Override public String convertToString(Boolean value) { return value.toString(); } } /** * Class defining how to convert Integer from/to String * * @author sguerin */ public static class NumberConverter extends Converter<Number> { protected NumberConverter() { super(Number.class); } @Override public Number convertFromString(String value) { try { Number returned = Integer.parseInt(value); // System.out.println("Build a integer: "+value); return returned; } catch (NumberFormatException e1) { try { Number returned = Long.parseLong(value); // System.out.println("Build a long: "+value); return returned; } catch (NumberFormatException e2) { try { Number returned = Float.parseFloat(value); // System.out.println("Build a float: "+value); return returned; } catch (NumberFormatException e3) { try { Number returned = Double.parseDouble(value); // System.out.println("Build a double: "+value); return returned; } catch (NumberFormatException e4) { } } } } return null; } @Override public String convertToString(Number value) { return value.toString(); } } /** * Class defining how to convert Integer from/to String * * @author sguerin */ public static class IntegerConverter extends Converter<Integer> { protected IntegerConverter() { super(Integer.class); } @Override public Integer convertFromString(String value) { return Integer.valueOf(value); } @Override public String convertToString(Integer value) { return value.toString(); } } /** * Class defining how to convert Short from/to String * * @author sguerin */ public static class ShortConverter extends Converter<Short> { protected ShortConverter() { super(Short.class); } @Override public Short convertFromString(String value) { return Short.valueOf(value); } @Override public String convertToString(Short value) { return value.toString(); } } /** * Class defining how to convert Long from/to String * * @author sguerin */ public static class LongConverter extends Converter<Long> { protected LongConverter() { super(Long.class); } @Override public Long convertFromString(String value) { return Long.valueOf(value); } @Override public String convertToString(Long value) { return value.toString(); } } /** * Class defining how to convert Float from/to String * * @author sguerin */ public static class FloatConverter extends Converter<Float> { protected FloatConverter() { super(Float.class); } @Override public Float convertFromString(String value) { return Float.valueOf(value); } @Override public String convertToString(Float value) { return value.toString(); } } /** * Class defining how to convert Double from/to String * * @author sguerin */ public static class DoubleConverter extends Converter<Double> { protected DoubleConverter() { super(Double.class); } @Override public Double convertFromString(String value) { return Double.valueOf(value); } @Override public String convertToString(Double value) { return value.toString(); } } /** * Class defining how to convert String from/to String (easy !) * * @author sguerin */ public static class StringConverter extends Converter<String> { protected StringConverter() { super(String.class); } @Override public String convertFromString(String value) { return value; } @Override public String convertToString(String value) { return value; } } /** * Class defining how to convert String from/to Date * * @author sguerin */ public static class DateConverter extends Converter<Date> { /** Specify date format */ protected String _dateFormat = new SimpleDateFormat().toPattern(); public DateConverter() { super(Date.class); } @Override public Date convertFromString(String value) { try { return tryToConvertFromString(value); } catch (ParseException e) { SimpleDateFormat formatter = new SimpleDateFormat(_dateFormat); Date currentTime = new Date(); String dateString = formatter.format(currentTime); System.err.println("Supplied value is not parsable as a date. " + " Date format should be for example " + dateString); return null; } } public Date tryToConvertFromString(String value) throws ParseException { Date returned = null; StringTokenizer st = new StringTokenizer(value, ","); String dateFormat = _dateFormat; String dateAsString = null; if (st.hasMoreTokens()) { dateFormat = st.nextToken(); } if (st.hasMoreTokens()) { dateAsString = st.nextToken(); } if (dateAsString != null) { try { returned = new SimpleDateFormat(dateFormat).parse(dateAsString); } catch (IllegalArgumentException e) { throw new ParseException("While parsing supposed date format: " + e.getMessage(), 0); } } if (returned == null) { throw new ParseException("Cannot parse as a date " + value, 0); } return returned; } @Override public String convertToString(Date date) { if (date != null) { return _dateFormat + "," + new SimpleDateFormat(_dateFormat).format(date); } else { return null; } } /** * Return a string representation of a date, according to valid date format */ public String getDateRepresentation(Date date) { if (date != null) { return new SimpleDateFormat(_dateFormat).format(date); } else { return null; } } } /** * Class defining how to convert String from/to URL * * @author sguerin */ public static class URLConverter extends Converter<URL> { protected URLConverter() { super(URL.class); } @Override public URL convertFromString(String value) { try { return new URL(value); } catch (MalformedURLException e) { System.err.println("Supplied value is not parsable as an URL:" + value); return null; } } @Override public String convertToString(URL anURL) { if (anURL != null) { return anURL.toExternalForm(); } else { return null; } } } /** * Class defining how to convert String from/to File * * @author sguerin */ public static class FileConverter extends Converter<File> { protected FileConverter() { super(File.class); } @Override public File convertFromString(String value) { return new File(value); } @Override public String convertToString(File aFile) { if (aFile != null) { return aFile.getAbsolutePath(); } else { return null; } } } /** * Class defining how to convert String from/to Class * * @author sguerin */ public static class ClassConverter extends Converter<Class> { protected ClassConverter() { super(Class.class); } @Override public Class<?> convertFromString(String value) { if (value == null || value.isEmpty()) { return null; } try { if (value.equals("boolean")) { return Boolean.TYPE; } if (value.equals("int")) { return Integer.TYPE; } if (value.equals("short")) { return Short.TYPE; } if (value.equals("long")) { return Long.TYPE; } if (value.equals("float")) { return Float.TYPE; } if (value.equals("double")) { return Double.TYPE; } if (value.equals("byte")) { return Byte.TYPE; } if (value.equals("char")) { return Character.TYPE; } return Class.forName(value); } catch (ClassNotFoundException e) { // Warns about the exception throw new InvalidDataException("Supplied value represents a class not found: " + value); + } catch (NoClassDefFoundError e) { + e.printStackTrace(); + throw new InvalidDataException("Supplied value triggered a class not found: " + value); } } @Override public String convertToString(Class aClass) { if (aClass != null) { return aClass.getName(); } else { return null; } } } /** * Class defining how to convert String from/to Point * * @author sguerin */ public static class PointConverter extends Converter<Point> { protected PointConverter() { super(Point.class); } @Override public Point convertFromString(String value) { try { Point returned = new Point(); StringTokenizer st = new StringTokenizer(value, ","); if (st.hasMoreTokens()) { returned.x = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { returned.y = Integer.parseInt(st.nextToken()); } return returned; } catch (NumberFormatException e) { // Warns about the exception System.err.println("Supplied value is not parsable as a Point:" + value); return null; } } @Override public String convertToString(Point aPoint) { if (aPoint != null) { return aPoint.x + "," + aPoint.y; } else { return null; } } } /** * Class defining how to convert String from/to Point * * @author sguerin */ public static class RectangleConverter extends Converter<Rectangle> { protected RectangleConverter() { super(Rectangle.class); } @Override public Rectangle convertFromString(String value) { try { Rectangle returned = new Rectangle(); StringTokenizer st = new StringTokenizer(value, ","); if (st.hasMoreTokens()) { returned.x = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { returned.y = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { returned.width = Integer.parseInt(st.nextToken()); } if (st.hasMoreTokens()) { returned.height = Integer.parseInt(st.nextToken()); } return returned; } catch (NumberFormatException e) { // Warns about the exception System.err.println("Supplied value is not parsable as a Rectangle:" + value); return null; } } @Override public String convertToString(Rectangle rect) { if (rect != null) { return rect.x + "," + rect.y + "," + rect.width + "," + rect.height; } else { return null; } } } /** * Class defining how to convert String from/to Color * * @author sguerin */ public static class ColorConverter extends Converter<Color> { protected ColorConverter() { super(Color.class); } @Override public Color convertFromString(String value) { return new Color(redFromString(value), greenFromString(value), blueFromString(value)); } @Override public String convertToString(Color aColor) { return aColor.getRed() + "," + aColor.getGreen() + "," + aColor.getBlue(); } private static int redFromString(String s) { return Integer.parseInt(s.substring(0, s.indexOf(","))); } private static int greenFromString(String s) { return Integer.parseInt(s.substring(s.indexOf(",") + 1, s.lastIndexOf(","))); } private static int blueFromString(String s) { return Integer.parseInt(s.substring(s.lastIndexOf(",") + 1)); } } /** * Class defining how to convert String from/to Font * * @author sguerin */ public static class FontConverter extends Converter<Font> { protected FontConverter() { super(Font.class); } @Override public Font convertFromString(String value) { return new Font(nameFromString(value), styleFromString(value), sizeFromString(value)); } @Override public String convertToString(Font aFont) { return aFont.getName() + "," + aFont.getStyle() + "," + aFont.getSize(); } private static String nameFromString(String s) { return s.substring(0, s.indexOf(",")); } private static int styleFromString(String s) { return Integer.parseInt(s.substring(s.indexOf(",") + 1, s.lastIndexOf(","))); } private static int sizeFromString(String s) { return Integer.parseInt(s.substring(s.lastIndexOf(",") + 1)); } } /** * Hereunder are all the non-static elements of this class. Only those should be used. */ private Hashtable<Class<?>, Converter<?>> converters = new Hashtable<Class<?>, Converter<?>>(); private boolean isInitialized = false; private StringEncoder delegate; public StringEncoder() { } public StringEncoder(StringEncoder delegate, Converter<?>... converters) { super(); this.delegate = delegate; for (Converter<?> converter : converters) { _addConverter(converter); } isInitialized = true; } public List<Converter<?>> getConverters() { List<Converter<?>> converters = new ArrayList<StringEncoder.Converter<?>>(); if (delegate != null) { converters.addAll(delegate.getConverters()); } converters.addAll(this.converters.values()); return converters; } @SuppressWarnings("unchecked") public <T> T _decodeObject(String value, Class<T> objectType) { if (!isInitialized) { _initialize(); } if (value == null) { return null; } Converter<T> converter = _converterForClass(objectType); if (converter != null) { return converter.convertFromString(value); } else if (objectType.isEnum()) { try { return (T) Enum.valueOf((Class) objectType, value); } catch (IllegalArgumentException e) { System.err.println("Could not decode " + value + " as a " + objectType); return null; } } else { throw new InvalidDataException("Supplied value has no converter for type " + objectType.getName()); } } public <T> String _encodeObject(T object) { if (!isInitialized) { _initialize(); } if (object == null) { return null; } Converter<T> converter = (Converter<T>) _converterForClass(object.getClass()); if (converter != null) { return converter.convertToString(object); } else { if (object instanceof StringConvertable) { converter = ((StringConvertable) object).getConverter(); if (converter != null) { // System.out.println ("Registering my own converter"); _addConverter(converter); return converter.convertToString(object); } } else if (object instanceof Enum) { return ((Enum<?>) object).name(); } throw new InvalidDataException("Supplied value has no converter for type " + object.getClass().getName()); } } public <T> Converter<T> _converterForClass(Class<T> objectType) { if (!isInitialized) { _initialize(); } /* * System.out.println ("I've got those converters:"); for (Enumeration e = * converters.keys(); e.hasMoreElements();) { Class key = * (Class)e.nextElement(); Converter converter = * (Converter)converters.get(key); System.out.println ("Key: "+key+" * Converter: "+converter.getConverterClass().getName()); } */ Converter<?> returned; Class<? super T> tryThis = objectType; do { returned = converters.get(tryThis); if (tryThis.equals(Object.class)) { break; } tryThis = tryThis.getSuperclass(); } while (returned == null && tryThis != null); if (returned == null && delegate != null) { return delegate._converterForClass(objectType); } return (Converter<T>) returned; } public <T> boolean _isConvertable(Class<T> objectType) { if (!isInitialized) { _initialize(); } return _converterForClass(objectType) != null; } public <T> boolean _isEncodable(Class<T> objectType) { return _isConvertable(objectType) || objectType.isEnum(); } /** * Sets date format, under the form <code>"yyyy.MM.dd G 'at' HH:mm:ss a zzz"</code> */ public void _setDateFormat(String aFormat) { DateConverter dc = (DateConverter) _converterForClass(Date.class); dc._dateFormat = aFormat; } public String _getDateFormat() { DateConverter dc = (DateConverter) _converterForClass(Date.class); return dc._dateFormat; } /** * Return a string representation of a date, according to valid date format */ public String _getDateRepresentation(Date aDate) { DateConverter dc = (DateConverter) _converterForClass(Date.class); return dc.getDateRepresentation(aDate); } public <T> Converter<T> _addConverter(Converter<T> converter) { converters.put(converter.getConverterClass(), converter); return converter; } /** * @param converter */ public void _removeConverter(Converter<?> converter) { converters.remove(converter.getConverterClass()); } public void _initialize() { if (!isInitialized) { _addConverter(new BooleanConverter()); _addConverter(new IntegerConverter()); _addConverter(new ShortConverter()); _addConverter(new LongConverter()); _addConverter(new FloatConverter()); _addConverter(new DoubleConverter()); _addConverter(new StringConverter()); _addConverter(new DateConverter()); _addConverter(new URLConverter()); _addConverter(new FileConverter()); _addConverter(new ClassConverter()); _addConverter(new PointConverter()); _addConverter(new RectangleConverter()); _addConverter(new ColorConverter()); _addConverter(new FontConverter()); _addConverter(new NumberConverter()); isInitialized = true; } } public static StringEncoder getDefaultInstance() { return defaultInstance; } }
true
true
public Class<?> convertFromString(String value) { if (value == null || value.isEmpty()) { return null; } try { if (value.equals("boolean")) { return Boolean.TYPE; } if (value.equals("int")) { return Integer.TYPE; } if (value.equals("short")) { return Short.TYPE; } if (value.equals("long")) { return Long.TYPE; } if (value.equals("float")) { return Float.TYPE; } if (value.equals("double")) { return Double.TYPE; } if (value.equals("byte")) { return Byte.TYPE; } if (value.equals("char")) { return Character.TYPE; } return Class.forName(value); } catch (ClassNotFoundException e) { // Warns about the exception throw new InvalidDataException("Supplied value represents a class not found: " + value); } }
public Class<?> convertFromString(String value) { if (value == null || value.isEmpty()) { return null; } try { if (value.equals("boolean")) { return Boolean.TYPE; } if (value.equals("int")) { return Integer.TYPE; } if (value.equals("short")) { return Short.TYPE; } if (value.equals("long")) { return Long.TYPE; } if (value.equals("float")) { return Float.TYPE; } if (value.equals("double")) { return Double.TYPE; } if (value.equals("byte")) { return Byte.TYPE; } if (value.equals("char")) { return Character.TYPE; } return Class.forName(value); } catch (ClassNotFoundException e) { // Warns about the exception throw new InvalidDataException("Supplied value represents a class not found: " + value); } catch (NoClassDefFoundError e) { e.printStackTrace(); throw new InvalidDataException("Supplied value triggered a class not found: " + value); } }
diff --git a/modules/Core/src/main/java/jpower/core/Worker.java b/modules/Core/src/main/java/jpower/core/Worker.java index 2999c87..a59b57f 100644 --- a/modules/Core/src/main/java/jpower/core/Worker.java +++ b/modules/Core/src/main/java/jpower/core/Worker.java @@ -1,137 +1,137 @@ package jpower.core; import jpower.core.utils.ThreadUtils; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * Executes Tasks in a Thread. Can be used like ThreadPools. */ public class Worker implements Runnable { private boolean isWorking; private Thread thread; private boolean stop; protected final LinkedBlockingQueue<Task> queue; /** * Create a Worker with the Default Queue Size */ public Worker() { queue = new LinkedBlockingQueue<>(); } /** * Create a Worker with the specified Task Queue Size * * @param queueSize Task Queue Size */ public Worker(int queueSize) { queue = new LinkedBlockingQueue<>(queueSize); } /** * Adds a Task to the Queue * * @param task task to add */ public boolean addTask(Task task) { try { queue.put(task); } catch (InterruptedException e) { return false; } return true; } public boolean offer(Task task, long time, TimeUnit unit) throws InterruptedException { return queue.offer(task, time, unit); } @Override public void run() { while (!stop) { try { Task task = queue.poll(250, TimeUnit.MILLISECONDS); if (task == null) - return; + continue; if (!task.isCanceled()) { isWorking = true; task.execute(); isWorking = false; } } catch (InterruptedException ignored) { } } thread = null; } /** * Gets if the Worker is currently working. * * @return Is Worker Working */ public boolean isWorking() { return isWorking; } /** * Stops the Worker (Takes no more than 250 milliseconds) */ public void stop() { stop = true; } /** * Starts the Worker */ public void start() { if (!isRunning()) { thread = new Thread(this); thread.start(); } } /** * Gets the remaining capacity of the Task Queue * * @return Remaining Capacity */ public int remainingCapacity() { return queue.remainingCapacity(); } /** * Remove a Task from the Queue * * @param task task * @return if it was removed */ public boolean removeTask(Task task) { return queue.remove(task); } /** * The current size of the Task Queue * * @return Size */ public int size() { return queue.size(); } /** * Wait for the task queue to be empty */ public void waitFor() { while (isWorking() || !queue.isEmpty()) { ThreadUtils.sleep(1); } } public boolean isRunning() { return thread != null; } }
true
true
public void run() { while (!stop) { try { Task task = queue.poll(250, TimeUnit.MILLISECONDS); if (task == null) return; if (!task.isCanceled()) { isWorking = true; task.execute(); isWorking = false; } } catch (InterruptedException ignored) { } } thread = null; }
public void run() { while (!stop) { try { Task task = queue.poll(250, TimeUnit.MILLISECONDS); if (task == null) continue; if (!task.isCanceled()) { isWorking = true; task.execute(); isWorking = false; } } catch (InterruptedException ignored) { } } thread = null; }
diff --git a/assets/src/org/ruboto/JRubyAdapter.java b/assets/src/org/ruboto/JRubyAdapter.java index 265491f..0efce0b 100644 --- a/assets/src/org/ruboto/JRubyAdapter.java +++ b/assets/src/org/ruboto/JRubyAdapter.java @@ -1,529 +1,529 @@ package org.ruboto; import java.io.File; import java.io.FilenameFilter; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Environment; import dalvik.system.PathClassLoader; public class JRubyAdapter { private static Object ruby; private static boolean isDebugBuild = false; private static PrintStream output = null; private static boolean initialized = false; private static String localContextScope = "SINGLETON"; // FIXME(uwe): Why not CONCURRENT ? Help needed! private static String localVariableBehavior = "TRANSIENT"; private static String RUBOTO_CORE_VERSION_NAME; /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Object receiver, String methodName, Object... args)} */ @Deprecated public static void callMethod(Object receiver, String methodName, Object[] args) { runRubyMethod(receiver, methodName, args); } /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Object receiver, String methodName, Object... args)} */ @Deprecated public static void callMethod(Object object, String methodName, Object arg) { runRubyMethod(object, methodName, arg); } /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Object receiver, String methodName, Object... args)} */ @Deprecated public static void callMethod(Object object, String methodName) { runRubyMethod(object, methodName, new Object[] {}); } /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Class<T> returnType, Object receiver, String methodName, Object... args)} */ @SuppressWarnings("unchecked") @Deprecated public static <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType) { return (T) runRubyMethod(returnType, receiver, methodName, args); } /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Class<T> returnType, Object receiver, String methodName, Object... args)} */ @SuppressWarnings("unchecked") @Deprecated public static <T> T callMethod(Object receiver, String methodName, Object arg, Class<T> returnType) { return (T) runRubyMethod(returnType, receiver, methodName, arg); } /** * @deprecated As of Ruboto 0.7.1, replaced by {@link #runRubyMethod(Class<T> returnType, Object receiver, String methodName, Object... args)} */ @SuppressWarnings("unchecked") @Deprecated public static <T> T callMethod(Object receiver, String methodName, Class<T> returnType) { return (T) runRubyMethod(returnType, receiver, methodName); } /** * @deprecated As of Ruboto 0.7.0, replaced by {@link #put(String name, Object object)} */ @Deprecated public static void defineGlobalConstant(String name, Object object) { put(name, object); } /** * @deprecated As of Ruboto 0.7.0, replaced by {@link #put(String name, Object object)} */ @Deprecated public static void defineGlobalVariable(String name, Object object) { put(name, object); } /** * @deprecated As of Ruboto 0.7.0, replaced by {@link #runScriptlet(String code)} */ @Deprecated public static Object exec(String code) { try { Method runScriptletMethod = ruby.getClass().getMethod("runScriptlet", String.class); return runScriptletMethod.invoke(ruby, code); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { if (isDebugBuild) { throw ((RuntimeException) ite.getCause()); } else { return null; } } } /** * @deprecated As of Ruboto 0.7.0, replaced by {@link #runScriptlet(String code)} */ @Deprecated public static String execute(String code) { return (String) runRubyMethod(String.class, exec(code), "inspect"); } public static Object get(String name) { try { Method getMethod = ruby.getClass().getMethod("get", String.class); return getMethod.invoke(ruby, name); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { throw new RuntimeException(ite); } } public static String getPlatformVersionName() { return RUBOTO_CORE_VERSION_NAME; } public static String getScriptFilename() { return (String) callScriptingContainerMethod(String.class, "getScriptFilename"); } public static Object runRubyMethod(Object receiver, String methodName, Object... args) { try { // FIXME(uwe): Simplify when we stop supporting JRuby < 1.7.0 if (isJRubyPreOneSeven()) { if (args.length == 0) { Method m = ruby.getClass().getMethod("callMethod", Object.class, String.class, Class.class); // System.out.println("Calling callMethod(" + receiver + ", " + methodName + ", " + Object.class + ")"); return m.invoke(ruby, receiver, methodName, Object.class); } else { Method m = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class, Class.class); // System.out.println("Calling callMethod(" + receiver + ", " + methodName + ", " + args + ", " + Object.class + ")"); return m.invoke(ruby, receiver, methodName, args, Object.class); } } else { Method m = ruby.getClass().getMethod("runRubyMethod", Class.class, Object.class, String.class, Object[].class); return m.invoke(ruby, Object.class, receiver, methodName, args); } } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); if (isDebugBuild) { throw new RuntimeException(ite); } } return null; } @SuppressWarnings("unchecked") public static <T> T runRubyMethod(Class<T> returnType, Object receiver, String methodName, Object... args) { try { // FIXME(uwe): Simplify when we stop supporting JRuby < 1.7.0 if (isJRubyPreOneSeven()) { if (args.length == 0) { Method m = ruby.getClass().getMethod("callMethod", Object.class, String.class, Class.class); return (T) m.invoke(ruby, receiver, methodName, returnType); } else { Method m = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class, Class.class); return (T) m.invoke(ruby, receiver, methodName, args, returnType); } } else { Method m = ruby.getClass().getMethod("runRubyMethod", Class.class, Object.class, String.class, Object[].class); return (T) m.invoke(ruby, returnType, receiver, methodName, args); } } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); } return null; } public static boolean isDebugBuild() { return isDebugBuild; } public static boolean isInitialized() { return initialized; } public static void put(String name, Object object) { try { Method putMethod = ruby.getClass().getMethod("put", String.class, Object.class); putMethod.invoke(ruby, name, object); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { throw new RuntimeException(ite); } } public static Object runScriptlet(String code) { try { Method runScriptletMethod = ruby.getClass().getMethod("runScriptlet", String.class); return runScriptletMethod.invoke(ruby, code); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { if (isDebugBuild) { if (ite.getCause() instanceof RuntimeException) { throw ((RuntimeException) ite.getCause()); } else { throw ((Error) ite.getCause()); } } else { return null; } } } public static boolean setUpJRuby(Context appContext) { return setUpJRuby(appContext, output == null ? System.out : output); } @SuppressWarnings({ "unchecked", "rawtypes" }) public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { // BEGIN Ruboto HeapAlloc @SuppressWarnings("unused") byte[] arrayForHeapAllocation = new byte[13 * 1024 * 1024]; arrayForHeapAllocation = null; // END Ruboto HeapAlloc setDebugBuild(appContext); Log.d("Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); - System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCEIR + System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCE FORCEIR // System.setProperty("jruby.compile.backend", "DALVIK"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default in JRuby 1.7 System.setProperty("jruby.ir.passes", "LocalOptimizationPass,DeadCodeElimination"); System.setProperty("jruby.backtrace.style", "normal"); // normal raw full mri // Uncomment these to debug/profile Ruby source loading - System.setProperty("jruby.debug.loadService", "true"); + // System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); // Used to enable JRuby to generate proxy classes System.setProperty("jruby.ji.proxyClassFactory", "org.ruboto.DalvikProxyClassFactory"); System.setProperty("jruby.class.cache.path", appContext.getDir("dex", 0).getAbsolutePath()); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = JRubyAdapter.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { System.out.println("JRuby not found in local APK:"); e1.printStackTrace(); System.out.println("JRuby not found in platform APK:"); e2.printStackTrace(); return false; } System.out.println("Found JRuby in platform APK"); classLoader = new PathClassLoader(apkName, JRubyAdapter.class.getClassLoader()); try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d("Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!/jruby.home"; // FIXME(uwe): Remove when we stop supporting RubotoCore 0.4.7 Log.i("RUBOTO_CORE_VERSION_NAME: " + RUBOTO_CORE_VERSION_NAME); if (RUBOTO_CORE_VERSION_NAME != null && (RUBOTO_CORE_VERSION_NAME.equals("0.4.7") || RUBOTO_CORE_VERSION_NAME.equals("0.4.8"))) { jrubyHome = "file:" + apkName + "!"; } // EMXIF Log.i("Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); addLoadPath(scriptsDirName(appContext)); initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; } public static void setScriptFilename(String name) { callScriptingContainerMethod(Void.class, "setScriptFilename", name); } public static boolean usesPlatformApk() { return RUBOTO_CORE_VERSION_NAME != null; } // Private methods private static Boolean addLoadPath(String scriptsDir) { if (new File(scriptsDir).exists()) { Log.i("Added directory to load path: " + scriptsDir); Script.addDir(scriptsDir); runScriptlet("$:.unshift '" + scriptsDir + "' ; $:.uniq!"); Log.d("Changing JRuby current directory to " + scriptsDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir); return true; } else { Log.i("Extra scripts dir not present: " + scriptsDir); return false; } } @SuppressWarnings("unchecked") private static <T> T callScriptingContainerMethod(Class<T> returnType, String methodName, Object... args) { Class<?>[] argClasses = new Class[args.length]; for (int i = 0; i < argClasses.length; i++) { argClasses[i] = args[i].getClass(); } try { Method method = ruby.getClass().getMethod(methodName, argClasses); T result = (T) method.invoke(ruby, args); return result; } catch (RuntimeException re) { re.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { printStackTrace(e); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } private static void handleInitException(Exception e) { Log.e("Exception starting JRuby"); Log.e(e.getMessage() != null ? e.getMessage() : e.getClass().getName()); e.printStackTrace(); ruby = null; } // FIXME(uwe): Remove when we stop supporting JRuby < 1.7.0 @Deprecated public static boolean isJRubyPreOneSeven() { return ((String)get("JRUBY_VERSION")).equals("1.7.0.dev") || ((String)get("JRUBY_VERSION")).startsWith("1.6."); } // FIXME(uwe): Remove when we stop supporting JRuby < 1.7.0 @Deprecated public static boolean isJRubyOneSeven() { return !isJRubyPreOneSeven() && ((String)get("JRUBY_VERSION")).startsWith("1.7."); } // FIXME(uwe): Remove when we stop supporting Ruby 1.8 @Deprecated public static boolean isRubyOneEight() { return ((String)get("RUBY_VERSION")).startsWith("1.8."); } // FIXME(uwe): Remove when we stop supporting Ruby 1.8 @Deprecated public static boolean isRubyOneNine() { return ((String)get("RUBY_VERSION")).startsWith("1.9."); } static void printStackTrace(Throwable t) { // TODO(uwe): Simplify this when Issue #144 is resolved try { t.printStackTrace(output); } catch (NullPointerException npe) { // TODO(uwe): printStackTrace should not fail for (java.lang.StackTraceElement ste : t.getStackTrace()) { output.append(ste.toString() + "\n"); } } } private static String scriptsDirName(Context context) { File storageDir = null; if (isDebugBuild()) { // FIXME(uwe): Simplify this as soon as we drop support for android-7 if (android.os.Build.VERSION.SDK_INT >= 8) { try { Method method = context.getClass().getMethod("getExternalFilesDir", String.class); storageDir = (File) method.invoke(context, (Object) null); } catch (SecurityException e) { printStackTrace(e); } catch (NoSuchMethodException e) { printStackTrace(e); } catch (IllegalArgumentException e) { printStackTrace(e); } catch (IllegalAccessException e) { printStackTrace(e); } catch (InvocationTargetException e) { printStackTrace(e); } } else { storageDir = new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/files"); Log.e("Calculated path to sdcard the old way: " + storageDir); } // FIXME end if (storageDir == null || (!storageDir.exists() && !storageDir.mkdirs())) { Log.e("Development mode active, but sdcard is not available. Make sure you have added\n<uses-permission android:name='android.permission.WRITE_EXTERNAL_STORAGE' />\nto your AndroidManifest.xml file."); storageDir = context.getFilesDir(); } } else { storageDir = context.getFilesDir(); } return storageDir.getAbsolutePath() + "/scripts"; } private static void setDebugBuild(Context context) { PackageManager pm = context.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(context.getPackageName(), 0); isDebugBuild = ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); } catch (NameNotFoundException e) { isDebugBuild = false; } } private static void setLocalContextScope(String val) { localContextScope = val; } private static void setLocalVariableBehavior(String val) { localVariableBehavior = val; } private static void setOutputStream(PrintStream out) { if (ruby == null) { output = out; } else { try { Method setOutputMethod = ruby.getClass().getMethod("setOutput", PrintStream.class); setOutputMethod.invoke(ruby, out); Method setErrorMethod = ruby.getClass().getMethod("setError", PrintStream.class); setErrorMethod.invoke(ruby, out); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } } }
false
true
public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { // BEGIN Ruboto HeapAlloc @SuppressWarnings("unused") byte[] arrayForHeapAllocation = new byte[13 * 1024 * 1024]; arrayForHeapAllocation = null; // END Ruboto HeapAlloc setDebugBuild(appContext); Log.d("Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCEIR // System.setProperty("jruby.compile.backend", "DALVIK"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default in JRuby 1.7 System.setProperty("jruby.ir.passes", "LocalOptimizationPass,DeadCodeElimination"); System.setProperty("jruby.backtrace.style", "normal"); // normal raw full mri // Uncomment these to debug/profile Ruby source loading System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); // Used to enable JRuby to generate proxy classes System.setProperty("jruby.ji.proxyClassFactory", "org.ruboto.DalvikProxyClassFactory"); System.setProperty("jruby.class.cache.path", appContext.getDir("dex", 0).getAbsolutePath()); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = JRubyAdapter.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { System.out.println("JRuby not found in local APK:"); e1.printStackTrace(); System.out.println("JRuby not found in platform APK:"); e2.printStackTrace(); return false; } System.out.println("Found JRuby in platform APK"); classLoader = new PathClassLoader(apkName, JRubyAdapter.class.getClassLoader()); try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d("Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!/jruby.home"; // FIXME(uwe): Remove when we stop supporting RubotoCore 0.4.7 Log.i("RUBOTO_CORE_VERSION_NAME: " + RUBOTO_CORE_VERSION_NAME); if (RUBOTO_CORE_VERSION_NAME != null && (RUBOTO_CORE_VERSION_NAME.equals("0.4.7") || RUBOTO_CORE_VERSION_NAME.equals("0.4.8"))) { jrubyHome = "file:" + apkName + "!"; } // EMXIF Log.i("Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); addLoadPath(scriptsDirName(appContext)); initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; }
public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { // BEGIN Ruboto HeapAlloc @SuppressWarnings("unused") byte[] arrayForHeapAllocation = new byte[13 * 1024 * 1024]; arrayForHeapAllocation = null; // END Ruboto HeapAlloc setDebugBuild(appContext); Log.d("Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); System.setProperty("jruby.compile.mode", "OFF"); // OFF OFFIR JITIR? FORCE FORCEIR // System.setProperty("jruby.compile.backend", "DALVIK"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default in JRuby 1.7 System.setProperty("jruby.ir.passes", "LocalOptimizationPass,DeadCodeElimination"); System.setProperty("jruby.backtrace.style", "normal"); // normal raw full mri // Uncomment these to debug/profile Ruby source loading // System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); // Used to enable JRuby to generate proxy classes System.setProperty("jruby.ji.proxyClassFactory", "org.ruboto.DalvikProxyClassFactory"); System.setProperty("jruby.class.cache.path", appContext.getDir("dex", 0).getAbsolutePath()); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = JRubyAdapter.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { System.out.println("JRuby not found in local APK:"); e1.printStackTrace(); System.out.println("JRuby not found in platform APK:"); e2.printStackTrace(); return false; } System.out.println("Found JRuby in platform APK"); classLoader = new PathClassLoader(apkName, JRubyAdapter.class.getClassLoader()); try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d("Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!/jruby.home"; // FIXME(uwe): Remove when we stop supporting RubotoCore 0.4.7 Log.i("RUBOTO_CORE_VERSION_NAME: " + RUBOTO_CORE_VERSION_NAME); if (RUBOTO_CORE_VERSION_NAME != null && (RUBOTO_CORE_VERSION_NAME.equals("0.4.7") || RUBOTO_CORE_VERSION_NAME.equals("0.4.8"))) { jrubyHome = "file:" + apkName + "!"; } // EMXIF Log.i("Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); addLoadPath(scriptsDirName(appContext)); initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; }
diff --git a/src/com/dwarfholm/activitystats/braizhauler/ASData.java b/src/com/dwarfholm/activitystats/braizhauler/ASData.java index e130f5a..8225174 100644 --- a/src/com/dwarfholm/activitystats/braizhauler/ASData.java +++ b/src/com/dwarfholm/activitystats/braizhauler/ASData.java @@ -1,117 +1,117 @@ package com.dwarfholm.activitystats.braizhauler; import java.util.HashMap; import org.bukkit.entity.Player; public class ASData { private HashMap <String, ASPlayer> playerlist; private ASDatabase database; private ActivityStats plugin; public ASData(ActivityStats plugin) { this.plugin = plugin; playerlist = new HashMap<String, ASPlayer>(); database = new ASDatabase(plugin); } public void saveAll() { for (ASPlayer player:playerlist.values()) database.updatePlayer(player); } public void createDatabase() { database.createTables(); } public void recordOnline() { - if (playerlist.size() > 0) { + if (playerlist!=null && playerlist.size() > 0) { for (ASPlayer player:playerlist.values()) if ( plugin.getServer().getPlayer(player.getName()).isOnline() ) player.curPeriod.addOnline(); if( plugin.PeriodRolloverDue()) { plugin.info("Paying all Players"); for (ASPlayer player:playerlist.values()) { plugin.info(player.getName()); plugin.payPlayer(player); } if( plugin.DayRolloverDue()) rolloverDay(); if( plugin.WeekRolloverDue()) rolloverWeek(); if( plugin.MonthRolloverDue()) rolloverMonth(); rolloverPeriod(); Player pPlayer; for (ASPlayer player:playerlist.values()) { pPlayer = plugin.getServer().getPlayer(player.getName()); if ( pPlayer.isOnline() ) plugin.autoPromoterCheck(pPlayer); else playerlist.remove(player.getName()); } saveAll(); } } } public void loadPlayer(String player) { database.loadPlayer(player); } public void savePlayer(String name) { savePlayer(playerlist.get(name)); } public void savePlayer(ASPlayer player) { database.updatePlayer(player); } public void setPlayer(ASPlayer player) { playerlist.put(player.getName(), player); } public ASPlayer getPlayer(String name) { return playerlist.get(name); } public void rolloverPeriod() { for(String player: playerlist.keySet()) { playerlist.get(player).rolloverPeriod(); } plugin.rolledoverPeriod(); } public void rolloverDay() { for(String player: playerlist.keySet()) playerlist.get(player).rolloverDay(); plugin.rolledoverDay(); } public void rolloverWeek() { for(String player: playerlist.keySet()) playerlist.get(player).rolloverWeek(); plugin.rolledoverWeek(); } public void rolloverMonth() { for(String player: playerlist.keySet()) playerlist.get(player).rolloverMonth(); plugin.rolledoverMonth(); } public void loadOnlinePlayers() { for (Player player: plugin.getServer().getOnlinePlayers() ) loadPlayer(player.getName()); } }
true
true
public void recordOnline() { if (playerlist.size() > 0) { for (ASPlayer player:playerlist.values()) if ( plugin.getServer().getPlayer(player.getName()).isOnline() ) player.curPeriod.addOnline(); if( plugin.PeriodRolloverDue()) { plugin.info("Paying all Players"); for (ASPlayer player:playerlist.values()) { plugin.info(player.getName()); plugin.payPlayer(player); } if( plugin.DayRolloverDue()) rolloverDay(); if( plugin.WeekRolloverDue()) rolloverWeek(); if( plugin.MonthRolloverDue()) rolloverMonth(); rolloverPeriod(); Player pPlayer; for (ASPlayer player:playerlist.values()) { pPlayer = plugin.getServer().getPlayer(player.getName()); if ( pPlayer.isOnline() ) plugin.autoPromoterCheck(pPlayer); else playerlist.remove(player.getName()); } saveAll(); } } }
public void recordOnline() { if (playerlist!=null && playerlist.size() > 0) { for (ASPlayer player:playerlist.values()) if ( plugin.getServer().getPlayer(player.getName()).isOnline() ) player.curPeriod.addOnline(); if( plugin.PeriodRolloverDue()) { plugin.info("Paying all Players"); for (ASPlayer player:playerlist.values()) { plugin.info(player.getName()); plugin.payPlayer(player); } if( plugin.DayRolloverDue()) rolloverDay(); if( plugin.WeekRolloverDue()) rolloverWeek(); if( plugin.MonthRolloverDue()) rolloverMonth(); rolloverPeriod(); Player pPlayer; for (ASPlayer player:playerlist.values()) { pPlayer = plugin.getServer().getPlayer(player.getName()); if ( pPlayer.isOnline() ) plugin.autoPromoterCheck(pPlayer); else playerlist.remove(player.getName()); } saveAll(); } } }
diff --git a/Cocoa4Android/src/org/cocoa4android/third/sbjson/SBJsonParser.java b/Cocoa4Android/src/org/cocoa4android/third/sbjson/SBJsonParser.java index b95eeec..5bddc39 100644 --- a/Cocoa4Android/src/org/cocoa4android/third/sbjson/SBJsonParser.java +++ b/Cocoa4Android/src/org/cocoa4android/third/sbjson/SBJsonParser.java @@ -1,102 +1,103 @@ /* * Copyright (C) 2012 Wu Tong * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cocoa4android.third.sbjson; import java.util.Iterator; import org.cocoa4android.ns.NSMutableArray; import org.cocoa4android.ns.NSMutableDictionary; import org.cocoa4android.ns.NSObject; import org.cocoa4android.ns.NSString; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class SBJsonParser extends NSObject { public NSObject objectWithString(NSString repr){ String content = repr.getString(); content = content.trim(); if(content.startsWith("[")){ //NSArray return this.parseArray(content); }else if(content.startsWith("{")){ return this.parseDictionary(content); }else if(!content.toLowerCase().equals("null")){ return repr; } return null; } private NSObject parseArray(String content){ try { JSONArray arJsonArray = new JSONArray(content); NSMutableArray array = NSMutableArray.array(); for (int i = 0; i < arJsonArray.length(); i++) { String value = arJsonArray.getString(i).trim(); if(value.startsWith("[")){ NSObject nsArray = this.parseArray(value); array.add(nsArray); }else if(value.startsWith("{")){ NSObject nsDictionary = this.parseDictionary(value); array.add(nsDictionary); }else if(!content.toLowerCase().equals("null")){ array.add(new NSString(value)); }else{ array.add(null); } } return array; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private NSObject parseDictionary(String content){ try { JSONObject jsonObject = new JSONObject(content); @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); NSMutableDictionary dic = NSMutableDictionary.dictionary(); while (iterator.hasNext()) { String key = (String) iterator.next().trim(); String value = jsonObject.getString(key).trim(); if(value.startsWith("[")){ NSObject array = this.parseArray(content); dic.setObject(array, key); }else if(value.startsWith("{")){ NSObject object = this.parseDictionary(content); dic.setObject(object, key); }else if(!value.toLowerCase().equals("null")){ dic.setObject(new NSString(value), key); }else{ dic.setObject(null, key); } } + return dic; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
true
true
private NSObject parseDictionary(String content){ try { JSONObject jsonObject = new JSONObject(content); @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); NSMutableDictionary dic = NSMutableDictionary.dictionary(); while (iterator.hasNext()) { String key = (String) iterator.next().trim(); String value = jsonObject.getString(key).trim(); if(value.startsWith("[")){ NSObject array = this.parseArray(content); dic.setObject(array, key); }else if(value.startsWith("{")){ NSObject object = this.parseDictionary(content); dic.setObject(object, key); }else if(!value.toLowerCase().equals("null")){ dic.setObject(new NSString(value), key); }else{ dic.setObject(null, key); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
private NSObject parseDictionary(String content){ try { JSONObject jsonObject = new JSONObject(content); @SuppressWarnings("unchecked") Iterator<String> iterator = jsonObject.keys(); NSMutableDictionary dic = NSMutableDictionary.dictionary(); while (iterator.hasNext()) { String key = (String) iterator.next().trim(); String value = jsonObject.getString(key).trim(); if(value.startsWith("[")){ NSObject array = this.parseArray(content); dic.setObject(array, key); }else if(value.startsWith("{")){ NSObject object = this.parseDictionary(content); dic.setObject(object, key); }else if(!value.toLowerCase().equals("null")){ dic.setObject(new NSString(value), key); }else{ dic.setObject(null, key); } } return dic; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
diff --git a/src/be/ibridge/kettle/trans/step/tableoutput/TableOutput.java b/src/be/ibridge/kettle/trans/step/tableoutput/TableOutput.java index a34facbb..48ae1eb7 100644 --- a/src/be/ibridge/kettle/trans/step/tableoutput/TableOutput.java +++ b/src/be/ibridge/kettle/trans/step/tableoutput/TableOutput.java @@ -1,349 +1,348 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.trans.step.tableoutput; import java.sql.PreparedStatement; import java.text.SimpleDateFormat; import java.util.Iterator; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.exception.KettleDatabaseBatchException; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Writes rows to a database table. * * @author Matt * @since 6-apr-2003 */ public class TableOutput extends BaseStep implements StepInterface { private TableOutputMeta meta; private TableOutputData data; public TableOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; Row r; r=getRow(); // this also waits for a previous step to be finished. if (r==null) // no more input to be expected... { setOutputDone(); return false; } try { writeToTable(r); putRow(r); // in case we want it go further... if (checkFeedback(linesOutput)) logBasic("linenr "+linesOutput); } catch(KettleException e) { logError("Because of an error, this step can't continue: "+e.getMessage()); setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } return true; } - private boolean writeToTable(Row r) - throws KettleException + private boolean writeToTable(Row r) throws KettleException { if (r==null) // Stop: last line or error encountered { if (log.isDetailed()) logDetailed("Last line inserted: stop"); return false; } PreparedStatement insertStatement = null; String tableName = null; Value removedValue = null; if ( meta.isTableNameInField() ) { // Cache the position of the table name field if (data.indexOfTableNameField<0) { data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField()); if (data.indexOfTableNameField<0) { String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row"; log.logError(toString(), message); throw new KettleStepException(message); } } tableName = r.getValue(data.indexOfTableNameField).getString(); if (!meta.isTableNameInTable()) { removedValue = r.getValue(data.indexOfTableNameField); r.removeValue(data.indexOfTableNameField); } } else if ( meta.isPartitioningEnabled() && ( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) && ( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 ) ) { // Initialize some stuff! if (data.indexOfPartitioningField<0) { data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField()); if (data.indexOfPartitioningField<0) { throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!"); } if (meta.isPartitioningDaily()) { data.dateFormater = new SimpleDateFormat("yyyyMMdd"); } else { data.dateFormater = new SimpleDateFormat("yyyyMM"); } } Value partitioningValue = r.getValue(data.indexOfPartitioningField); if (!partitioningValue.isDate() || partitioningValue.isNull()) { throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!"); } - tableName+="_"+data.dateFormater.format(partitioningValue.getDate()); + tableName=StringUtil.environmentSubstitute(meta.getTablename())+"_"+data.dateFormater.format(partitioningValue.getDate()); } else { tableName = data.tableName; } if (Const.isEmpty(tableName)) { throw new KettleStepException("The tablename is not defined (empty)"); } insertStatement = (PreparedStatement) data.preparedStatements.get(tableName); if (insertStatement==null) { String sql = data.db.getInsertStatement(meta.getSchemaName(), tableName, r); if (log.isDetailed()) logDetailed("Prepared statement : "+sql); insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys()); data.preparedStatements.put(tableName, insertStatement); } try { data.db.setValues(r, insertStatement); data.db.insertRow(insertStatement, data.batchMode); linesOutput++; // See if we need to get back the keys as well... if (meta.isReturningGeneratedKeys()) { Row extra = data.db.getGeneratedKeys(insertStatement); // Send out the good word! // Only 1 key at the moment. (should be enough for now :-) Value keyVal = extra.getValue(0); keyVal.setName(meta.getGeneratedKeyField()); r.addValue(keyVal); } } catch(KettleDatabaseBatchException be) { data.db.clearBatch(insertStatement); data.db.rollback(); throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be); } catch(KettleDatabaseException dbe) { if (meta.ignoreErrors()) { if (data.warnings<20) { logBasic("WARNING: Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } else if (data.warnings==20) { logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } data.warnings++; } else { setErrors(getErrors()+1); data.db.rollback(); throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe); } } if (meta.isTableNameInField() && !meta.isTableNameInTable()) { r.addValue(data.indexOfTableNameField, removedValue); } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; if (super.init(smi, sdi)) { try { data.batchMode = meta.getCommitSize()>0 && meta.useBatchUpdate(); data.db=new Database(meta.getDatabaseMeta()); if (getTransMeta().isUsingUniqueConnections()) { synchronized (getTrans()) { data.db.connect(getTrans().getThreadName(), getPartitionID()); } } else { data.db.connect(getPartitionID()); } logBasic("Connected to database ["+meta.getDatabaseMeta()+"] (commit="+meta.getCommitSize()+")"); data.db.setCommit(meta.getCommitSize()); if (!meta.isPartitioningEnabled() && !meta.isTableNameInField()) { data.tableName = StringUtil.environmentSubstitute( meta.getTablename()); // Only the first one truncates in a non-partitioned step copy // if (meta.truncateTable() && ( getCopy()==0 || !Const.isEmpty(getPartitionID())) ) { data.db.truncateTable(data.tableName); } } return true; } catch(KettleException e) { logError("An error occurred intialising this step: "+e.getMessage()); stopAll(); setErrors(1); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(TableOutputMeta)smi; data=(TableOutputData)sdi; try { Iterator preparedStatements = data.preparedStatements.values().iterator(); while (preparedStatements.hasNext()) { PreparedStatement insertStatement = (PreparedStatement) preparedStatements.next(); data.db.insertFinished(insertStatement, data.batchMode); } } catch(KettleDatabaseBatchException be) { logError("Unexpected batch update error committing the database connection: "+be.toString()); setErrors(1); stopAll(); } catch(Exception dbe) { // dbe.printStackTrace(); logError("Unexpected error committing the database connection: "+dbe.toString()); setErrors(1); stopAll(); } finally { if (getErrors()>0) { try { data.db.rollback(); } catch(KettleDatabaseException e) { logError("Unexpected error rolling back the database connection: "+e.toString()); } } data.db.disconnect(); super.dispose(smi, sdi); } } /** * Run is were the action happens! */ public void run() { try { logBasic("Starting to run..."); while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError("Unexpected error : "+e.toString()); logError(Const.getStackTracker(e)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
false
true
private boolean writeToTable(Row r) throws KettleException { if (r==null) // Stop: last line or error encountered { if (log.isDetailed()) logDetailed("Last line inserted: stop"); return false; } PreparedStatement insertStatement = null; String tableName = null; Value removedValue = null; if ( meta.isTableNameInField() ) { // Cache the position of the table name field if (data.indexOfTableNameField<0) { data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField()); if (data.indexOfTableNameField<0) { String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row"; log.logError(toString(), message); throw new KettleStepException(message); } } tableName = r.getValue(data.indexOfTableNameField).getString(); if (!meta.isTableNameInTable()) { removedValue = r.getValue(data.indexOfTableNameField); r.removeValue(data.indexOfTableNameField); } } else if ( meta.isPartitioningEnabled() && ( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) && ( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 ) ) { // Initialize some stuff! if (data.indexOfPartitioningField<0) { data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField()); if (data.indexOfPartitioningField<0) { throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!"); } if (meta.isPartitioningDaily()) { data.dateFormater = new SimpleDateFormat("yyyyMMdd"); } else { data.dateFormater = new SimpleDateFormat("yyyyMM"); } } Value partitioningValue = r.getValue(data.indexOfPartitioningField); if (!partitioningValue.isDate() || partitioningValue.isNull()) { throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!"); } tableName+="_"+data.dateFormater.format(partitioningValue.getDate()); } else { tableName = data.tableName; } if (Const.isEmpty(tableName)) { throw new KettleStepException("The tablename is not defined (empty)"); } insertStatement = (PreparedStatement) data.preparedStatements.get(tableName); if (insertStatement==null) { String sql = data.db.getInsertStatement(meta.getSchemaName(), tableName, r); if (log.isDetailed()) logDetailed("Prepared statement : "+sql); insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys()); data.preparedStatements.put(tableName, insertStatement); } try { data.db.setValues(r, insertStatement); data.db.insertRow(insertStatement, data.batchMode); linesOutput++; // See if we need to get back the keys as well... if (meta.isReturningGeneratedKeys()) { Row extra = data.db.getGeneratedKeys(insertStatement); // Send out the good word! // Only 1 key at the moment. (should be enough for now :-) Value keyVal = extra.getValue(0); keyVal.setName(meta.getGeneratedKeyField()); r.addValue(keyVal); } } catch(KettleDatabaseBatchException be) { data.db.clearBatch(insertStatement); data.db.rollback(); throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be); } catch(KettleDatabaseException dbe) { if (meta.ignoreErrors()) { if (data.warnings<20) { logBasic("WARNING: Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } else if (data.warnings==20) { logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } data.warnings++; } else { setErrors(getErrors()+1); data.db.rollback(); throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe); } } if (meta.isTableNameInField() && !meta.isTableNameInTable()) { r.addValue(data.indexOfTableNameField, removedValue); } return true; }
private boolean writeToTable(Row r) throws KettleException { if (r==null) // Stop: last line or error encountered { if (log.isDetailed()) logDetailed("Last line inserted: stop"); return false; } PreparedStatement insertStatement = null; String tableName = null; Value removedValue = null; if ( meta.isTableNameInField() ) { // Cache the position of the table name field if (data.indexOfTableNameField<0) { data.indexOfTableNameField = r.searchValueIndex(meta.getTableNameField()); if (data.indexOfTableNameField<0) { String message = "Unable to find table name field ["+meta.getTableNameField()+"] in input row"; log.logError(toString(), message); throw new KettleStepException(message); } } tableName = r.getValue(data.indexOfTableNameField).getString(); if (!meta.isTableNameInTable()) { removedValue = r.getValue(data.indexOfTableNameField); r.removeValue(data.indexOfTableNameField); } } else if ( meta.isPartitioningEnabled() && ( meta.isPartitioningDaily() || meta.isPartitioningMonthly()) && ( meta.getPartitioningField()!=null && meta.getPartitioningField().length()>0 ) ) { // Initialize some stuff! if (data.indexOfPartitioningField<0) { data.indexOfPartitioningField = r.searchValueIndex(meta.getPartitioningField()); if (data.indexOfPartitioningField<0) { throw new KettleStepException("Unable to find field ["+meta.getPartitioningField()+"] in the input row!"); } if (meta.isPartitioningDaily()) { data.dateFormater = new SimpleDateFormat("yyyyMMdd"); } else { data.dateFormater = new SimpleDateFormat("yyyyMM"); } } Value partitioningValue = r.getValue(data.indexOfPartitioningField); if (!partitioningValue.isDate() || partitioningValue.isNull()) { throw new KettleStepException("Sorry, the partitioning field needs to contain a data value and can't be empty!"); } tableName=StringUtil.environmentSubstitute(meta.getTablename())+"_"+data.dateFormater.format(partitioningValue.getDate()); } else { tableName = data.tableName; } if (Const.isEmpty(tableName)) { throw new KettleStepException("The tablename is not defined (empty)"); } insertStatement = (PreparedStatement) data.preparedStatements.get(tableName); if (insertStatement==null) { String sql = data.db.getInsertStatement(meta.getSchemaName(), tableName, r); if (log.isDetailed()) logDetailed("Prepared statement : "+sql); insertStatement = data.db.prepareSQL(sql, meta.isReturningGeneratedKeys()); data.preparedStatements.put(tableName, insertStatement); } try { data.db.setValues(r, insertStatement); data.db.insertRow(insertStatement, data.batchMode); linesOutput++; // See if we need to get back the keys as well... if (meta.isReturningGeneratedKeys()) { Row extra = data.db.getGeneratedKeys(insertStatement); // Send out the good word! // Only 1 key at the moment. (should be enough for now :-) Value keyVal = extra.getValue(0); keyVal.setName(meta.getGeneratedKeyField()); r.addValue(keyVal); } } catch(KettleDatabaseBatchException be) { data.db.clearBatch(insertStatement); data.db.rollback(); throw new KettleException("Error batch inserting rows into table ["+tableName+"]", be); } catch(KettleDatabaseException dbe) { if (meta.ignoreErrors()) { if (data.warnings<20) { logBasic("WARNING: Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } else if (data.warnings==20) { logBasic("FINAL WARNING (no more then 20 displayed): Couldn't insert row into table: "+r+Const.CR+dbe.getMessage()); } data.warnings++; } else { setErrors(getErrors()+1); data.db.rollback(); throw new KettleException("Error inserting row into table ["+tableName+"] with values: "+r, dbe); } } if (meta.isTableNameInField() && !meta.isTableNameInTable()) { r.addValue(data.indexOfTableNameField, removedValue); } return true; }
diff --git a/src/java/org/apache/fop/events/LoggingEventListener.java b/src/java/org/apache/fop/events/LoggingEventListener.java index 03467303e..58fbb7f97 100644 --- a/src/java/org/apache/fop/events/LoggingEventListener.java +++ b/src/java/org/apache/fop/events/LoggingEventListener.java @@ -1,92 +1,100 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.events; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.fop.events.model.EventSeverity; /** * EventListener implementation that redirects events to Commons Logging. The events are * converted to localized messages. */ public class LoggingEventListener implements EventListener { /** Default logger instance */ private static Log defaultLog = LogFactory.getLog(LoggingEventListener.class); private Log log; private boolean skipFatal; /** * Creates an instance logging to the default log category of this class. */ public LoggingEventListener() { this(defaultLog); } /** * Creates an instance logging to a given logger. Events with fatal severity level will be * skipped. * @param log the target logger */ public LoggingEventListener(Log log) { this(log, true); } /** * Creates an instance logging to a given logger. * @param log the target logger * @param skipFatal true if events with fatal severity level should be skipped (i.e. not logged) */ public LoggingEventListener(Log log, boolean skipFatal) { this.log = log; this.skipFatal = skipFatal; } /** * Returns the target logger for this instance. * @return the target logger */ public Log getLog() { return this.log; } /** {@inheritDoc} */ public void processEvent(Event event) { String msg = EventFormatter.format(event); EventSeverity severity = event.getSeverity(); if (severity == EventSeverity.INFO) { log.info(msg); } else if (severity == EventSeverity.WARN) { log.warn(msg); } else if (severity == EventSeverity.ERROR) { - log.error(msg); + if (event.getParam("e") != null) { + log.error(msg, (Throwable)event.getParam("e")); + } else { + log.error(msg); + } } else if (severity == EventSeverity.FATAL) { if (!skipFatal) { - log.fatal(msg); + if (event.getParam("e") != null) { + log.fatal(msg, (Throwable)event.getParam("e")); + } else { + log.fatal(msg); + } } } else { assert false; } } }
false
true
public void processEvent(Event event) { String msg = EventFormatter.format(event); EventSeverity severity = event.getSeverity(); if (severity == EventSeverity.INFO) { log.info(msg); } else if (severity == EventSeverity.WARN) { log.warn(msg); } else if (severity == EventSeverity.ERROR) { log.error(msg); } else if (severity == EventSeverity.FATAL) { if (!skipFatal) { log.fatal(msg); } } else { assert false; } }
public void processEvent(Event event) { String msg = EventFormatter.format(event); EventSeverity severity = event.getSeverity(); if (severity == EventSeverity.INFO) { log.info(msg); } else if (severity == EventSeverity.WARN) { log.warn(msg); } else if (severity == EventSeverity.ERROR) { if (event.getParam("e") != null) { log.error(msg, (Throwable)event.getParam("e")); } else { log.error(msg); } } else if (severity == EventSeverity.FATAL) { if (!skipFatal) { if (event.getParam("e") != null) { log.fatal(msg, (Throwable)event.getParam("e")); } else { log.fatal(msg); } } } else { assert false; } }
diff --git a/core/src/visad/trunk/data/amanda/NuView.java b/core/src/visad/trunk/data/amanda/NuView.java index 0409c70d1..15d165782 100644 --- a/core/src/visad/trunk/data/amanda/NuView.java +++ b/core/src/visad/trunk/data/amanda/NuView.java @@ -1,324 +1,324 @@ /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad.data.amanda; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.URL; import java.rmi.RemoteException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import visad.BaseColorControl; import visad.DataReferenceImpl; import visad.Display; import visad.DisplayImpl; import visad.DisplayRenderer; import visad.FieldImpl; import visad.GraphicsModeControl; import visad.Integer1DSet; import visad.ScalarType; import visad.RealType; import visad.ScalarMap; import visad.ShapeControl; import visad.VisADException; import visad.java3d.DisplayImplJ3D; import visad.util.AnimationWidget; import visad.util.CmdlineConsumer; import visad.util.CmdlineParser; import visad.util.LabeledColorWidget; import visad.util.VisADSlider; /** run 'java NuView in_file' to display data.<br> * try 'java NuView 100events.r' */ public class NuView extends WindowAdapter implements CmdlineConsumer { private String fileName; private boolean timeSequence; private DisplayImpl display; public NuView(String[] args) throws RemoteException, VisADException { CmdlineParser cmdline = new CmdlineParser(this); if (!cmdline.processArgs(args)) { System.exit(1); return; } AmandaFile file = openFile(fileName); final FieldImpl amanda = file.makeEventData(timeSequence); final FieldImpl modules = file.makeModuleData(); display = new DisplayImplJ3D("amanda"); final double halfRange = getMaxRange(file) / 2.0; ScalarMap xMap = new ScalarMap(RealType.XAxis, Display.XAxis); setRange(xMap, file.getXMin(), file.getXMax(), halfRange); display.addMap(xMap); ScalarMap yMap = new ScalarMap(RealType.YAxis, Display.YAxis); setRange(yMap, file.getYMin(), file.getYMax(), halfRange); display.addMap(yMap); ScalarMap zMap = new ScalarMap(RealType.ZAxis, Display.ZAxis); setRange(zMap, file.getZMin(), file.getZMax(), halfRange); display.addMap(zMap); ScalarMap trackMap; if (timeSequence) { trackMap = null; } else { trackMap = new ScalarMap(BaseTrack.indexType, Display.SelectValue); display.addMap(trackMap); } ScalarMap shapeMap = new ScalarMap(Hit.amplitudeType, Display.Shape); display.addMap(shapeMap); ShapeControl sctl = (ShapeControl )shapeMap.getControl(); sctl.setShapeSet(new Integer1DSet(Hit.amplitudeType, 1)); sctl.setShapes(F2000Util.getCubeArray()); if (!timeSequence) { ScalarMap shapeScaleMap = new ScalarMap(Hit.amplitudeType, Display.ShapeScale); display.addMap(shapeScaleMap); shapeScaleMap.setRange(-20.0, 50.0); } ScalarMap colorMap = new ScalarMap(Hit.leadingEdgeTimeType, Display.RGB); display.addMap(colorMap); - // invert color table so colors match is expected + // invert color table so colors match what is expected BaseColorControl colorCtl = (BaseColorControl )colorMap.getControl(); final int numColors = colorCtl.getNumberOfColors(); final int numComps = colorCtl.getNumberOfComponents(); float[][] table = colorCtl.getTable(); for (int i = 0; i < numColors / 2; i++) { final int swaploc = numColors - (i + 1); for (int j = 0; j < numComps; j++) { float tmp = table[j][i]; table[j][i] = table[j][swaploc]; table[j][swaploc] = tmp; } } colorCtl.setTable(table); ScalarMap animMap; if (timeSequence) { animMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(animMap); } else { animMap = null; } DisplayRenderer displayRenderer = display.getDisplayRenderer(); displayRenderer.setBoxOn(false); final DataReferenceImpl amandaRef = new DataReferenceImpl("amanda"); // data set by eventWidget below display.addReference(amandaRef); final DataReferenceImpl modulesRef = new DataReferenceImpl("modules"); modulesRef.setData(modules); display.addReference(modulesRef); LabeledColorWidget colorWidget = new LabeledColorWidget(colorMap); // align along left side, to match VisADSlider alignment // (if we don't left-align, BoxLayout hoses everything) colorWidget.setAlignmentX(Component.LEFT_ALIGNMENT); EventWidget eventWidget = new EventWidget(file, amanda, amandaRef, trackMap); AnimationWidget animWidget; if (animMap == null) { animWidget = null; } else { try { animWidget = new AnimationWidget(animMap); } catch (Exception ex) { ex.printStackTrace(); animWidget = null; } } JPanel widgetPanel = new JPanel(); widgetPanel.setLayout(new BoxLayout(widgetPanel, BoxLayout.Y_AXIS)); widgetPanel.setMaximumSize(new Dimension(400, 600)); widgetPanel.add(colorWidget); widgetPanel.add(eventWidget); if (animWidget != null) { widgetPanel.add(animWidget); } widgetPanel.add(Box.createHorizontalGlue()); JPanel displayPanel = (JPanel )display.getComponent(); Dimension dim = new Dimension(800, 800); displayPanel.setPreferredSize(dim); displayPanel.setMinimumSize(dim); // if widgetPanel alignment doesn't match // displayPanel alignment, BoxLayout will freak out widgetPanel.setAlignmentX(displayPanel.getAlignmentX()); widgetPanel.setAlignmentY(displayPanel.getAlignmentY()); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(widgetPanel); panel.add(displayPanel); JFrame frame = new JFrame("VisAD AMANDA Viewer"); frame.addWindowListener(this); frame.getContentPane().add(panel); frame.pack(); panel.invalidate(); Dimension fSize = frame.getSize(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((screenSize.width - fSize.width)/2, (screenSize.height - fSize.height)/2); frame.setVisible(true); } public int checkKeyword(String mainName, int thisArg, String[] args) { if (fileName == null) { fileName = args[thisArg]; return 1; } return 0; } public int checkOption(String mainName, char ch, String arg) { if (ch == 'o') { timeSequence = false; return 1; } return 0; } public boolean finalizeArgs(String mainName) { if (fileName == null) { System.err.println(mainName + ": No file specified!"); return false; } return true; } private static final double getMaxRange(AmandaFile file) { final double xRange = file.getXMax() - file.getXMin(); final double yRange = file.getYMax() - file.getYMin(); final double zRange = file.getZMax() - file.getZMin(); return -0.5 * Math.max(xRange, Math.max(yRange, zRange)); } public void initializeArgs() { fileName = null; timeSequence = true; } private static final AmandaFile openFile(String fileName) throws VisADException { AmandaFile file; try { if (fileName.startsWith("http://")) { // "ftp://" throws "sun.net.ftp.FtpProtocolException: RETR ..." file = new AmandaFile(new URL(fileName)); } else { file = new AmandaFile(fileName); } } catch (IOException ioe) { ioe.printStackTrace(); throw new VisADException(ioe.getMessage()); } return file; } public String keywordUsage() { return " fileName"; } public String optionUsage() { return " [-o(ldData)]"; } private static final void setRange(ScalarMap map, double min, double max, double halfRange) throws RemoteException, VisADException { final double mid = (min + max) / 2.0; map.setRange(mid - halfRange, mid + halfRange); } public void windowClosing(WindowEvent evt) { try { display.destroy(); } catch (Exception e) { } System.exit(0); } public static void main(String[] args) throws RemoteException, VisADException { new NuView(args); } }
true
true
public NuView(String[] args) throws RemoteException, VisADException { CmdlineParser cmdline = new CmdlineParser(this); if (!cmdline.processArgs(args)) { System.exit(1); return; } AmandaFile file = openFile(fileName); final FieldImpl amanda = file.makeEventData(timeSequence); final FieldImpl modules = file.makeModuleData(); display = new DisplayImplJ3D("amanda"); final double halfRange = getMaxRange(file) / 2.0; ScalarMap xMap = new ScalarMap(RealType.XAxis, Display.XAxis); setRange(xMap, file.getXMin(), file.getXMax(), halfRange); display.addMap(xMap); ScalarMap yMap = new ScalarMap(RealType.YAxis, Display.YAxis); setRange(yMap, file.getYMin(), file.getYMax(), halfRange); display.addMap(yMap); ScalarMap zMap = new ScalarMap(RealType.ZAxis, Display.ZAxis); setRange(zMap, file.getZMin(), file.getZMax(), halfRange); display.addMap(zMap); ScalarMap trackMap; if (timeSequence) { trackMap = null; } else { trackMap = new ScalarMap(BaseTrack.indexType, Display.SelectValue); display.addMap(trackMap); } ScalarMap shapeMap = new ScalarMap(Hit.amplitudeType, Display.Shape); display.addMap(shapeMap); ShapeControl sctl = (ShapeControl )shapeMap.getControl(); sctl.setShapeSet(new Integer1DSet(Hit.amplitudeType, 1)); sctl.setShapes(F2000Util.getCubeArray()); if (!timeSequence) { ScalarMap shapeScaleMap = new ScalarMap(Hit.amplitudeType, Display.ShapeScale); display.addMap(shapeScaleMap); shapeScaleMap.setRange(-20.0, 50.0); } ScalarMap colorMap = new ScalarMap(Hit.leadingEdgeTimeType, Display.RGB); display.addMap(colorMap); // invert color table so colors match is expected BaseColorControl colorCtl = (BaseColorControl )colorMap.getControl(); final int numColors = colorCtl.getNumberOfColors(); final int numComps = colorCtl.getNumberOfComponents(); float[][] table = colorCtl.getTable(); for (int i = 0; i < numColors / 2; i++) { final int swaploc = numColors - (i + 1); for (int j = 0; j < numComps; j++) { float tmp = table[j][i]; table[j][i] = table[j][swaploc]; table[j][swaploc] = tmp; } } colorCtl.setTable(table); ScalarMap animMap; if (timeSequence) { animMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(animMap); } else { animMap = null; } DisplayRenderer displayRenderer = display.getDisplayRenderer(); displayRenderer.setBoxOn(false); final DataReferenceImpl amandaRef = new DataReferenceImpl("amanda"); // data set by eventWidget below display.addReference(amandaRef); final DataReferenceImpl modulesRef = new DataReferenceImpl("modules"); modulesRef.setData(modules); display.addReference(modulesRef); LabeledColorWidget colorWidget = new LabeledColorWidget(colorMap); // align along left side, to match VisADSlider alignment // (if we don't left-align, BoxLayout hoses everything) colorWidget.setAlignmentX(Component.LEFT_ALIGNMENT); EventWidget eventWidget = new EventWidget(file, amanda, amandaRef, trackMap); AnimationWidget animWidget; if (animMap == null) { animWidget = null; } else { try { animWidget = new AnimationWidget(animMap); } catch (Exception ex) { ex.printStackTrace(); animWidget = null; } } JPanel widgetPanel = new JPanel(); widgetPanel.setLayout(new BoxLayout(widgetPanel, BoxLayout.Y_AXIS)); widgetPanel.setMaximumSize(new Dimension(400, 600)); widgetPanel.add(colorWidget); widgetPanel.add(eventWidget); if (animWidget != null) { widgetPanel.add(animWidget); } widgetPanel.add(Box.createHorizontalGlue()); JPanel displayPanel = (JPanel )display.getComponent(); Dimension dim = new Dimension(800, 800); displayPanel.setPreferredSize(dim); displayPanel.setMinimumSize(dim); // if widgetPanel alignment doesn't match // displayPanel alignment, BoxLayout will freak out widgetPanel.setAlignmentX(displayPanel.getAlignmentX()); widgetPanel.setAlignmentY(displayPanel.getAlignmentY()); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(widgetPanel); panel.add(displayPanel); JFrame frame = new JFrame("VisAD AMANDA Viewer"); frame.addWindowListener(this); frame.getContentPane().add(panel); frame.pack(); panel.invalidate(); Dimension fSize = frame.getSize(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((screenSize.width - fSize.width)/2, (screenSize.height - fSize.height)/2); frame.setVisible(true); }
public NuView(String[] args) throws RemoteException, VisADException { CmdlineParser cmdline = new CmdlineParser(this); if (!cmdline.processArgs(args)) { System.exit(1); return; } AmandaFile file = openFile(fileName); final FieldImpl amanda = file.makeEventData(timeSequence); final FieldImpl modules = file.makeModuleData(); display = new DisplayImplJ3D("amanda"); final double halfRange = getMaxRange(file) / 2.0; ScalarMap xMap = new ScalarMap(RealType.XAxis, Display.XAxis); setRange(xMap, file.getXMin(), file.getXMax(), halfRange); display.addMap(xMap); ScalarMap yMap = new ScalarMap(RealType.YAxis, Display.YAxis); setRange(yMap, file.getYMin(), file.getYMax(), halfRange); display.addMap(yMap); ScalarMap zMap = new ScalarMap(RealType.ZAxis, Display.ZAxis); setRange(zMap, file.getZMin(), file.getZMax(), halfRange); display.addMap(zMap); ScalarMap trackMap; if (timeSequence) { trackMap = null; } else { trackMap = new ScalarMap(BaseTrack.indexType, Display.SelectValue); display.addMap(trackMap); } ScalarMap shapeMap = new ScalarMap(Hit.amplitudeType, Display.Shape); display.addMap(shapeMap); ShapeControl sctl = (ShapeControl )shapeMap.getControl(); sctl.setShapeSet(new Integer1DSet(Hit.amplitudeType, 1)); sctl.setShapes(F2000Util.getCubeArray()); if (!timeSequence) { ScalarMap shapeScaleMap = new ScalarMap(Hit.amplitudeType, Display.ShapeScale); display.addMap(shapeScaleMap); shapeScaleMap.setRange(-20.0, 50.0); } ScalarMap colorMap = new ScalarMap(Hit.leadingEdgeTimeType, Display.RGB); display.addMap(colorMap); // invert color table so colors match what is expected BaseColorControl colorCtl = (BaseColorControl )colorMap.getControl(); final int numColors = colorCtl.getNumberOfColors(); final int numComps = colorCtl.getNumberOfComponents(); float[][] table = colorCtl.getTable(); for (int i = 0; i < numColors / 2; i++) { final int swaploc = numColors - (i + 1); for (int j = 0; j < numComps; j++) { float tmp = table[j][i]; table[j][i] = table[j][swaploc]; table[j][swaploc] = tmp; } } colorCtl.setTable(table); ScalarMap animMap; if (timeSequence) { animMap = new ScalarMap(RealType.Time, Display.Animation); display.addMap(animMap); } else { animMap = null; } DisplayRenderer displayRenderer = display.getDisplayRenderer(); displayRenderer.setBoxOn(false); final DataReferenceImpl amandaRef = new DataReferenceImpl("amanda"); // data set by eventWidget below display.addReference(amandaRef); final DataReferenceImpl modulesRef = new DataReferenceImpl("modules"); modulesRef.setData(modules); display.addReference(modulesRef); LabeledColorWidget colorWidget = new LabeledColorWidget(colorMap); // align along left side, to match VisADSlider alignment // (if we don't left-align, BoxLayout hoses everything) colorWidget.setAlignmentX(Component.LEFT_ALIGNMENT); EventWidget eventWidget = new EventWidget(file, amanda, amandaRef, trackMap); AnimationWidget animWidget; if (animMap == null) { animWidget = null; } else { try { animWidget = new AnimationWidget(animMap); } catch (Exception ex) { ex.printStackTrace(); animWidget = null; } } JPanel widgetPanel = new JPanel(); widgetPanel.setLayout(new BoxLayout(widgetPanel, BoxLayout.Y_AXIS)); widgetPanel.setMaximumSize(new Dimension(400, 600)); widgetPanel.add(colorWidget); widgetPanel.add(eventWidget); if (animWidget != null) { widgetPanel.add(animWidget); } widgetPanel.add(Box.createHorizontalGlue()); JPanel displayPanel = (JPanel )display.getComponent(); Dimension dim = new Dimension(800, 800); displayPanel.setPreferredSize(dim); displayPanel.setMinimumSize(dim); // if widgetPanel alignment doesn't match // displayPanel alignment, BoxLayout will freak out widgetPanel.setAlignmentX(displayPanel.getAlignmentX()); widgetPanel.setAlignmentY(displayPanel.getAlignmentY()); // create JPanel in frame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(widgetPanel); panel.add(displayPanel); JFrame frame = new JFrame("VisAD AMANDA Viewer"); frame.addWindowListener(this); frame.getContentPane().add(panel); frame.pack(); panel.invalidate(); Dimension fSize = frame.getSize(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation((screenSize.width - fSize.width)/2, (screenSize.height - fSize.height)/2); frame.setVisible(true); }
diff --git a/src/com/android/camera/ui/SharePopup.java b/src/com/android/camera/ui/SharePopup.java index aa34abf2..6bd6aee3 100644 --- a/src/com/android/camera/ui/SharePopup.java +++ b/src/com/android/camera/ui/SharePopup.java @@ -1,228 +1,228 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.ui; import com.android.camera.R; import com.android.camera.Util; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup.MarginLayoutParams; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.SimpleAdapter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; // A popup window that contains a big thumbnail and a list of apps to share. public class SharePopup extends PopupWindow implements View.OnClickListener, View.OnTouchListener, AdapterView.OnItemClickListener { private static final String TAG = "SharePopup"; private Context mContext; private Uri mUri; private String mMimeType; private ImageView mThumbnail; private int mBitmapWidth; private int mBitmapHeight; // A view that contains a thumbnail and a share view. private ViewGroup mRootView; // A view that contains the title and the list of applications to share. private View mShareView; // The list of the applications to share. private ListView mShareList; // A rotated view that contains the share view. private RotateLayout mShareViewRotateLayout; // A rotated view that contains the thumbnail. private RotateLayout mThumbnailRotateLayout; private ArrayList<ComponentName> mComponent = new ArrayList<ComponentName>(); // The maximum width of the thumbnail in landscape orientation. private final float mImageMaxWidthLandscape; // The maximum height of the thumbnail in landscape orientation. private final float mImageMaxHeightLandscape; // The maximum width of the thumbnail in portrait orientation. private final float mImageMaxWidthPortrait; // The maximum height of the thumbnail in portrait orientation. private final float mImageMaxHeightPortrait; // The width of the share list in landscape mode. private final float mShareListWidthLandscape; public SharePopup(Activity activity, Uri uri, Bitmap bitmap, String mimeType, int orientation, View anchor) { super(activity); // Initialize variables mContext = activity; mUri = uri; mMimeType = mimeType; LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); ViewGroup sharePopup = (ViewGroup) inflater.inflate(R.layout.share_popup, null, false); // This is required because popup window is full screen. sharePopup.setOnTouchListener(this); mShareViewRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.share_view_rotate_layout); mThumbnailRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.thumbnail_rotate_layout); mShareList = (ListView) sharePopup.findViewById(R.id.share_list); mShareView = sharePopup.findViewById(R.id.share_view); mThumbnail = (ImageView) sharePopup.findViewById(R.id.thumbnail); mRootView = (ViewGroup) sharePopup.findViewById(R.id.root); mThumbnail.setImageBitmap(bitmap); mThumbnail.setOnClickListener(this); mBitmapWidth = bitmap.getWidth(); mBitmapHeight = bitmap.getHeight(); Resources res = mContext.getResources(); mImageMaxWidthLandscape = res.getDimension(R.dimen.share_image_max_width_landscape); mImageMaxHeightLandscape = res.getDimension(R.dimen.share_image_max_height_landscape); mImageMaxWidthPortrait = res.getDimension(R.dimen.share_image_max_width_portrait); mImageMaxHeightPortrait = res.getDimension(R.dimen.share_image_max_height_portrait); mShareListWidthLandscape = res.getDimension(R.dimen.share_list_width_landscape); // Initialize popup window setWidth(WindowManager.LayoutParams.MATCH_PARENT); setHeight(WindowManager.LayoutParams.MATCH_PARENT); setBackgroundDrawable(new ColorDrawable()); setContentView(sharePopup); setOrientation(orientation); setFocusable(true); - setAnimationStyle(R.style.AnimationPopup); + setAnimationStyle(android.R.style.Animation_Dialog); initializeLocation(activity, anchor); createShareMenu(); } private void initializeLocation(Activity activity, View anchor) { int location[] = new int[2]; anchor.getLocationOnScreen(location); DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); MarginLayoutParams params = (MarginLayoutParams) mRootView.getLayoutParams(); params.topMargin = location[1]; params.rightMargin = (metrics.widthPixels - location[0] - anchor.getWidth()); mRootView.setLayoutParams(params); } public void setOrientation(int orientation) { // Calculate the width and the height of the thumbnail. float maxWidth, maxHeight; if (orientation == 90 || orientation == 270) { maxWidth = mImageMaxWidthPortrait; maxHeight = mImageMaxHeightPortrait; } else { maxWidth = mImageMaxWidthLandscape; maxHeight = mImageMaxHeightLandscape; } float actualAspect = maxWidth / maxHeight; float desiredAspect = (float) mBitmapWidth / mBitmapHeight; LayoutParams params = mThumbnail.getLayoutParams(); if (actualAspect > desiredAspect) { params.width = Math.round(maxHeight * desiredAspect); params.height = Math.round(maxHeight); } else { params.width = Math.round(maxWidth); params.height = Math.round(maxWidth / desiredAspect); } mThumbnail.setLayoutParams(params); // Calculate the width of the share application list. LayoutParams shareListParams = mShareView.getLayoutParams(); if ((orientation == 90 || orientation == 270)) { shareListParams.width = params.width; } else { shareListParams.width = (int) mShareListWidthLandscape; } mShareView.setLayoutParams(shareListParams); if (mShareViewRotateLayout != null) mShareViewRotateLayout.setOrientation(orientation); if (mThumbnailRotateLayout != null) mThumbnailRotateLayout.setOrientation(orientation); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.thumbnail: Util.viewUri(mUri, mContext); break; } } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { dismiss(); return true; } return false; } public void createShareMenu() { PackageManager packageManager = mContext.getPackageManager(); List<ResolveInfo> infos; infos = packageManager.queryIntentActivities( new Intent(Intent.ACTION_SEND).setType(mMimeType), 0); ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>(); for(ResolveInfo info: infos) { String label = info.loadLabel(packageManager).toString(); ComponentName component = new ComponentName( info.activityInfo.packageName, info.activityInfo.name); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("text", label); listItem.add(map); mComponent.add(component); } SimpleAdapter listItemAdapter = new SimpleAdapter(mContext, listItem, R.layout.share_item, new String[] {"text"}, new int[] {R.id.text}); mShareList.setAdapter(listItemAdapter); mShareList.setOnItemClickListener(this); } public Uri getUri() { return mUri; } @Override public void onItemClick(AdapterView<?> parent, View view, int index, long id) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType(mMimeType); intent.putExtra(Intent.EXTRA_STREAM, mUri); intent.setComponent(mComponent.get(index)); mContext.startActivity(intent); } }
true
true
public SharePopup(Activity activity, Uri uri, Bitmap bitmap, String mimeType, int orientation, View anchor) { super(activity); // Initialize variables mContext = activity; mUri = uri; mMimeType = mimeType; LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); ViewGroup sharePopup = (ViewGroup) inflater.inflate(R.layout.share_popup, null, false); // This is required because popup window is full screen. sharePopup.setOnTouchListener(this); mShareViewRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.share_view_rotate_layout); mThumbnailRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.thumbnail_rotate_layout); mShareList = (ListView) sharePopup.findViewById(R.id.share_list); mShareView = sharePopup.findViewById(R.id.share_view); mThumbnail = (ImageView) sharePopup.findViewById(R.id.thumbnail); mRootView = (ViewGroup) sharePopup.findViewById(R.id.root); mThumbnail.setImageBitmap(bitmap); mThumbnail.setOnClickListener(this); mBitmapWidth = bitmap.getWidth(); mBitmapHeight = bitmap.getHeight(); Resources res = mContext.getResources(); mImageMaxWidthLandscape = res.getDimension(R.dimen.share_image_max_width_landscape); mImageMaxHeightLandscape = res.getDimension(R.dimen.share_image_max_height_landscape); mImageMaxWidthPortrait = res.getDimension(R.dimen.share_image_max_width_portrait); mImageMaxHeightPortrait = res.getDimension(R.dimen.share_image_max_height_portrait); mShareListWidthLandscape = res.getDimension(R.dimen.share_list_width_landscape); // Initialize popup window setWidth(WindowManager.LayoutParams.MATCH_PARENT); setHeight(WindowManager.LayoutParams.MATCH_PARENT); setBackgroundDrawable(new ColorDrawable()); setContentView(sharePopup); setOrientation(orientation); setFocusable(true); setAnimationStyle(R.style.AnimationPopup); initializeLocation(activity, anchor); createShareMenu(); }
public SharePopup(Activity activity, Uri uri, Bitmap bitmap, String mimeType, int orientation, View anchor) { super(activity); // Initialize variables mContext = activity; mUri = uri; mMimeType = mimeType; LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); ViewGroup sharePopup = (ViewGroup) inflater.inflate(R.layout.share_popup, null, false); // This is required because popup window is full screen. sharePopup.setOnTouchListener(this); mShareViewRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.share_view_rotate_layout); mThumbnailRotateLayout = (RotateLayout) sharePopup.findViewById(R.id.thumbnail_rotate_layout); mShareList = (ListView) sharePopup.findViewById(R.id.share_list); mShareView = sharePopup.findViewById(R.id.share_view); mThumbnail = (ImageView) sharePopup.findViewById(R.id.thumbnail); mRootView = (ViewGroup) sharePopup.findViewById(R.id.root); mThumbnail.setImageBitmap(bitmap); mThumbnail.setOnClickListener(this); mBitmapWidth = bitmap.getWidth(); mBitmapHeight = bitmap.getHeight(); Resources res = mContext.getResources(); mImageMaxWidthLandscape = res.getDimension(R.dimen.share_image_max_width_landscape); mImageMaxHeightLandscape = res.getDimension(R.dimen.share_image_max_height_landscape); mImageMaxWidthPortrait = res.getDimension(R.dimen.share_image_max_width_portrait); mImageMaxHeightPortrait = res.getDimension(R.dimen.share_image_max_height_portrait); mShareListWidthLandscape = res.getDimension(R.dimen.share_list_width_landscape); // Initialize popup window setWidth(WindowManager.LayoutParams.MATCH_PARENT); setHeight(WindowManager.LayoutParams.MATCH_PARENT); setBackgroundDrawable(new ColorDrawable()); setContentView(sharePopup); setOrientation(orientation); setFocusable(true); setAnimationStyle(android.R.style.Animation_Dialog); initializeLocation(activity, anchor); createShareMenu(); }
diff --git a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrap.java b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrap.java index 42fe11673..0ba98f129 100644 --- a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrap.java +++ b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrap.java @@ -1,309 +1,311 @@ package org.jboss.resteasy.plugins.server.servlet; import org.jboss.resteasy.core.Dispatcher; import org.jboss.resteasy.core.ResourceMethodRegistry; import org.jboss.resteasy.core.SynchronousDispatcher; import org.jboss.resteasy.plugins.providers.RegisterBuiltin; import org.jboss.resteasy.spi.Registry; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.util.GetRestful; import org.scannotation.AnnotationDB; import org.scannotation.WarUrlFinder; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.ws.rs.Path; import javax.ws.rs.core.Application; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * This is a ServletContextListener that creates the registry for resteasy and stuffs it as a servlet context attribute * * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ public class ResteasyBootstrap implements ServletContextListener { private ResteasyProviderFactory factory = new ResteasyProviderFactory(); private Registry registry; private Dispatcher dispatcher; public void contextInitialized(ServletContextEvent event) { ResteasyProviderFactory.setInstance(factory); event.getServletContext().setAttribute(ResteasyProviderFactory.class.getName(), factory); dispatcher = new SynchronousDispatcher(); dispatcher.setProviderFactory(factory); registry = dispatcher.getRegistry(); String rootPath = event.getServletContext().getInitParameter("resteasy.servlet.mapping.prefix"); if (rootPath != null) ((ResourceMethodRegistry) registry).setRootPath(rootPath.trim()); event.getServletContext().setAttribute(Dispatcher.class.getName(), dispatcher); event.getServletContext().setAttribute(Registry.class.getName(), registry); String applicationConfig = event.getServletContext().getInitParameter(Application.class.getName()); String providers = event.getServletContext().getInitParameter("resteasy.providers"); if (providers != null) setProviders(providers); String resourceMethodInterceptors = event.getServletContext().getInitParameter("resteasy.resource.method.interceptors"); if (resourceMethodInterceptors != null) setProviders(resourceMethodInterceptors); String builtin = event.getServletContext().getInitParameter("resteasy.use.builtin.providers"); if (builtin == null || Boolean.valueOf(builtin.trim())) RegisterBuiltin.register(factory); boolean scanProviders = false; boolean scanResources = false; String sProviders = event.getServletContext().getInitParameter("resteasy.scan.providers"); if (sProviders != null) { scanProviders = Boolean.valueOf(sProviders.trim()); } String scanAll = event.getServletContext().getInitParameter("resteasy.scan"); if (scanAll != null) { boolean tmp = Boolean.valueOf(scanAll.trim()); scanProviders = tmp || scanProviders; scanResources = tmp || scanResources; } String sResources = event.getServletContext().getInitParameter("resteasy.scan.resources"); if (sResources != null) { scanResources = Boolean.valueOf(sResources.trim()); } if (scanProviders || scanResources) { if (applicationConfig != null) throw new RuntimeException("You cannot deploy a javax.ws.rs.core.Application and have scanning on as this may create errors"); URL[] urls = WarUrlFinder.findWebInfLibClasspaths(event); URL url = WarUrlFinder.findWebInfClassesPath(event); AnnotationDB db = new AnnotationDB(); String[] ignoredPackages = {"org.jboss.resteasy.plugins", "javax.ws.rs"}; db.setIgnoredPackages(ignoredPackages); try { if (url != null) db.scanArchives(url); db.scanArchives(urls); try { db.crossReferenceImplementedInterfaces(); db.crossReferenceMetaAnnotations(); } catch (AnnotationDB.CrossReferenceException ignored) { } } catch (IOException e) { throw new RuntimeException("Unable to scan WEB-INF for JAX-RS annotations, you must manually register your classes/resources", e); } if (scanProviders) processProviders(db); if (scanResources) processResources(db); } String jndiResources = event.getServletContext().getInitParameter("resteasy.jndi.resources"); if (jndiResources != null) { processJndiResources(jndiResources); } String resources = event.getServletContext().getInitParameter("resteasy.resources"); if (resources != null) { processResources(resources); } + // Mappings don't work anymore, but leaving the code in just in case users demand to put it back in String mimeExtentions = event.getServletContext().getInitParameter("resteasy.media.type.mappings"); if (mimeExtentions != null) { Map<String, String> map = parseMap(mimeExtentions); Map<String, MediaType> extMap = new HashMap<String, MediaType>(); for (String ext : map.keySet()) { String value = map.get(ext); extMap.put(ext, MediaType.valueOf(value)); } if (dispatcher.getMediaTypeMappings() != null) dispatcher.getMediaTypeMappings().putAll(extMap); else dispatcher.setMediaTypeMappings(extMap); } + // Mappings don't work anymore, but leaving the code in just in case users demand to put it back in String languageExtensions = event.getServletContext().getInitParameter("resteasy.language.mappings"); if (languageExtensions != null) { Map<String, String> map = parseMap(languageExtensions); if (dispatcher.getLanguageMappings() != null) dispatcher.getLanguageMappings().putAll(map); else dispatcher.setLanguageMappings(map); } if (applicationConfig != null) { try { //System.out.println("application config: " + applicationConfig.trim()); Class configClass = Thread.currentThread().getContextClassLoader().loadClass(applicationConfig.trim()); Application config = (Application) configClass.newInstance(); processApplication(config, registry, factory); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } public static void processApplication(Application config, Registry registry, ResteasyProviderFactory factory) { if (config.getClasses() != null) { for (Class clazz : config.getClasses()) { if (clazz.isAnnotationPresent(Path.class)) registry.addPerRequestResource(clazz); else factory.registerProvider(clazz); } } if (config.getSingletons() != null) { for (Object obj : config.getSingletons()) { if (obj.getClass().isAnnotationPresent(Path.class)) { registry.addSingletonResource(obj); } else { factory.registerProviderInstance(obj); } } } } protected Map<String, String> parseMap(String map) { Map<String, String> parsed = new HashMap<String, String>(); String[] entries = map.trim().split(","); for (String entry : entries) { String[] split = entry.trim().split(":"); parsed.put(split[0].trim(), split[1].trim()); } return parsed; } protected void processJndiResources(String jndiResources) { String[] resources = jndiResources.trim().split(","); for (String resource : resources) { registry.addJndiResource(resource.trim()); } } protected void processResources(String list) { String[] resources = list.trim().split(","); for (String resource : resources) { try { Class clazz = Thread.currentThread().getContextClassLoader().loadClass(resource.trim()); registry.addPerRequestResource(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } } protected void processProviders(AnnotationDB db) { Set<String> classes = db.getAnnotationIndex().get(Provider.class.getName()); if (classes == null) return; for (String clazz : classes) { registerProvider(clazz); } } private void registerProvider(String clazz) { Class provider = null; try { provider = Thread.currentThread().getContextClassLoader().loadClass(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } System.out.println("FOUND JAX-RS @Provider: " + clazz); factory.registerProvider(provider); } protected void processResources(AnnotationDB db) { Set<String> classes = new HashSet<String>(); Set<String> paths = db.getAnnotationIndex().get(Path.class.getName()); if (paths != null) classes.addAll(paths); for (String clazz : classes) { processResource(clazz); } } protected void processResource(String clazz) { Class resource = null; try { resource = Thread.currentThread().getContextClassLoader().loadClass(clazz); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } if (resource.isInterface()) return; if (GetRestful.isRootResource(resource) == false) return; System.out.println("FOUND JAX-RS resource: " + clazz); registry.addPerRequestResource(resource); } protected void setProviders(String providers) { String[] p = providers.split(","); for (String provider : p) { provider = provider.trim(); registerProvider(provider); } } public void contextDestroyed(ServletContextEvent event) { } }
false
true
public void contextInitialized(ServletContextEvent event) { ResteasyProviderFactory.setInstance(factory); event.getServletContext().setAttribute(ResteasyProviderFactory.class.getName(), factory); dispatcher = new SynchronousDispatcher(); dispatcher.setProviderFactory(factory); registry = dispatcher.getRegistry(); String rootPath = event.getServletContext().getInitParameter("resteasy.servlet.mapping.prefix"); if (rootPath != null) ((ResourceMethodRegistry) registry).setRootPath(rootPath.trim()); event.getServletContext().setAttribute(Dispatcher.class.getName(), dispatcher); event.getServletContext().setAttribute(Registry.class.getName(), registry); String applicationConfig = event.getServletContext().getInitParameter(Application.class.getName()); String providers = event.getServletContext().getInitParameter("resteasy.providers"); if (providers != null) setProviders(providers); String resourceMethodInterceptors = event.getServletContext().getInitParameter("resteasy.resource.method.interceptors"); if (resourceMethodInterceptors != null) setProviders(resourceMethodInterceptors); String builtin = event.getServletContext().getInitParameter("resteasy.use.builtin.providers"); if (builtin == null || Boolean.valueOf(builtin.trim())) RegisterBuiltin.register(factory); boolean scanProviders = false; boolean scanResources = false; String sProviders = event.getServletContext().getInitParameter("resteasy.scan.providers"); if (sProviders != null) { scanProviders = Boolean.valueOf(sProviders.trim()); } String scanAll = event.getServletContext().getInitParameter("resteasy.scan"); if (scanAll != null) { boolean tmp = Boolean.valueOf(scanAll.trim()); scanProviders = tmp || scanProviders; scanResources = tmp || scanResources; } String sResources = event.getServletContext().getInitParameter("resteasy.scan.resources"); if (sResources != null) { scanResources = Boolean.valueOf(sResources.trim()); } if (scanProviders || scanResources) { if (applicationConfig != null) throw new RuntimeException("You cannot deploy a javax.ws.rs.core.Application and have scanning on as this may create errors"); URL[] urls = WarUrlFinder.findWebInfLibClasspaths(event); URL url = WarUrlFinder.findWebInfClassesPath(event); AnnotationDB db = new AnnotationDB(); String[] ignoredPackages = {"org.jboss.resteasy.plugins", "javax.ws.rs"}; db.setIgnoredPackages(ignoredPackages); try { if (url != null) db.scanArchives(url); db.scanArchives(urls); try { db.crossReferenceImplementedInterfaces(); db.crossReferenceMetaAnnotations(); } catch (AnnotationDB.CrossReferenceException ignored) { } } catch (IOException e) { throw new RuntimeException("Unable to scan WEB-INF for JAX-RS annotations, you must manually register your classes/resources", e); } if (scanProviders) processProviders(db); if (scanResources) processResources(db); } String jndiResources = event.getServletContext().getInitParameter("resteasy.jndi.resources"); if (jndiResources != null) { processJndiResources(jndiResources); } String resources = event.getServletContext().getInitParameter("resteasy.resources"); if (resources != null) { processResources(resources); } String mimeExtentions = event.getServletContext().getInitParameter("resteasy.media.type.mappings"); if (mimeExtentions != null) { Map<String, String> map = parseMap(mimeExtentions); Map<String, MediaType> extMap = new HashMap<String, MediaType>(); for (String ext : map.keySet()) { String value = map.get(ext); extMap.put(ext, MediaType.valueOf(value)); } if (dispatcher.getMediaTypeMappings() != null) dispatcher.getMediaTypeMappings().putAll(extMap); else dispatcher.setMediaTypeMappings(extMap); } String languageExtensions = event.getServletContext().getInitParameter("resteasy.language.mappings"); if (languageExtensions != null) { Map<String, String> map = parseMap(languageExtensions); if (dispatcher.getLanguageMappings() != null) dispatcher.getLanguageMappings().putAll(map); else dispatcher.setLanguageMappings(map); } if (applicationConfig != null) { try { //System.out.println("application config: " + applicationConfig.trim()); Class configClass = Thread.currentThread().getContextClassLoader().loadClass(applicationConfig.trim()); Application config = (Application) configClass.newInstance(); processApplication(config, registry, factory); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
public void contextInitialized(ServletContextEvent event) { ResteasyProviderFactory.setInstance(factory); event.getServletContext().setAttribute(ResteasyProviderFactory.class.getName(), factory); dispatcher = new SynchronousDispatcher(); dispatcher.setProviderFactory(factory); registry = dispatcher.getRegistry(); String rootPath = event.getServletContext().getInitParameter("resteasy.servlet.mapping.prefix"); if (rootPath != null) ((ResourceMethodRegistry) registry).setRootPath(rootPath.trim()); event.getServletContext().setAttribute(Dispatcher.class.getName(), dispatcher); event.getServletContext().setAttribute(Registry.class.getName(), registry); String applicationConfig = event.getServletContext().getInitParameter(Application.class.getName()); String providers = event.getServletContext().getInitParameter("resteasy.providers"); if (providers != null) setProviders(providers); String resourceMethodInterceptors = event.getServletContext().getInitParameter("resteasy.resource.method.interceptors"); if (resourceMethodInterceptors != null) setProviders(resourceMethodInterceptors); String builtin = event.getServletContext().getInitParameter("resteasy.use.builtin.providers"); if (builtin == null || Boolean.valueOf(builtin.trim())) RegisterBuiltin.register(factory); boolean scanProviders = false; boolean scanResources = false; String sProviders = event.getServletContext().getInitParameter("resteasy.scan.providers"); if (sProviders != null) { scanProviders = Boolean.valueOf(sProviders.trim()); } String scanAll = event.getServletContext().getInitParameter("resteasy.scan"); if (scanAll != null) { boolean tmp = Boolean.valueOf(scanAll.trim()); scanProviders = tmp || scanProviders; scanResources = tmp || scanResources; } String sResources = event.getServletContext().getInitParameter("resteasy.scan.resources"); if (sResources != null) { scanResources = Boolean.valueOf(sResources.trim()); } if (scanProviders || scanResources) { if (applicationConfig != null) throw new RuntimeException("You cannot deploy a javax.ws.rs.core.Application and have scanning on as this may create errors"); URL[] urls = WarUrlFinder.findWebInfLibClasspaths(event); URL url = WarUrlFinder.findWebInfClassesPath(event); AnnotationDB db = new AnnotationDB(); String[] ignoredPackages = {"org.jboss.resteasy.plugins", "javax.ws.rs"}; db.setIgnoredPackages(ignoredPackages); try { if (url != null) db.scanArchives(url); db.scanArchives(urls); try { db.crossReferenceImplementedInterfaces(); db.crossReferenceMetaAnnotations(); } catch (AnnotationDB.CrossReferenceException ignored) { } } catch (IOException e) { throw new RuntimeException("Unable to scan WEB-INF for JAX-RS annotations, you must manually register your classes/resources", e); } if (scanProviders) processProviders(db); if (scanResources) processResources(db); } String jndiResources = event.getServletContext().getInitParameter("resteasy.jndi.resources"); if (jndiResources != null) { processJndiResources(jndiResources); } String resources = event.getServletContext().getInitParameter("resteasy.resources"); if (resources != null) { processResources(resources); } // Mappings don't work anymore, but leaving the code in just in case users demand to put it back in String mimeExtentions = event.getServletContext().getInitParameter("resteasy.media.type.mappings"); if (mimeExtentions != null) { Map<String, String> map = parseMap(mimeExtentions); Map<String, MediaType> extMap = new HashMap<String, MediaType>(); for (String ext : map.keySet()) { String value = map.get(ext); extMap.put(ext, MediaType.valueOf(value)); } if (dispatcher.getMediaTypeMappings() != null) dispatcher.getMediaTypeMappings().putAll(extMap); else dispatcher.setMediaTypeMappings(extMap); } // Mappings don't work anymore, but leaving the code in just in case users demand to put it back in String languageExtensions = event.getServletContext().getInitParameter("resteasy.language.mappings"); if (languageExtensions != null) { Map<String, String> map = parseMap(languageExtensions); if (dispatcher.getLanguageMappings() != null) dispatcher.getLanguageMappings().putAll(map); else dispatcher.setLanguageMappings(map); } if (applicationConfig != null) { try { //System.out.println("application config: " + applicationConfig.trim()); Class configClass = Thread.currentThread().getContextClassLoader().loadClass(applicationConfig.trim()); Application config = (Application) configClass.newInstance(); processApplication(config, registry, factory); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
diff --git a/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java b/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java index 9090e1b0f..0b7163cfb 100644 --- a/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java +++ b/modules/rampart-integration/src/test/java/org/apache/rampart/RampartTest.java @@ -1,146 +1,146 @@ /* * Copyright 2004,2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rampart; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axis2.Constants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContextFactory; import org.apache.axis2.integration.UtilServer; import org.apache.neethi.Policy; import org.apache.neethi.PolicyEngine; import javax.xml.namespace.QName; import junit.framework.TestCase; public class RampartTest extends TestCase { public final static int PORT = UtilServer.TESTING_PORT; public RampartTest(String name) { super(name); } protected void setUp() throws Exception { UtilServer.start(Constants.TESTING_PATH + "rampart_service_repo" ,null); } protected void tearDown() throws Exception { UtilServer.stop(); } public void testWithPolicy() { try { String repo = Constants.TESTING_PATH + "rampart_client_repo"; ConfigurationContext configContext = ConfigurationContextFactory. createConfigurationContextFromFileSystem(repo, null); ServiceClient serviceClient = new ServiceClient(configContext, null); serviceClient.engageModule(new QName("addressing")); serviceClient.engageModule(new QName("rampart")); //TODO : figure this out !! boolean basic256Supported = true; if(basic256Supported) { System.out.println("\nWARNING: We are using key sizes from JCE " + "Unlimited Strength Jurisdiction Policy !!!"); } - for (int i = 1; i <= 9; i++) { //<-The number of tests we have + for (int i = 1; i <= 10; i++) { //<-The number of tests we have if(!basic256Supported && (i == 3 || i == 4 || i ==5)) { //Skip the Basic256 tests continue; } Options options = new Options(); System.out.println("Testing WS-Sec: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureService" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); } for (int i = 1; i <= 2; i++) { //<-The number of tests we have Options options = new Options(); System.out.println("Testing WS-SecConv: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); serviceClient.sendReceive(getEchoElement()); //Cancel the token options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } private OMElement getEchoElement() { OMFactory fac = OMAbstractFactory.getOMFactory(); OMNamespace omNs = fac.createOMNamespace( "http://example1.org/example1", "example1"); OMElement method = fac.createOMElement("echo", omNs); OMElement value = fac.createOMElement("Text", omNs); value.addChild(fac.createOMText(value, "Testing Rampart with WS-SecPolicy")); method.addChild(value); return method; } private Policy loadPolicy(String xmlPath) throws Exception { StAXOMBuilder builder = new StAXOMBuilder(RampartTest.class.getResourceAsStream(xmlPath)); return PolicyEngine.getPolicy(builder.getDocumentElement()); } }
true
true
public void testWithPolicy() { try { String repo = Constants.TESTING_PATH + "rampart_client_repo"; ConfigurationContext configContext = ConfigurationContextFactory. createConfigurationContextFromFileSystem(repo, null); ServiceClient serviceClient = new ServiceClient(configContext, null); serviceClient.engageModule(new QName("addressing")); serviceClient.engageModule(new QName("rampart")); //TODO : figure this out !! boolean basic256Supported = true; if(basic256Supported) { System.out.println("\nWARNING: We are using key sizes from JCE " + "Unlimited Strength Jurisdiction Policy !!!"); } for (int i = 1; i <= 9; i++) { //<-The number of tests we have if(!basic256Supported && (i == 3 || i == 4 || i ==5)) { //Skip the Basic256 tests continue; } Options options = new Options(); System.out.println("Testing WS-Sec: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureService" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); } for (int i = 1; i <= 2; i++) { //<-The number of tests we have Options options = new Options(); System.out.println("Testing WS-SecConv: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); serviceClient.sendReceive(getEchoElement()); //Cancel the token options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
public void testWithPolicy() { try { String repo = Constants.TESTING_PATH + "rampart_client_repo"; ConfigurationContext configContext = ConfigurationContextFactory. createConfigurationContextFromFileSystem(repo, null); ServiceClient serviceClient = new ServiceClient(configContext, null); serviceClient.engageModule(new QName("addressing")); serviceClient.engageModule(new QName("rampart")); //TODO : figure this out !! boolean basic256Supported = true; if(basic256Supported) { System.out.println("\nWARNING: We are using key sizes from JCE " + "Unlimited Strength Jurisdiction Policy !!!"); } for (int i = 1; i <= 10; i++) { //<-The number of tests we have if(!basic256Supported && (i == 3 || i == 4 || i ==5)) { //Skip the Basic256 tests continue; } Options options = new Options(); System.out.println("Testing WS-Sec: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureService" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); } for (int i = 1; i <= 2; i++) { //<-The number of tests we have Options options = new Options(); System.out.println("Testing WS-SecConv: custom scenario " + i); options.setAction("urn:echo"); options.setTo(new EndpointReference("http://127.0.0.1:" + PORT + "/axis2/services/SecureServiceSC" + i)); options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, loadPolicy("/rampart/policy/sc-" + i + ".xml")); serviceClient.setOptions(options); //Blocking invocation serviceClient.sendReceive(getEchoElement()); serviceClient.sendReceive(getEchoElement()); //Cancel the token options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_FALSE); serviceClient.sendReceive(getEchoElement()); options.setProperty(RampartMessageData.CANCEL_REQUEST, Constants.VALUE_TRUE); serviceClient.sendReceive(getEchoElement()); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
diff --git a/puyopuyo-android/src/com/tacoid/puyopuyo/Controller.java b/puyopuyo-android/src/com/tacoid/puyopuyo/Controller.java index 0e3e321..a04dbe5 100644 --- a/puyopuyo-android/src/com/tacoid/puyopuyo/Controller.java +++ b/puyopuyo-android/src/com/tacoid/puyopuyo/Controller.java @@ -1,90 +1,93 @@ package com.tacoid.puyopuyo; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.tacoid.puyopuyo.logic.GameLogic; import com.tacoid.puyopuyo.screens.MainMenuScreen; public class Controller implements InputProcessor { private GameLogic gameLogic; private Stage stage; public Controller(GameLogic gameLogic, Stage stage) { this.gameLogic = gameLogic; this.stage = stage; } @Override public boolean keyDown(int key) { + if (key != Keys.BACK && gameLogic.isPaused()) { + return false; + } switch (key) { case Keys.LEFT: gameLogic.moveLeft(); break; case Keys.RIGHT: gameLogic.moveRight(); break; case Keys.DOWN: gameLogic.down(); break; case Keys.ALT_LEFT: case Keys.UP: gameLogic.rotateRight(); break; case Keys.CONTROL_LEFT: gameLogic.rotateLeft(); break; case Keys.SPACE: gameLogic.dropPiece(); break; case Keys.BACK: PuyoPuyo.getInstance().setScreen(MainMenuScreen.getInstance()); break; } return false; } @Override public boolean keyTyped(char arg0) { // TODO Auto-generated method stub return false; } @Override public boolean keyUp(int key) { switch (key) { case Keys.DOWN: gameLogic.up(); break; } return false; } @Override public boolean scrolled(int arg0) { // TODO Auto-generated method stub return false; } @Override public boolean touchDown(int x, int y, int pointer, int button) { return stage.touchDown(x, y, pointer, button); } @Override public boolean touchDragged(int arg0, int arg1, int arg2) { return stage.touchDragged(arg0, arg1, arg2); } @Override public boolean touchMoved(int x, int y) { return stage.touchMoved(x, y); } @Override public boolean touchUp(int x, int y, int pointer, int button) { return stage.touchUp(x, y, pointer, button); } }
true
true
public boolean keyDown(int key) { switch (key) { case Keys.LEFT: gameLogic.moveLeft(); break; case Keys.RIGHT: gameLogic.moveRight(); break; case Keys.DOWN: gameLogic.down(); break; case Keys.ALT_LEFT: case Keys.UP: gameLogic.rotateRight(); break; case Keys.CONTROL_LEFT: gameLogic.rotateLeft(); break; case Keys.SPACE: gameLogic.dropPiece(); break; case Keys.BACK: PuyoPuyo.getInstance().setScreen(MainMenuScreen.getInstance()); break; } return false; }
public boolean keyDown(int key) { if (key != Keys.BACK && gameLogic.isPaused()) { return false; } switch (key) { case Keys.LEFT: gameLogic.moveLeft(); break; case Keys.RIGHT: gameLogic.moveRight(); break; case Keys.DOWN: gameLogic.down(); break; case Keys.ALT_LEFT: case Keys.UP: gameLogic.rotateRight(); break; case Keys.CONTROL_LEFT: gameLogic.rotateLeft(); break; case Keys.SPACE: gameLogic.dropPiece(); break; case Keys.BACK: PuyoPuyo.getInstance().setScreen(MainMenuScreen.getInstance()); break; } return false; }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/executor/QueryItemExecutor.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/executor/QueryItemExecutor.java index 58f16ae40..ad8b68fd9 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/executor/QueryItemExecutor.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/executor/QueryItemExecutor.java @@ -1,92 +1,93 @@ package org.eclipse.birt.report.engine.executor; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IDataQueryDefinition; import org.eclipse.birt.report.engine.emitter.IContentEmitter; import org.eclipse.birt.report.engine.extension.IBaseResultSet; import org.eclipse.birt.report.engine.extension.IQueryResultSet; import org.eclipse.birt.report.engine.ir.ReportItemDesign; abstract public class QueryItemExecutor extends StyledItemExecutor { protected boolean rsetEmpty; protected QueryItemExecutor( ExecutorManager manager ) { super( manager ); } protected QueryItemExecutor( ) { } /** * close dataset if the dataset is not null: * <p> * <ul> * <li>close the dataset. * <li>exit current script scope. * </ul> * * @param ds * the dataset object, null is valid */ protected void closeQuery( ) { if ( rset != null ) { rset.close( ); } } /** * register dataset of this item. * <p> * if dataset design of this item is not null, create a new * <code>DataSet</code> object by the dataset design. open the dataset, * move cursor to the first record , register the first row to script * context, and return this <code>DataSet</code> object if dataset design * is null, or open error, or empty resultset, return null. * * @param item * the report item design * @return the DataSet object if not null, else return null */ protected void executeQuery( ) { rset = null; IDataQueryDefinition query = design.getQuery( ); IBaseResultSet parentRset = getParentResultSet( ); context.setResultSet( parentRset ); if ( query != null ) { try { rset = (IQueryResultSet) context.executeQuery( parentRset, query ); context.setResultSet( rset ); if ( rset != null ) { rsetEmpty = !rset.next( ); return; } } catch ( BirtException ex ) { + rsetEmpty = true; context.addException( ex ); } } } protected void accessQuery( ReportItemDesign design, IContentEmitter emitter ) { } public void reset( ) { rset = null; rsetEmpty = false; super.reset( ); } }
true
true
protected void executeQuery( ) { rset = null; IDataQueryDefinition query = design.getQuery( ); IBaseResultSet parentRset = getParentResultSet( ); context.setResultSet( parentRset ); if ( query != null ) { try { rset = (IQueryResultSet) context.executeQuery( parentRset, query ); context.setResultSet( rset ); if ( rset != null ) { rsetEmpty = !rset.next( ); return; } } catch ( BirtException ex ) { context.addException( ex ); } } }
protected void executeQuery( ) { rset = null; IDataQueryDefinition query = design.getQuery( ); IBaseResultSet parentRset = getParentResultSet( ); context.setResultSet( parentRset ); if ( query != null ) { try { rset = (IQueryResultSet) context.executeQuery( parentRset, query ); context.setResultSet( rset ); if ( rset != null ) { rsetEmpty = !rset.next( ); return; } } catch ( BirtException ex ) { rsetEmpty = true; context.addException( ex ); } } }
diff --git a/src/biz/bokhorst/xprivacy/XPrivacy.java b/src/biz/bokhorst/xprivacy/XPrivacy.java index 9285ab25..f08030fe 100644 --- a/src/biz/bokhorst/xprivacy/XPrivacy.java +++ b/src/biz/bokhorst/xprivacy/XPrivacy.java @@ -1,456 +1,457 @@ package biz.bokhorst.xprivacy; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.annotation.SuppressLint; import android.content.Context; import android.os.Binder; import android.os.Build; import android.os.Process; import android.util.Log; import de.robv.android.xposed.IXposedHookZygoteInit; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.XC_MethodHook; import static de.robv.android.xposed.XposedHelpers.findClass; @SuppressLint("DefaultLocale") public class XPrivacy implements IXposedHookLoadPackage, IXposedHookZygoteInit { private static String mSecret = null; private static boolean mAccountManagerHooked = false; private static boolean mActivityManagerHooked = false; private static boolean mClipboardManagerHooked = false; private static boolean mConnectivityManagerHooked = false; private static boolean mLocationManagerHooked = false; private static boolean mPackageManagerHooked = false; private static boolean mSensorManagerHooked = false; private static boolean mTelephonyManagerHooked = false; private static boolean mWindowManagerHooked = false; private static boolean mWiFiManagerHooked = false; private static List<String> mListHookError = new ArrayList<String>(); // http://developer.android.com/reference/android/Manifest.permission.html @SuppressLint("InlinedApi") public void initZygote(StartupParam startupParam) throws Throwable { // Check for LBE security master if (Util.hasLBE()) return; Util.log(null, Log.INFO, String.format("Load %s", startupParam.modulePath)); // Generate secret mSecret = Long.toHexString(new Random().nextLong()); // System server try { // frameworks/base/services/java/com/android/server/SystemServer.java Class<?> cSystemServer = Class.forName("com.android.server.SystemServer"); Method mMain = cSystemServer.getDeclaredMethod("main", String[].class); XposedBridge.hookMethod(mMain, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { PrivacyService.register(mListHookError, mSecret); } }); } catch (Throwable ex) { Util.bug(null, ex); } // Activity manager service hookAll(XActivityManagerService.getInstances(), mSecret); // App widget manager hookAll(XAppWidgetManager.getInstances(), mSecret); // Application hookAll(XApplication.getInstances(), mSecret); // Audio record hookAll(XAudioRecord.getInstances(), mSecret); // Binder device hookAll(XBinder.getInstances(), mSecret); // Bluetooth adapater hookAll(XBluetoothAdapter.getInstances(), mSecret); // Bluetooth device hookAll(XBluetoothDevice.getInstances(), mSecret); // Camera hookAll(XCamera.getInstances(), mSecret); // Content resolver hookAll(XContentResolver.getInstances(), mSecret); // Context wrapper hookAll(XContextImpl.getInstances(), mSecret); // Environment hookAll(XEnvironment.getInstances(), mSecret); // InetAddress hookAll(XInetAddress.getInstances(), mSecret); // InputDevice hookAll(XInputDevice.getInstances(), mSecret); // IO bridge hookAll(XIoBridge.getInstances(), mSecret); // Media recorder hookAll(XMediaRecorder.getInstances(), mSecret); // Network info hookAll(XNetworkInfo.getInstances(), mSecret); // Network interface hookAll(XNetworkInterface.getInstances(), mSecret); // NFC adapter hookAll(XNfcAdapter.getInstances(), mSecret); // Package manager service hookAll(XProcess.getInstances(), mSecret); // Process builder hookAll(XProcessBuilder.getInstances(), mSecret); // Resources hookAll(XResources.getInstances(), mSecret); // Runtime hookAll(XRuntime.getInstances(), mSecret); // Settings secure hookAll(XSettingsSecure.getInstances(), mSecret); // SMS manager hookAll(XSmsManager.getInstances(), mSecret); // System properties hookAll(XSystemProperties.getInstances(), mSecret); // Web view hookAll(XWebView.getInstances(), mSecret); // Intent receive hookAll(XActivityThread.getInstances(), mSecret); // Intent send hookAll(XActivity.getInstances(), mSecret); } public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { // Check for LBE security master if (Util.hasLBE()) return; // Log load Util.log(null, Log.INFO, String.format("Load package=%s uid=%d", lpparam.packageName, Process.myUid())); // Skip hooking self String self = XPrivacy.class.getPackage().getName(); if (lpparam.packageName.equals(self)) { hookAll(XUtilHook.getInstances(), lpparam.classLoader, mSecret); return; } // Build SERIAL if (PrivacyManager.getRestriction(null, Process.myUid(), PrivacyManager.cIdentification, "SERIAL", mSecret)) XposedHelpers.setStaticObjectField(Build.class, "SERIAL", PrivacyManager.getDefacedProp(Process.myUid(), "SERIAL")); // Advertising Id try { Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient$Info", false, lpparam.classLoader); hookAll(XAdvertisingIdClientInfo.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } // Google auth try { Class.forName("com.google.android.gms.auth.GoogleAuthUtil", false, lpparam.classLoader); hookAll(XGoogleAuthUtil.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } // Location client try { Class.forName("com.google.android.gms.location.LocationClient", false, lpparam.classLoader); hookAll(XLocationClient.getInstances(), lpparam.classLoader, mSecret); } catch (Throwable ignored) { } } public static void handleGetSystemService(XHook hook, String name, Object instance) { Util.log(hook, Log.INFO, "getSystemService " + name + "=" + instance.getClass().getName() + " uid=" + Binder.getCallingUid()); if ("android.telephony.MSimTelephonyManager".equals(instance.getClass().getName())) { Util.log(hook, Log.WARN, "Telephone service=" + Context.TELEPHONY_SERVICE); Class<?> clazz = instance.getClass(); while (clazz != null) { Util.log(hook, Log.WARN, "Class " + clazz); for (Method method : clazz.getDeclaredMethods()) Util.log(hook, Log.WARN, "Declared " + method); clazz = clazz.getSuperclass(); } } if (name.equals(Context.ACCOUNT_SERVICE)) { // Account manager if (!mAccountManagerHooked) { hookAll(XAccountManager.getInstances(instance), mSecret); mAccountManagerHooked = true; } } else if (name.equals(Context.ACTIVITY_SERVICE)) { // Activity manager if (!mActivityManagerHooked) { hookAll(XActivityManager.getInstances(instance), mSecret); mActivityManagerHooked = true; } } else if (name.equals(Context.CLIPBOARD_SERVICE)) { // Clipboard manager if (!mClipboardManagerHooked) { XPrivacy.hookAll(XClipboardManager.getInstances(instance), mSecret); mClipboardManagerHooked = true; } } else if (name.equals(Context.CONNECTIVITY_SERVICE)) { // Connectivity manager if (!mConnectivityManagerHooked) { hookAll(XConnectivityManager.getInstances(instance), mSecret); mConnectivityManagerHooked = true; } } else if (name.equals(Context.LOCATION_SERVICE)) { // Location manager if (!mLocationManagerHooked) { hookAll(XLocationManager.getInstances(instance), mSecret); mLocationManagerHooked = true; } } else if (name.equals("PackageManager")) { // Package manager if (!mPackageManagerHooked) { hookAll(XPackageManager.getInstances(instance), mSecret); mPackageManagerHooked = true; } } else if (name.equals(Context.SENSOR_SERVICE)) { // Sensor manager if (!mSensorManagerHooked) { hookAll(XSensorManager.getInstances(instance), mSecret); mSensorManagerHooked = true; } } else if (name.equals(Context.TELEPHONY_SERVICE)) { // Telephony manager if (!mTelephonyManagerHooked) { hookAll(XTelephonyManager.getInstances(instance), mSecret); mTelephonyManagerHooked = true; } } else if (name.equals(Context.WINDOW_SERVICE)) { // Window manager if (!mWindowManagerHooked) { XPrivacy.hookAll(XWindowManager.getInstances(instance), mSecret); mWindowManagerHooked = true; } } else if (name.equals(Context.WIFI_SERVICE)) { // WiFi manager if (!mWiFiManagerHooked) { XPrivacy.hookAll(XWifiManager.getInstances(instance), mSecret); mWiFiManagerHooked = true; } } } public static void hookAll(List<XHook> listHook, String secret) { for (XHook hook : listHook) hook(hook, secret); } public static void hookAll(List<XHook> listHook, ClassLoader classLoader, String secret) { for (XHook hook : listHook) hook(hook, classLoader, secret); } private static void hook(XHook hook, String secret) { hook(hook, null, secret); } private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); - mListHookError.add(message); + if (!hook.isOptional()) + mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } } // WORKAROUND: when a native lib is loaded after hooking, the hook is undone private static List<XC_MethodHook.Unhook> mUnhookNativeMethod = new ArrayList<XC_MethodHook.Unhook>(); @SuppressWarnings("unused") private static void registerNativeMethod(final XHook hook, Method method, XC_MethodHook.Unhook unhook) { if (Process.myUid() > 0) { synchronized (mUnhookNativeMethod) { mUnhookNativeMethod.add(unhook); Util.log(hook, Log.INFO, "Native " + method + " uid=" + Process.myUid()); } } } @SuppressWarnings("unused") private static void hookCheckNative() { try { XC_MethodHook hook = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (Process.myUid() > 0) try { synchronized (mUnhookNativeMethod) { Util.log(null, Log.INFO, "Loading " + param.args[0] + " uid=" + Process.myUid() + " count=" + mUnhookNativeMethod.size()); for (XC_MethodHook.Unhook unhook : mUnhookNativeMethod) { XposedBridge.hookMethod(unhook.getHookedMethod(), unhook.getCallback()); unhook.unhook(); } } } catch (Throwable ex) { Util.bug(null, ex); } } }; Class<?> runtimeClass = Class.forName("java.lang.Runtime"); for (Method method : runtimeClass.getDeclaredMethods()) if (method.getName().equals("load") || method.getName().equals("loadLibrary")) { XposedBridge.hookMethod(method, hook); Util.log(null, Log.WARN, "Hooked " + method); } } catch (Throwable ex) { Util.bug(null, ex); } } }
true
true
private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } }
private static void hook(final XHook hook, ClassLoader classLoader, String secret) { // Check SDK version Hook md = null; String message = null; if (hook.getRestrictionName() == null) { if (hook.getSdk() == 0) message = "No SDK specified for " + hook; } else { md = PrivacyManager.getHook(hook.getRestrictionName(), hook.getSpecifier()); if (md == null) message = "Hook not found " + hook; else if (hook.getSdk() != 0) message = "SDK not expected for " + hook; } if (message != null) { mListHookError.add(message); Util.log(hook, Log.ERROR, message); } int sdk = 0; if (hook.getRestrictionName() == null) sdk = hook.getSdk(); else if (md != null) sdk = md.getSdk(); if (Build.VERSION.SDK_INT < sdk) return; // Provide secret hook.setSecret(secret); try { // Create hook method XC_MethodHook methodHook = new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); hook.before(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); param.setObjectExtra("xextra", xparam.getExtras()); } catch (Throwable ex) { Util.bug(null, ex); } } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { if (!param.hasThrowable()) try { if (Process.myUid() <= 0) return; XParam xparam = XParam.fromXposed(param); xparam.setExtras(param.getObjectExtra("xextra")); hook.after(xparam); if (xparam.hasResult()) param.setResult(xparam.getResult()); if (xparam.hasThrowable()) param.setThrowable(xparam.getThrowable()); } catch (Throwable ex) { Util.bug(null, ex); } } }; // Find class Class<?> hookClass = null; try { // hookClass = Class.forName(hook.getClassName()); hookClass = findClass(hook.getClassName(), classLoader); } catch (Throwable ex) { message = String.format("Class not found for %s", hook); mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } // Get members List<Member> listMember = new ArrayList<Member>(); Class<?> clazz = hookClass; while (clazz != null) { if (hook.getMethodName() == null) { for (Constructor<?> constructor : clazz.getDeclaredConstructors()) if (Modifier.isPublic(constructor.getModifiers()) ? hook.isVisible() : !hook.isVisible()) listMember.add(constructor); break; } else { for (Method method : clazz.getDeclaredMethods()) if (method.getName().equals(hook.getMethodName()) && (Modifier.isPublic(method.getModifiers()) ? hook.isVisible() : !hook.isVisible())) listMember.add(method); } clazz = clazz.getSuperclass(); } // Hook members for (Member member : listMember) try { XposedBridge.hookMethod(member, methodHook); } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } // Check if members found if (listMember.isEmpty() && !hook.getClassName().startsWith("com.google.android.gms")) { message = String.format("Method not found for %s", hook); if (!hook.isOptional()) mListHookError.add(message); Util.log(hook, hook.isOptional() ? Log.WARN : Log.ERROR, message); } } catch (Throwable ex) { mListHookError.add(ex.toString()); Util.bug(hook, ex); } }
diff --git a/src/main/java/test/JacksonBug.java b/src/main/java/test/JacksonBug.java index a1874c9..85472bd 100644 --- a/src/main/java/test/JacksonBug.java +++ b/src/main/java/test/JacksonBug.java @@ -1,62 +1,64 @@ package test; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import static org.apache.commons.lang3.Validate.notNull; public class JacksonBug { @JsonUnwrapped private final Name name; private final Map<String, String> data; @JsonCreator public JacksonBug(@JsonProperty("first") String first, @JsonProperty("last") String last) { notNull(first); notNull(last); this.name = new Name(first, last); this.data = new HashMap<String, String>(); } public Name getName() { return name; } public Map<String, String> getData() { return data; } @JsonAnySetter public void addMetadata(String key, String value) { data.put(key, value); } public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { String json = "{" + - "\"first\":\"Bob\"" + - ", \"last\":\"Builder\"" + - ", \"eyeColor\":\"brown\"" + + "\"one\":\"one\"" + + ", \"first\":\"Bob\"" + + ", \"two\":\"two\"" + + ", \"last\":\"Builder\"" + + ", \"three\":\"three\"" + "}"; ObjectMapper mapper = new ObjectMapper(); JacksonBug bug = mapper.readValue(json, JacksonBug.class); System.out.println(bug.getData()); - if (bug.getData().size() > 0) { + if (bug.getData().size() == 3) { System.out.println("SUCCESS!!!"); } else { System.out.println("back to the drawing board..."); } } }
false
true
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { String json = "{" + "\"first\":\"Bob\"" + ", \"last\":\"Builder\"" + ", \"eyeColor\":\"brown\"" + "}"; ObjectMapper mapper = new ObjectMapper(); JacksonBug bug = mapper.readValue(json, JacksonBug.class); System.out.println(bug.getData()); if (bug.getData().size() > 0) { System.out.println("SUCCESS!!!"); } else { System.out.println("back to the drawing board..."); } }
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { String json = "{" + "\"one\":\"one\"" + ", \"first\":\"Bob\"" + ", \"two\":\"two\"" + ", \"last\":\"Builder\"" + ", \"three\":\"three\"" + "}"; ObjectMapper mapper = new ObjectMapper(); JacksonBug bug = mapper.readValue(json, JacksonBug.class); System.out.println(bug.getData()); if (bug.getData().size() == 3) { System.out.println("SUCCESS!!!"); } else { System.out.println("back to the drawing board..."); } }
diff --git a/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/comment/CommentWidget.java b/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/comment/CommentWidget.java index a26bb8db43..642103fe82 100644 --- a/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/comment/CommentWidget.java +++ b/web-core/src/main/java/com/stratelia/webactiv/util/viewGenerator/html/comment/CommentWidget.java @@ -1,240 +1,240 @@ /* * Copyright (C) 2000 - 2009 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.util.viewGenerator.html.comment; import com.silverpeas.SilverpeasServiceProvider; import com.silverpeas.personalization.UserPreferences; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.util.ResourcesWrapper; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.OrganizationController; import com.stratelia.webactiv.util.ResourceLocator; import org.apache.ecs.ElementContainer; import org.apache.ecs.xhtml.div; import org.apache.ecs.xhtml.script; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.TagSupport; import java.util.Arrays; import static com.silverpeas.util.StringUtil.isDefined; /** * It defines the base class of a widget for the rendering and handling of comments in Silverpeas. */ public abstract class CommentWidget extends TagSupport { private static final long serialVersionUID = 441573421690625472L; /** * The identifier of the XHTML div tag within which the comment widgets are displayed. */ public static final String COMMENT_WIDGET_DIV_ID = "commentaires"; /** * The CSS class name of the XHTML div tag within which the comment widgets are displayed. */ public static final String COMMENT_WIDGET_DIV_CLASS = "commentaires"; private String componentId; private String resourceId; private String userId; private String callback; /** * Gets a javascript function to call when an event occurs on a comment or on a list of comments. * * @return the callback to invoke. */ public String getCallback() { return callback; } /** * Sets the javascript function to call when an event occurs on a comment or on a list of * comments. * * @param callback the callback to invoke. */ public void setCallback(String callback) { this.callback = callback; } /** * Sets up the widget with all required information. It initializes the JQuery comment plugin with * and it parameterizes from Silverpeas settings and from the resource for which the comments * should be rendered. * * @return a container of rendering elements. * @throws JspException if an error occurs while initializing the JQuery comment plugin. */ public ElementContainer initWidget() throws JspException { String context = URLManager.getApplicationURL(); ElementContainer xhtmlcontainer = new ElementContainer(); div comments = new div(); comments.setID(COMMENT_WIDGET_DIV_ID); comments.setClass(COMMENT_WIDGET_DIV_CLASS); script checkForm = new script().setType("text/javascript"). setSrc(context + "/util/javaScript/checkForm.js"); script initCommentPlugin = new script().setType("text/javascript"). addElement(setUpJQueryCommentPlugin()); script commentJqueryScript = new script().setType("text/javascript"). setSrc(URLManager.getApplicationURL() + "/util/javaScript/jquery/jquery-comment.js"); xhtmlcontainer.addElement(checkForm). addElement(commentJqueryScript). addElement(comments). addElement(initCommentPlugin); return xhtmlcontainer; } /** * Gets the unique identifier of the user that requested the page in which will be rendered the * widget. * * @return the unique identifier of the user. */ public String getUserId() { return userId; } /** * Sets the unique identifier of the user that requested the page in which will be rendered the * widget. * * @param userId the user identifier. */ public void setUserId(String userId) { this.userId = userId; } /** * Sets the unique identifier of the Silverpeas component instance to which the commented resource * belongs. * * @param componentId the unique identifier of the instance of a Silverpeas component. */ public void setComponentId(String componentId) { this.componentId = componentId; } /** * Sets the unique identifier of the resource that is commented out. * * @param resourceId the unique identifier of the commented resource. */ public void setResourceId(String resourceId) { this.resourceId = resourceId; } /** * Gets the identifier of the Silverpeas component instance to which the resource belongs. * * @return the component identifier. */ public String getComponentId() { return componentId; } /** * Gets the unique identifier of the resource in Silverpeas. * * @return the resource identifier. */ public String getResourceId() { return resourceId; } private UserPreferences getUserPreferences() throws JspTagException { return SilverpeasServiceProvider.getPersonalizationService().getUserSettings(getUserId()); } private ResourcesWrapper getSettings() throws JspTagException { String language = getUserPreferences().getLanguage(); ResourceLocator messages = new ResourceLocator( "com.stratelia.webactiv.util.comment.multilang.comment", language); ResourcesWrapper resources = new ResourcesWrapper(messages, new ResourceLocator("com.stratelia.webactiv.util.comment.icons", ""), new ResourceLocator("com.stratelia.webactiv.util.comment.Comment", ""), language); return resources; } private String getUpdateIconURL() { return URLManager.getApplicationURL() + "/util/icons/update.gif"; } private String getDeletionIconURL() { return URLManager.getApplicationURL() + "/util/icons/delete.gif"; } private String getMandatoryFieldSymbolURL() { return URLManager.getApplicationURL() + "/util/icons/mandatoryField.gif"; } /** * This method generates the Javascript instructions to retrieve in AJAX the comments on the given * resource and to display them. The generated code is built upon the JQuery toolkit, so that it * is required to be included within the the XHTML header section. * * @return the javascript code to handle a list of comments on a given resource. */ private String setUpJQueryCommentPlugin() throws JspTagException { String context = URLManager.getApplicationURL(); OrganizationController controller = new OrganizationController(); ResourcesWrapper settings = getSettings(); String[] profiles = controller.getUserProfiles(getUserId(), getComponentId()); boolean isAdmin = false; if (Arrays.asList(profiles).contains(SilverpeasRole.admin.name())) { isAdmin = true; } boolean canBeUpdated = settings.getSetting("AdminAllowedToUpdate", true) && isAdmin; String script = "$('#commentaires').comment({" + "uri: '" + context + "/services/comments/" + getComponentId() + "/" + getResourceId() + "', update: { activated: function( comment ) {" + "if (" + canBeUpdated + "|| (comment.author.id === '" + getUserId() + "'))" + "return true; else return false;},icon: '" + getUpdateIconURL() + "'," + "altText: '" + settings.getString("GML.update") + "'}," + "deletion: {activated: function( comment ) {if (" + canBeUpdated + " || (comment.author.id === '" + getUserId() + "')) return true; else return false;}," + "confirmation: '" + settings.getString("comment.suppressionConfirmation") + "'," + "icon: '" + getDeletionIconURL() + "',altText: '" + settings.getString("GML.delete") + "'}, updateBox: { title: '" + settings.getString("comment.comment") + "'}, editionBox: { title: '" + settings.getString("comment.add") + "', ok: '" + settings.getString("GML.validate") - + "'}, validate: function(text) { if (text == null || text.length == 0) { " + "alert('" + + "'}, validate: function(text) { if (text == null || $.trim(text).length == 0) { " + "alert('" + settings.getString("comment.pleaseFill_single") + "');" + "} else if (!isValidTextArea(text)) { alert('" + settings.getString( "comment.champsTropLong") + "'); } else { return true; } return false; }," + "mandatory: '" + getMandatoryFieldSymbolURL() + "', mandatoryText: '" + settings.getString( "GML.requiredField") + "'"; if (isDefined(getCallback())) { script += ",callback: " + getCallback() + "});"; } else { script += "});"; } return script; } }
true
true
private String setUpJQueryCommentPlugin() throws JspTagException { String context = URLManager.getApplicationURL(); OrganizationController controller = new OrganizationController(); ResourcesWrapper settings = getSettings(); String[] profiles = controller.getUserProfiles(getUserId(), getComponentId()); boolean isAdmin = false; if (Arrays.asList(profiles).contains(SilverpeasRole.admin.name())) { isAdmin = true; } boolean canBeUpdated = settings.getSetting("AdminAllowedToUpdate", true) && isAdmin; String script = "$('#commentaires').comment({" + "uri: '" + context + "/services/comments/" + getComponentId() + "/" + getResourceId() + "', update: { activated: function( comment ) {" + "if (" + canBeUpdated + "|| (comment.author.id === '" + getUserId() + "'))" + "return true; else return false;},icon: '" + getUpdateIconURL() + "'," + "altText: '" + settings.getString("GML.update") + "'}," + "deletion: {activated: function( comment ) {if (" + canBeUpdated + " || (comment.author.id === '" + getUserId() + "')) return true; else return false;}," + "confirmation: '" + settings.getString("comment.suppressionConfirmation") + "'," + "icon: '" + getDeletionIconURL() + "',altText: '" + settings.getString("GML.delete") + "'}, updateBox: { title: '" + settings.getString("comment.comment") + "'}, editionBox: { title: '" + settings.getString("comment.add") + "', ok: '" + settings.getString("GML.validate") + "'}, validate: function(text) { if (text == null || text.length == 0) { " + "alert('" + settings.getString("comment.pleaseFill_single") + "');" + "} else if (!isValidTextArea(text)) { alert('" + settings.getString( "comment.champsTropLong") + "'); } else { return true; } return false; }," + "mandatory: '" + getMandatoryFieldSymbolURL() + "', mandatoryText: '" + settings.getString( "GML.requiredField") + "'"; if (isDefined(getCallback())) { script += ",callback: " + getCallback() + "});"; } else { script += "});"; } return script; }
private String setUpJQueryCommentPlugin() throws JspTagException { String context = URLManager.getApplicationURL(); OrganizationController controller = new OrganizationController(); ResourcesWrapper settings = getSettings(); String[] profiles = controller.getUserProfiles(getUserId(), getComponentId()); boolean isAdmin = false; if (Arrays.asList(profiles).contains(SilverpeasRole.admin.name())) { isAdmin = true; } boolean canBeUpdated = settings.getSetting("AdminAllowedToUpdate", true) && isAdmin; String script = "$('#commentaires').comment({" + "uri: '" + context + "/services/comments/" + getComponentId() + "/" + getResourceId() + "', update: { activated: function( comment ) {" + "if (" + canBeUpdated + "|| (comment.author.id === '" + getUserId() + "'))" + "return true; else return false;},icon: '" + getUpdateIconURL() + "'," + "altText: '" + settings.getString("GML.update") + "'}," + "deletion: {activated: function( comment ) {if (" + canBeUpdated + " || (comment.author.id === '" + getUserId() + "')) return true; else return false;}," + "confirmation: '" + settings.getString("comment.suppressionConfirmation") + "'," + "icon: '" + getDeletionIconURL() + "',altText: '" + settings.getString("GML.delete") + "'}, updateBox: { title: '" + settings.getString("comment.comment") + "'}, editionBox: { title: '" + settings.getString("comment.add") + "', ok: '" + settings.getString("GML.validate") + "'}, validate: function(text) { if (text == null || $.trim(text).length == 0) { " + "alert('" + settings.getString("comment.pleaseFill_single") + "');" + "} else if (!isValidTextArea(text)) { alert('" + settings.getString( "comment.champsTropLong") + "'); } else { return true; } return false; }," + "mandatory: '" + getMandatoryFieldSymbolURL() + "', mandatoryText: '" + settings.getString( "GML.requiredField") + "'"; if (isDefined(getCallback())) { script += ",callback: " + getCallback() + "});"; } else { script += "});"; } return script; }
diff --git a/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java b/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java index c6c9f236..65060ece 100644 --- a/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java +++ b/deduplication-document/deduplication-document-impl/src/main/java/pl/edu/icm/coansys/deduplication/document/DuplicateWorkDetectReduceService.java @@ -1,234 +1,235 @@ /* * This file is part of CoAnSys project. * Copyright (c) 2012-2013 ICM-UW * * CoAnSys is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * CoAnSys is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CoAnSys. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.coansys.deduplication.document; import pl.edu.icm.coansys.commons.java.DocumentWrapperUtils; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.edu.icm.coansys.commons.spring.DiReduceService; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.hadoop.conf.Configuration; import org.springframework.beans.factory.annotation.Value; import pl.edu.icm.coansys.deduplication.document.keygenerator.WorkKeyGenerator; import pl.edu.icm.coansys.models.DocumentProtos; /** * * @author Łukasz Dumiszewski * */ @Service("duplicateWorkDetectReduceService") public class DuplicateWorkDetectReduceService implements DiReduceService<Text, BytesWritable, Text, Text> { //@SuppressWarnings("unused") private static Logger log = LoggerFactory.getLogger(DuplicateWorkDetectReduceService.class); @Autowired private DuplicateWorkService duplicateWorkService; @Autowired private WorkKeyGenerator keyGen; private int initialMaxDocsSetSize; private int maxDocsSetSizeInc; private int maxSplitLevel; //******************** DiReduceService Implementation ******************** @Override public void reduce(Text key, Iterable<BytesWritable> values, Reducer<Text, BytesWritable, Text, Text>.Context context) throws IOException, InterruptedException { log.info("starting reduce, key: " + key.toString()); List<DocumentProtos.DocumentMetadata> documents = DocumentWrapperUtils.extractDocumentMetadata(key, values); long startTime = new Date().getTime(); Configuration conf = context.getConfiguration(); initialMaxDocsSetSize = conf.getInt("INITIAL_MAX_DOCS_SET_SIZE", initialMaxDocsSetSize); maxDocsSetSizeInc = conf.getInt("MAX_DOCS_SET_SIZE_INC", maxDocsSetSizeInc); maxSplitLevel = conf.getInt("MAX_SPLIT_LEVEL", maxSplitLevel); process(key, context, documents, 0, initialMaxDocsSetSize); log.info("time [msec]: " + (new Date().getTime()-startTime)); } //******************** PRIVATE ******************** /** * Processes the given documents: finds duplicates and saves them to the context under the same, common key. * If the number of the passed documents is greater than the <b>maxNumberOfDocuments</b> then the documents are split into smaller parts and * then the method is recursively invoked for each one of those parts. * @param key a common key of the documents * @param level the recursive depth of the method used to generate a proper key of the passed documents. The greater the level the longer (and more unique) the * generated key. */ void process(Text key, Reducer<Text, BytesWritable, Text, Text>.Context context, List<DocumentProtos.DocumentMetadata> documents, int level, int maxNumberOfDocuments) throws IOException, InterruptedException { String dashes = getDashes(level); log.info(dashes+ "start process, key: {}, number of documents: {}", key.toString(), documents.size()); if (documents.size()<2) { log.info(dashes+ "one document only, ommiting"); return; } int lev = level + 1; int maxNumOfDocs = maxNumberOfDocuments; if (documents.size()>maxNumOfDocs) { Map<Text, List<DocumentProtos.DocumentMetadata>> documentPacks = splitDocuments(key, documents, lev); log.info(dashes+ "documents split into: {} packs", documentPacks.size()); for (Map.Entry<Text, List<DocumentProtos.DocumentMetadata>> docs : documentPacks.entrySet()) { if (docs.getValue().size()==documents.size()) { // docs were not splitted, the generated key is the same for all the titles, may happen if the documents have the same short title, e.g. news in brief maxNumOfDocs+=maxDocsSetSizeInc; } process(docs.getKey(), context, docs.getValue(), lev, maxNumOfDocs); } } else { if (isDebugMode(context.getConfiguration())) { duplicateWorkService.findDuplicates(documents, context); } else { Map<Integer, Set<DocumentProtos.DocumentMetadata>> duplicateWorksMap = duplicateWorkService.findDuplicates(documents, null); saveDuplicatesToContext(duplicateWorksMap, key, context); } context.progress(); } log.info(dashes+ "end process, key: {}", key); } private String getDashes(int level) { StringBuilder sb = new StringBuilder(); for (int i=0; i<=level; i++) { sb.append("-"); } return sb.toString(); } private boolean isDebugMode(Configuration conf) { if (conf == null) { return false; } String debugOptionValue = conf.get("DEDUPLICATION_DEBUG_MODE", "false"); return debugOptionValue.equals("true"); } /** * Splits the passed documents into smaller parts. The documents are divided into smaller packs according to the generated keys. * The keys are generated by using the {@link WorkKeyGenerator.generateKey(doc, level)} method. */ Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) { // check if set was forced to split; if yes, keep the suffix String keyStr = key.toString(); String suffix = ""; if (keyStr.contains("-")) { String[] parts = keyStr.split("-"); suffix = parts[1]; } Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap(); for (DocumentProtos.DocumentMetadata doc : documents) { String newKeyStr = keyGen.generateKey(doc, level); if (!suffix.isEmpty()) { newKeyStr = newKeyStr + "-" + suffix; } Text newKey = new Text(newKeyStr); List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey); if (list == null) { list = Lists.newArrayList(); splitDocuments.put(newKey, list); } list.add(doc); } if (level > maxSplitLevel && splitDocuments.size() == 1) { //force split into 2 parts - String commonKey = splitDocuments.keySet().iterator().next().toString(); - if (!commonKey.contains("-")) { - commonKey += "-"; + Text commonKey = splitDocuments.keySet().iterator().next(); + String commonKeyStr = commonKey.toString(); + if (!commonKeyStr.contains("-")) { + commonKeyStr += "-"; } - Text firstKey = new Text(commonKey + "0"); - Text secondKey = new Text(commonKey + "1"); - List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(firstKey); + Text firstKey = new Text(commonKeyStr + "0"); + Text secondKey = new Text(commonKeyStr + "1"); + List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(commonKey); int items = fullList.size(); List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2); List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items); splitDocuments.put(firstKey, firstHalf); splitDocuments.put(secondKey, secondHalf); } return splitDocuments; } private void saveDuplicatesToContext(Map<Integer, Set<DocumentProtos.DocumentMetadata>> sameWorksMap, Text key, Reducer<Text, BytesWritable, Text, Text>.Context context) throws IOException, InterruptedException { for (Map.Entry<Integer, Set<DocumentProtos.DocumentMetadata>> entry : sameWorksMap.entrySet()) { String sameWorksKey = key.toString() + "_" + entry.getKey(); for (DocumentProtos.DocumentMetadata doc : entry.getValue()) { context.write(new Text(sameWorksKey), new Text(doc.getKey())); } } } @Value("1000") public void setBeginPackSize(int beginPackSize) { this.initialMaxDocsSetSize = beginPackSize; } @Value("200") public void setPackSizeInc(int packSizeInc) { this.maxDocsSetSizeInc = packSizeInc; } @Value("10") public void setMaxSplitLevels(int maxSplitLevels) { this.maxSplitLevel = maxSplitLevels; } static enum UnparseableIssue { UNPARSEABLE }; }
false
true
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) { // check if set was forced to split; if yes, keep the suffix String keyStr = key.toString(); String suffix = ""; if (keyStr.contains("-")) { String[] parts = keyStr.split("-"); suffix = parts[1]; } Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap(); for (DocumentProtos.DocumentMetadata doc : documents) { String newKeyStr = keyGen.generateKey(doc, level); if (!suffix.isEmpty()) { newKeyStr = newKeyStr + "-" + suffix; } Text newKey = new Text(newKeyStr); List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey); if (list == null) { list = Lists.newArrayList(); splitDocuments.put(newKey, list); } list.add(doc); } if (level > maxSplitLevel && splitDocuments.size() == 1) { //force split into 2 parts String commonKey = splitDocuments.keySet().iterator().next().toString(); if (!commonKey.contains("-")) { commonKey += "-"; } Text firstKey = new Text(commonKey + "0"); Text secondKey = new Text(commonKey + "1"); List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(firstKey); int items = fullList.size(); List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2); List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items); splitDocuments.put(firstKey, firstHalf); splitDocuments.put(secondKey, secondHalf); } return splitDocuments; }
Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments(Text key, List<DocumentProtos.DocumentMetadata> documents, int level) { // check if set was forced to split; if yes, keep the suffix String keyStr = key.toString(); String suffix = ""; if (keyStr.contains("-")) { String[] parts = keyStr.split("-"); suffix = parts[1]; } Map<Text, List<DocumentProtos.DocumentMetadata>> splitDocuments = Maps.newHashMap(); for (DocumentProtos.DocumentMetadata doc : documents) { String newKeyStr = keyGen.generateKey(doc, level); if (!suffix.isEmpty()) { newKeyStr = newKeyStr + "-" + suffix; } Text newKey = new Text(newKeyStr); List<DocumentProtos.DocumentMetadata> list = splitDocuments.get(newKey); if (list == null) { list = Lists.newArrayList(); splitDocuments.put(newKey, list); } list.add(doc); } if (level > maxSplitLevel && splitDocuments.size() == 1) { //force split into 2 parts Text commonKey = splitDocuments.keySet().iterator().next(); String commonKeyStr = commonKey.toString(); if (!commonKeyStr.contains("-")) { commonKeyStr += "-"; } Text firstKey = new Text(commonKeyStr + "0"); Text secondKey = new Text(commonKeyStr + "1"); List<DocumentProtos.DocumentMetadata> fullList = splitDocuments.get(commonKey); int items = fullList.size(); List<DocumentProtos.DocumentMetadata> firstHalf = fullList.subList(0, items/2); List<DocumentProtos.DocumentMetadata> secondHalf = fullList.subList(items/2, items); splitDocuments.put(firstKey, firstHalf); splitDocuments.put(secondKey, secondHalf); } return splitDocuments; }
diff --git a/src/main/java/com/gitblit/wicket/pages/SessionPage.java b/src/main/java/com/gitblit/wicket/pages/SessionPage.java index 22ae6e2e..8065c5aa 100644 --- a/src/main/java/com/gitblit/wicket/pages/SessionPage.java +++ b/src/main/java/com/gitblit/wicket/pages/SessionPage.java @@ -1,98 +1,98 @@ /* * Copyright 2013 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.wicket.pages; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.wicket.PageParameters; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.protocol.http.WebRequest; import org.apache.wicket.protocol.http.WebResponse; import com.gitblit.Keys; import com.gitblit.models.UserModel; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.GitBlitWebApp; import com.gitblit.wicket.GitBlitWebSession; public abstract class SessionPage extends WebPage { public SessionPage() { super(); login(); } public SessionPage(final PageParameters params) { super(params); login(); } protected String [] getEncodings() { return app().settings().getStrings(Keys.web.blobEncodings).toArray(new String[0]); } protected GitBlitWebApp app() { return GitBlitWebApp.get(); } private void login() { GitBlitWebSession session = GitBlitWebSession.get(); if (session.isLoggedIn() && !session.isSessionInvalidated()) { // already have a session, refresh usermodel to pick up // any changes to permissions or roles (issue-186) UserModel user = app().users().getUserModel(session.getUser().username); // validate cookie during session (issue-361) - if (app().settings().getBoolean(Keys.web.allowCookieAuthentication, true)) { + if (user != null && app().settings().getBoolean(Keys.web.allowCookieAuthentication, true)) { HttpServletRequest request = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); String requestCookie = app().authentication().getCookie(request); if (!StringUtils.isEmpty(requestCookie) && !StringUtils.isEmpty(user.cookie)) { if (!requestCookie.equals(user.cookie)) { // cookie was changed during our session HttpServletResponse response = ((WebResponse) getRequestCycle().getResponse()) .getHttpServletResponse(); app().authentication().logout(response, user); session.setUser(null); session.invalidateNow(); return; } } } session.setUser(user); return; } // try to authenticate by servlet request HttpServletRequest httpRequest = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); UserModel user = app().authentication().authenticate(httpRequest); // Login the user if (user != null) { // issue 62: fix session fixation vulnerability session.replaceSession(); session.setUser(user); // Set Cookie WebResponse response = (WebResponse) getRequestCycle().getResponse(); app().authentication().setCookie(response.getHttpServletResponse(), user); session.continueRequest(); } } }
true
true
private void login() { GitBlitWebSession session = GitBlitWebSession.get(); if (session.isLoggedIn() && !session.isSessionInvalidated()) { // already have a session, refresh usermodel to pick up // any changes to permissions or roles (issue-186) UserModel user = app().users().getUserModel(session.getUser().username); // validate cookie during session (issue-361) if (app().settings().getBoolean(Keys.web.allowCookieAuthentication, true)) { HttpServletRequest request = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); String requestCookie = app().authentication().getCookie(request); if (!StringUtils.isEmpty(requestCookie) && !StringUtils.isEmpty(user.cookie)) { if (!requestCookie.equals(user.cookie)) { // cookie was changed during our session HttpServletResponse response = ((WebResponse) getRequestCycle().getResponse()) .getHttpServletResponse(); app().authentication().logout(response, user); session.setUser(null); session.invalidateNow(); return; } } } session.setUser(user); return; } // try to authenticate by servlet request HttpServletRequest httpRequest = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); UserModel user = app().authentication().authenticate(httpRequest); // Login the user if (user != null) { // issue 62: fix session fixation vulnerability session.replaceSession(); session.setUser(user); // Set Cookie WebResponse response = (WebResponse) getRequestCycle().getResponse(); app().authentication().setCookie(response.getHttpServletResponse(), user); session.continueRequest(); } }
private void login() { GitBlitWebSession session = GitBlitWebSession.get(); if (session.isLoggedIn() && !session.isSessionInvalidated()) { // already have a session, refresh usermodel to pick up // any changes to permissions or roles (issue-186) UserModel user = app().users().getUserModel(session.getUser().username); // validate cookie during session (issue-361) if (user != null && app().settings().getBoolean(Keys.web.allowCookieAuthentication, true)) { HttpServletRequest request = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); String requestCookie = app().authentication().getCookie(request); if (!StringUtils.isEmpty(requestCookie) && !StringUtils.isEmpty(user.cookie)) { if (!requestCookie.equals(user.cookie)) { // cookie was changed during our session HttpServletResponse response = ((WebResponse) getRequestCycle().getResponse()) .getHttpServletResponse(); app().authentication().logout(response, user); session.setUser(null); session.invalidateNow(); return; } } } session.setUser(user); return; } // try to authenticate by servlet request HttpServletRequest httpRequest = ((WebRequest) getRequestCycle().getRequest()) .getHttpServletRequest(); UserModel user = app().authentication().authenticate(httpRequest); // Login the user if (user != null) { // issue 62: fix session fixation vulnerability session.replaceSession(); session.setUser(user); // Set Cookie WebResponse response = (WebResponse) getRequestCycle().getResponse(); app().authentication().setCookie(response.getHttpServletResponse(), user); session.continueRequest(); } }
diff --git a/src/main/java/com/authdb/util/Config.java b/src/main/java/com/authdb/util/Config.java index f845ce9..4683386 100644 --- a/src/main/java/com/authdb/util/Config.java +++ b/src/main/java/com/authdb/util/Config.java @@ -1,371 +1,372 @@ /* * This file is part of AuthDB <http://www.authdb.com/>. * * AuthDB is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AuthDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.authdb.util; import org.bukkit.configuration.file.FileConfiguration; import com.authdb.AuthDB; //import com.ensifera.animosity.craftirc.CraftIRC; public class Config { public static boolean database_ison, authdb_enabled = true; public static boolean has_badcharacters; public static boolean hasForumBoard,capitalization; public static boolean hasBackpack = false, hasSpout = false, hasBuildr = false; public static boolean onlineMode = true; public static boolean database_keepalive; public static String database_type, database_username,database_password,database_port,database_host,database_database,dbDb; public static boolean autoupdate_enable,debug_enable,usagestats_enabled,logging_enabled; public static String language_commands, language_messages, logformat; public static String script_name,script_version,script_salt,script_tableprefix; public static boolean script_updatestatus; public static String custom_table,custom_userfield,custom_passfield,custom_encryption,custom_emailfield; public static boolean custom_enabled,custom_autocreate,custom_salt, custom_emailrequired; public static boolean register_enabled,register_force; public static String register_delay_length,register_delay_time,register_timeout_length,register_timeout_time,register_show_length,register_show_time; public static int register_delay,register_timeout,register_show; public static boolean login_enabled; public static String login_method,login_tries,login_action,login_delay_length,login_delay_time,login_timeout_length,login_timeout_time,login_show_length,login_show_time; public static int login_delay,login_timeout,login_show; public static boolean link_enabled,link_rename; public static boolean unlink_enabled,unlink_rename; public static String username_minimum,username_maximum; public static String password_minimum,password_maximum; public static boolean session_protect, session_enabled; public static String session_time,session_thelength,session_start; public static int session_length; public static boolean guests_commands,guests_movement,guests_inventory,guests_drop,guests_pickup,guests_health,guests_mobdamage,guests_interact,guests_build,guests_destroy,guests_chat,guests_mobtargeting,guests_pvp; public static boolean protection_notify, protection_freeze; public static int protection_notify_delay, protection_freeze_delay; public static String protection_notify_delay_time, protection_notify_delay_length, protection_freeze_delay_time, protection_freeze_delay_length; public static String filter_action,filter_username,filter_password,filter_whitelist=""; public static boolean geoip_enabled; public static boolean CraftIRC_enabled; public static String CraftIRC_tag,CraftIRC_prefix; public static boolean CraftIRC_messages_enabled,CraftIRC_messages_welcome_enabled,CraftIRC_messages_register_enabled,CraftIRC_messages_unregister_enabled,CraftIRC_messages_login_enabled,CraftIRC_messages_email_enabled,CraftIRC_messages_username_enabled,CraftIRC_messages_password_enabled,CraftIRC_messages_idle_enabled; public static String commands_user_register,commands_user_link,commands_user_unlink,commands_user_login,commands_user_logout; public static String commands_admin_login, commands_admin_logout, commands_admin_reload; public static String aliases_user_register,aliases_user_link,aliases_user_unlink,aliases_user_login,aliases_user_logout; public static String aliases_admin_login, aliases_admin_logout, aliases_admin_reload; public static FileConfiguration configFile = null; public Config(AuthDB plugin, String config, String directory, String filename) { if (config.equalsIgnoreCase("basic")) { configFile = plugin.getBasicConfig(); language_commands = getConfigString("plugin.language.commands", "English"); language_messages = getConfigString("plugin.language.messages", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); - dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database; + dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database + + "?jdbcCompliantTruncation=false"; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { configFile = plugin.getAdvancedConfig(); custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); protection_freeze = getConfigBoolean("protection.freeze.enabled", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); protection_notify = getConfigBoolean("protection.notify.enabled", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "$&\"\\"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { configFile = plugin.getPluginsConfig(); CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { configFile = plugin.getMessagesConfig(); Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_register_processing = Config.getConfigString("Core.register.processing", "{YELLOW}Processing registration..."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registered yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_login_processing = Config.getConfigString("Core.login.processing", "{YELLOW}Processing login..."); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_logout_processing = Config.getConfigString("Core.logout.processing", "{YELLOW}Attempting to logout..."); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registered = Config.getConfigString("Core.link.registered", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}."); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_link_processing = Config.getConfigString("Core.link.processing", "{YELLOW}Attempting to link username..."); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}."); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_unlink_processing = Config.getConfigString("Core.unlink.processing", "{YELLOW}Attempting to unlink username..."); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { configFile = plugin.getCommandsConfig(); commands_user_register = Config.getConfigString("Core.commands.user.register", "/register"); commands_user_link = Config.getConfigString("Core.commands.user.link", "/link"); commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink"); commands_user_login = Config.getConfigString("Core.commands.user.login", "/login"); commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout"); commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login"); commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout"); commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload"); aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/reg"); aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li"); aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul"); aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l"); aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo"); aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/al"); aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/alo"); aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar"); } } public static String getConfigString(String key, String defaultvalue) { return configFile.getString(key, defaultvalue); } public static boolean getConfigBoolean(String key, boolean defaultvalue) { return configFile.getBoolean(key, defaultvalue); } public String raw(String key, String line) { return configFile.getString(key, line); } }
true
true
public Config(AuthDB plugin, String config, String directory, String filename) { if (config.equalsIgnoreCase("basic")) { configFile = plugin.getBasicConfig(); language_commands = getConfigString("plugin.language.commands", "English"); language_messages = getConfigString("plugin.language.messages", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { configFile = plugin.getAdvancedConfig(); custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); protection_freeze = getConfigBoolean("protection.freeze.enabled", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); protection_notify = getConfigBoolean("protection.notify.enabled", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "$&\"\\"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { configFile = plugin.getPluginsConfig(); CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { configFile = plugin.getMessagesConfig(); Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_register_processing = Config.getConfigString("Core.register.processing", "{YELLOW}Processing registration..."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registered yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_login_processing = Config.getConfigString("Core.login.processing", "{YELLOW}Processing login..."); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_logout_processing = Config.getConfigString("Core.logout.processing", "{YELLOW}Attempting to logout..."); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registered = Config.getConfigString("Core.link.registered", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}."); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_link_processing = Config.getConfigString("Core.link.processing", "{YELLOW}Attempting to link username..."); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}."); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_unlink_processing = Config.getConfigString("Core.unlink.processing", "{YELLOW}Attempting to unlink username..."); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { configFile = plugin.getCommandsConfig(); commands_user_register = Config.getConfigString("Core.commands.user.register", "/register"); commands_user_link = Config.getConfigString("Core.commands.user.link", "/link"); commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink"); commands_user_login = Config.getConfigString("Core.commands.user.login", "/login"); commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout"); commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login"); commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout"); commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload"); aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/reg"); aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li"); aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul"); aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l"); aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo"); aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/al"); aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/alo"); aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar"); } }
public Config(AuthDB plugin, String config, String directory, String filename) { if (config.equalsIgnoreCase("basic")) { configFile = plugin.getBasicConfig(); language_commands = getConfigString("plugin.language.commands", "English"); language_messages = getConfigString("plugin.language.messages", "English"); autoupdate_enable = getConfigBoolean("plugin.autoupdate", true); debug_enable = getConfigBoolean("plugin.debugmode", false); usagestats_enabled = getConfigBoolean("plugin.usagestats", true); logformat = getConfigString("plugin.logformat", "yyyy-MM-dd"); logging_enabled = getConfigBoolean("plugin.logging", true); database_type = getConfigString("database.type", "mysql"); database_username = getConfigString("database.username", "root"); database_password = getConfigString("database.password", ""); database_port = getConfigString("database.port", "3306"); database_host = getConfigString("database.host", "localhost"); database_database = getConfigString("database.name", "forum"); database_keepalive = getConfigBoolean("database.keepalive", false); dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database + "?jdbcCompliantTruncation=false"; script_name = getConfigString("script.name", "phpbb").toLowerCase(); script_version = getConfigString("script.version", "3.0.8"); script_tableprefix = getConfigString("script.tableprefix", ""); script_updatestatus = getConfigBoolean("script.updatestatus", true); script_salt = getConfigString("script.salt", ""); } else if (config.equalsIgnoreCase("advanced")) { configFile = plugin.getAdvancedConfig(); custom_enabled = getConfigBoolean("customdb.enabled", false); custom_autocreate = getConfigBoolean("customdb.autocreate", true); custom_emailrequired = getConfigBoolean("customdb.emailrequired", false); custom_table = getConfigString("customdb.table", "authdb_users"); custom_userfield = getConfigString("customdb.userfield", "username"); custom_passfield = getConfigString("customdb.passfield", "password"); custom_emailfield = getConfigString("customdb.emailfield", "email"); custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase(); register_enabled = getConfigBoolean("register.enabled", true); register_force = getConfigBoolean("register.force", true); register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0]; register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1]; register_delay = Util.toTicks(register_delay_time,register_delay_length); register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0]; register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1]; register_show = Util.toSeconds(register_show_time,register_show_length); register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0]; register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1]; register_timeout = Util.toTicks(register_timeout_time,register_timeout_length); login_method = getConfigString("login.method", "prompt"); login_tries = getConfigString("login.tries", "3"); login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0]; login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1]; login_delay = Util.toTicks(login_delay_time,login_delay_length); login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0]; login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1]; login_show = Util.toSeconds(login_show_time,login_show_length); login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0]; login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1]; login_timeout = Util.toTicks(login_timeout_time,login_timeout_length); link_enabled = getConfigBoolean("link.enabled", true); link_rename = getConfigBoolean("link.rename", true); unlink_enabled = getConfigBoolean("unlink.enabled", true); unlink_rename = getConfigBoolean("unlink.rename", true); username_minimum = getConfigString("username.minimum", "3"); username_maximum = getConfigString("username.maximum", "16"); password_minimum = getConfigString("password.minimum", "6"); password_maximum = getConfigString("password.maximum", "16"); session_enabled = getConfigBoolean("session.enabled", false); session_protect = getConfigBoolean("session.protect", true); session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0]; session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1]; session_length = Util.toSeconds(session_time,session_thelength); session_start = Util.checkSessionStart(getConfigString("session.start", "login")); guests_commands = getConfigBoolean("guest.commands", false); guests_movement = getConfigBoolean("guest.movement", false); guests_inventory = getConfigBoolean("guest.inventory", false); guests_drop = getConfigBoolean("guest.drop", false); guests_pickup = getConfigBoolean("guest.pickup", false); guests_health = getConfigBoolean("guest.health", false); guests_mobdamage = getConfigBoolean("guest.mobdamage", false); guests_interact = getConfigBoolean("guest.interactions", false); guests_build = getConfigBoolean("guest.building", false); guests_destroy = getConfigBoolean("guest.destruction", false); guests_chat = getConfigBoolean("guest.chat", false); guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false); guests_pvp = getConfigBoolean("guest.pvp", false); protection_freeze = getConfigBoolean("protection.freeze.enabled", true); protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0]; protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1]; protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length); protection_notify = getConfigBoolean("protection.notify.enabled", true); protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0]; protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1]; protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length); filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase()); filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/"); filter_password = getConfigString("filter.password", "$&\"\\"); filter_whitelist= getConfigString("filter.whitelist", ""); } else if (config.equalsIgnoreCase("plugins")) { configFile = plugin.getPluginsConfig(); CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true); CraftIRC_tag = getConfigString("CraftIRC.tag", "admin"); CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%"); /* CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true); CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true); CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true); CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true); CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true); CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true); CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true); CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true); CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true); */ } else if (config.equalsIgnoreCase("messages")) { configFile = plugin.getMessagesConfig(); Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond"); Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds"); Messages.time_second = Config.getConfigString("Core.time.second.", "second"); Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds"); Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute"); Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes"); Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour"); Messages.time_hours = Config.getConfigString("Core.time.hours", "hours"); Messages.time_day = Config.getConfigString("Core.time.day", "day"); Messages.time_days = Config.getConfigString("Core.time.days", "days"); Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!"); Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin."); Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email"); Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!"); Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!"); Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!"); Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!"); Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email"); Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}."); Messages.AuthDB_message_register_processing = Config.getConfigString("Core.register.processing", "{YELLOW}Processing registration..."); Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!"); Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!"); Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password"); Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password"); Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:"); Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!"); Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again."); Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!"); Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!"); Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registered yet!"); Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}."); Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin."); Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}."); Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in."); Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password"); Messages.AuthDB_message_login_processing = Config.getConfigString("Core.login.processing", "{YELLOW}Processing login..."); Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!"); Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!"); Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin."); Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}."); Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in"); Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again."); Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}"); Messages.AuthDB_message_logout_processing = Config.getConfigString("Core.logout.processing", "{YELLOW}Attempting to logout..."); Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password"); Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in"); Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!"); Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!"); Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!"); Messages.AuthDB_message_link_registered = Config.getConfigString("Core.link.registered", "{RED}You cannot link as this username is already registered!"); Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!"); Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}."); Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password"); Messages.AuthDB_message_link_processing = Config.getConfigString("Core.link.processing", "{YELLOW}Attempting to link username..."); Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!"); Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!"); Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!"); Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!"); Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!"); Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}."); Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password"); Messages.AuthDB_message_unlink_processing = Config.getConfigString("Core.unlink.processing", "{YELLOW}Attempting to unlink username..."); Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!"); Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!"); Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!"); Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}."); Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!"); Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!"); Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!"); Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!"); Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!"); Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!"); Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!"); Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!"); Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!"); Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!"); Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password"); Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!"); Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server."); Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command."); Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!"); Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server."); Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server."); Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!"); Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!"); Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again."); Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!"); Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!"); Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters."); Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!"); Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!"); } else if (config.equalsIgnoreCase("commands")) { configFile = plugin.getCommandsConfig(); commands_user_register = Config.getConfigString("Core.commands.user.register", "/register"); commands_user_link = Config.getConfigString("Core.commands.user.link", "/link"); commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink"); commands_user_login = Config.getConfigString("Core.commands.user.login", "/login"); commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout"); commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login"); commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout"); commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload"); aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/reg"); aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li"); aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul"); aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l"); aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo"); aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/al"); aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/alo"); aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar"); } }
diff --git a/modules/resin/src/com/caucho/transaction/enhancer/TransactionEnhancer.java b/modules/resin/src/com/caucho/transaction/enhancer/TransactionEnhancer.java index a102b74b4..31f252031 100644 --- a/modules/resin/src/com/caucho/transaction/enhancer/TransactionEnhancer.java +++ b/modules/resin/src/com/caucho/transaction/enhancer/TransactionEnhancer.java @@ -1,115 +1,115 @@ /* * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.transaction.enhancer; import com.caucho.bytecode.JAnnotation; import com.caucho.bytecode.JMethod; import com.caucho.config.ConfigException; import com.caucho.java.gen.BaseMethod; import com.caucho.java.gen.CallChain; import com.caucho.java.gen.GenClass; import com.caucho.loader.enhancer.MethodEnhancer; import com.caucho.util.L10N; import javax.ejb.TransactionAttributeType; import java.lang.reflect.Method; /** * Enhancing a method objects. */ public class TransactionEnhancer implements MethodEnhancer { private static final L10N L = new L10N(TransactionEnhancer.class); private Class _annotationType; /** * Sets the annotation type. */ public void setAnnotation(Class type) throws ConfigException { _annotationType = type; try { Method method = type.getMethod("value"); if (method != null && method.getReturnType().equals(TransactionAttributeType.class)) return; } catch (Throwable e) { } throw new ConfigException(L.l("'{0}' is an illegal annotation type for TransactionEnhancer. The annotation must have a value() method returning a TransactionAttributeType.", type.getName())); } /** * Enhances the method. * * @param genClass the generated class * @param jMethod the method to be enhanced * @param jAnn the annotation to be enhanced */ public void enhance(GenClass genClass, JMethod jMethod, JAnnotation jAnn) { TransactionAttributeType type; type = (TransactionAttributeType) jAnn.get("value"); BaseMethod genMethod = genClass.createMethod(jMethod); CallChain call = genMethod.getCall(); switch (type) { case MANDATORY: call = new MandatoryCallChain(call); break; case REQUIRED: call = new RequiredCallChain(call); break; - case REQUIRESNEW: + case REQUIRES_NEW: call = new RequiresNewCallChain(call); break; case NEVER: call = new NeverCallChain(call); break; case SUPPORTS: call = new SupportsCallChain(call); break; - case NOTSUPPORTED: + case NOT_SUPPORTED: call = new SuspendCallChain(call); break; default: break; } genMethod.setCall(call); } }
false
true
public void enhance(GenClass genClass, JMethod jMethod, JAnnotation jAnn) { TransactionAttributeType type; type = (TransactionAttributeType) jAnn.get("value"); BaseMethod genMethod = genClass.createMethod(jMethod); CallChain call = genMethod.getCall(); switch (type) { case MANDATORY: call = new MandatoryCallChain(call); break; case REQUIRED: call = new RequiredCallChain(call); break; case REQUIRESNEW: call = new RequiresNewCallChain(call); break; case NEVER: call = new NeverCallChain(call); break; case SUPPORTS: call = new SupportsCallChain(call); break; case NOTSUPPORTED: call = new SuspendCallChain(call); break; default: break; } genMethod.setCall(call); }
public void enhance(GenClass genClass, JMethod jMethod, JAnnotation jAnn) { TransactionAttributeType type; type = (TransactionAttributeType) jAnn.get("value"); BaseMethod genMethod = genClass.createMethod(jMethod); CallChain call = genMethod.getCall(); switch (type) { case MANDATORY: call = new MandatoryCallChain(call); break; case REQUIRED: call = new RequiredCallChain(call); break; case REQUIRES_NEW: call = new RequiresNewCallChain(call); break; case NEVER: call = new NeverCallChain(call); break; case SUPPORTS: call = new SupportsCallChain(call); break; case NOT_SUPPORTED: call = new SuspendCallChain(call); break; default: break; } genMethod.setCall(call); }
diff --git a/Java_CCN/test/ccn/data/content/CollectionObjectTestRepo.java b/Java_CCN/test/ccn/data/content/CollectionObjectTestRepo.java index 32f4622cc..4b53623b3 100644 --- a/Java_CCN/test/ccn/data/content/CollectionObjectTestRepo.java +++ b/Java_CCN/test/ccn/data/content/CollectionObjectTestRepo.java @@ -1,100 +1,100 @@ /** * */ package test.ccn.data.content; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.Random; import javax.xml.stream.XMLStreamException; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.parc.ccn.data.ContentName; import com.parc.ccn.data.content.Link; import com.parc.ccn.data.content.Collection.CollectionObject; import com.parc.ccn.data.util.CCNStringObject; import com.parc.ccn.library.CCNLibrary; /** * @author smetters * */ public class CollectionObjectTestRepo { static ContentName baseName; static CCNLibrary getLibrary; static CCNLibrary putLibrary; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { baseName = ContentName.fromNative("/libraryTest/CollectionObjectTestRepo-" + new Random().nextInt(10000)); putLibrary = CCNLibrary.open(); getLibrary = CCNLibrary.open(); } @Test public void testCollections() throws Exception { ContentName testPrefix = ContentName.fromNative(baseName, "testCollections"); ContentName nonCollectionName = ContentName.fromNative(testPrefix, "myNonCollection"); ContentName collectionName = ContentName.fromNative(testPrefix, "myCollection"); // Write something that isn't a collection CCNStringObject so = new CCNStringObject(nonCollectionName, "This is not a collection.", putLibrary); so.saveToRepository(); Link[] references = new Link[2]; references[0] = new Link(ContentName.fromNative(collectionName, "r1")); references[1] = new Link(ContentName.fromNative(collectionName, "r2")); CollectionObject collection = new CollectionObject(collectionName, references, putLibrary); collection.saveToRepository(); try { CollectionObject notAnObject = new CollectionObject(nonCollectionName, getLibrary); notAnObject.waitForData(); Assert.fail("Reading collection from non-collection succeeded."); } catch (IOException ioe) { } catch (XMLStreamException ex) { // this is what we actually expect } // test reading latest version CollectionObject readCollection = new CollectionObject(collectionName, getLibrary); readCollection.waitForData(); LinkedList<Link> checkReferences = collection.contents(); Assert.assertEquals(checkReferences.size(), 2); - Assert.assertEquals(references[0], checkReferences.get(0).targetName()); - Assert.assertEquals(references[1], checkReferences.get(1).targetName()); + Assert.assertEquals(references[0], checkReferences.get(0)); + Assert.assertEquals(references[1], checkReferences.get(1)); // test addToCollection ArrayList<Link> newReferences = new ArrayList<Link>(); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r3"))); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r4"))); collection.contents().addAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(checkReferences.size(), 4); Assert.assertEquals(newReferences.get(0), checkReferences.get(2)); Assert.assertEquals(newReferences.get(1), checkReferences.get(3)); collection.contents().removeAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(collection.contents(), readCollection.contents()); } }
true
true
public void testCollections() throws Exception { ContentName testPrefix = ContentName.fromNative(baseName, "testCollections"); ContentName nonCollectionName = ContentName.fromNative(testPrefix, "myNonCollection"); ContentName collectionName = ContentName.fromNative(testPrefix, "myCollection"); // Write something that isn't a collection CCNStringObject so = new CCNStringObject(nonCollectionName, "This is not a collection.", putLibrary); so.saveToRepository(); Link[] references = new Link[2]; references[0] = new Link(ContentName.fromNative(collectionName, "r1")); references[1] = new Link(ContentName.fromNative(collectionName, "r2")); CollectionObject collection = new CollectionObject(collectionName, references, putLibrary); collection.saveToRepository(); try { CollectionObject notAnObject = new CollectionObject(nonCollectionName, getLibrary); notAnObject.waitForData(); Assert.fail("Reading collection from non-collection succeeded."); } catch (IOException ioe) { } catch (XMLStreamException ex) { // this is what we actually expect } // test reading latest version CollectionObject readCollection = new CollectionObject(collectionName, getLibrary); readCollection.waitForData(); LinkedList<Link> checkReferences = collection.contents(); Assert.assertEquals(checkReferences.size(), 2); Assert.assertEquals(references[0], checkReferences.get(0).targetName()); Assert.assertEquals(references[1], checkReferences.get(1).targetName()); // test addToCollection ArrayList<Link> newReferences = new ArrayList<Link>(); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r3"))); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r4"))); collection.contents().addAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(checkReferences.size(), 4); Assert.assertEquals(newReferences.get(0), checkReferences.get(2)); Assert.assertEquals(newReferences.get(1), checkReferences.get(3)); collection.contents().removeAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(collection.contents(), readCollection.contents()); }
public void testCollections() throws Exception { ContentName testPrefix = ContentName.fromNative(baseName, "testCollections"); ContentName nonCollectionName = ContentName.fromNative(testPrefix, "myNonCollection"); ContentName collectionName = ContentName.fromNative(testPrefix, "myCollection"); // Write something that isn't a collection CCNStringObject so = new CCNStringObject(nonCollectionName, "This is not a collection.", putLibrary); so.saveToRepository(); Link[] references = new Link[2]; references[0] = new Link(ContentName.fromNative(collectionName, "r1")); references[1] = new Link(ContentName.fromNative(collectionName, "r2")); CollectionObject collection = new CollectionObject(collectionName, references, putLibrary); collection.saveToRepository(); try { CollectionObject notAnObject = new CollectionObject(nonCollectionName, getLibrary); notAnObject.waitForData(); Assert.fail("Reading collection from non-collection succeeded."); } catch (IOException ioe) { } catch (XMLStreamException ex) { // this is what we actually expect } // test reading latest version CollectionObject readCollection = new CollectionObject(collectionName, getLibrary); readCollection.waitForData(); LinkedList<Link> checkReferences = collection.contents(); Assert.assertEquals(checkReferences.size(), 2); Assert.assertEquals(references[0], checkReferences.get(0)); Assert.assertEquals(references[1], checkReferences.get(1)); // test addToCollection ArrayList<Link> newReferences = new ArrayList<Link>(); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r3"))); newReferences.add(new Link(ContentName.fromNative("/libraryTest/r4"))); collection.contents().addAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(checkReferences.size(), 4); Assert.assertEquals(newReferences.get(0), checkReferences.get(2)); Assert.assertEquals(newReferences.get(1), checkReferences.get(3)); collection.contents().removeAll(newReferences); collection.save(); readCollection.update(5000); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); checkReferences = collection.contents(); Assert.assertEquals(collection.getCurrentVersion(), readCollection.getCurrentVersion()); Assert.assertEquals(collection.contents(), readCollection.contents()); }
diff --git a/plugins/ui/com.vectorsf.jvoice.ui.navigator/src/com/vectorsf/jvoice/ui/navigator/handler/AddBeanScopeHandler.java b/plugins/ui/com.vectorsf.jvoice.ui.navigator/src/com/vectorsf/jvoice/ui/navigator/handler/AddBeanScopeHandler.java index 7eb32f7c..06293b49 100644 --- a/plugins/ui/com.vectorsf.jvoice.ui.navigator/src/com/vectorsf/jvoice/ui/navigator/handler/AddBeanScopeHandler.java +++ b/plugins/ui/com.vectorsf.jvoice.ui.navigator/src/com/vectorsf/jvoice/ui/navigator/handler/AddBeanScopeHandler.java @@ -1,139 +1,139 @@ package com.vectorsf.jvoice.ui.navigator.handler; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.URI; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.handlers.HandlerUtil; import com.vectorsf.jvoice.model.operations.Flow; import com.vectorsf.jvoice.model.operations.provider.flow.ScopeItemProvider; public class AddBeanScopeHandler extends AbstractHandler implements IHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { Flow flow = getFlow(event); if (flow == null) { return null; } IProject project = getProject(flow); IJavaProject jProject = JavaCore.create(project); Shell shell = HandlerUtil.getActiveShell(event); StandardJavaElementContentProvider contentProvider = new StandardJavaElementContentProvider( false); ILabelProvider labelProvider = new JavaElementLabelProvider( JavaElementLabelProvider.SHOW_BASICS); ComponentsSelectionDialog dialog = new ComponentsSelectionDialog(shell, labelProvider, contentProvider); dialog.setInput(jProject); dialog.addFilter(new ComponentFilter()); dialog.open(); return null; } private IProject getProject(Flow flow) { URI uri = flow.eResource().getURI(); IPath path = new Path(uri.toPlatformString(true)); return ResourcesPlugin.getWorkspace().getRoot().getFile(path) .getProject(); } private Flow getFlow(ExecutionEvent event) { ISelection currentSelection = HandlerUtil.getCurrentSelection(event); if (currentSelection instanceof IStructuredSelection) { Object firstElement = ((IStructuredSelection) currentSelection) .getFirstElement(); if (firstElement instanceof ScopeItemProvider) { return ((ScopeItemProvider) firstElement).getFlow(); } } return null; } public class ComponentFilter extends ViewerFilter { @Override public boolean select(Viewer viewer, Object parentElement, Object element) { - if (element instanceof ICompilationUnit) { + if (element instanceof ITypeRoot) { ITypeRoot unit = (ITypeRoot) element; IType type = unit.findPrimaryType(); if(type == null) return false; IAnnotation[] annotations; try { annotations = type.getAnnotations(); for (IAnnotation annotation : annotations) { String elementName = annotation.getElementName(); if (elementName .equals("org.springframework.stereotype.Component")) { return true; } else if (elementName.equals("Component") && element instanceof ICompilationUnit){ for (IImportDeclaration _import : ((ICompilationUnit) unit).getImports()) { String importedType = _import.getElementName(); if (importedType .equals("org.springframework.stereotype.Component")) { return true; } if (importedType .equals("org.springframework.stereotype.*")) { return true; } } } } } catch (JavaModelException e) { return false; } return false; } if (element instanceof IPackageFragment) { try { return ((IPackageFragment) element).hasChildren(); } catch (JavaModelException e) { return false; } } if (element instanceof IPackageFragmentRoot) { return !((IPackageFragmentRoot) element).isArchive(); } return false; } } }
true
true
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof ICompilationUnit) { ITypeRoot unit = (ITypeRoot) element; IType type = unit.findPrimaryType(); if(type == null) return false; IAnnotation[] annotations; try { annotations = type.getAnnotations(); for (IAnnotation annotation : annotations) { String elementName = annotation.getElementName(); if (elementName .equals("org.springframework.stereotype.Component")) { return true; } else if (elementName.equals("Component") && element instanceof ICompilationUnit){ for (IImportDeclaration _import : ((ICompilationUnit) unit).getImports()) { String importedType = _import.getElementName(); if (importedType .equals("org.springframework.stereotype.Component")) { return true; } if (importedType .equals("org.springframework.stereotype.*")) { return true; } } } } } catch (JavaModelException e) { return false; } return false; } if (element instanceof IPackageFragment) { try { return ((IPackageFragment) element).hasChildren(); } catch (JavaModelException e) { return false; } } if (element instanceof IPackageFragmentRoot) { return !((IPackageFragmentRoot) element).isArchive(); } return false; }
public boolean select(Viewer viewer, Object parentElement, Object element) { if (element instanceof ITypeRoot) { ITypeRoot unit = (ITypeRoot) element; IType type = unit.findPrimaryType(); if(type == null) return false; IAnnotation[] annotations; try { annotations = type.getAnnotations(); for (IAnnotation annotation : annotations) { String elementName = annotation.getElementName(); if (elementName .equals("org.springframework.stereotype.Component")) { return true; } else if (elementName.equals("Component") && element instanceof ICompilationUnit){ for (IImportDeclaration _import : ((ICompilationUnit) unit).getImports()) { String importedType = _import.getElementName(); if (importedType .equals("org.springframework.stereotype.Component")) { return true; } if (importedType .equals("org.springframework.stereotype.*")) { return true; } } } } } catch (JavaModelException e) { return false; } return false; } if (element instanceof IPackageFragment) { try { return ((IPackageFragment) element).hasChildren(); } catch (JavaModelException e) { return false; } } if (element instanceof IPackageFragmentRoot) { return !((IPackageFragmentRoot) element).isArchive(); } return false; }
diff --git a/src/main/java/com/greatmancode/craftconomy3/commands/setup/SetupDatabaseCommand.java b/src/main/java/com/greatmancode/craftconomy3/commands/setup/SetupDatabaseCommand.java index a475707..1b30e41 100644 --- a/src/main/java/com/greatmancode/craftconomy3/commands/setup/SetupDatabaseCommand.java +++ b/src/main/java/com/greatmancode/craftconomy3/commands/setup/SetupDatabaseCommand.java @@ -1,133 +1,141 @@ /* * This file is part of Craftconomy3. * * Copyright (c) 2011-2012, Greatman <http://github.com/greatman/> * * Craftconomy3 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Craftconomy3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Craftconomy3. If not, see <http://www.gnu.org/licenses/>. */ package com.greatmancode.craftconomy3.commands.setup; import com.alta189.simplesave.exceptions.ConnectionException; import com.alta189.simplesave.exceptions.TableRegistrationException; import com.greatmancode.craftconomy3.Common; import com.greatmancode.craftconomy3.SetupWizard; import com.greatmancode.craftconomy3.commands.CraftconomyCommand; public class SetupDatabaseCommand implements CraftconomyCommand { private static final String ERROR_MESSAGE = "{{DARK_RED}}A error occured. The error is: {{WHITE}}%s"; private static final String CONFIG_NODE = "System.Database.Type"; @Override public void execute(String sender, String[] args) { if (SetupWizard.getState() == SetupWizard.DATABASE_SETUP) { if (args.length == 0) { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Database setup step. Please select the database backend by using those following commands. (Use SQLite if unsure)"); Common.getInstance().getServerCaller().sendMessage(sender, "/ccsetup database type <sqlite/mysql/h2>"); } else if (args.length == 2) { if (args[0].equalsIgnoreCase("type")) { if (args[1].equalsIgnoreCase("sqlite")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "sqlite"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } else if (args[1].equalsIgnoreCase("mysql")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "mysql"); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database address <Your host> {{DARK_GREEN}}to set your MySQL address"); } else if (args[1].equalsIgnoreCase("h2")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "h2"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } } else if (args[0].equals("address")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Address", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database port <Your port> {{DARK_GREEN}}to set your MySQL port (Usually 3306)"); } else if (args[0].equals("port")) { - Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Port", args[1]); - Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database username <Username> {{DARK_GREEN}}to set your MySQL username"); + int port = 3306; + try + { + port = Integer.parseInt(args[1]); + Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Port", port); + Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database username <Username> {{DARK_GREEN}}to set your MySQL username"); + } + catch(NumberFormatException e) { + Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Invalid port!"); + } } else if (args[0].equals("username")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Username", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database password <Password> {{DARK_GREEN}}to set your MySQL password (enter \"\" for none)"); } else if (args[0].equals("password")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Password", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Last step for database! Please type {{WHITE}}/ccsetup database db <Database Name> {{DARK_GREEN}}to set your MySQL database."); } else if (args[0].equals("db")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Db", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Done! Please type {{WHITE}}/ccsetup database test {{DARK_GREEN}}to test your settings!"); } } else if (args.length == 1 && args[0].equals("test")) { if (Common.getInstance().getConfigurationManager().getConfig().getString(CONFIG_NODE).equals("mysql")) { try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Must be in MySQL mode for this command."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong usage."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong setup status for this cmd. If you didin't start the setup yet, use /ccsetup"); } } @Override public boolean permission(String sender) { return Common.getInstance().getServerCaller().checkPermission(sender, "craftconomy.setup"); } @Override public String help() { return "/ccsetup - Start the setup"; } @Override public int maxArgs() { return 2; } @Override public int minArgs() { return 0; } @Override public boolean playerOnly() { return false; } }
true
true
public void execute(String sender, String[] args) { if (SetupWizard.getState() == SetupWizard.DATABASE_SETUP) { if (args.length == 0) { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Database setup step. Please select the database backend by using those following commands. (Use SQLite if unsure)"); Common.getInstance().getServerCaller().sendMessage(sender, "/ccsetup database type <sqlite/mysql/h2>"); } else if (args.length == 2) { if (args[0].equalsIgnoreCase("type")) { if (args[1].equalsIgnoreCase("sqlite")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "sqlite"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } else if (args[1].equalsIgnoreCase("mysql")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "mysql"); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database address <Your host> {{DARK_GREEN}}to set your MySQL address"); } else if (args[1].equalsIgnoreCase("h2")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "h2"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } } else if (args[0].equals("address")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Address", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database port <Your port> {{DARK_GREEN}}to set your MySQL port (Usually 3306)"); } else if (args[0].equals("port")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Port", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database username <Username> {{DARK_GREEN}}to set your MySQL username"); } else if (args[0].equals("username")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Username", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database password <Password> {{DARK_GREEN}}to set your MySQL password (enter \"\" for none)"); } else if (args[0].equals("password")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Password", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Last step for database! Please type {{WHITE}}/ccsetup database db <Database Name> {{DARK_GREEN}}to set your MySQL database."); } else if (args[0].equals("db")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Db", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Done! Please type {{WHITE}}/ccsetup database test {{DARK_GREEN}}to test your settings!"); } } else if (args.length == 1 && args[0].equals("test")) { if (Common.getInstance().getConfigurationManager().getConfig().getString(CONFIG_NODE).equals("mysql")) { try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Must be in MySQL mode for this command."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong usage."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong setup status for this cmd. If you didin't start the setup yet, use /ccsetup"); } }
public void execute(String sender, String[] args) { if (SetupWizard.getState() == SetupWizard.DATABASE_SETUP) { if (args.length == 0) { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Database setup step. Please select the database backend by using those following commands. (Use SQLite if unsure)"); Common.getInstance().getServerCaller().sendMessage(sender, "/ccsetup database type <sqlite/mysql/h2>"); } else if (args.length == 2) { if (args[0].equalsIgnoreCase("type")) { if (args[1].equalsIgnoreCase("sqlite")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "sqlite"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } else if (args[1].equalsIgnoreCase("mysql")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "mysql"); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database address <Your host> {{DARK_GREEN}}to set your MySQL address"); } else if (args[1].equalsIgnoreCase("h2")) { Common.getInstance().getConfigurationManager().getConfig().setValue(CONFIG_NODE, "h2"); try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); } } } else if (args[0].equals("address")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Address", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Alright! Please type {{WHITE}}/ccsetup database port <Your port> {{DARK_GREEN}}to set your MySQL port (Usually 3306)"); } else if (args[0].equals("port")) { int port = 3306; try { port = Integer.parseInt(args[1]); Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Port", port); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database username <Username> {{DARK_GREEN}}to set your MySQL username"); } catch(NumberFormatException e) { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Invalid port!"); } } else if (args[0].equals("username")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Username", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Saved! Please type {{WHITE}}/ccsetup database password <Password> {{DARK_GREEN}}to set your MySQL password (enter \"\" for none)"); } else if (args[0].equals("password")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Password", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Last step for database! Please type {{WHITE}}/ccsetup database db <Database Name> {{DARK_GREEN}}to set your MySQL database."); } else if (args[0].equals("db")) { Common.getInstance().getConfigurationManager().getConfig().setValue("System.Database.Db", args[1]); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Done! Please type {{WHITE}}/ccsetup database test {{DARK_GREEN}}to test your settings!"); } } else if (args.length == 1 && args[0].equals("test")) { if (Common.getInstance().getConfigurationManager().getConfig().getString(CONFIG_NODE).equals("mysql")) { try { Common.getInstance().initialiseDatabase(); SetupWizard.setState(SetupWizard.MULTIWORLD_SETUP); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Awesome! You can type {{WHITE}}/ccsetup multiworld {{DARK_GREEN}}to continue the setup!"); } catch(TableRegistrationException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } catch(ConnectionException e) { Common.getInstance().getServerCaller().sendMessage(sender, String.format(ERROR_MESSAGE,e.getMessage())); Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_GREEN}}Be sure that you entered valid information! Commands are: {{WHITE}}/ccsetup database <address/port/username/password/db> <Value>"); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Must be in MySQL mode for this command."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong usage."); } } else { Common.getInstance().getServerCaller().sendMessage(sender, "{{DARK_RED}}Wrong setup status for this cmd. If you didin't start the setup yet, use /ccsetup"); } }
diff --git a/me/Guga/Guga_SERVER_MOD/GugaVirtualCurrency.java b/me/Guga/Guga_SERVER_MOD/GugaVirtualCurrency.java index 262578c..05e1bbe 100644 --- a/me/Guga/Guga_SERVER_MOD/GugaVirtualCurrency.java +++ b/me/Guga/Guga_SERVER_MOD/GugaVirtualCurrency.java @@ -1,304 +1,304 @@ package me.Guga.Guga_SERVER_MOD; import java.util.Date; import me.Guga.Guga_SERVER_MOD.Handlers.ChatHandler; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class GugaVirtualCurrency { GugaVirtualCurrency(Guga_SERVER_MOD gugaSM, String pName) { playerName = pName; plugin = gugaSM; } public GugaVirtualCurrency(Guga_SERVER_MOD gugaSM, String pName, int curr, Date exprDate) { playerName = pName; currency = curr; plugin = gugaSM; vipExpiration = exprDate; UpdateVipStatus(); } public int GetCurrency() { return currency; } public boolean IsVip() { return vipActive; } public long GetExpirationDate() { return vipExpiration.getTime(); } public void SetExpirationDate(Date date) { vipExpiration = date; UpdateVipStatus(); UpdateDisplayName(); } public void AddCurrency(int curr) { currency +=curr; } public void RemoveCurrency(int curr) { currency -= curr; } public void SetCurrency(int curr) { currency = curr; } public enum VipItems { SAND(12), COBBLESTONE(4), WOODEN_PLANKS(5), STONE(1), DIRT(3), SANDSTONE(24); private VipItems(int id) { this.id = id; } public int GetID() { return this.id; } public static boolean IsVipItem(int itemID) { for (VipItems i : VipItems.values()) { if (i.GetID() == itemID) return true; } return false; } private int id; } public Location GetLastTeleportLoc() { return lastTeleportLoc; } public void SetLastTeleportLoc(Location loc) { lastTeleportLoc = loc; } public String GetPlayerName() { return playerName; } public void UpdateDisplayName() { Player p = plugin.getServer().getPlayer(playerName); if (p==null) return; if (IsVip()) { ChatHandler.SetPrefix(p, "vip"); p.setPlayerListName(ChatColor.GOLD+p.getName()); } else { p.setDisplayName(p.getName()); p.setPlayerListName(p.getName()); } } public void ToggleFly(boolean fly) { Player p = plugin.getServer().getPlayer(playerName); p.setAllowFlight(fly); p.setFlying(fly); } public void BuyItem(String itemName, int amount) { Player p = plugin.getServer().getPlayer(playerName); if (amount < 0) { p.sendMessage("Pocet musi byt vyssi nez 0!"); return; } Prices item = null; for (Prices i : Prices.values()) { if (i.toString().equalsIgnoreCase(itemName)) { item = i; break; } } if (item == null) { p.sendMessage("Item nenalezen"); return; } int totalPrice = GetTotalPrice(item, amount); if (totalPrice > 0) { if (CanBuyItem(totalPrice)) { amount *= item.GetAmmount(); Purchase(item, totalPrice, amount); p.sendMessage("Koupil jste " + amount + "x " + item.toString() + " za " + totalPrice + " kreditu."); p.sendMessage("Zbyva kreditu: " + currency); } else { p.sendMessage("Nemate dostatecne mnozstvi kreditu!"); } } } private void UpdateVipStatus() { if (vipExpiration.after(new Date())) vipActive = true; else vipActive = false; } private boolean CanBuyItem(int price) { if (currency >= price) { return true; } return false; } private int GetTotalPrice(Prices item, int amount) { return item.GetItemPrice() * amount; } private void Purchase(Prices item, int price, int amount) { Player p = plugin.getServer().getPlayer(playerName); if (p == null) return; ItemStack order = null; if (item.toString().contains("EGG_")) { if (item == Prices.EGG_CAVE_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 59); else if (item == Prices.EGG_CHICKEN) order = new ItemStack(item.GetItemID(), amount, (short) 93); else if (item == Prices.EGG_COW) order = new ItemStack(item.GetItemID(), amount, (short) 92); else if (item == Prices.EGG_ENDERMAN) order = new ItemStack(item.GetItemID(), amount, (short) 58); else if (item == Prices.EGG_MAGMA_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 62); else if (item == Prices.EGG_MOOSHROOM) order = new ItemStack(item.GetItemID(), amount, (short) 96); else if (item == Prices.EGG_PIG) order = new ItemStack(item.GetItemID(), amount, (short) 90); else if (item == Prices.EGG_PIGMAN) order = new ItemStack(item.GetItemID(), amount, (short) 57); else if (item == Prices.EGG_SHEEP) order = new ItemStack(item.GetItemID(), amount, (short) 91); /*else if (item == Prices.EGG_SILVERFISH) order = new ItemStack(item.GetItemID(), amount, (short) 60);*/ else if (item == Prices.EGG_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 51); else if (item == Prices.EGG_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 55); else if (item == Prices.EGG_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 52); else if (item == Prices.EGG_VILLAGER) order = new ItemStack(item.GetItemID(), amount, (short) 120); else if (item == Prices.EGG_WOLF) order = new ItemStack(item.GetItemID(), amount, (short) 95); else if (item == Prices.EGG_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 54); else if (item==Prices.EGG_OCELOT) order = new ItemStack(item.GetItemID(), amount, (short) 98); else if (item==Prices.EGG_WITCH) - order = new ItemStack(item.GetItemID(), amount, (short) 64); + order = new ItemStack(item.GetItemID(), amount, (short) 66); else if (item==Prices.EGG_BAT) - order = new ItemStack(item.GetItemID(), amount, (short) 63); + order = new ItemStack(item.GetItemID(), amount, (short) 65); } else if(item.toString().contains("WOOL_")) { if (item == Prices.WOOL_ORANGE) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.WOOL_MAGENTA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.WOOL_LIGHTBLUE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.WOOL_YELLOW) order = new ItemStack(item.GetItemID(), amount, (short) 4); else if (item==Prices.WOOL_LIME) order = new ItemStack(item.GetItemID(), amount, (short) 5); else if (item==Prices.WOOL_PINK) order = new ItemStack(item.GetItemID(), amount, (short) 6); else if (item==Prices.WOOL_GRAY) order = new ItemStack(item.GetItemID(), amount, (short) 7); else if (item==Prices.WOOL_LIGHTGRAY) order = new ItemStack(item.GetItemID(), amount, (short) 8); else if (item==Prices.WOOL_CYAN) order = new ItemStack(item.GetItemID(), amount, (short) 9); else if (item==Prices.WOOL_PURPLE) order = new ItemStack(item.GetItemID(), amount, (short) 10); else if (item==Prices.WOOL_BLUE) order = new ItemStack(item.GetItemID(), amount, (short) 11); else if (item==Prices.WOOL_BROWN) order = new ItemStack(item.GetItemID(), amount, (short) 12); else if (item==Prices.WOOL_GREEN) order = new ItemStack(item.GetItemID(), amount, (short) 13); else if (item==Prices.WOOL_RED) order = new ItemStack(item.GetItemID(), amount, (short) 14); else if (item==Prices.WOOL_BLACK) order = new ItemStack(item.GetItemID(), amount, (short) 15); } else if (item == Prices.COCOA) { order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if(item.toString().contains("SAPLING_")) { if (item == Prices.SAPLING_DUB) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.SAPLING_BRIZA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.SAPLING_SMRK) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.SAPLING_JUNGLE) order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if (item == Prices.KRUMPAC_EFFICIENCY_V) { order = new ItemStack(item.GetItemID(), amount); order.addEnchantment(Enchantment.DIG_SPEED, 5); order.addEnchantment(Enchantment.DURABILITY, 3); } else if(item.toString().contains("HEAD_")) { if (item == Prices.HEAD_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.HEAD_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.HEAD_STEVE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.HEAD_CREEPER) order = new ItemStack(item.GetItemID(), amount, (short) 4); } else order = new ItemStack(item.GetItemID(), amount); if (item != null) plugin.logger.LogShopTransaction(item, amount, this.playerName); PlayerInventory pInventory = p.getInventory(); pInventory.addItem(order); currency -= price; plugin.SaveCurrency(); } public Guga_SERVER_MOD GetPlugin() { return plugin; } private String playerName; private int currency; private Location lastTeleportLoc; private boolean vipActive; private Date vipExpiration; private Guga_SERVER_MOD plugin; }
false
true
private void Purchase(Prices item, int price, int amount) { Player p = plugin.getServer().getPlayer(playerName); if (p == null) return; ItemStack order = null; if (item.toString().contains("EGG_")) { if (item == Prices.EGG_CAVE_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 59); else if (item == Prices.EGG_CHICKEN) order = new ItemStack(item.GetItemID(), amount, (short) 93); else if (item == Prices.EGG_COW) order = new ItemStack(item.GetItemID(), amount, (short) 92); else if (item == Prices.EGG_ENDERMAN) order = new ItemStack(item.GetItemID(), amount, (short) 58); else if (item == Prices.EGG_MAGMA_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 62); else if (item == Prices.EGG_MOOSHROOM) order = new ItemStack(item.GetItemID(), amount, (short) 96); else if (item == Prices.EGG_PIG) order = new ItemStack(item.GetItemID(), amount, (short) 90); else if (item == Prices.EGG_PIGMAN) order = new ItemStack(item.GetItemID(), amount, (short) 57); else if (item == Prices.EGG_SHEEP) order = new ItemStack(item.GetItemID(), amount, (short) 91); /*else if (item == Prices.EGG_SILVERFISH) order = new ItemStack(item.GetItemID(), amount, (short) 60);*/ else if (item == Prices.EGG_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 51); else if (item == Prices.EGG_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 55); else if (item == Prices.EGG_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 52); else if (item == Prices.EGG_VILLAGER) order = new ItemStack(item.GetItemID(), amount, (short) 120); else if (item == Prices.EGG_WOLF) order = new ItemStack(item.GetItemID(), amount, (short) 95); else if (item == Prices.EGG_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 54); else if (item==Prices.EGG_OCELOT) order = new ItemStack(item.GetItemID(), amount, (short) 98); else if (item==Prices.EGG_WITCH) order = new ItemStack(item.GetItemID(), amount, (short) 64); else if (item==Prices.EGG_BAT) order = new ItemStack(item.GetItemID(), amount, (short) 63); } else if(item.toString().contains("WOOL_")) { if (item == Prices.WOOL_ORANGE) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.WOOL_MAGENTA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.WOOL_LIGHTBLUE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.WOOL_YELLOW) order = new ItemStack(item.GetItemID(), amount, (short) 4); else if (item==Prices.WOOL_LIME) order = new ItemStack(item.GetItemID(), amount, (short) 5); else if (item==Prices.WOOL_PINK) order = new ItemStack(item.GetItemID(), amount, (short) 6); else if (item==Prices.WOOL_GRAY) order = new ItemStack(item.GetItemID(), amount, (short) 7); else if (item==Prices.WOOL_LIGHTGRAY) order = new ItemStack(item.GetItemID(), amount, (short) 8); else if (item==Prices.WOOL_CYAN) order = new ItemStack(item.GetItemID(), amount, (short) 9); else if (item==Prices.WOOL_PURPLE) order = new ItemStack(item.GetItemID(), amount, (short) 10); else if (item==Prices.WOOL_BLUE) order = new ItemStack(item.GetItemID(), amount, (short) 11); else if (item==Prices.WOOL_BROWN) order = new ItemStack(item.GetItemID(), amount, (short) 12); else if (item==Prices.WOOL_GREEN) order = new ItemStack(item.GetItemID(), amount, (short) 13); else if (item==Prices.WOOL_RED) order = new ItemStack(item.GetItemID(), amount, (short) 14); else if (item==Prices.WOOL_BLACK) order = new ItemStack(item.GetItemID(), amount, (short) 15); } else if (item == Prices.COCOA) { order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if(item.toString().contains("SAPLING_")) { if (item == Prices.SAPLING_DUB) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.SAPLING_BRIZA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.SAPLING_SMRK) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.SAPLING_JUNGLE) order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if (item == Prices.KRUMPAC_EFFICIENCY_V) { order = new ItemStack(item.GetItemID(), amount); order.addEnchantment(Enchantment.DIG_SPEED, 5); order.addEnchantment(Enchantment.DURABILITY, 3); } else if(item.toString().contains("HEAD_")) { if (item == Prices.HEAD_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.HEAD_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.HEAD_STEVE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.HEAD_CREEPER) order = new ItemStack(item.GetItemID(), amount, (short) 4); } else order = new ItemStack(item.GetItemID(), amount); if (item != null) plugin.logger.LogShopTransaction(item, amount, this.playerName); PlayerInventory pInventory = p.getInventory(); pInventory.addItem(order); currency -= price; plugin.SaveCurrency(); }
private void Purchase(Prices item, int price, int amount) { Player p = plugin.getServer().getPlayer(playerName); if (p == null) return; ItemStack order = null; if (item.toString().contains("EGG_")) { if (item == Prices.EGG_CAVE_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 59); else if (item == Prices.EGG_CHICKEN) order = new ItemStack(item.GetItemID(), amount, (short) 93); else if (item == Prices.EGG_COW) order = new ItemStack(item.GetItemID(), amount, (short) 92); else if (item == Prices.EGG_ENDERMAN) order = new ItemStack(item.GetItemID(), amount, (short) 58); else if (item == Prices.EGG_MAGMA_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 62); else if (item == Prices.EGG_MOOSHROOM) order = new ItemStack(item.GetItemID(), amount, (short) 96); else if (item == Prices.EGG_PIG) order = new ItemStack(item.GetItemID(), amount, (short) 90); else if (item == Prices.EGG_PIGMAN) order = new ItemStack(item.GetItemID(), amount, (short) 57); else if (item == Prices.EGG_SHEEP) order = new ItemStack(item.GetItemID(), amount, (short) 91); /*else if (item == Prices.EGG_SILVERFISH) order = new ItemStack(item.GetItemID(), amount, (short) 60);*/ else if (item == Prices.EGG_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 51); else if (item == Prices.EGG_SLIME) order = new ItemStack(item.GetItemID(), amount, (short) 55); else if (item == Prices.EGG_SPIDER) order = new ItemStack(item.GetItemID(), amount, (short) 52); else if (item == Prices.EGG_VILLAGER) order = new ItemStack(item.GetItemID(), amount, (short) 120); else if (item == Prices.EGG_WOLF) order = new ItemStack(item.GetItemID(), amount, (short) 95); else if (item == Prices.EGG_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 54); else if (item==Prices.EGG_OCELOT) order = new ItemStack(item.GetItemID(), amount, (short) 98); else if (item==Prices.EGG_WITCH) order = new ItemStack(item.GetItemID(), amount, (short) 66); else if (item==Prices.EGG_BAT) order = new ItemStack(item.GetItemID(), amount, (short) 65); } else if(item.toString().contains("WOOL_")) { if (item == Prices.WOOL_ORANGE) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.WOOL_MAGENTA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.WOOL_LIGHTBLUE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.WOOL_YELLOW) order = new ItemStack(item.GetItemID(), amount, (short) 4); else if (item==Prices.WOOL_LIME) order = new ItemStack(item.GetItemID(), amount, (short) 5); else if (item==Prices.WOOL_PINK) order = new ItemStack(item.GetItemID(), amount, (short) 6); else if (item==Prices.WOOL_GRAY) order = new ItemStack(item.GetItemID(), amount, (short) 7); else if (item==Prices.WOOL_LIGHTGRAY) order = new ItemStack(item.GetItemID(), amount, (short) 8); else if (item==Prices.WOOL_CYAN) order = new ItemStack(item.GetItemID(), amount, (short) 9); else if (item==Prices.WOOL_PURPLE) order = new ItemStack(item.GetItemID(), amount, (short) 10); else if (item==Prices.WOOL_BLUE) order = new ItemStack(item.GetItemID(), amount, (short) 11); else if (item==Prices.WOOL_BROWN) order = new ItemStack(item.GetItemID(), amount, (short) 12); else if (item==Prices.WOOL_GREEN) order = new ItemStack(item.GetItemID(), amount, (short) 13); else if (item==Prices.WOOL_RED) order = new ItemStack(item.GetItemID(), amount, (short) 14); else if (item==Prices.WOOL_BLACK) order = new ItemStack(item.GetItemID(), amount, (short) 15); } else if (item == Prices.COCOA) { order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if(item.toString().contains("SAPLING_")) { if (item == Prices.SAPLING_DUB) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.SAPLING_BRIZA) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.SAPLING_SMRK) order = new ItemStack(item.GetItemID(), amount, (short) 1); else if (item==Prices.SAPLING_JUNGLE) order = new ItemStack(item.GetItemID(), amount, (short) 3); } else if (item == Prices.KRUMPAC_EFFICIENCY_V) { order = new ItemStack(item.GetItemID(), amount); order.addEnchantment(Enchantment.DIG_SPEED, 5); order.addEnchantment(Enchantment.DURABILITY, 3); } else if(item.toString().contains("HEAD_")) { if (item == Prices.HEAD_SKELETON) order = new ItemStack(item.GetItemID(), amount, (short) 0); else if (item==Prices.HEAD_ZOMBIE) order = new ItemStack(item.GetItemID(), amount, (short) 2); else if (item==Prices.HEAD_STEVE) order = new ItemStack(item.GetItemID(), amount, (short) 3); else if (item==Prices.HEAD_CREEPER) order = new ItemStack(item.GetItemID(), amount, (short) 4); } else order = new ItemStack(item.GetItemID(), amount); if (item != null) plugin.logger.LogShopTransaction(item, amount, this.playerName); PlayerInventory pInventory = p.getInventory(); pInventory.addItem(order); currency -= price; plugin.SaveCurrency(); }
diff --git a/src/client/FibClient.java b/src/client/FibClient.java index d9d0bfe..87d382c 100644 --- a/src/client/FibClient.java +++ b/src/client/FibClient.java @@ -1,50 +1,50 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import api.RMIUtils; import api.Result; import api.SpaceAPI; import api.Task; import java.rmi.RemoteException; import java.util.logging.Level; import java.util.logging.Logger; import tasks.FibTask; /** * * @author ninj0x */ public class FibClient { private static int N = 16; public static void main(String[] args) { SpaceAPI space = RMIUtils.connectToSpace(args[0]); int fib; long startTime, endTime; startTime = System.currentTimeMillis(); fib = run(space); endTime = System.currentTimeMillis() - startTime; System.out.println("Tasks Done! f(" + N + ") = " + fib); System.out.println("Total Time: " + endTime); } private static int run(SpaceAPI space) { try { // Send out the tasks FibTask task = new FibTask(N); space.put(task); // Get the results Result result = space.take(); - return (int)((Task)result.getTaskReturnValue()).getValue(); + return (Integer)((Task)result.getTaskReturnValue()).getValue(); } catch (RemoteException ex) { Logger.getLogger(FibClient.class.getName()).log(Level.SEVERE, null, ex); } return 0; } }
true
true
private static int run(SpaceAPI space) { try { // Send out the tasks FibTask task = new FibTask(N); space.put(task); // Get the results Result result = space.take(); return (int)((Task)result.getTaskReturnValue()).getValue(); } catch (RemoteException ex) { Logger.getLogger(FibClient.class.getName()).log(Level.SEVERE, null, ex); } return 0; }
private static int run(SpaceAPI space) { try { // Send out the tasks FibTask task = new FibTask(N); space.put(task); // Get the results Result result = space.take(); return (Integer)((Task)result.getTaskReturnValue()).getValue(); } catch (RemoteException ex) { Logger.getLogger(FibClient.class.getName()).log(Level.SEVERE, null, ex); } return 0; }
diff --git a/subsonic-main/src/main/java/net/sourceforge/subsonic/dao/schema/Schema28.java b/subsonic-main/src/main/java/net/sourceforge/subsonic/dao/schema/Schema28.java index 2d31305a..c76fb035 100644 --- a/subsonic-main/src/main/java/net/sourceforge/subsonic/dao/schema/Schema28.java +++ b/subsonic-main/src/main/java/net/sourceforge/subsonic/dao/schema/Schema28.java @@ -1,87 +1,87 @@ package net.sourceforge.subsonic.dao.schema; import net.sourceforge.subsonic.*; import org.springframework.jdbc.core.*; /** * Used for creating and evolving the database schema. * This class implementes the database schema for Subsonic version 2.8. * * @author Sindre Mehus */ public class Schema28 extends Schema { private static final Logger LOG = Logger.getLogger(Schema28.class); public void execute(JdbcTemplate template) { if (template.queryForInt("select count(*) from version where version = 4") == 0) { Schema28.LOG.info("Updating database schema to version 4."); template.execute("insert into version values (4)"); } if (!tableExists(template, "user_settings")) { LOG.info("Database table 'user_settings' not found. Creating it."); template.execute("create table user_settings (" + "username varchar not null," + "locale varchar," + "theme_id varchar," + "final_version_notification boolean default true not null," + "beta_version_notification boolean default false not null," + "main_caption_cutoff int default 35 not null," + "main_track_number boolean default true not null," + "main_artist boolean default true not null," + "main_album boolean default false not null," + "main_genre boolean default false not null," + "main_year boolean default false not null," + "main_bit_rate boolean default false not null," + "main_duration boolean default true not null," + "main_format boolean default false not null," + "main_file_size boolean default false not null," + "playlist_caption_cutoff int default 35 not null," + "playlist_track_number boolean default false not null," + "playlist_artist boolean default true not null," + "playlist_album boolean default true not null," + "playlist_genre boolean default false not null," + "playlist_year boolean default true not null," + "playlist_bit_rate boolean default false not null," + "playlist_duration boolean default true not null," + "playlist_format boolean default true not null," + "playlist_file_size boolean default true not null," + "primary key (username)," + "foreign key (username) references user(username) on delete cascade)"); LOG.info("Database table 'user_settings' was created successfully."); } if (!tableExists(template, "transcoding")) { LOG.info("Database table 'transcoding' not found. Creating it."); template.execute("create table transcoding (" + "id identity," + "name varchar not null," + "source_format varchar not null," + "target_format varchar not null," + "step1 varchar not null," + "step2 varchar," + "step3 varchar," + "enabled boolean not null)"); template.execute("insert into transcoding values(null,'ogg > mp3','ogg','mp3','oggdec %s -o','lame - -',null,false)"); - template.execute("insert into transcoding values(null,'wma > mp3','wma','mp3','wmadec -w %s','lame - -',null,false)"); + template.execute("insert into transcoding values(null,'wma > mp3','wma','mp3','wmadec %s','lame -x - -',null,false)"); template.execute("insert into transcoding values(null,'flac > mp3','flac','mp3','flac -c -s -d %s','lame - -',null,false)"); - template.execute("insert into transcoding values(null,'ape > mp3','ape','mp3','macpipe.exe %s - -d','lame - -',null,false)"); + template.execute("insert into transcoding values(null,'ape > mp3','ape','mp3','mac %s - -d','lame - -',null,false)"); template.execute("insert into transcoding values(null,'m4a > mp3','m4a','mp3','faad -w %s','lame -x - -',null,false)"); template.execute("insert into transcoding values(null,'mpc > mp3','mpc','mp3','mppdec --wav --silent %s -','lame - -',null,false)"); template.execute("insert into transcoding values(null,'ofr > mp3','ofr','mp3','ofr --decode --silent %s --output -','lame - -',null,false)"); LOG.info("Database table 'transcoding' was created successfully."); } if (!tableExists(template, "player_transcoding")) { LOG.info("Database table 'player_transcoding' not found. Creating it."); template.execute("create table player_transcoding (" + "player_id int not null," + "transcoding_id int not null," + "primary key (player_id, transcoding_id)," + "foreign key (player_id) references player(id) on delete cascade," + "foreign key (transcoding_id) references transcoding(id) on delete cascade)"); LOG.info("Database table 'player_transcoding' was created successfully."); } } }
false
true
public void execute(JdbcTemplate template) { if (template.queryForInt("select count(*) from version where version = 4") == 0) { Schema28.LOG.info("Updating database schema to version 4."); template.execute("insert into version values (4)"); } if (!tableExists(template, "user_settings")) { LOG.info("Database table 'user_settings' not found. Creating it."); template.execute("create table user_settings (" + "username varchar not null," + "locale varchar," + "theme_id varchar," + "final_version_notification boolean default true not null," + "beta_version_notification boolean default false not null," + "main_caption_cutoff int default 35 not null," + "main_track_number boolean default true not null," + "main_artist boolean default true not null," + "main_album boolean default false not null," + "main_genre boolean default false not null," + "main_year boolean default false not null," + "main_bit_rate boolean default false not null," + "main_duration boolean default true not null," + "main_format boolean default false not null," + "main_file_size boolean default false not null," + "playlist_caption_cutoff int default 35 not null," + "playlist_track_number boolean default false not null," + "playlist_artist boolean default true not null," + "playlist_album boolean default true not null," + "playlist_genre boolean default false not null," + "playlist_year boolean default true not null," + "playlist_bit_rate boolean default false not null," + "playlist_duration boolean default true not null," + "playlist_format boolean default true not null," + "playlist_file_size boolean default true not null," + "primary key (username)," + "foreign key (username) references user(username) on delete cascade)"); LOG.info("Database table 'user_settings' was created successfully."); } if (!tableExists(template, "transcoding")) { LOG.info("Database table 'transcoding' not found. Creating it."); template.execute("create table transcoding (" + "id identity," + "name varchar not null," + "source_format varchar not null," + "target_format varchar not null," + "step1 varchar not null," + "step2 varchar," + "step3 varchar," + "enabled boolean not null)"); template.execute("insert into transcoding values(null,'ogg > mp3','ogg','mp3','oggdec %s -o','lame - -',null,false)"); template.execute("insert into transcoding values(null,'wma > mp3','wma','mp3','wmadec -w %s','lame - -',null,false)"); template.execute("insert into transcoding values(null,'flac > mp3','flac','mp3','flac -c -s -d %s','lame - -',null,false)"); template.execute("insert into transcoding values(null,'ape > mp3','ape','mp3','macpipe.exe %s - -d','lame - -',null,false)"); template.execute("insert into transcoding values(null,'m4a > mp3','m4a','mp3','faad -w %s','lame -x - -',null,false)"); template.execute("insert into transcoding values(null,'mpc > mp3','mpc','mp3','mppdec --wav --silent %s -','lame - -',null,false)"); template.execute("insert into transcoding values(null,'ofr > mp3','ofr','mp3','ofr --decode --silent %s --output -','lame - -',null,false)"); LOG.info("Database table 'transcoding' was created successfully."); } if (!tableExists(template, "player_transcoding")) { LOG.info("Database table 'player_transcoding' not found. Creating it."); template.execute("create table player_transcoding (" + "player_id int not null," + "transcoding_id int not null," + "primary key (player_id, transcoding_id)," + "foreign key (player_id) references player(id) on delete cascade," + "foreign key (transcoding_id) references transcoding(id) on delete cascade)"); LOG.info("Database table 'player_transcoding' was created successfully."); } }
public void execute(JdbcTemplate template) { if (template.queryForInt("select count(*) from version where version = 4") == 0) { Schema28.LOG.info("Updating database schema to version 4."); template.execute("insert into version values (4)"); } if (!tableExists(template, "user_settings")) { LOG.info("Database table 'user_settings' not found. Creating it."); template.execute("create table user_settings (" + "username varchar not null," + "locale varchar," + "theme_id varchar," + "final_version_notification boolean default true not null," + "beta_version_notification boolean default false not null," + "main_caption_cutoff int default 35 not null," + "main_track_number boolean default true not null," + "main_artist boolean default true not null," + "main_album boolean default false not null," + "main_genre boolean default false not null," + "main_year boolean default false not null," + "main_bit_rate boolean default false not null," + "main_duration boolean default true not null," + "main_format boolean default false not null," + "main_file_size boolean default false not null," + "playlist_caption_cutoff int default 35 not null," + "playlist_track_number boolean default false not null," + "playlist_artist boolean default true not null," + "playlist_album boolean default true not null," + "playlist_genre boolean default false not null," + "playlist_year boolean default true not null," + "playlist_bit_rate boolean default false not null," + "playlist_duration boolean default true not null," + "playlist_format boolean default true not null," + "playlist_file_size boolean default true not null," + "primary key (username)," + "foreign key (username) references user(username) on delete cascade)"); LOG.info("Database table 'user_settings' was created successfully."); } if (!tableExists(template, "transcoding")) { LOG.info("Database table 'transcoding' not found. Creating it."); template.execute("create table transcoding (" + "id identity," + "name varchar not null," + "source_format varchar not null," + "target_format varchar not null," + "step1 varchar not null," + "step2 varchar," + "step3 varchar," + "enabled boolean not null)"); template.execute("insert into transcoding values(null,'ogg > mp3','ogg','mp3','oggdec %s -o','lame - -',null,false)"); template.execute("insert into transcoding values(null,'wma > mp3','wma','mp3','wmadec %s','lame -x - -',null,false)"); template.execute("insert into transcoding values(null,'flac > mp3','flac','mp3','flac -c -s -d %s','lame - -',null,false)"); template.execute("insert into transcoding values(null,'ape > mp3','ape','mp3','mac %s - -d','lame - -',null,false)"); template.execute("insert into transcoding values(null,'m4a > mp3','m4a','mp3','faad -w %s','lame -x - -',null,false)"); template.execute("insert into transcoding values(null,'mpc > mp3','mpc','mp3','mppdec --wav --silent %s -','lame - -',null,false)"); template.execute("insert into transcoding values(null,'ofr > mp3','ofr','mp3','ofr --decode --silent %s --output -','lame - -',null,false)"); LOG.info("Database table 'transcoding' was created successfully."); } if (!tableExists(template, "player_transcoding")) { LOG.info("Database table 'player_transcoding' not found. Creating it."); template.execute("create table player_transcoding (" + "player_id int not null," + "transcoding_id int not null," + "primary key (player_id, transcoding_id)," + "foreign key (player_id) references player(id) on delete cascade," + "foreign key (transcoding_id) references transcoding(id) on delete cascade)"); LOG.info("Database table 'player_transcoding' was created successfully."); } }
diff --git a/E-Adventure/src/es/eucm/eadventure/common/loader/subparsers/EffectSubParser.java b/E-Adventure/src/es/eucm/eadventure/common/loader/subparsers/EffectSubParser.java index 4d78a59c..6de3154d 100644 --- a/E-Adventure/src/es/eucm/eadventure/common/loader/subparsers/EffectSubParser.java +++ b/E-Adventure/src/es/eucm/eadventure/common/loader/subparsers/EffectSubParser.java @@ -1,657 +1,657 @@ /******************************************************************************* * <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM> * research group. * * Copyright 2005-2010 <e-UCM> research group. * * You can access a list of all the contributors to <e-Adventure> at: * http://e-adventure.e-ucm.es/contributors * * <e-UCM> is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * C Profesor Jose Garcia Santesmases sn, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of <e-Adventure>, version 1.2. * * <e-Adventure> is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * <e-Adventure> is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with <e-Adventure>. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package es.eucm.eadventure.common.loader.subparsers; import org.xml.sax.Attributes; import es.eucm.eadventure.common.data.chapter.Chapter; import es.eucm.eadventure.common.data.chapter.conditions.Conditions; import es.eucm.eadventure.common.data.chapter.effects.AbstractEffect; import es.eucm.eadventure.common.data.chapter.effects.ActivateEffect; import es.eucm.eadventure.common.data.chapter.effects.CancelActionEffect; import es.eucm.eadventure.common.data.chapter.effects.ConsumeObjectEffect; import es.eucm.eadventure.common.data.chapter.effects.DeactivateEffect; import es.eucm.eadventure.common.data.chapter.effects.DecrementVarEffect; import es.eucm.eadventure.common.data.chapter.effects.Effects; import es.eucm.eadventure.common.data.chapter.effects.GenerateObjectEffect; import es.eucm.eadventure.common.data.chapter.effects.HighlightItemEffect; import es.eucm.eadventure.common.data.chapter.effects.IncrementVarEffect; import es.eucm.eadventure.common.data.chapter.effects.MacroReferenceEffect; import es.eucm.eadventure.common.data.chapter.effects.MoveNPCEffect; import es.eucm.eadventure.common.data.chapter.effects.MoveObjectEffect; import es.eucm.eadventure.common.data.chapter.effects.MovePlayerEffect; import es.eucm.eadventure.common.data.chapter.effects.PlayAnimationEffect; import es.eucm.eadventure.common.data.chapter.effects.PlaySoundEffect; import es.eucm.eadventure.common.data.chapter.effects.RandomEffect; import es.eucm.eadventure.common.data.chapter.effects.SetValueEffect; import es.eucm.eadventure.common.data.chapter.effects.ShowTextEffect; import es.eucm.eadventure.common.data.chapter.effects.SpeakCharEffect; import es.eucm.eadventure.common.data.chapter.effects.SpeakPlayerEffect; import es.eucm.eadventure.common.data.chapter.effects.TriggerBookEffect; import es.eucm.eadventure.common.data.chapter.effects.TriggerConversationEffect; import es.eucm.eadventure.common.data.chapter.effects.TriggerCutsceneEffect; import es.eucm.eadventure.common.data.chapter.effects.TriggerLastSceneEffect; import es.eucm.eadventure.common.data.chapter.effects.TriggerSceneEffect; import es.eucm.eadventure.common.data.chapter.effects.WaitTimeEffect; /** * Class to subparse effects */ public class EffectSubParser extends SubParser { /* Constants */ /** * Constant for no subparsing */ private static final int SUBPARSING_NONE = 0; /** * Constant for subparsing conditions */ private static final int SUBPARSING_CONDITION = 1; /* Attributes */ /** * The current subparser being used */ private SubParser subParser; /** * Indicates the current element being subparsed */ private int subParsing; /** * Stores the current id target */ private String currentCharIdTarget; /** * Stores the effects being parsed */ private Effects effects; /** * Atributes for show-text effects */ int x = 0; int y = 0; int frontColor = 0; int borderColor = 0; /** * Constants for reading random-effect */ private boolean positiveBlockRead = false; private boolean readingRandomEffect = false; private RandomEffect randomEffect; /** * Stores the current conditions being read */ private Conditions currentConditions; /** * CurrentEffect. Stores the last created effect to add it later the * conditions */ private AbstractEffect currentEffect; /** * New effects */ private AbstractEffect newEffect; /** * Audio path for speak player and character */ private String audioPath; /* Methods */ /** * Constructor * * @param effects * Structure in which the effects will be placed * @param chapter * Chapter data to store the read data */ public EffectSubParser( Effects effects, Chapter chapter ) { super( chapter ); this.effects = effects; } /* * (non-Javadoc) * * @see es.eucm.eadventure.engine.loader.subparsers.SubParser#startElement(java.lang.String, java.lang.String, * java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement( String namespaceURI, String sName, String qName, Attributes attrs ) { newEffect = null; audioPath=new String(); // If it is a cancel-action tag if( qName.equals( "cancel-action" ) ) { newEffect = new CancelActionEffect( ); } // If it is a activate tag else if( qName.equals( "activate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new ActivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a deactivate tag else if( qName.equals( "deactivate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new DeactivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a set-value tag else if( qName.equals( "set-value" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new SetValueEffect( var, value ); chapter.addVar( var ); } // If it is a set-value tag else if( qName.equals( "increment" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new IncrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a decrement tag else if( qName.equals( "decrement" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new DecrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a macro-reference tag else if( qName.equals( "macro-ref" ) ) { // Id String id = null; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "id" ) ) { id = attrs.getValue( i ); } } // Store the inactive flag in the conditions or either conditions newEffect = new MacroReferenceEffect( id ); } // If it is a consume-object tag else if( qName.equals( "consume-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new ConsumeObjectEffect( attrs.getValue( i ) ); } // If it is a generate-object tag else if( qName.equals( "generate-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new GenerateObjectEffect( attrs.getValue( i ) ); } // If it is a speak-char tag else if( qName.equals( "speak-char" ) ) { // Store the idTarget, to store the effect when the tag is closed currentCharIdTarget = null; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) currentCharIdTarget = attrs.getValue( i ); } // If it is a trigger-book tag else if( qName.equals( "trigger-book" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerBookEffect( attrs.getValue( i ) ); } // If it is a trigger-last-scene tag else if( qName.equals( "trigger-last-scene" ) ) { newEffect = new TriggerLastSceneEffect( ); } // If it is a play-sound tag else if( qName.equals( "play-sound" ) ) { // Store the path and background String path = ""; boolean background = true; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "background" ) ) background = attrs.getValue( i ).equals( "yes" ); else if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); } // Add the new play sound effect newEffect = new PlaySoundEffect( background, path ); } // If it is a trigger-conversation tag else if( qName.equals( "trigger-conversation" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerConversationEffect( attrs.getValue( i ) ); } // If it is a trigger-cutscene tag else if( qName.equals( "trigger-cutscene" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerCutsceneEffect( attrs.getValue( i ) ); } // If it is a trigger-scene tag else if( qName.equals( "trigger-scene" ) ) { String scene = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) scene = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); newEffect = new TriggerSceneEffect( scene, x, y ); } // If it is a play-animation tag else if( qName.equals( "play-animation" ) ) { String path = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new play sound effect newEffect = new PlayAnimationEffect( path, x, y ); } // If it is a move-player tag else if( qName.equals( "move-player" ) ) { int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move player effect newEffect = new MovePlayerEffect( x, y ); } // If it is a move-npc tag else if( qName.equals( "move-npc" ) ) { String npcTarget = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "idTarget" ) ) npcTarget = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new MoveNPCEffect( npcTarget, x, y ); } // Random effect tag else if( qName.equals( "random-effect" ) ) { int probability = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "probability" ) ) probability = Integer.parseInt( attrs.getValue( i ) ); } // Add the new random effect randomEffect = new RandomEffect( probability ); newEffect = randomEffect; readingRandomEffect = true; positiveBlockRead = false; } // wait-time effect else if( qName.equals( "wait-time" ) ) { int time = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "time" ) ) time = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new WaitTimeEffect( time ); } // show-text effect else if( qName.equals( "show-text" ) ) { x = 0; y = 0; frontColor = 0; borderColor = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "frontColor" ) ) frontColor = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "borderColor" ) ) borderColor = Integer.parseInt( attrs.getValue( i ) ); } } else if (qName.equals( "highlight-item" )) { int type = 0; boolean animated = false; String id = ""; for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "type" )) { if (attrs.getValue( i ).equals( "none" )) type = HighlightItemEffect.NO_HIGHLIGHT; if (attrs.getValue( i ).equals( "green" )) type = HighlightItemEffect.HIGHLIGHT_GREEN; if (attrs.getValue( i ).equals( "red" )) type = HighlightItemEffect.HIGHLIGHT_RED; if (attrs.getValue( i ).equals( "blue" )) type = HighlightItemEffect.HIGHLIGHT_BLUE; if (attrs.getValue( i ).equals( "border" )) type = HighlightItemEffect.HIGHLIGHT_BORDER; } } newEffect = new HighlightItemEffect(id, type, animated); } else if (qName.equals( "move-object" )) { boolean animated = false; String id = ""; int x = 0; int y = 0; float scale = 1.0f; int translateSpeed = 20; int scaleSpeed = 20; for (int i = 0; i < attrs.getLength( ); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "x" )) x = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "y" )) y = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scale" )) scale = Float.parseFloat( attrs.getValue( i )); if (attrs.getQName( i ).equals( "translateSpeed" )) translateSpeed = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scaleSpeed" )) scaleSpeed = Integer.parseInt( attrs.getValue( i ) ); } newEffect = new MoveObjectEffect(id, x, y, scale, animated, translateSpeed, scaleSpeed); } - else if( qName.equals( "speak-player" ) || qName.equals( "speak-character" )) { + else if( qName.equals( "speak-player" ) || qName.equals( "speak-char" )) { audioPath = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { // If there is a "uri" attribute, store it as audio path if( attrs.getQName( i ).equals( "uri" ) ) audioPath = attrs.getValue( i ); } } // If it is a condition tag, create new conditions and switch the state else if( qName.equals( "condition" ) ) { currentConditions = new Conditions( ); subParser = new ConditionSubParser( currentConditions, chapter ); subParsing = SUBPARSING_CONDITION; } // Not reading Random effect: Add the new Effect if not null if( !readingRandomEffect && newEffect != null ) { effects.add( newEffect ); // Store current effect currentEffect = newEffect; } // Reading random effect if( readingRandomEffect ) { // When we have just created the effect, add it if( newEffect != null && newEffect == randomEffect ) { effects.add( newEffect ); } // Otherwise, determine if it is positive or negative effect else if( newEffect != null && !positiveBlockRead ) { randomEffect.setPositiveEffect( newEffect ); positiveBlockRead = true; } // Negative effect else if( newEffect != null && positiveBlockRead ) { randomEffect.setNegativeEffect( newEffect ); positiveBlockRead = false; readingRandomEffect = false; newEffect = randomEffect; randomEffect = null; } // Store current effect currentEffect = newEffect; } // If it is reading an effect or a condition, spread the call if( subParsing != SUBPARSING_NONE ) { subParser.startElement( namespaceURI, sName, qName, attrs ); } } /* * (non-Javadoc) * * @see es.eucm.eadventure.engine.loader.subparsers.SubParser#endElement(java.lang.String, java.lang.String, * java.lang.String) */ @Override public void endElement( String namespaceURI, String sName, String qName ) { // If no element is being subparsed if( subParsing == SUBPARSING_NONE ) { newEffect = null; // If it is a speak-player if( qName.equals( "speak-player" ) ) { // Add the effect and clear the current string newEffect = new SpeakPlayerEffect( currentString.toString( ).trim( ) ); ((SpeakPlayerEffect) newEffect).setAudioPath( audioPath ); } // If it is a speak-char else if( qName.equals( "speak-char" ) ) { // Add the effect and clear the current string newEffect = new SpeakCharEffect( currentCharIdTarget, currentString.toString( ).trim( ) ); ((SpeakCharEffect) newEffect).setAudioPath( audioPath ); }// If it is a show-text else if( qName.equals( "show-text" ) ) { // Add the new ShowTextEffect newEffect = new ShowTextEffect( currentString.toString( ).trim( ), x, y, frontColor, borderColor ); } // Not reading Random effect: Add the new Effect if not null if( !readingRandomEffect && newEffect != null ) { effects.add( newEffect ); // Store current effect currentEffect = newEffect; } // Reading random effect if( readingRandomEffect ) { // When we have just created the effect, add it if( newEffect != null && newEffect == randomEffect ) { effects.add( newEffect ); } // Otherwise, determine if it is positive or negative effect else if( newEffect != null && !positiveBlockRead ) { randomEffect.setPositiveEffect( newEffect ); positiveBlockRead = true; } // Negative effect else if( newEffect != null && positiveBlockRead ) { randomEffect.setNegativeEffect( newEffect ); positiveBlockRead = false; readingRandomEffect = false; newEffect = randomEffect; randomEffect = null; } // Store current effect currentEffect = newEffect; } // Reset the current string currentString = new StringBuffer( ); } // If a condition is being subparsed else if( subParsing == SUBPARSING_CONDITION ) { // Spread the call subParser.endElement( namespaceURI, sName, qName ); // If the condition tag is being closed if( qName.equals( "condition" ) ) { // Store the conditions in the effect currentEffect.setConditions( currentConditions ); // Switch state subParsing = SUBPARSING_NONE; } } } /* * (non-Javadoc) * * @see es.eucm.eadventure.engine.loader.subparsers.SubParser#characters(char[], int, int) */ @Override public void characters( char[] buf, int offset, int len ) { // If no element is being subparsed if( subParsing == SUBPARSING_NONE ) super.characters( buf, offset, len ); // If it is reading an effect or a condition, spread the call else subParser.characters( buf, offset, len ); } }
true
true
public void startElement( String namespaceURI, String sName, String qName, Attributes attrs ) { newEffect = null; audioPath=new String(); // If it is a cancel-action tag if( qName.equals( "cancel-action" ) ) { newEffect = new CancelActionEffect( ); } // If it is a activate tag else if( qName.equals( "activate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new ActivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a deactivate tag else if( qName.equals( "deactivate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new DeactivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a set-value tag else if( qName.equals( "set-value" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new SetValueEffect( var, value ); chapter.addVar( var ); } // If it is a set-value tag else if( qName.equals( "increment" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new IncrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a decrement tag else if( qName.equals( "decrement" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new DecrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a macro-reference tag else if( qName.equals( "macro-ref" ) ) { // Id String id = null; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "id" ) ) { id = attrs.getValue( i ); } } // Store the inactive flag in the conditions or either conditions newEffect = new MacroReferenceEffect( id ); } // If it is a consume-object tag else if( qName.equals( "consume-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new ConsumeObjectEffect( attrs.getValue( i ) ); } // If it is a generate-object tag else if( qName.equals( "generate-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new GenerateObjectEffect( attrs.getValue( i ) ); } // If it is a speak-char tag else if( qName.equals( "speak-char" ) ) { // Store the idTarget, to store the effect when the tag is closed currentCharIdTarget = null; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) currentCharIdTarget = attrs.getValue( i ); } // If it is a trigger-book tag else if( qName.equals( "trigger-book" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerBookEffect( attrs.getValue( i ) ); } // If it is a trigger-last-scene tag else if( qName.equals( "trigger-last-scene" ) ) { newEffect = new TriggerLastSceneEffect( ); } // If it is a play-sound tag else if( qName.equals( "play-sound" ) ) { // Store the path and background String path = ""; boolean background = true; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "background" ) ) background = attrs.getValue( i ).equals( "yes" ); else if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); } // Add the new play sound effect newEffect = new PlaySoundEffect( background, path ); } // If it is a trigger-conversation tag else if( qName.equals( "trigger-conversation" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerConversationEffect( attrs.getValue( i ) ); } // If it is a trigger-cutscene tag else if( qName.equals( "trigger-cutscene" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerCutsceneEffect( attrs.getValue( i ) ); } // If it is a trigger-scene tag else if( qName.equals( "trigger-scene" ) ) { String scene = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) scene = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); newEffect = new TriggerSceneEffect( scene, x, y ); } // If it is a play-animation tag else if( qName.equals( "play-animation" ) ) { String path = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new play sound effect newEffect = new PlayAnimationEffect( path, x, y ); } // If it is a move-player tag else if( qName.equals( "move-player" ) ) { int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move player effect newEffect = new MovePlayerEffect( x, y ); } // If it is a move-npc tag else if( qName.equals( "move-npc" ) ) { String npcTarget = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "idTarget" ) ) npcTarget = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new MoveNPCEffect( npcTarget, x, y ); } // Random effect tag else if( qName.equals( "random-effect" ) ) { int probability = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "probability" ) ) probability = Integer.parseInt( attrs.getValue( i ) ); } // Add the new random effect randomEffect = new RandomEffect( probability ); newEffect = randomEffect; readingRandomEffect = true; positiveBlockRead = false; } // wait-time effect else if( qName.equals( "wait-time" ) ) { int time = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "time" ) ) time = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new WaitTimeEffect( time ); } // show-text effect else if( qName.equals( "show-text" ) ) { x = 0; y = 0; frontColor = 0; borderColor = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "frontColor" ) ) frontColor = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "borderColor" ) ) borderColor = Integer.parseInt( attrs.getValue( i ) ); } } else if (qName.equals( "highlight-item" )) { int type = 0; boolean animated = false; String id = ""; for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "type" )) { if (attrs.getValue( i ).equals( "none" )) type = HighlightItemEffect.NO_HIGHLIGHT; if (attrs.getValue( i ).equals( "green" )) type = HighlightItemEffect.HIGHLIGHT_GREEN; if (attrs.getValue( i ).equals( "red" )) type = HighlightItemEffect.HIGHLIGHT_RED; if (attrs.getValue( i ).equals( "blue" )) type = HighlightItemEffect.HIGHLIGHT_BLUE; if (attrs.getValue( i ).equals( "border" )) type = HighlightItemEffect.HIGHLIGHT_BORDER; } } newEffect = new HighlightItemEffect(id, type, animated); } else if (qName.equals( "move-object" )) { boolean animated = false; String id = ""; int x = 0; int y = 0; float scale = 1.0f; int translateSpeed = 20; int scaleSpeed = 20; for (int i = 0; i < attrs.getLength( ); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "x" )) x = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "y" )) y = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scale" )) scale = Float.parseFloat( attrs.getValue( i )); if (attrs.getQName( i ).equals( "translateSpeed" )) translateSpeed = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scaleSpeed" )) scaleSpeed = Integer.parseInt( attrs.getValue( i ) ); } newEffect = new MoveObjectEffect(id, x, y, scale, animated, translateSpeed, scaleSpeed); } else if( qName.equals( "speak-player" ) || qName.equals( "speak-character" )) { audioPath = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { // If there is a "uri" attribute, store it as audio path if( attrs.getQName( i ).equals( "uri" ) ) audioPath = attrs.getValue( i ); } } // If it is a condition tag, create new conditions and switch the state else if( qName.equals( "condition" ) ) { currentConditions = new Conditions( ); subParser = new ConditionSubParser( currentConditions, chapter ); subParsing = SUBPARSING_CONDITION; } // Not reading Random effect: Add the new Effect if not null if( !readingRandomEffect && newEffect != null ) { effects.add( newEffect ); // Store current effect currentEffect = newEffect; } // Reading random effect if( readingRandomEffect ) { // When we have just created the effect, add it if( newEffect != null && newEffect == randomEffect ) { effects.add( newEffect ); } // Otherwise, determine if it is positive or negative effect else if( newEffect != null && !positiveBlockRead ) { randomEffect.setPositiveEffect( newEffect ); positiveBlockRead = true; } // Negative effect else if( newEffect != null && positiveBlockRead ) { randomEffect.setNegativeEffect( newEffect ); positiveBlockRead = false; readingRandomEffect = false; newEffect = randomEffect; randomEffect = null; } // Store current effect currentEffect = newEffect; } // If it is reading an effect or a condition, spread the call if( subParsing != SUBPARSING_NONE ) { subParser.startElement( namespaceURI, sName, qName, attrs ); } }
public void startElement( String namespaceURI, String sName, String qName, Attributes attrs ) { newEffect = null; audioPath=new String(); // If it is a cancel-action tag if( qName.equals( "cancel-action" ) ) { newEffect = new CancelActionEffect( ); } // If it is a activate tag else if( qName.equals( "activate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new ActivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a deactivate tag else if( qName.equals( "deactivate" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "flag" ) ) { newEffect = new DeactivateEffect( attrs.getValue( i ) ); chapter.addFlag( attrs.getValue( i ) ); } } // If it is a set-value tag else if( qName.equals( "set-value" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new SetValueEffect( var, value ); chapter.addVar( var ); } // If it is a set-value tag else if( qName.equals( "increment" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new IncrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a decrement tag else if( qName.equals( "decrement" ) ) { String var = null; int value = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "var" ) ) { var = attrs.getValue( i ); } else if( attrs.getQName( i ).equals( "value" ) ) { value = Integer.parseInt( attrs.getValue( i ) ); } } newEffect = new DecrementVarEffect( var, value ); chapter.addVar( var ); } // If it is a macro-reference tag else if( qName.equals( "macro-ref" ) ) { // Id String id = null; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "id" ) ) { id = attrs.getValue( i ); } } // Store the inactive flag in the conditions or either conditions newEffect = new MacroReferenceEffect( id ); } // If it is a consume-object tag else if( qName.equals( "consume-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new ConsumeObjectEffect( attrs.getValue( i ) ); } // If it is a generate-object tag else if( qName.equals( "generate-object" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new GenerateObjectEffect( attrs.getValue( i ) ); } // If it is a speak-char tag else if( qName.equals( "speak-char" ) ) { // Store the idTarget, to store the effect when the tag is closed currentCharIdTarget = null; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) currentCharIdTarget = attrs.getValue( i ); } // If it is a trigger-book tag else if( qName.equals( "trigger-book" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerBookEffect( attrs.getValue( i ) ); } // If it is a trigger-last-scene tag else if( qName.equals( "trigger-last-scene" ) ) { newEffect = new TriggerLastSceneEffect( ); } // If it is a play-sound tag else if( qName.equals( "play-sound" ) ) { // Store the path and background String path = ""; boolean background = true; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "background" ) ) background = attrs.getValue( i ).equals( "yes" ); else if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); } // Add the new play sound effect newEffect = new PlaySoundEffect( background, path ); } // If it is a trigger-conversation tag else if( qName.equals( "trigger-conversation" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerConversationEffect( attrs.getValue( i ) ); } // If it is a trigger-cutscene tag else if( qName.equals( "trigger-cutscene" ) ) { for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) newEffect = new TriggerCutsceneEffect( attrs.getValue( i ) ); } // If it is a trigger-scene tag else if( qName.equals( "trigger-scene" ) ) { String scene = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) if( attrs.getQName( i ).equals( "idTarget" ) ) scene = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); newEffect = new TriggerSceneEffect( scene, x, y ); } // If it is a play-animation tag else if( qName.equals( "play-animation" ) ) { String path = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "uri" ) ) path = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new play sound effect newEffect = new PlayAnimationEffect( path, x, y ); } // If it is a move-player tag else if( qName.equals( "move-player" ) ) { int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move player effect newEffect = new MovePlayerEffect( x, y ); } // If it is a move-npc tag else if( qName.equals( "move-npc" ) ) { String npcTarget = ""; int x = 0; int y = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "idTarget" ) ) npcTarget = attrs.getValue( i ); else if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new MoveNPCEffect( npcTarget, x, y ); } // Random effect tag else if( qName.equals( "random-effect" ) ) { int probability = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "probability" ) ) probability = Integer.parseInt( attrs.getValue( i ) ); } // Add the new random effect randomEffect = new RandomEffect( probability ); newEffect = randomEffect; readingRandomEffect = true; positiveBlockRead = false; } // wait-time effect else if( qName.equals( "wait-time" ) ) { int time = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "time" ) ) time = Integer.parseInt( attrs.getValue( i ) ); } // Add the new move NPC effect newEffect = new WaitTimeEffect( time ); } // show-text effect else if( qName.equals( "show-text" ) ) { x = 0; y = 0; frontColor = 0; borderColor = 0; for( int i = 0; i < attrs.getLength( ); i++ ) { if( attrs.getQName( i ).equals( "x" ) ) x = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "y" ) ) y = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "frontColor" ) ) frontColor = Integer.parseInt( attrs.getValue( i ) ); else if( attrs.getQName( i ).equals( "borderColor" ) ) borderColor = Integer.parseInt( attrs.getValue( i ) ); } } else if (qName.equals( "highlight-item" )) { int type = 0; boolean animated = false; String id = ""; for (int i = 0; i < attrs.getLength(); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "type" )) { if (attrs.getValue( i ).equals( "none" )) type = HighlightItemEffect.NO_HIGHLIGHT; if (attrs.getValue( i ).equals( "green" )) type = HighlightItemEffect.HIGHLIGHT_GREEN; if (attrs.getValue( i ).equals( "red" )) type = HighlightItemEffect.HIGHLIGHT_RED; if (attrs.getValue( i ).equals( "blue" )) type = HighlightItemEffect.HIGHLIGHT_BLUE; if (attrs.getValue( i ).equals( "border" )) type = HighlightItemEffect.HIGHLIGHT_BORDER; } } newEffect = new HighlightItemEffect(id, type, animated); } else if (qName.equals( "move-object" )) { boolean animated = false; String id = ""; int x = 0; int y = 0; float scale = 1.0f; int translateSpeed = 20; int scaleSpeed = 20; for (int i = 0; i < attrs.getLength( ); i++) { if (attrs.getQName( i ).equals( "idTarget" )) id = attrs.getValue( i ); if (attrs.getQName( i ).equals( "animated" )) animated = (attrs.getValue( i ).equals( "yes" ) ? true : false); if (attrs.getQName( i ).equals( "x" )) x = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "y" )) y = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scale" )) scale = Float.parseFloat( attrs.getValue( i )); if (attrs.getQName( i ).equals( "translateSpeed" )) translateSpeed = Integer.parseInt( attrs.getValue( i ) ); if (attrs.getQName( i ).equals( "scaleSpeed" )) scaleSpeed = Integer.parseInt( attrs.getValue( i ) ); } newEffect = new MoveObjectEffect(id, x, y, scale, animated, translateSpeed, scaleSpeed); } else if( qName.equals( "speak-player" ) || qName.equals( "speak-char" )) { audioPath = ""; for( int i = 0; i < attrs.getLength( ); i++ ) { // If there is a "uri" attribute, store it as audio path if( attrs.getQName( i ).equals( "uri" ) ) audioPath = attrs.getValue( i ); } } // If it is a condition tag, create new conditions and switch the state else if( qName.equals( "condition" ) ) { currentConditions = new Conditions( ); subParser = new ConditionSubParser( currentConditions, chapter ); subParsing = SUBPARSING_CONDITION; } // Not reading Random effect: Add the new Effect if not null if( !readingRandomEffect && newEffect != null ) { effects.add( newEffect ); // Store current effect currentEffect = newEffect; } // Reading random effect if( readingRandomEffect ) { // When we have just created the effect, add it if( newEffect != null && newEffect == randomEffect ) { effects.add( newEffect ); } // Otherwise, determine if it is positive or negative effect else if( newEffect != null && !positiveBlockRead ) { randomEffect.setPositiveEffect( newEffect ); positiveBlockRead = true; } // Negative effect else if( newEffect != null && positiveBlockRead ) { randomEffect.setNegativeEffect( newEffect ); positiveBlockRead = false; readingRandomEffect = false; newEffect = randomEffect; randomEffect = null; } // Store current effect currentEffect = newEffect; } // If it is reading an effect or a condition, spread the call if( subParsing != SUBPARSING_NONE ) { subParser.startElement( namespaceURI, sName, qName, attrs ); } }
diff --git a/AsteroidMiner/src/ch/kanti_wohlen/asteroidminer/entities/SpaceShip.java b/AsteroidMiner/src/ch/kanti_wohlen/asteroidminer/entities/SpaceShip.java index da5df4d..7e27e44 100644 --- a/AsteroidMiner/src/ch/kanti_wohlen/asteroidminer/entities/SpaceShip.java +++ b/AsteroidMiner/src/ch/kanti_wohlen/asteroidminer/entities/SpaceShip.java @@ -1,127 +1,126 @@ package ch.kanti_wohlen.asteroidminer.entities; import ch.kanti_wohlen.asteroidminer.Textures; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; import com.badlogic.gdx.physics.box2d.World; public class SpaceShip extends Entity { public static final int MAX_HEALTH = 100; public static final float HEALTH_BAR_ALPHA_MAX = 5f; private int health; private float healthAlpha; private boolean shieldEnabled = false; public SpaceShip(World world) { super(world, createBodyDef(), createFixture()); health = MAX_HEALTH; healthAlpha = HEALTH_BAR_ALPHA_MAX; } @Override public void render(SpriteBatch batch) { Sprite s = Textures.SPACESHIP; positionSprite(s); s.draw(batch); getPhysicsBody().setGravityScale(5f); healthAlpha = Math.max(0f, healthAlpha - 0.01f); // If taken some health lately, render the health bar if (healthAlpha > 0f) { renderHealthBar(batch, s); } } private void renderHealthBar(SpriteBatch batch, Sprite s) { // Render health overlay - final float x = s.getX() - s.getWidth() * 0.05f; // Space ship texture - // is off.... + final float x = s.getX() - s.getWidth() * 0.05f; // Space ship texture is off.... final float y = s.getY() + s.getHeight() * 1.15f; final int xm = Math.round((float) health / SpaceShip.MAX_HEALTH * Textures.HEALTH_HIGH.getRegionWidth()); final int xn = Textures.HEALTH_LOW.getRegionWidth() - xm; final int wHigh = Textures.HEALTH_HIGH.getRegionWidth(); final int xLow = Textures.HEALTH_LOW.getRegionX(); final int wLow = Textures.HEALTH_LOW.getRegionWidth(); Textures.HEALTH_HIGH.setBounds(x, y, xm, Textures.HEALTH_HIGH.getHeight()); Textures.HEALTH_HIGH.setRegionWidth(xm); Textures.HEALTH_HIGH.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_HIGH.setRegionWidth(wHigh); Textures.HEALTH_LOW.setBounds(x + xm, y, xn, Textures.HEALTH_LOW.getHeight()); Textures.HEALTH_LOW.setRegionX(xLow + xm); Textures.HEALTH_LOW.setRegionWidth(xn); Textures.HEALTH_LOW.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_LOW.setRegionX(xLow); Textures.HEALTH_LOW.setRegionWidth(wLow); } @Override public boolean isRemoved() { return false; } public int getHealth() { return health; } public void setHealth(int newHealth) { if (newHealth != health) { health = MathUtils.clamp(newHealth, 0, MAX_HEALTH); healthAlpha = HEALTH_BAR_ALPHA_MAX; } } public void heal(int healingAmoung) { setHealth(health + healingAmoung); } public void damage(int damageAmount) { setHealth(health - damageAmount); } public void kill() { setHealth(0); } public boolean getShieldEnabled() { return shieldEnabled; } public void setShieldEnabled(boolean shieldEnabled) { this.shieldEnabled = shieldEnabled; } public Laser fireLaser() { return new Laser(getPhysicsBody().getWorld(), this); } private static BodyDef createBodyDef() { BodyDef bd = new BodyDef(); bd.allowSleep = false; bd.type = BodyType.DynamicBody; bd.angularDamping = 10f; bd.linearDamping = 2.5f; bd.position.set(2f, 2f); return bd; } private static FixtureDef createFixture() { final FixtureDef fixture = new FixtureDef(); fixture.density = 1f; final PolygonShape ps = new PolygonShape(); ps.setAsBox(Textures.SPACESHIP.getWidth() / 2f * PIXEL_TO_BOX2D, Textures.SPACESHIP.getHeight() / 2f * PIXEL_TO_BOX2D); fixture.shape = ps; return fixture; } }
true
true
private void renderHealthBar(SpriteBatch batch, Sprite s) { // Render health overlay final float x = s.getX() - s.getWidth() * 0.05f; // Space ship texture // is off.... final float y = s.getY() + s.getHeight() * 1.15f; final int xm = Math.round((float) health / SpaceShip.MAX_HEALTH * Textures.HEALTH_HIGH.getRegionWidth()); final int xn = Textures.HEALTH_LOW.getRegionWidth() - xm; final int wHigh = Textures.HEALTH_HIGH.getRegionWidth(); final int xLow = Textures.HEALTH_LOW.getRegionX(); final int wLow = Textures.HEALTH_LOW.getRegionWidth(); Textures.HEALTH_HIGH.setBounds(x, y, xm, Textures.HEALTH_HIGH.getHeight()); Textures.HEALTH_HIGH.setRegionWidth(xm); Textures.HEALTH_HIGH.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_HIGH.setRegionWidth(wHigh); Textures.HEALTH_LOW.setBounds(x + xm, y, xn, Textures.HEALTH_LOW.getHeight()); Textures.HEALTH_LOW.setRegionX(xLow + xm); Textures.HEALTH_LOW.setRegionWidth(xn); Textures.HEALTH_LOW.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_LOW.setRegionX(xLow); Textures.HEALTH_LOW.setRegionWidth(wLow); }
private void renderHealthBar(SpriteBatch batch, Sprite s) { // Render health overlay final float x = s.getX() - s.getWidth() * 0.05f; // Space ship texture is off.... final float y = s.getY() + s.getHeight() * 1.15f; final int xm = Math.round((float) health / SpaceShip.MAX_HEALTH * Textures.HEALTH_HIGH.getRegionWidth()); final int xn = Textures.HEALTH_LOW.getRegionWidth() - xm; final int wHigh = Textures.HEALTH_HIGH.getRegionWidth(); final int xLow = Textures.HEALTH_LOW.getRegionX(); final int wLow = Textures.HEALTH_LOW.getRegionWidth(); Textures.HEALTH_HIGH.setBounds(x, y, xm, Textures.HEALTH_HIGH.getHeight()); Textures.HEALTH_HIGH.setRegionWidth(xm); Textures.HEALTH_HIGH.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_HIGH.setRegionWidth(wHigh); Textures.HEALTH_LOW.setBounds(x + xm, y, xn, Textures.HEALTH_LOW.getHeight()); Textures.HEALTH_LOW.setRegionX(xLow + xm); Textures.HEALTH_LOW.setRegionWidth(xn); Textures.HEALTH_LOW.draw(batch, Math.min(healthAlpha, 1f)); Textures.HEALTH_LOW.setRegionX(xLow); Textures.HEALTH_LOW.setRegionWidth(wLow); }
diff --git a/src/com/jeffreyregalia/Tower.java b/src/com/jeffreyregalia/Tower.java index 0739be8..f520337 100644 --- a/src/com/jeffreyregalia/Tower.java +++ b/src/com/jeffreyregalia/Tower.java @@ -1,134 +1,133 @@ package com.jeffreyregalia; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.ArrayList; public class Tower implements Entity{ int size; int radius; int x; int y; Enemy target; double targetDistance; Point targetPoint; int timeSinceAttack = 0; int attackTime = 250; int attackFrames = 0; boolean attacked = false; int power = 2; Tower(int size, int radius, int x, int y){ this.size = size; this.radius = radius; this.x = x; this.y = y; } public void update(int time){ this.timeSinceAttack += time; if(this.timeSinceAttack > this.attackTime) this.timeSinceAttack = this.attackTime; if(this.target == null){ this.targetDistance = 0.0; this.targetPoint = null; }else{ if(this.timeSinceAttack == this.attackTime){ this.target.attack(this.power); this.timeSinceAttack = 0; this.attacked = true; if(this.target.getHP() < 1){ this.target = null; } } } // fire? // rotate gun? } public void render(Graphics g){ //draw tower if(!attacked && this.timeSinceAttack == this.attackTime) g.setColor( new Color (150, 150, 0)); else g.setColor( new Color(0,0,0)); g.fillRect(x-size/2, y-size/2, size, size); //draw radius if(target == null){ g.setColor( new Color(0,255,0)); }else { g.setColor( new Color(255,0,0)); } g.drawOval(x-radius, y-radius, radius*2, radius*2); if(targetPoint != null){ //if(attacked){ g.setColor( new Color(0,0,0)); g.drawLine(x,y,(int) targetPoint.getX(),(int) targetPoint.getY()); attackFrames++; if(attackFrames > 5){ attackFrames = 0; this.attacked = false; } //} // g.drawString("TX: " + targetPoint.getX() + " TY: " + targetPoint.getY(), 50, 90); } else { this.attacked = false; } // g.drawString("Distance: "+this.targetDistance,50,50); // g.drawString("X: " + x + " Y: " + y, x, y); } public void findTarget(ArrayList<Enemy> enemyList){ double tempDistance = 0.0; if(target==null){ for(Enemy enemy: enemyList){ for(Point point: enemy.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); - if(distance < radius){ - this.target = enemy; + if(distance < radius) if(tempDistance == 0.0 || distance < tempDistance){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; + this.target = enemy; } - } } } if(tempDistance == 0.0){ this.targetPoint = null; this.targetDistance = 0.0; this.target = null; } }else{ boolean stillValid = false; for(Point point: this.target.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); if(distance < radius &&(tempDistance == 0.0 || distance < tempDistance)){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; stillValid = true; } } if(!stillValid){ this.target = null; this.targetDistance = 0.0; this.targetPoint = null; } } } public void setTarget(){ } public Entity getTarget(){ return this.target; } public boolean isAlive(){ return true; } }
false
true
public void findTarget(ArrayList<Enemy> enemyList){ double tempDistance = 0.0; if(target==null){ for(Enemy enemy: enemyList){ for(Point point: enemy.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); if(distance < radius){ this.target = enemy; if(tempDistance == 0.0 || distance < tempDistance){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; } } } } if(tempDistance == 0.0){ this.targetPoint = null; this.targetDistance = 0.0; this.target = null; } }else{ boolean stillValid = false; for(Point point: this.target.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); if(distance < radius &&(tempDistance == 0.0 || distance < tempDistance)){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; stillValid = true; } } if(!stillValid){ this.target = null; this.targetDistance = 0.0; this.targetPoint = null; } } }
public void findTarget(ArrayList<Enemy> enemyList){ double tempDistance = 0.0; if(target==null){ for(Enemy enemy: enemyList){ for(Point point: enemy.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); if(distance < radius) if(tempDistance == 0.0 || distance < tempDistance){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; this.target = enemy; } } } if(tempDistance == 0.0){ this.targetPoint = null; this.targetDistance = 0.0; this.target = null; } }else{ boolean stillValid = false; for(Point point: this.target.getHitBox()){ double distance = Math.sqrt((x-point.getX())*(x-point.getX())+(y-point.getY())*(y-point.getY())); if(distance < radius &&(tempDistance == 0.0 || distance < tempDistance)){ tempDistance = distance; this.targetDistance = distance; this.targetPoint = point; stillValid = true; } } if(!stillValid){ this.target = null; this.targetDistance = 0.0; this.targetPoint = null; } } }
diff --git a/commons/src/main/java/org/archive/io/arc/ARCWriter.java b/commons/src/main/java/org/archive/io/arc/ARCWriter.java index 10acfe8..be3ab38 100644 --- a/commons/src/main/java/org/archive/io/arc/ARCWriter.java +++ b/commons/src/main/java/org/archive/io/arc/ARCWriter.java @@ -1,489 +1,489 @@ /* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.archive.io.arc; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.archive.io.GzippedInputStream; import org.archive.io.ReplayInputStream; import org.archive.io.WriterPoolMember; import org.archive.util.ArchiveUtils; import org.archive.util.DevUtils; import org.archive.util.MimetypeUtils; /** * Write ARC files. * * Assumption is that the caller is managing access to this ARCWriter ensuring * only one thread of control accessing this ARC file instance at any one time. * * <p>ARC files are described here: * <a href="http://www.archive.org/web/researcher/ArcFileFormat.php">Arc * File Format</a>. This class does version 1 of the ARC file format. It also * writes version 1.1 which is version 1 with data stuffed into the body of the * first arc record in the file, the arc file meta record itself. * * <p>An ARC file is three lines of meta data followed by an optional 'body' and * then a couple of '\n' and then: record, '\n', record, '\n', record, etc. * If we are writing compressed ARC files, then each of the ARC file records is * individually gzipped and concatenated together to make up a single ARC file. * In GZIP terms, each ARC record is a GZIP <i>member</i> of a total gzip'd * file. * * <p>The GZIPping of the ARC file meta data is exceptional. It is GZIPped * w/ an extra GZIP header, a special Internet Archive (IA) extra header field * (e.g. FEXTRA is set in the GZIP header FLG field and an extra field is * appended to the GZIP header). The extra field has little in it but its * presence denotes this GZIP as an Internet Archive gzipped ARC. See RFC1952 * to learn about the GZIP header structure. * * <p>This class then does its GZIPping in the following fashion. Each GZIP * member is written w/ a new instance of GZIPOutputStream -- actually * ARCWriterGZIPOututStream so we can get access to the underlying stream. * The underlying stream stays open across GZIPoutputStream instantiations. * For the 'special' GZIPing of the ARC file meta data, we cheat by catching the * GZIPOutputStream output into a byte array, manipulating it adding the * IA GZIP header, before writing to the stream. * * <p>I tried writing a resettable GZIPOutputStream and could make it work w/ * the SUN JDK but the IBM JDK threw NPE inside in the deflate.reset -- its zlib * native call doesn't seem to like the notion of resetting -- so I gave up on * it. * * <p>Because of such as the above and troubles with GZIPInputStream, we should * write our own GZIP*Streams, ones that resettable and consious of gzip * members. * * <p>This class will write until we hit >= maxSize. The check is done at * record boundary. Records do not span ARC files. We will then close current * file and open another and then continue writing. * * <p><b>TESTING: </b>Here is how to test that produced ARC files are good * using the * <a href="http://www.archive.org/web/researcher/tool_documentation.php">alexa * ARC c-tools</a>: * <pre> * % av_procarc hx20040109230030-0.arc.gz | av_ziparc > \ * /tmp/hx20040109230030-0.dat.gz * % av_ripdat /tmp/hx20040109230030-0.dat.gz > /tmp/hx20040109230030-0.cdx * </pre> * Examine the produced cdx file to make sure it makes sense. Search * for 'no-type 0'. If found, then we're opening a gzip record w/o data to * write. This is bad. * * <p>You can also do <code>gzip -t FILENAME</code> and it will tell you if the * ARC makes sense to GZIP. * * <p>While being written, ARCs have a '.open' suffix appended. * * @author stack */ public class ARCWriter extends WriterPoolMember implements ARCConstants { private static final Logger logger = Logger.getLogger(ARCWriter.class.getName()); /** * Metadata line pattern. */ private static final Pattern METADATA_LINE_PATTERN = Pattern.compile("^\\S+ \\S+ \\S+ \\S+ \\S+(" + LINE_SEPARATOR + "?)$"); private List<String> metadata = null; /** * Constructor. * Takes a stream. Use with caution. There is no upperbound check on size. * Will just keep writing. * * @param serialNo used to generate unique file name sequences * @param out Where to write. * @param arc File the <code>out</code> is connected to. * @param cmprs Compress the content written. * @param metadata File meta data. Can be null. Is list of File and/or * String objects. * @param a14DigitDate If null, we'll write current time. * @throws IOException */ public ARCWriter(final AtomicInteger serialNo, final PrintStream out, final File arc, final boolean cmprs, String a14DigitDate, final List<String> metadata) throws IOException { super(serialNo, out, arc, cmprs, a14DigitDate); this.metadata = metadata; writeFirstRecord(a14DigitDate); } /** * Constructor. * * @param serialNo used to generate unique file name sequences * @param dirs Where to drop the ARC files. * @param prefix ARC file prefix to use. If null, we use * DEFAULT_ARC_FILE_PREFIX. * @param cmprs Compress the ARC files written. The compression is done * by individually gzipping each record added to the ARC file: i.e. the * ARC file is a bunch of gzipped records concatenated together. * @param maxSize Maximum size for ARC files written. */ public ARCWriter(final AtomicInteger serialNo, final List<File> dirs, final String prefix, final boolean cmprs, final long maxSize) { this(serialNo, dirs, prefix, "", cmprs, maxSize, null); } /** * Constructor. * * @param serialNo used to generate unique file name sequences * @param dirs Where to drop files. * @param prefix File prefix to use. * @param cmprs Compress the records written. * @param maxSize Maximum size for ARC files written. * @param suffix File tail to use. If null, unused. * @param meta File meta data. Can be null. Is list of File and/or * String objects. */ public ARCWriter(final AtomicInteger serialNo, final List<File> dirs, final String prefix, final String suffix, final boolean cmprs, final long maxSize, final List<String> meta) { super(serialNo, dirs, prefix, suffix, cmprs, maxSize, ARC_FILE_EXTENSION); this.metadata = meta; } protected String createFile() throws IOException { String name = super.createFile(); writeFirstRecord(currentTimestamp); return name; } private void writeFirstRecord(final String ts) throws IOException { write(generateARCFileMetaData(ts)); } /** * Write out the ARCMetaData. * * <p>Generate ARC file meta data. Currently we only do version 1 of the * ARC file formats or version 1.1 when metadata has been supplied (We * write it into the body of the first record in the arc file). * * <p>Version 1 metadata looks roughly like this: * * <pre>filedesc://testWriteRecord-JunitIAH20040110013326-2.arc 0.0.0.0 \\ * 20040110013326 text/plain 77 * 1 0 InternetArchive * URL IP-address Archive-date Content-type Archive-length * </pre> * * <p>If compress is set, then we generate a header that has been gzipped * in the Internet Archive manner. Such a gzipping enables the FEXTRA * flag in the FLG field of the gzip header. It then appends an extra * header field: '8', '0', 'L', 'X', '0', '0', '0', '0'. The first two * bytes are the length of the field and the last 6 bytes the Internet * Archive header. To learn about GZIP format, see RFC1952. To learn * about the Internet Archive extra header field, read the source for * av_ziparc which can be found at * <code>alexa/vista/alexa-tools-1.2/src/av_ziparc.cc</code>. * * <p>We do things in this roundabout manner because the java * GZIPOutputStream does not give access to GZIP header fields. * * @param date Date to put into the ARC metadata; if 17-digit will be * truncated to traditional 14-digits * * @return Byte array filled w/ the arc header. * @throws IOException */ private byte [] generateARCFileMetaData(String date) throws IOException { - if(date.length()>14) { + if(date!=null && date.length()>14) { date = date.substring(0,14); } int metadataBodyLength = getMetadataLength(); // If metadata body, then the minor part of the version is '1' rather // than '0'. String metadataHeaderLinesTwoAndThree = getMetadataHeaderLinesTwoAndThree("1 " + ((metadataBodyLength > 0)? "1": "0")); int recordLength = metadataBodyLength + metadataHeaderLinesTwoAndThree.getBytes(DEFAULT_ENCODING).length; String metadataHeaderStr = ARC_MAGIC_NUMBER + getBaseFilename() + " 0.0.0.0 " + date + " text/plain " + recordLength + metadataHeaderLinesTwoAndThree; ByteArrayOutputStream metabaos = new ByteArrayOutputStream(recordLength); // Write the metadata header. metabaos.write(metadataHeaderStr.getBytes(DEFAULT_ENCODING)); // Write the metadata body, if anything to write. if (metadataBodyLength > 0) { writeMetaData(metabaos); } // Write out a LINE_SEPARATORs to end this record. metabaos.write(LINE_SEPARATOR); // Now get bytes of all just written and compress if flag set. byte [] bytes = metabaos.toByteArray(); if(isCompressed()) { // GZIP the header but catch the gzipping into a byte array so we // can add the special IA GZIP header to the product. After // manipulations, write to the output stream (The JAVA GZIP // implementation does not give access to GZIP header. It // produces a 'default' header only). We can get away w/ these // maniupulations because the GZIP 'default' header doesn't // do the 'optional' CRC'ing of the header. byte [] gzippedMetaData = GzippedInputStream.gzip(bytes); if (gzippedMetaData[3] != 0) { throw new IOException("The GZIP FLG header is unexpectedly " + " non-zero. Need to add smarter code that can deal " + " when already extant extra GZIP header fields."); } // Set the GZIP FLG header to '4' which says that the GZIP header // has extra fields. Then insert the alex {'L', 'X', '0', '0', '0, // '0'} 'extra' field. The IA GZIP header will also set byte // 9 (zero-based), the OS byte, to 3 (Unix). We'll do the same. gzippedMetaData[3] = 4; gzippedMetaData[9] = 3; byte [] assemblyBuffer = new byte[gzippedMetaData.length + ARC_GZIP_EXTRA_FIELD.length]; // '10' in the below is a pointer past the following bytes of the // GZIP header: ID1 ID2 CM FLG + MTIME(4-bytes) XFL OS. See // RFC1952 for explaination of the abbreviations just used. System.arraycopy(gzippedMetaData, 0, assemblyBuffer, 0, 10); System.arraycopy(ARC_GZIP_EXTRA_FIELD, 0, assemblyBuffer, 10, ARC_GZIP_EXTRA_FIELD.length); System.arraycopy(gzippedMetaData, 10, assemblyBuffer, 10 + ARC_GZIP_EXTRA_FIELD.length, gzippedMetaData.length - 10); bytes = assemblyBuffer; } return bytes; } public String getMetadataHeaderLinesTwoAndThree(String version) { StringBuffer buffer = new StringBuffer(); buffer.append(LINE_SEPARATOR); buffer.append(version); buffer.append(" InternetArchive"); buffer.append(LINE_SEPARATOR); buffer.append("URL IP-address Archive-date Content-type Archive-length"); buffer.append(LINE_SEPARATOR); return buffer.toString(); } /** * Write all metadata to passed <code>baos</code>. * * @param baos Byte array to write to. * @throws UnsupportedEncodingException * @throws IOException */ private void writeMetaData(ByteArrayOutputStream baos) throws UnsupportedEncodingException, IOException { if (this.metadata == null) { return; } for (Iterator<String> i = this.metadata.iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof String) { baos.write(((String)obj).getBytes(DEFAULT_ENCODING)); } else if (obj instanceof File) { InputStream is = null; try { is = new BufferedInputStream( new FileInputStream((File)obj)); byte [] buffer = new byte[4096]; for (int read = -1; (read = is.read(buffer)) != -1;) { baos.write(buffer, 0, read); } } finally { if (is != null) { is.close(); } } } else if (obj != null) { logger.severe("Unsupported metadata type: " + obj); } } return; } /** * @return Total length of metadata. * @throws UnsupportedEncodingException */ private int getMetadataLength() throws UnsupportedEncodingException { int result = -1; if (this.metadata == null) { result = 0; } else { for (Iterator<String> i = this.metadata.iterator(); i.hasNext();) { Object obj = i.next(); if (obj instanceof String) { result += ((String)obj).getBytes(DEFAULT_ENCODING).length; } else if (obj instanceof File) { result += ((File)obj).length(); } else { logger.severe("Unsupported metadata type: " + obj); } } } return result; } /** * @deprecated use input-stream version directly instead */ public void write(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength, ByteArrayOutputStream baos) throws IOException { write(uri, contentType, hostIP, fetchBeginTimeStamp, recordLength, new ByteArrayInputStream(baos.toByteArray()), false); } public void write(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength, InputStream in) throws IOException { write(uri,contentType,hostIP,fetchBeginTimeStamp,recordLength,in,true); } /** * Write a record with the given metadata/content. * * @param uri * URI for metadata-line * @param contentType * MIME content-type for metadata-line * @param hostIP * IP for metadata-line * @param fetchBeginTimeStamp * timestamp for metadata-line * @param recordLength * length for metadata-line; also may be enforced * @param in * source InputStream for record content * @param enforceLength * whether to enforce the declared length; should be true * unless intentionally writing bad records for testing * @throws IOException */ public void write(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength, InputStream in, boolean enforceLength) throws IOException { preWriteRecordTasks(); try { write(getMetaLine(uri, contentType, hostIP, fetchBeginTimeStamp, recordLength).getBytes(UTF8)); copyFrom(in, recordLength, enforceLength); if (in instanceof ReplayInputStream) { // check for consumption of entire recorded material long remaining = ((ReplayInputStream) in).remaining(); // Should be zero at this stage. If not, something is // wrong. if (remaining != 0) { String message = "Gap between expected and actual: " + remaining + LINE_SEPARATOR + DevUtils.extraInfo() + " writing arc " + this.getFile().getAbsolutePath(); DevUtils.warnHandle(new Throwable(message), message); throw new IOException(message); } } write(LINE_SEPARATOR); } finally { postWriteRecordTasks(); } } /** * @param uri * @param contentType * @param hostIP * @param fetchBeginTimeStamp * @param recordLength * @return Metadata line for an ARCRecord made of passed components. * @exception IOException */ protected String getMetaLine(String uri, String contentType, String hostIP, long fetchBeginTimeStamp, long recordLength) throws IOException { if (fetchBeginTimeStamp <= 0) { throw new IOException("Bogus fetchBeginTimestamp: " + Long.toString(fetchBeginTimeStamp)); } return validateMetaLine(createMetaline(uri, hostIP, ArchiveUtils.get14DigitDate(fetchBeginTimeStamp), MimetypeUtils.truncate(contentType), Long.toString(recordLength))); } public String createMetaline(String uri, String hostIP, String timeStamp, String mimetype, String recordLength) { return uri + HEADER_FIELD_SEPARATOR + hostIP + HEADER_FIELD_SEPARATOR + timeStamp + HEADER_FIELD_SEPARATOR + mimetype + HEADER_FIELD_SEPARATOR + recordLength + LINE_SEPARATOR; } /** * Test that the metadata line is valid before writing. * @param metaLineStr * @throws IOException * @return The passed in metaline. */ protected String validateMetaLine(String metaLineStr) throws IOException { if (metaLineStr.length() > MAX_METADATA_LINE_LENGTH) { throw new IOException("Metadata line too long (" + metaLineStr.length() + ">" + MAX_METADATA_LINE_LENGTH + "): " + metaLineStr); } Matcher m = METADATA_LINE_PATTERN.matcher(metaLineStr); if (!m.matches()) { throw new IOException("Metadata line doesn't match expected" + " pattern: " + metaLineStr); } return metaLineStr; } }
true
true
private byte [] generateARCFileMetaData(String date) throws IOException { if(date.length()>14) { date = date.substring(0,14); } int metadataBodyLength = getMetadataLength(); // If metadata body, then the minor part of the version is '1' rather // than '0'. String metadataHeaderLinesTwoAndThree = getMetadataHeaderLinesTwoAndThree("1 " + ((metadataBodyLength > 0)? "1": "0")); int recordLength = metadataBodyLength + metadataHeaderLinesTwoAndThree.getBytes(DEFAULT_ENCODING).length; String metadataHeaderStr = ARC_MAGIC_NUMBER + getBaseFilename() + " 0.0.0.0 " + date + " text/plain " + recordLength + metadataHeaderLinesTwoAndThree; ByteArrayOutputStream metabaos = new ByteArrayOutputStream(recordLength); // Write the metadata header. metabaos.write(metadataHeaderStr.getBytes(DEFAULT_ENCODING)); // Write the metadata body, if anything to write. if (metadataBodyLength > 0) { writeMetaData(metabaos); } // Write out a LINE_SEPARATORs to end this record. metabaos.write(LINE_SEPARATOR); // Now get bytes of all just written and compress if flag set. byte [] bytes = metabaos.toByteArray(); if(isCompressed()) { // GZIP the header but catch the gzipping into a byte array so we // can add the special IA GZIP header to the product. After // manipulations, write to the output stream (The JAVA GZIP // implementation does not give access to GZIP header. It // produces a 'default' header only). We can get away w/ these // maniupulations because the GZIP 'default' header doesn't // do the 'optional' CRC'ing of the header. byte [] gzippedMetaData = GzippedInputStream.gzip(bytes); if (gzippedMetaData[3] != 0) { throw new IOException("The GZIP FLG header is unexpectedly " + " non-zero. Need to add smarter code that can deal " + " when already extant extra GZIP header fields."); } // Set the GZIP FLG header to '4' which says that the GZIP header // has extra fields. Then insert the alex {'L', 'X', '0', '0', '0, // '0'} 'extra' field. The IA GZIP header will also set byte // 9 (zero-based), the OS byte, to 3 (Unix). We'll do the same. gzippedMetaData[3] = 4; gzippedMetaData[9] = 3; byte [] assemblyBuffer = new byte[gzippedMetaData.length + ARC_GZIP_EXTRA_FIELD.length]; // '10' in the below is a pointer past the following bytes of the // GZIP header: ID1 ID2 CM FLG + MTIME(4-bytes) XFL OS. See // RFC1952 for explaination of the abbreviations just used. System.arraycopy(gzippedMetaData, 0, assemblyBuffer, 0, 10); System.arraycopy(ARC_GZIP_EXTRA_FIELD, 0, assemblyBuffer, 10, ARC_GZIP_EXTRA_FIELD.length); System.arraycopy(gzippedMetaData, 10, assemblyBuffer, 10 + ARC_GZIP_EXTRA_FIELD.length, gzippedMetaData.length - 10); bytes = assemblyBuffer; } return bytes; }
private byte [] generateARCFileMetaData(String date) throws IOException { if(date!=null && date.length()>14) { date = date.substring(0,14); } int metadataBodyLength = getMetadataLength(); // If metadata body, then the minor part of the version is '1' rather // than '0'. String metadataHeaderLinesTwoAndThree = getMetadataHeaderLinesTwoAndThree("1 " + ((metadataBodyLength > 0)? "1": "0")); int recordLength = metadataBodyLength + metadataHeaderLinesTwoAndThree.getBytes(DEFAULT_ENCODING).length; String metadataHeaderStr = ARC_MAGIC_NUMBER + getBaseFilename() + " 0.0.0.0 " + date + " text/plain " + recordLength + metadataHeaderLinesTwoAndThree; ByteArrayOutputStream metabaos = new ByteArrayOutputStream(recordLength); // Write the metadata header. metabaos.write(metadataHeaderStr.getBytes(DEFAULT_ENCODING)); // Write the metadata body, if anything to write. if (metadataBodyLength > 0) { writeMetaData(metabaos); } // Write out a LINE_SEPARATORs to end this record. metabaos.write(LINE_SEPARATOR); // Now get bytes of all just written and compress if flag set. byte [] bytes = metabaos.toByteArray(); if(isCompressed()) { // GZIP the header but catch the gzipping into a byte array so we // can add the special IA GZIP header to the product. After // manipulations, write to the output stream (The JAVA GZIP // implementation does not give access to GZIP header. It // produces a 'default' header only). We can get away w/ these // maniupulations because the GZIP 'default' header doesn't // do the 'optional' CRC'ing of the header. byte [] gzippedMetaData = GzippedInputStream.gzip(bytes); if (gzippedMetaData[3] != 0) { throw new IOException("The GZIP FLG header is unexpectedly " + " non-zero. Need to add smarter code that can deal " + " when already extant extra GZIP header fields."); } // Set the GZIP FLG header to '4' which says that the GZIP header // has extra fields. Then insert the alex {'L', 'X', '0', '0', '0, // '0'} 'extra' field. The IA GZIP header will also set byte // 9 (zero-based), the OS byte, to 3 (Unix). We'll do the same. gzippedMetaData[3] = 4; gzippedMetaData[9] = 3; byte [] assemblyBuffer = new byte[gzippedMetaData.length + ARC_GZIP_EXTRA_FIELD.length]; // '10' in the below is a pointer past the following bytes of the // GZIP header: ID1 ID2 CM FLG + MTIME(4-bytes) XFL OS. See // RFC1952 for explaination of the abbreviations just used. System.arraycopy(gzippedMetaData, 0, assemblyBuffer, 0, 10); System.arraycopy(ARC_GZIP_EXTRA_FIELD, 0, assemblyBuffer, 10, ARC_GZIP_EXTRA_FIELD.length); System.arraycopy(gzippedMetaData, 10, assemblyBuffer, 10 + ARC_GZIP_EXTRA_FIELD.length, gzippedMetaData.length - 10); bytes = assemblyBuffer; } return bytes; }
diff --git a/electro/basic/world/WorldGenStructures.java b/electro/basic/world/WorldGenStructures.java index 0748797..9afc2a3 100644 --- a/electro/basic/world/WorldGenStructures.java +++ b/electro/basic/world/WorldGenStructures.java @@ -1,617 +1,618 @@ package mods.Electrolysm.electro.basic.world; import static net.minecraftforge.common.ChestGenHooks.STRONGHOLD_CORRIDOR; import java.util.Random; import mods.Electrolysm.electro.electrolysmCore; import mods.Electrolysm.electro.biology.entity.EntityZombie_Scientist; import net.minecraft.block.Block; import net.minecraft.entity.EntityLiving; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityDispenser; import net.minecraft.util.Facing; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldManager; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.IChunkProvider; import net.minecraftforge.common.BiomeDictionary; import net.minecraftforge.common.ChestGenHooks; import net.minecraft.world.gen.feature.WorldGenMinable; import cpw.mods.fml.common.IWorldGenerator; public class WorldGenStructures implements IWorldGenerator{ @Override public void generate(Random random, int x, int z, World world,IChunkProvider chunkGenerator, IChunkProvider chunkProvider){ //Make sure it's not generating in the end or nether if(world.provider.dimensionId != 1 && world.provider.dimensionId != -1){ generateSurface(world, random, x*16, z*16); } } public static void generateSurface(World world, Random random, int x, int z){ //Science Lab Generation Code: if(world.getBiomeGenForCoords(x, z) == electrolysmCore.diseasedBiomeObj) { if(random.nextInt(100) == 1) { for(int i = 0; i < 1; i++) { int xCoord = ((x + random.nextInt(16))); int zCoord = z + random.nextInt(16); int yCoord = getSurface(world, xCoord, zCoord); int mossyStone = Block.cobblestoneMossy.blockID; int cobble = Block.cobblestone.blockID; int glow = Block.glowStone.blockID; int ironBar = Block.fenceIron.blockID; int wood = Block.wood.blockID; int grass = electrolysmCore.diseasedGrass.blockID; int stairs = Block.stairsCobblestone.blockID; int pressure = Block.pressurePlateStone.blockID; int dispenser = Block.tnt.blockID; int redstone = Block.redstoneWire.blockID; int stoneSlabHalf = 44; int stoneSlabFull = Block.stoneDoubleSlab.blockID; int desk = electrolysmCore.desk.blockID; int books = Block.bookShelf.blockID; + int dirt = Block.dirt.blockID; //Layer 2 for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { - createBlock(world, xCoord + gx, yCoord - 1, zCoord - gy, grass, 0); + createBlock(world, xCoord + gx, yCoord - 1, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { - createBlock(world, xCoord + gx, yCoord - 2, zCoord - gy, grass, 0); + createBlock(world, xCoord + gx, yCoord - 2, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { - createBlock(world, xCoord + gx, yCoord - 3, zCoord - gy, grass, 0); + createBlock(world, xCoord + gx, yCoord - 3, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { - createBlock(world, xCoord + gx, yCoord - 4, zCoord - gy, grass, 0); + createBlock(world, xCoord + gx, yCoord - 4, zCoord - gy, dirt, 0); } } createBlock(world, xCoord + 6, yCoord, zCoord - 10, dispenser, 0); createBlock(world, xCoord + 9, yCoord, zCoord - 10, dispenser, 0); //Half slabs! for(int l = 0; l <= 12; l++) { createBlock(world, xCoord, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } for(int l = 0; l <= 15; l++) { createBlock(world, xCoord + l, yCoord + 4, zCoord - 1, stoneSlabHalf, 0); } for(int l = 0; l <= 12; l++) { createBlock(world, xCoord + 15, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } createBlock(world, xCoord + 1, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 1, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); //====================== createBlock(world, xCoord + 6, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 6, cobble, 0); //Layer 3 Wood for(int WH = 1; WH <= 4 ; WH++){ createBlock(world, xCoord, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 3, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 7, wood, 0); } for(int CH = 1; CH <= 4; CH++){ //Wall 1 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 9, cobble, 0); //Wall 2 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 2, cobble, 0); //Wall 3 createBlock(world, xCoord + 14, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 12, cobble, 0); //Wall 3/4 createBlock(world, xCoord + 13, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 9, cobble, 0); } for(int W2H = 5; W2H <= 8; W2H++) { //Wall 2 createBlock(world, xCoord + 2, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + W2H, zCoord - 2, cobble, 0); } for(int C1 = 0; C1 <= 4; C1++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 5 - Width, yCoord + 5 + C1, zCoord - 9 + C1, stairs, 2); for(int Length = 0; Length <= 2; Length++) { createBlock(world, xCoord + 1 + Width, yCoord + 9, zCoord - 4 + Length, cobble, 0); } } } for(int C2 = 0; C2 <= 4; C2++) { for(int Width = 0; Width < 4; Width++) { createBlock(world, xCoord + 9 - Width, yCoord + 5 + C2, zCoord - 6 + C2, stairs, 2); } } for(int C3 = 0; C3 <= 4; C3++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 14 - Width, yCoord + 5 + C3, zCoord - 12 + C3, stairs, 2); for(int Length = 0; Length < 6; Length++) { createBlock(world, xCoord + 10 + Width, yCoord + 9, zCoord - 7 + Length, cobble, 0); } } } //Wall 1 layer 1 createBlock(world, xCoord + 1, yCoord + 5, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 8, cobble, 0); //Wall Layer 2 createBlock(world, xCoord + 1, yCoord + 6, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 7, cobble, 0); //Wall Layer 3 createBlock(world, xCoord + 1, yCoord + 7, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 6, cobble, 0); //Wall Layer 4 createBlock(world, xCoord + 1, yCoord + 8, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 5, cobble, 0); /** * =============================================================== */ //Wall 2 Layer 1 createBlock(world, xCoord + 5, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 7, cobble, 0); //Wall 2 Layer 2 createBlock(world, xCoord + 5, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 6, cobble, 0); //Wall 2 Layer 3 createBlock(world, xCoord + 5, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 5, cobble, 0); //Wall 2 Layer 4 createBlock(world, xCoord + 5, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 4, cobble, 0); //Wall 2 Layer 5 createBlock(world, xCoord + 5, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 3 Layer 1 createBlock(world, xCoord + 10, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 7, cobble, 0); //Wall 3 Layer 2 createBlock(world, xCoord + 10, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 6, cobble, 0); //Wall 3 Layer 3 createBlock(world, xCoord + 10, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 5, cobble, 0); //Wall 3 Layer 4 createBlock(world, xCoord + 10, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 4, cobble, 0); //Wall 3 Layer 5 createBlock(world, xCoord + 10, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 4 layer 1 createBlock(world, xCoord + 14, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 3, cobble, 0); //Wall 4 Layer 2 createBlock(world, xCoord + 14, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 3, cobble, 0); //Wall 4 Layer 3 createBlock(world, xCoord + 14, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 3, cobble, 0); //Wall 4 Layer 4 createBlock(world, xCoord + 14, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 3, cobble, 0); //Wall 4 Layer 5 createBlock(world, xCoord + 14, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== * Decorations!! * =============================================================== */ //Slabs above wood createBlock(world, xCoord, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); //Other createBlock(world, xCoord, yCoord, zCoord, cobble, 0); createBlock(world, xCoord, yCoord, zCoord, cobble, 0); //IronBars createBlock(world, xCoord, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 1, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 5, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 8, zCoord - 2, ironBar, 0); //Floor for(int length = 0; length < 13; length++) { createBlock(world, xCoord + 7, yCoord, zCoord - 15 + length, stoneSlabFull, 0); createBlock(world, xCoord + 8, yCoord, zCoord - 15 + length, stoneSlabFull, 0); } for(int length = 0; length < 6; length++) { createBlock(world, xCoord + 2, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 3, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 4, yCoord, zCoord - 8 + length, stoneSlabFull, 0); } for(int length = 0; length < 9; length++) { createBlock(world, xCoord + 11, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 12, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 13, yCoord, zCoord - 11 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 5, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 6, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 9, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 10, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } //Tnt Explosion //Layer 1 createBlock(world, xCoord + 7, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 8, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 7, yCoord + 1, zCoord - 10, pressure, 0); createBlock(world, xCoord + 8, yCoord + 1, zCoord - 10, pressure, 0); //Cage! createBlock(world, xCoord + 9, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); //================= createBlock(world, xCoord + 11, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 11, desk, 0); createBlock(world, xCoord + 12, yCoord + 1, zCoord - 11, books, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 11, books, 0); spawnZombie_Scientist(world, xCoord, yCoord, zCoord); } } } } private static void createBlock(World world, int xCoord, int yCoord, int zCoord, int blockID, int metadata) { world.setBlock(xCoord, yCoord, zCoord, blockID, metadata, 2); } private static int getSurface(World world, int x, int z) { int height = 256; boolean continueQ = true; while(continueQ) { if(world.isAirBlock(x, height, z)) { height = height - 1; } else { continueQ = false; } } return height + 1; } public static EntityZombie_Scientist spawnZombie_Scientist(World world, int x, int y, int z) { EntityZombie_Scientist robot = new EntityZombie_Scientist(world); EntityLiving entity = robot; robot.setLocationAndAngles(x, y, z, MathHelper .wrapAngleTo180_float(world.rand.nextFloat() * 360.0F), 0.0F); entity.rotationYawHead = entity.rotationYaw; entity.renderYawOffset = entity.rotationYaw; entity.initCreature(); world.spawnEntityInWorld(robot); entity.playLivingSound(); return robot; } }
false
true
public static void generateSurface(World world, Random random, int x, int z){ //Science Lab Generation Code: if(world.getBiomeGenForCoords(x, z) == electrolysmCore.diseasedBiomeObj) { if(random.nextInt(100) == 1) { for(int i = 0; i < 1; i++) { int xCoord = ((x + random.nextInt(16))); int zCoord = z + random.nextInt(16); int yCoord = getSurface(world, xCoord, zCoord); int mossyStone = Block.cobblestoneMossy.blockID; int cobble = Block.cobblestone.blockID; int glow = Block.glowStone.blockID; int ironBar = Block.fenceIron.blockID; int wood = Block.wood.blockID; int grass = electrolysmCore.diseasedGrass.blockID; int stairs = Block.stairsCobblestone.blockID; int pressure = Block.pressurePlateStone.blockID; int dispenser = Block.tnt.blockID; int redstone = Block.redstoneWire.blockID; int stoneSlabHalf = 44; int stoneSlabFull = Block.stoneDoubleSlab.blockID; int desk = electrolysmCore.desk.blockID; int books = Block.bookShelf.blockID; //Layer 2 for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 1, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 2, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 3, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 4, zCoord - gy, grass, 0); } } createBlock(world, xCoord + 6, yCoord, zCoord - 10, dispenser, 0); createBlock(world, xCoord + 9, yCoord, zCoord - 10, dispenser, 0); //Half slabs! for(int l = 0; l <= 12; l++) { createBlock(world, xCoord, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } for(int l = 0; l <= 15; l++) { createBlock(world, xCoord + l, yCoord + 4, zCoord - 1, stoneSlabHalf, 0); } for(int l = 0; l <= 12; l++) { createBlock(world, xCoord + 15, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } createBlock(world, xCoord + 1, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 1, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); //====================== createBlock(world, xCoord + 6, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 6, cobble, 0); //Layer 3 Wood for(int WH = 1; WH <= 4 ; WH++){ createBlock(world, xCoord, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 3, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 7, wood, 0); } for(int CH = 1; CH <= 4; CH++){ //Wall 1 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 9, cobble, 0); //Wall 2 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 2, cobble, 0); //Wall 3 createBlock(world, xCoord + 14, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 12, cobble, 0); //Wall 3/4 createBlock(world, xCoord + 13, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 9, cobble, 0); } for(int W2H = 5; W2H <= 8; W2H++) { //Wall 2 createBlock(world, xCoord + 2, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + W2H, zCoord - 2, cobble, 0); } for(int C1 = 0; C1 <= 4; C1++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 5 - Width, yCoord + 5 + C1, zCoord - 9 + C1, stairs, 2); for(int Length = 0; Length <= 2; Length++) { createBlock(world, xCoord + 1 + Width, yCoord + 9, zCoord - 4 + Length, cobble, 0); } } } for(int C2 = 0; C2 <= 4; C2++) { for(int Width = 0; Width < 4; Width++) { createBlock(world, xCoord + 9 - Width, yCoord + 5 + C2, zCoord - 6 + C2, stairs, 2); } } for(int C3 = 0; C3 <= 4; C3++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 14 - Width, yCoord + 5 + C3, zCoord - 12 + C3, stairs, 2); for(int Length = 0; Length < 6; Length++) { createBlock(world, xCoord + 10 + Width, yCoord + 9, zCoord - 7 + Length, cobble, 0); } } } //Wall 1 layer 1 createBlock(world, xCoord + 1, yCoord + 5, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 8, cobble, 0); //Wall Layer 2 createBlock(world, xCoord + 1, yCoord + 6, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 7, cobble, 0); //Wall Layer 3 createBlock(world, xCoord + 1, yCoord + 7, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 6, cobble, 0); //Wall Layer 4 createBlock(world, xCoord + 1, yCoord + 8, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 5, cobble, 0); /** * =============================================================== */ //Wall 2 Layer 1 createBlock(world, xCoord + 5, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 7, cobble, 0); //Wall 2 Layer 2 createBlock(world, xCoord + 5, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 6, cobble, 0); //Wall 2 Layer 3 createBlock(world, xCoord + 5, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 5, cobble, 0); //Wall 2 Layer 4 createBlock(world, xCoord + 5, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 4, cobble, 0); //Wall 2 Layer 5 createBlock(world, xCoord + 5, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 3 Layer 1 createBlock(world, xCoord + 10, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 7, cobble, 0); //Wall 3 Layer 2 createBlock(world, xCoord + 10, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 6, cobble, 0); //Wall 3 Layer 3 createBlock(world, xCoord + 10, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 5, cobble, 0); //Wall 3 Layer 4 createBlock(world, xCoord + 10, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 4, cobble, 0); //Wall 3 Layer 5 createBlock(world, xCoord + 10, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 4 layer 1 createBlock(world, xCoord + 14, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 3, cobble, 0); //Wall 4 Layer 2 createBlock(world, xCoord + 14, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 3, cobble, 0); //Wall 4 Layer 3 createBlock(world, xCoord + 14, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 3, cobble, 0); //Wall 4 Layer 4 createBlock(world, xCoord + 14, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 3, cobble, 0); //Wall 4 Layer 5 createBlock(world, xCoord + 14, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== * Decorations!! * =============================================================== */ //Slabs above wood createBlock(world, xCoord, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); //Other createBlock(world, xCoord, yCoord, zCoord, cobble, 0); createBlock(world, xCoord, yCoord, zCoord, cobble, 0); //IronBars createBlock(world, xCoord, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 1, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 5, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 8, zCoord - 2, ironBar, 0); //Floor for(int length = 0; length < 13; length++) { createBlock(world, xCoord + 7, yCoord, zCoord - 15 + length, stoneSlabFull, 0); createBlock(world, xCoord + 8, yCoord, zCoord - 15 + length, stoneSlabFull, 0); } for(int length = 0; length < 6; length++) { createBlock(world, xCoord + 2, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 3, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 4, yCoord, zCoord - 8 + length, stoneSlabFull, 0); } for(int length = 0; length < 9; length++) { createBlock(world, xCoord + 11, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 12, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 13, yCoord, zCoord - 11 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 5, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 6, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 9, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 10, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } //Tnt Explosion //Layer 1 createBlock(world, xCoord + 7, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 8, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 7, yCoord + 1, zCoord - 10, pressure, 0); createBlock(world, xCoord + 8, yCoord + 1, zCoord - 10, pressure, 0); //Cage! createBlock(world, xCoord + 9, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); //================= createBlock(world, xCoord + 11, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 11, desk, 0); createBlock(world, xCoord + 12, yCoord + 1, zCoord - 11, books, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 11, books, 0); spawnZombie_Scientist(world, xCoord, yCoord, zCoord); } } } }
public static void generateSurface(World world, Random random, int x, int z){ //Science Lab Generation Code: if(world.getBiomeGenForCoords(x, z) == electrolysmCore.diseasedBiomeObj) { if(random.nextInt(100) == 1) { for(int i = 0; i < 1; i++) { int xCoord = ((x + random.nextInt(16))); int zCoord = z + random.nextInt(16); int yCoord = getSurface(world, xCoord, zCoord); int mossyStone = Block.cobblestoneMossy.blockID; int cobble = Block.cobblestone.blockID; int glow = Block.glowStone.blockID; int ironBar = Block.fenceIron.blockID; int wood = Block.wood.blockID; int grass = electrolysmCore.diseasedGrass.blockID; int stairs = Block.stairsCobblestone.blockID; int pressure = Block.pressurePlateStone.blockID; int dispenser = Block.tnt.blockID; int redstone = Block.redstoneWire.blockID; int stoneSlabHalf = 44; int stoneSlabFull = Block.stoneDoubleSlab.blockID; int desk = electrolysmCore.desk.blockID; int books = Block.bookShelf.blockID; int dirt = Block.dirt.blockID; //Layer 2 for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord, zCoord - gy, grass, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 1, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 2, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 3, zCoord - gy, dirt, 0); } } for(int gx = 0; gx < 16; gx++) { for(int gy = 0; gy < 16; gy++) { createBlock(world, xCoord + gx, yCoord - 4, zCoord - gy, dirt, 0); } } createBlock(world, xCoord + 6, yCoord, zCoord - 10, dispenser, 0); createBlock(world, xCoord + 9, yCoord, zCoord - 10, dispenser, 0); //Half slabs! for(int l = 0; l <= 12; l++) { createBlock(world, xCoord, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } for(int l = 0; l <= 15; l++) { createBlock(world, xCoord + l, yCoord + 4, zCoord - 1, stoneSlabHalf, 0); } for(int l = 0; l <= 12; l++) { createBlock(world, xCoord + 15, yCoord + 4, zCoord - 13 + l, stoneSlabHalf, 0); } createBlock(world, xCoord + 1, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 1, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 2, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 7, stoneSlabHalf, 0); //====================== createBlock(world, xCoord + 6, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 11, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 12, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 9, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 4, zCoord - 8, stoneSlabHalf, 0); createBlock(world, xCoord + 8, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 7, yCoord + 4, zCoord - 6, cobble, 0); //Layer 3 Wood for(int WH = 1; WH <= 4 ; WH++){ createBlock(world, xCoord, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 13, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 4, wood, 0); createBlock(world, xCoord + 15, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 12, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 3, yCoord + WH, zCoord - 1, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 9, yCoord + WH, zCoord - 7, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 10, wood, 0); createBlock(world, xCoord + 6, yCoord + WH, zCoord - 7, wood, 0); } for(int CH = 1; CH <= 4; CH++){ //Wall 1 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 1, yCoord + CH, zCoord - 9, cobble, 0); //Wall 2 createBlock(world, xCoord + 1, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + CH, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 2, cobble, 0); //Wall 3 createBlock(world, xCoord + 14, yCoord + CH, zCoord - 3, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + CH, zCoord - 12, cobble, 0); //Wall 3/4 createBlock(world, xCoord + 13, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 12, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 11, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 9, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 6, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 4, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 3, yCoord + CH, zCoord - 9, cobble, 0); createBlock(world, xCoord + 2, yCoord + CH, zCoord - 9, cobble, 0); } for(int W2H = 5; W2H <= 8; W2H++) { //Wall 2 createBlock(world, xCoord + 2, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 3, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 4, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 5, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 6, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 7, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 8, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 9, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 10, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 11, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 12, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 13, yCoord + W2H, zCoord - 2, cobble, 0); createBlock(world, xCoord + 14, yCoord + W2H, zCoord - 2, cobble, 0); } for(int C1 = 0; C1 <= 4; C1++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 5 - Width, yCoord + 5 + C1, zCoord - 9 + C1, stairs, 2); for(int Length = 0; Length <= 2; Length++) { createBlock(world, xCoord + 1 + Width, yCoord + 9, zCoord - 4 + Length, cobble, 0); } } } for(int C2 = 0; C2 <= 4; C2++) { for(int Width = 0; Width < 4; Width++) { createBlock(world, xCoord + 9 - Width, yCoord + 5 + C2, zCoord - 6 + C2, stairs, 2); } } for(int C3 = 0; C3 <= 4; C3++) { for(int Width = 0; Width < 5; Width++) { createBlock(world, xCoord + 14 - Width, yCoord + 5 + C3, zCoord - 12 + C3, stairs, 2); for(int Length = 0; Length < 6; Length++) { createBlock(world, xCoord + 10 + Width, yCoord + 9, zCoord - 7 + Length, cobble, 0); } } } //Wall 1 layer 1 createBlock(world, xCoord + 1, yCoord + 5, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 1, yCoord + 5, zCoord - 8, cobble, 0); //Wall Layer 2 createBlock(world, xCoord + 1, yCoord + 6, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 1, yCoord + 6, zCoord - 7, cobble, 0); //Wall Layer 3 createBlock(world, xCoord + 1, yCoord + 7, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 1, yCoord + 7, zCoord - 6, cobble, 0); //Wall Layer 4 createBlock(world, xCoord + 1, yCoord + 8, zCoord - 2, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 3, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 1, yCoord + 8, zCoord - 5, cobble, 0); /** * =============================================================== */ //Wall 2 Layer 1 createBlock(world, xCoord + 5, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 4, zCoord - 7, cobble, 0); //Wall 2 Layer 2 createBlock(world, xCoord + 5, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 5, zCoord - 6, cobble, 0); //Wall 2 Layer 3 createBlock(world, xCoord + 5, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 6, zCoord - 5, cobble, 0); //Wall 2 Layer 4 createBlock(world, xCoord + 5, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 7, zCoord - 4, cobble, 0); //Wall 2 Layer 5 createBlock(world, xCoord + 5, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 5, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 3 Layer 1 createBlock(world, xCoord + 10, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 7, cobble, 0); //Wall 3 Layer 2 createBlock(world, xCoord + 10, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 5, zCoord - 6, cobble, 0); //Wall 3 Layer 3 createBlock(world, xCoord + 10, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 6, zCoord - 5, cobble, 0); //Wall 3 Layer 4 createBlock(world, xCoord + 10, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 7, zCoord - 4, cobble, 0); //Wall 3 Layer 5 createBlock(world, xCoord + 10, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 10, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== */ //Wall 4 layer 1 createBlock(world, xCoord + 14, yCoord + 4, zCoord - 12, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 4, zCoord - 3, cobble, 0); //Wall 4 Layer 2 createBlock(world, xCoord + 14, yCoord + 5, zCoord - 11, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 5, zCoord - 3, cobble, 0); //Wall 4 Layer 3 createBlock(world, xCoord + 14, yCoord + 6, zCoord - 10, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 6, zCoord - 3, cobble, 0); //Wall 4 Layer 4 createBlock(world, xCoord + 14, yCoord + 7, zCoord - 9, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 7, zCoord - 3, cobble, 0); //Wall 4 Layer 5 createBlock(world, xCoord + 14, yCoord + 8, zCoord - 8, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 7, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 6, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 5, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 4, cobble, 0); createBlock(world, xCoord + 14, yCoord + 8, zCoord - 3, cobble, 0); /** * =============================================================== * Decorations!! * =============================================================== */ //Slabs above wood createBlock(world, xCoord, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 13, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 15, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 3, yCoord + 5, zCoord - 1, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 9, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 10, stoneSlabHalf, 0); createBlock(world, xCoord + 6, yCoord + 5, zCoord - 7, stoneSlabHalf, 0); //Other createBlock(world, xCoord, yCoord, zCoord, cobble, 0); createBlock(world, xCoord, yCoord, zCoord, cobble, 0); //IronBars createBlock(world, xCoord, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 1, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 5, yCoord + 1, zCoord - 13, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 11, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 1, zCoord - 12, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 2, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 2, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 4, yCoord + 3, zCoord - 9, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 3, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 6, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 8, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 7, zCoord - 2, ironBar, 0); createBlock(world, xCoord + 12, yCoord + 8, zCoord - 2, ironBar, 0); //Floor for(int length = 0; length < 13; length++) { createBlock(world, xCoord + 7, yCoord, zCoord - 15 + length, stoneSlabFull, 0); createBlock(world, xCoord + 8, yCoord, zCoord - 15 + length, stoneSlabFull, 0); } for(int length = 0; length < 6; length++) { createBlock(world, xCoord + 2, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 3, yCoord, zCoord - 8 + length, stoneSlabFull, 0); createBlock(world, xCoord + 4, yCoord, zCoord - 8 + length, stoneSlabFull, 0); } for(int length = 0; length < 9; length++) { createBlock(world, xCoord + 11, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 12, yCoord, zCoord - 11 + length, stoneSlabFull, 0); createBlock(world, xCoord + 13, yCoord, zCoord - 11 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 5, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 6, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } for(int length = 0; length < 3; length++) { createBlock(world, xCoord + 9, yCoord, zCoord - 5 + length, stoneSlabFull, 0); createBlock(world, xCoord + 10, yCoord, zCoord - 5 + length, stoneSlabFull, 0); } //Tnt Explosion //Layer 1 createBlock(world, xCoord + 7, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 8, yCoord - 1, zCoord - 10, redstone, 0); createBlock(world, xCoord + 7, yCoord + 1, zCoord - 10, pressure, 0); createBlock(world, xCoord + 8, yCoord + 1, zCoord - 10, pressure, 0); //Cage! createBlock(world, xCoord + 9, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 3, ironBar, 0); createBlock(world, xCoord + 9, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 3, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 4, ironBar, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 3, stoneSlabHalf, 0); createBlock(world, xCoord + 10, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 4, stoneSlabHalf, 0); //================= createBlock(world, xCoord + 11, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 2, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 13, yCoord + 3, zCoord - 6, ironBar, 0); createBlock(world, xCoord + 11, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 12, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 13, yCoord + 4, zCoord - 6, stoneSlabHalf, 0); createBlock(world, xCoord + 4, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 3, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 2, yCoord + 1, zCoord - 8, desk, 0); createBlock(world, xCoord + 13, yCoord + 1, zCoord - 11, desk, 0); createBlock(world, xCoord + 12, yCoord + 1, zCoord - 11, books, 0); createBlock(world, xCoord + 11, yCoord + 1, zCoord - 11, books, 0); spawnZombie_Scientist(world, xCoord, yCoord, zCoord); } } } }
diff --git a/src/crawl/DyttCrawler.java b/src/crawl/DyttCrawler.java index cc00aed..f1bb60e 100644 --- a/src/crawl/DyttCrawler.java +++ b/src/crawl/DyttCrawler.java @@ -1,196 +1,196 @@ package crawl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import model.Movie_Info; import util.BasicUtil; import util.LogUtil; import witer.DBWriter; import witer.ImageWriter; public class DyttCrawler extends BaseCrawler{ private static final String ROOT_URL = "http://www.dytt8.net/"; public static void main(String[] args) { DyttCrawler dc = new DyttCrawler(); dc.begin(); } public DyttCrawler(){ movie_src = "Dytt"; CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/china/list_4_%d.html"); CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/rihan/list_6_%d.html"); CRAWLABLE_URLS.add("http://www.dytt8.net/html/gndy/oumei/list_7_%d.html"); } protected void begin(){ super.begin(); } /** * 获取指定网页内容 * @param surl :网址 * @return 网页源代码 */ private String getContent(String surl){ StringBuffer sb = new StringBuffer(); try { URL url = new URL(surl); URLConnection urlconnection = url.openConnection(); urlconnection.addRequestProperty("User-Agent", AGENT); urlconnection.setConnectTimeout(TIME_OUT); InputStream is = url.openStream(); BufferedReader bReader = new BufferedReader(new InputStreamReader(is, "GBK")); String rLine = null; while((rLine=bReader.readLine())!=null){ sb.append(rLine); sb.append("/r/n"); } }catch (IOException e) { } return sb.toString(); } /** * 获取当前最大页 * @return MAX_PAGE */ protected boolean getMaxPage(){ for(int i = 0; i < CRAWLABLE_URLS.size() ; i ++){ String url = CRAWLABLE_URLS.get(i); String content = getContent(String.format(url, 1)); String regex = "共\\d+页/\\d+条记录"; Pattern pt = Pattern.compile(regex); Matcher mt = pt.matcher(content); if(mt.find()){ String str = mt.group(); str = str.substring(1, str.indexOf("/") - 1); try { int last_page = Integer.parseInt(str); CRAWLABLE_MAX_PAGE.add(i, last_page); System.out.println("last page found: " + last_page); } catch (NumberFormatException e) { LogUtil.getInstance().write(this.getClass().getName() + " [error] getting max page at URL : " + url); e.printStackTrace(); } } } return true; } private final static String MOVIE_URL_PATTERN = "<a href=\"/html/gndy/[a-zA-Z]+/[0-9]{1,}/[0-9]{1,}.html\""; private final static String HAIBAO_PATTERN = "<img[^<]*src=\"http.*?(jpg|gif|JPG|GIF)\""; private final static String PIANMING_PATTERN = "(◎译  名|◎片  名|◎中 文 名|◎英 文 名|◎译   名|◎片   名)[^<]*<br />"; private final static String XIAZAIMING_PATTERN = "(rmvb|avi|mp4|mkv|RMVB|AVI|PM4|MKV)\">[^<]*(rmvb|avi|mp4|mkv|RMVB|AVI|PM4|MKV)"; private final static String[] MOVIE_PATTERNS = {HAIBAO_PATTERN, PIANMING_PATTERN, XIAZAIMING_PATTERN}; /** * 获取电影信息 * @param id : 当前线程ID * @param sUrl : 网页网址 * @return 当前页获取电影数量 */ protected int crawlMovies(int id, String sUrl){ String s = getContent(sUrl); int movie_counter = 0; ArrayList<Movie_Info> movie_list = new ArrayList<Movie_Info>(); Pattern pt = Pattern.compile(MOVIE_URL_PATTERN); Matcher mt = pt.matcher(s); while(mt.find()){ String str = mt.group(); str =ROOT_URL + str.substring(10, str.length() - 1); Movie_Info movie_info = new Movie_Info(); if(DBWriter.getInstance().ifCrawled(str)){ continue; } String content = getContent(str); for(int i = 0; i < MOVIE_PATTERNS.length; i ++){ parsePattern(movie_info, content, i); } movie_counter ++; if(movie_info.getMovieName() != null){ ImageWriter.getInstance().addMovieList(movie_info.clone()); } movie_list.add(movie_info); } DBWriter.getInstance().addMovieList(movie_list); return movie_counter; } /** * 按照正则表达式解析电影信息 * @param movie_info : 电影类 * @param s : 网页源代码 * @param n : 当前正则表达式. 0 : HAIBAO_PATTERN; 1 : PIANMING_PATTERN; 2 : XIAZAIMING_PATTERN. */ private void parsePattern(Movie_Info movie_info, String s, int n){ Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]); Matcher mt = pt.matcher(s); while (mt.find()) { //先去除一些特殊的符号 String str = mt.group(); str = BasicUtil.formatString(str); //用正则表达式进行匹配,通过字符串处理找到相应内容 switch(n){ case 0: str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1); if(!movie_info.hasHaiBaoPath()){ str = str.trim(); movie_info.setHaiBaoPath(str); } break; case 1: if(str.startsWith("◎译  名")){ - str = str.substring(6, str.length() - 6); + str = str.substring(6, str.lastIndexOf("<")); }else if(str.startsWith("◎片  名")){ - str = str.substring(6, str.length() - 6); + str = str.substring(6, str.lastIndexOf("<")); }else if(str.startsWith("◎中 文 名")){ - str = str.substring(7, str.length() - 7); + str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎英 文 名")){ - str = str.substring(7, str.length() - 7); + str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎译   名")){ - str = str.substring(7, str.length() - 7); + str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎片   名")){ - str = str.substring(7, str.length() - 7); + str = str.substring(7, str.lastIndexOf("<")); } while(str.startsWith(" ")){ - str = str.substring(1, str.length() - 1); + str = str.substring(1, str.length()); } StringTokenizer st = new StringTokenizer(str, "/"); if(st.countTokens() == 0){ movie_info.setMovieName(str.trim()); } while(st.hasMoreElements()){ String tmp = st.nextToken().trim(); if(!movie_info.hasName()){ movie_info.setMovieName(tmp); }else{ movie_info.addName(tmp); } } break; case 2: str = str.substring(str.indexOf("\">") + 2).trim(); movie_info.addDownLoadLinks(str); break; default:break; } } } }
false
true
private void parsePattern(Movie_Info movie_info, String s, int n){ Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]); Matcher mt = pt.matcher(s); while (mt.find()) { //先去除一些特殊的符号 String str = mt.group(); str = BasicUtil.formatString(str); //用正则表达式进行匹配,通过字符串处理找到相应内容 switch(n){ case 0: str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1); if(!movie_info.hasHaiBaoPath()){ str = str.trim(); movie_info.setHaiBaoPath(str); } break; case 1: if(str.startsWith("◎译  名")){ str = str.substring(6, str.length() - 6); }else if(str.startsWith("◎片  名")){ str = str.substring(6, str.length() - 6); }else if(str.startsWith("◎中 文 名")){ str = str.substring(7, str.length() - 7); }else if(str.startsWith("◎英 文 名")){ str = str.substring(7, str.length() - 7); }else if(str.startsWith("◎译   名")){ str = str.substring(7, str.length() - 7); }else if(str.startsWith("◎片   名")){ str = str.substring(7, str.length() - 7); } while(str.startsWith(" ")){ str = str.substring(1, str.length() - 1); } StringTokenizer st = new StringTokenizer(str, "/"); if(st.countTokens() == 0){ movie_info.setMovieName(str.trim()); } while(st.hasMoreElements()){ String tmp = st.nextToken().trim(); if(!movie_info.hasName()){ movie_info.setMovieName(tmp); }else{ movie_info.addName(tmp); } } break; case 2: str = str.substring(str.indexOf("\">") + 2).trim(); movie_info.addDownLoadLinks(str); break; default:break; } } }
private void parsePattern(Movie_Info movie_info, String s, int n){ Pattern pt = Pattern.compile(MOVIE_PATTERNS[n]); Matcher mt = pt.matcher(s); while (mt.find()) { //先去除一些特殊的符号 String str = mt.group(); str = BasicUtil.formatString(str); //用正则表达式进行匹配,通过字符串处理找到相应内容 switch(n){ case 0: str = str.substring(str.indexOf("src=\"") + 5, str.length() - 1); if(!movie_info.hasHaiBaoPath()){ str = str.trim(); movie_info.setHaiBaoPath(str); } break; case 1: if(str.startsWith("◎译  名")){ str = str.substring(6, str.lastIndexOf("<")); }else if(str.startsWith("◎片  名")){ str = str.substring(6, str.lastIndexOf("<")); }else if(str.startsWith("◎中 文 名")){ str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎英 文 名")){ str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎译   名")){ str = str.substring(7, str.lastIndexOf("<")); }else if(str.startsWith("◎片   名")){ str = str.substring(7, str.lastIndexOf("<")); } while(str.startsWith(" ")){ str = str.substring(1, str.length()); } StringTokenizer st = new StringTokenizer(str, "/"); if(st.countTokens() == 0){ movie_info.setMovieName(str.trim()); } while(st.hasMoreElements()){ String tmp = st.nextToken().trim(); if(!movie_info.hasName()){ movie_info.setMovieName(tmp); }else{ movie_info.addName(tmp); } } break; case 2: str = str.substring(str.indexOf("\">") + 2).trim(); movie_info.addDownLoadLinks(str); break; default:break; } } }
diff --git a/src/main/java/net/sf/testium/executor/general/SetVariable.java b/src/main/java/net/sf/testium/executor/general/SetVariable.java index 02d7f34..aef4d43 100644 --- a/src/main/java/net/sf/testium/executor/general/SetVariable.java +++ b/src/main/java/net/sf/testium/executor/general/SetVariable.java @@ -1,87 +1,87 @@ package net.sf.testium.executor.general; import java.util.ArrayList; import net.sf.testium.systemundertest.SutInterface; import org.testtoolinterfaces.testresult.TestStepCommandResult; import org.testtoolinterfaces.testsuite.ParameterArrayList; import org.testtoolinterfaces.testsuite.TestSuiteException; import org.testtoolinterfaces.utils.RunTimeData; import org.testtoolinterfaces.utils.RunTimeVariable; public class SetVariable extends GenericCommandExecutor { private static final String COMMAND = "setVariable"; private static final String PAR_NAME = "name"; private static final String PAR_VALUE = "value"; private static final String PAR_TYPE = "type"; private static final String PAR_SCOPE = "scope"; // private static final String TYPE_STRING = "String"; private static final String TYPE_INT = "Int"; private static final String TYPE_INTEGER = "Integer"; private static final String SCOPE_CURRENT = "current"; private static final String SCOPE_PARENT = "parent"; private static final SpecifiedParameter PARSPEC_NAME = new SpecifiedParameter ( PAR_NAME, String.class, false, true, false, false ); private static final SpecifiedParameter PARSPEC_VALUE = new SpecifiedParameter ( PAR_VALUE, String.class, false, true, true, true ); private static final SpecifiedParameter PARSPEC_TYPE = new SpecifiedParameter ( PAR_TYPE, String.class, true, true, false, false ) .setDefaultValue("String"); private static final SpecifiedParameter PARSPEC_SCOPE = new SpecifiedParameter ( PAR_SCOPE, String.class, true, true, true, false ) .setDefaultValue(SCOPE_CURRENT); public SetVariable(SutInterface anInterface) { super(COMMAND, anInterface, new ArrayList<SpecifiedParameter>() ); this.addParamSpec(PARSPEC_NAME); this.addParamSpec(PARSPEC_VALUE); this.addParamSpec(PARSPEC_TYPE); this.addParamSpec(PARSPEC_SCOPE); } @Override protected void doExecute(RunTimeData aVariables, ParameterArrayList parameters, TestStepCommandResult result) throws Exception { String variableName = (String) this.obtainValue(aVariables, parameters, PARSPEC_NAME); String valueString = (String) this.obtainValue(aVariables, parameters, PARSPEC_VALUE); String scope = (String) this.obtainOptionalValue(aVariables, parameters, PARSPEC_SCOPE); - String valueType = (String) this.obtainValue(aVariables, parameters, PARSPEC_TYPE); + String valueType = (String) this.obtainOptionalValue(aVariables, parameters, PARSPEC_TYPE); RunTimeVariable rtVariable; if ( valueType.equalsIgnoreCase(TYPE_INT) || valueType.equalsIgnoreCase(TYPE_INTEGER) ) { rtVariable = new RunTimeVariable( variableName, new Integer( valueString ) ); } else { rtVariable = new RunTimeVariable( variableName, valueString ); } // Class<?> type; // try // { // type = Class.forName("java.lang." + valueType); // } catch (ClassNotFoundException e) // { // throw new TestSuiteException("No class \"" + valueType + "\" known for variable \"" + variableName + "\"" ); // } result.setDisplayName( this.toString() + " " + variableName + "=\"" + rtVariable.getValue().toString() + "\"" ); if ( scope.equalsIgnoreCase(SCOPE_PARENT) ) { RunTimeData parentScope = aVariables.getParentScope(); if ( parentScope == null ) { throw new TestSuiteException( "There is no parent-scope, so the variable can't be added." ); } parentScope.add(rtVariable); } else { aVariables.add(rtVariable); } } }
true
true
protected void doExecute(RunTimeData aVariables, ParameterArrayList parameters, TestStepCommandResult result) throws Exception { String variableName = (String) this.obtainValue(aVariables, parameters, PARSPEC_NAME); String valueString = (String) this.obtainValue(aVariables, parameters, PARSPEC_VALUE); String scope = (String) this.obtainOptionalValue(aVariables, parameters, PARSPEC_SCOPE); String valueType = (String) this.obtainValue(aVariables, parameters, PARSPEC_TYPE); RunTimeVariable rtVariable; if ( valueType.equalsIgnoreCase(TYPE_INT) || valueType.equalsIgnoreCase(TYPE_INTEGER) ) { rtVariable = new RunTimeVariable( variableName, new Integer( valueString ) ); } else { rtVariable = new RunTimeVariable( variableName, valueString ); } // Class<?> type; // try // { // type = Class.forName("java.lang." + valueType); // } catch (ClassNotFoundException e) // { // throw new TestSuiteException("No class \"" + valueType + "\" known for variable \"" + variableName + "\"" ); // } result.setDisplayName( this.toString() + " " + variableName + "=\"" + rtVariable.getValue().toString() + "\"" ); if ( scope.equalsIgnoreCase(SCOPE_PARENT) ) { RunTimeData parentScope = aVariables.getParentScope(); if ( parentScope == null ) { throw new TestSuiteException( "There is no parent-scope, so the variable can't be added." ); } parentScope.add(rtVariable); } else { aVariables.add(rtVariable); } }
protected void doExecute(RunTimeData aVariables, ParameterArrayList parameters, TestStepCommandResult result) throws Exception { String variableName = (String) this.obtainValue(aVariables, parameters, PARSPEC_NAME); String valueString = (String) this.obtainValue(aVariables, parameters, PARSPEC_VALUE); String scope = (String) this.obtainOptionalValue(aVariables, parameters, PARSPEC_SCOPE); String valueType = (String) this.obtainOptionalValue(aVariables, parameters, PARSPEC_TYPE); RunTimeVariable rtVariable; if ( valueType.equalsIgnoreCase(TYPE_INT) || valueType.equalsIgnoreCase(TYPE_INTEGER) ) { rtVariable = new RunTimeVariable( variableName, new Integer( valueString ) ); } else { rtVariable = new RunTimeVariable( variableName, valueString ); } // Class<?> type; // try // { // type = Class.forName("java.lang." + valueType); // } catch (ClassNotFoundException e) // { // throw new TestSuiteException("No class \"" + valueType + "\" known for variable \"" + variableName + "\"" ); // } result.setDisplayName( this.toString() + " " + variableName + "=\"" + rtVariable.getValue().toString() + "\"" ); if ( scope.equalsIgnoreCase(SCOPE_PARENT) ) { RunTimeData parentScope = aVariables.getParentScope(); if ( parentScope == null ) { throw new TestSuiteException( "There is no parent-scope, so the variable can't be added." ); } parentScope.add(rtVariable); } else { aVariables.add(rtVariable); } }
diff --git a/src/main/java/org/iplantc/iptol/server/FileUploadServlet.java b/src/main/java/org/iplantc/iptol/server/FileUploadServlet.java index 0114269e..482215d2 100644 --- a/src/main/java/org/iplantc/iptol/server/FileUploadServlet.java +++ b/src/main/java/org/iplantc/iptol/server/FileUploadServlet.java @@ -1,102 +1,103 @@ package org.iplantc.iptol.server; import gwtupload.server.UploadAction; import gwtupload.server.exceptions.UploadActionException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.mule.MuleServer; /** * A class to accept files from the client. This class extends the UploadAction * class provided by the GWT Upload library * * @author sriram * */ public class FileUploadServlet extends UploadAction { public static final long MAX_FILE_SIZE = 3145728; public static final int UPLOAD_DELAY = 0; /** * This method is automatically called for file upload request */ private static final long serialVersionUID = 1L; @SuppressWarnings("unused") private FileUploadedEvent fileUploadedEvent; @SuppressWarnings("unchecked") @Override public String executeAction(HttpServletRequest request, List<FileItem> fileItems) throws UploadActionException { this.maxSize = MAX_FILE_SIZE; this.uploadDelay = UPLOAD_DELAY; String filetype = null; Map map = new HashMap(); List data_list = new ArrayList(); Map root = new HashMap(); JSONObject json = null; for (FileItem item : fileItems) { if (!item.isFormField()) { try { - String contents = item.getString(); + String contents = new String(item.get()); + System.out.println("contents==>" + contents); fileUploadedEvent.fileUploaded(contents, item.getName()); map.put("File Name", item.getName()); map.put("Uploaded Date/Time", (new Date()).toString()); map.put("Label", item.getName()); data_list.add(map); JSONArray jsonArray = JSONArray.fromObject(data_list); root.put("data", jsonArray); json = JSONObject.fromObject(root); System.out.println("filename ==>" + item.getName() + " size ==>" + item.getSize()); } catch (Exception e) { e.printStackTrace(); throw new UploadActionException("Upload failed!"); } } else { if (item.getFieldName().equals("file-type")) { filetype = new String(item.get()); } } } // remove files from session. this avoids duplicate submissions removeSessionFileItems(request, false); if (json != null) return json.toString(); else return null; } @Override public void init(ServletConfig config) throws ServletException { fileUploadedEvent = (FileUploadedEvent) MuleServer.getMuleContext() .getRegistry().lookupObject("fileUploadedEvent"); super.init(config); } public void setFileUploadedEvent(FileUploadedEvent fileUploadedEvent) { this.fileUploadedEvent = fileUploadedEvent; } }
true
true
public String executeAction(HttpServletRequest request, List<FileItem> fileItems) throws UploadActionException { this.maxSize = MAX_FILE_SIZE; this.uploadDelay = UPLOAD_DELAY; String filetype = null; Map map = new HashMap(); List data_list = new ArrayList(); Map root = new HashMap(); JSONObject json = null; for (FileItem item : fileItems) { if (!item.isFormField()) { try { String contents = item.getString(); fileUploadedEvent.fileUploaded(contents, item.getName()); map.put("File Name", item.getName()); map.put("Uploaded Date/Time", (new Date()).toString()); map.put("Label", item.getName()); data_list.add(map); JSONArray jsonArray = JSONArray.fromObject(data_list); root.put("data", jsonArray); json = JSONObject.fromObject(root); System.out.println("filename ==>" + item.getName() + " size ==>" + item.getSize()); } catch (Exception e) { e.printStackTrace(); throw new UploadActionException("Upload failed!"); } } else { if (item.getFieldName().equals("file-type")) { filetype = new String(item.get()); } } } // remove files from session. this avoids duplicate submissions removeSessionFileItems(request, false); if (json != null) return json.toString(); else return null; }
public String executeAction(HttpServletRequest request, List<FileItem> fileItems) throws UploadActionException { this.maxSize = MAX_FILE_SIZE; this.uploadDelay = UPLOAD_DELAY; String filetype = null; Map map = new HashMap(); List data_list = new ArrayList(); Map root = new HashMap(); JSONObject json = null; for (FileItem item : fileItems) { if (!item.isFormField()) { try { String contents = new String(item.get()); System.out.println("contents==>" + contents); fileUploadedEvent.fileUploaded(contents, item.getName()); map.put("File Name", item.getName()); map.put("Uploaded Date/Time", (new Date()).toString()); map.put("Label", item.getName()); data_list.add(map); JSONArray jsonArray = JSONArray.fromObject(data_list); root.put("data", jsonArray); json = JSONObject.fromObject(root); System.out.println("filename ==>" + item.getName() + " size ==>" + item.getSize()); } catch (Exception e) { e.printStackTrace(); throw new UploadActionException("Upload failed!"); } } else { if (item.getFieldName().equals("file-type")) { filetype = new String(item.get()); } } } // remove files from session. this avoids duplicate submissions removeSessionFileItems(request, false); if (json != null) return json.toString(); else return null; }
diff --git a/srcj/com/sun/electric/tool/routing/SimpleWirer.java b/srcj/com/sun/electric/tool/routing/SimpleWirer.java index 6a3274666..d44186013 100644 --- a/srcj/com/sun/electric/tool/routing/SimpleWirer.java +++ b/srcj/com/sun/electric/tool/routing/SimpleWirer.java @@ -1,209 +1,209 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: SimpleWirer.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.routing; import com.sun.electric.database.geometry.PolyMerge; import com.sun.electric.database.geometry.DBMath; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.prototype.PortProto; import com.sun.electric.technology.ArcProto; import com.sun.electric.technology.PrimitiveNode; import com.sun.electric.technology.Layer; import com.sun.electric.technology.SizeOffset; import com.sun.electric.technology.technologies.Generic; import com.sun.electric.tool.user.User; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * A Simple wiring tool for the user to draw wires. */ public class SimpleWirer extends InteractiveRouter { /* ----------------------- Router Methods ------------------------------------- */ public String toString() { return "SimpleWirer"; } protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultWidth() - useArc.getWidthOffset(); Layer pinLayer = useArc.getLayers()[0].getLayer(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); //System.out.println("angleD is "+angleD); int angle = (int)Math.round(angleD * 180 / Math.PI); //if (angle < 0) angle = angle + 360; //System.out.println("angle is "+angle+", incr is "+useArc.getAngleIncrement()); - if ((angle % useArc.getAngleIncrement()) == 0 || useArc.getAngleIncrement() == 0) { + if (useArc.getAngleIncrement() == 0 || (angle % useArc.getAngleIncrement()) == 0) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; } /** * Determines what route quadrant pt is compared to refPoint. * A route can be drawn vertically or horizontally so this * method will return a number between 0 and 3, inclusive, * where quadrants are defined based on the angle relationship * of refPoint to pt. Imagine a circle with <i>refPoint</i> as * the center and <i>pt</i> a point on the circumference of the * circle. Then theta is the angle described by the arc refPoint->pt, * and quadrants are defined as: * <code> * <p>quadrant : angle (theta) * <p>0 : -45 degrees to 45 degrees * <p>1 : 45 degress to 135 degrees * <p>2 : 135 degrees to 225 degrees * <p>3 : 225 degrees to 315 degrees (-45 degrees) * * @param refPoint reference point * @param pt variable point * @return which quadrant <i>pt</i> is in. */ protected static int findQuadrant(Point2D refPoint, Point2D pt) { // find angle double angle = Math.atan((pt.getY()-refPoint.getY())/(pt.getX()-refPoint.getX())); if (pt.getX() < refPoint.getX()) angle += Math.PI; if ((angle > -Math.PI/4) && (angle <= Math.PI/4)) return 0; else if ((angle > Math.PI/4) && (angle <= Math.PI*3/4)) return 1; else if ((angle > Math.PI*3/4) &&(angle <= Math.PI*5/4)) return 2; else return 3; } }
true
true
protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultWidth() - useArc.getWidthOffset(); Layer pinLayer = useArc.getLayers()[0].getLayer(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); //System.out.println("angleD is "+angleD); int angle = (int)Math.round(angleD * 180 / Math.PI); //if (angle < 0) angle = angle + 360; //System.out.println("angle is "+angle+", incr is "+useArc.getAngleIncrement()); if ((angle % useArc.getAngleIncrement()) == 0 || useArc.getAngleIncrement() == 0) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; }
protected boolean planRoute(Route route, Cell cell, RouteElementPort endRE, Point2D startLoc, Point2D endLoc, Point2D clicked, PolyMerge stayInside, VerticalRoute vroute, boolean contactsOnEndObj) { RouteElementPort startRE = route.getEnd(); // find port protos of startRE and endRE, and find connecting arc type PortProto startPort = startRE.getPortProto(); PortProto endPort = endRE.getPortProto(); ArcProto useArc = getArcToUse(startPort, endPort); // first, find location of corner of L if routing will be an L shape Point2D cornerLoc = null; if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY() || (useArc != null && (useArc.getAngleIncrement() == 0))) { // single arc if (contactsOnEndObj) cornerLoc = endLoc; else cornerLoc = startLoc; } else { Point2D pin1 = new Point2D.Double(startLoc.getX(), endLoc.getY()); Point2D pin2 = new Point2D.Double(endLoc.getX(), startLoc.getY()); // find which pin to use int clickedQuad = findQuadrant(endLoc, clicked); int pin1Quad = findQuadrant(endLoc, pin1); int pin2Quad = findQuadrant(endLoc, pin2); int oppositeQuad = (clickedQuad + 2) % 4; // presume pin1 by default cornerLoc = pin1; if (pin2Quad == clickedQuad) { cornerLoc = pin2; // same quad as pin2, use pin2 } else if (pin1Quad == clickedQuad) { cornerLoc = pin1; // same quad as pin1, use pin1 } else if (pin1Quad == oppositeQuad) { cornerLoc = pin2; // near to pin2 quad, use pin2 } if (stayInside != null && useArc != null) { // make sure the bend stays inside of the merge area double pinSize = useArc.getDefaultWidth() - useArc.getWidthOffset(); Layer pinLayer = useArc.getLayers()[0].getLayer(); Rectangle2D pin1Rect = new Rectangle2D.Double(pin1.getX()-pinSize/2, pin1.getY()-pinSize/2, pinSize, pinSize); Rectangle2D pin2Rect = new Rectangle2D.Double(pin2.getX()-pinSize/2, pin2.getY()-pinSize/2, pinSize, pinSize); if (stayInside.contains(pinLayer, pin1Rect)) cornerLoc = pin1; else if (stayInside.contains(pinLayer, pin2Rect)) cornerLoc = pin2; } } // never use universal arcs unless the user has selected them if (useArc == null) { // use universal if selected if (User.getUserTool().getCurrentArcProto() == Generic.tech.universal_arc) useArc = Generic.tech.universal_arc; else { route.add(endRE); route.setEnd(endRE); vroute.buildRoute(route, cell, startRE, endRE, startLoc, endLoc, cornerLoc); return true; } } route.add(endRE); route.setEnd(endRE); // startRE and endRE can be connected with an arc. If one of them is a bisectArcPin, // and can be replaced by the other, just replace it and we're done. if (route.replaceBisectPin(startRE, endRE)) { route.remove(startRE); return true; } else if (route.replaceBisectPin(endRE, startRE)) { route.remove(endRE); route.setEnd(startRE); return true; } // find arc width to use double width = getArcWidthToUse(startRE, useArc); double width2 = getArcWidthToUse(endRE, useArc); if (width2 > width) width = width2; // see if we should only draw a single arc double angleD = Math.atan2(endLoc.getY()-startLoc.getY(), endLoc.getX()-startLoc.getX()); //System.out.println("angleD is "+angleD); int angle = (int)Math.round(angleD * 180 / Math.PI); //if (angle < 0) angle = angle + 360; //System.out.println("angle is "+angle+", incr is "+useArc.getAngleIncrement()); if (useArc.getAngleIncrement() == 0 || (angle % useArc.getAngleIncrement()) == 0) { // draw single RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); return true; } // this router only draws horizontal and vertical arcs // if either X or Y coords are the same, create a single arc if (startLoc.getX() == endLoc.getX() || startLoc.getY() == endLoc.getY()) { // single arc RouteElement arcRE = RouteElementArc.newArc(cell, useArc, width, startRE, endRE, startLoc, endLoc, null, null, null); route.add(arcRE); } else { // otherwise, create new pin and two arcs for corner // make new pin of arc type PrimitiveNode pn = useArc.findOverridablePinProto(); SizeOffset so = pn.getProtoSizeOffset(); double defwidth = pn.getDefWidth()-so.getHighXOffset()-so.getLowXOffset(); double defheight = pn.getDefHeight()-so.getHighYOffset()-so.getLowYOffset(); RouteElementPort pinRE = RouteElementPort.newNode(cell, pn, pn.getPort(0), cornerLoc, defwidth, defheight); RouteElement arcRE1 = RouteElementArc.newArc(cell, useArc, width, startRE, pinRE, startLoc, cornerLoc, null, null, null); RouteElement arcRE2 = RouteElementArc.newArc(cell, useArc, width, pinRE, endRE, cornerLoc, endLoc, null, null, null); route.add(pinRE); route.add(arcRE1); route.add(arcRE2); } return true; }
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java index cd52c5e06..261ac733e 100644 --- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java +++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java @@ -1,276 +1,279 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openejb.cli; import org.apache.xbean.finder.ResourceFinder; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.util.OpenEjbVersion; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import java.util.ArrayList; import java.util.Locale; import java.util.Properties; import java.util.Enumeration; import java.util.Map; import java.util.List; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Method; import java.net.URL; /** * Entry point for ALL things OpenEJB. This will use the new service * architecture explained here: * * @link http://docs.codehaus.org/display/OPENEJB/Executables * * @version $Rev$ $Date$ */ public class MainImpl implements Main { private static final String BASE_PATH = "META-INF/org.apache.openejb.cli/"; private static final String MAIN_CLASS_PROPERTY_NAME = "main.class"; private static ResourceFinder finder = null; private static String locale = ""; private static String descriptionBase = "description"; private static String descriptionI18n; public void main(String[] args) { args = processSystemProperties(args); finder = new ResourceFinder(BASE_PATH); locale = Locale.getDefault().getLanguage(); descriptionI18n = descriptionBase + "." + locale; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(null, "version", false, ""); options.addOption("h", "help", false, ""); + options.addOption("e", "errors", false, "Produce execution error messages"); CommandLine line = null; String commandName = null; try { // parse the arguments up until the first // command, then let the rest fall into // the arguments array. line = parser.parse(options, args, true); // Get and remove the commandName (first arg) List<String> list = line.getArgList(); if (list.size() > 0){ commandName = list.get(0); list.remove(0); } // The rest of the args will be passed to the command args = line.getArgs(); } catch (ParseException exp) { exp.printStackTrace(); System.exit(-1); } if (line.hasOption("version")) { OpenEjbVersion.get().print(System.out); System.exit(0); } else if (line.hasOption("help") || commandName == null || commandName.equals("help")) { help(); System.exit(0); } Properties props = null; try { props = finder.findProperties(commandName); } catch (IOException e1) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } if (props == null) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } // Shift the command name itself off the args list String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME); if (mainClass == null) { throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property"); } Class<?> clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass); } catch (ClassNotFoundException cnfe) { throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe); } Method mainMethod = null; try { mainMethod = clazz.getMethod("main", String[].class); } catch (Exception e) { throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e); } try { // WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args' mainMethod.invoke(clazz, new Object[]{args}); } catch (Throwable e) { - e.printStackTrace(); + if (line.hasOption("errors")) { + e.printStackTrace(); + } System.exit(-10); } } private String[] processSystemProperties(String[] args) { ArrayList<String> argsList = new ArrayList<String>(); // We have to pre-screen for openejb.base as it has a direct affect // on where we look for the conf/system.properties file which we // need to read in and apply before we apply the command line -D // properties. Once SystemInstance.init() is called in the next // section of code, the openejb.base value is cemented and cannot // be changed. for (String arg : args) { if (arg.indexOf("-Dopenejb.base") != -1) { String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("=")); String val = arg.substring(arg.indexOf("=") + 1); System.setProperty(prop, val); } } // get SystemInstance (the only static class in the system) // so we'll set up all the props in it SystemInstance systemInstance = null; try { SystemInstance.init(System.getProperties()); systemInstance = SystemInstance.get(); } catch (Exception e) { e.printStackTrace(); System.exit(2); } // Read in and apply the conf/system.properties try { File conf = systemInstance.getBase().getDirectory("conf"); File file = new File(conf, "system.properties"); if (file.exists()){ Properties systemProperties = new Properties(); FileInputStream fin = new FileInputStream(file); InputStream in = new BufferedInputStream(fin); systemProperties.load(in); System.getProperties().putAll(systemProperties); } } catch (IOException e) { System.out.println("Processing conf/system.properties failed: "+e.getMessage()); } // Now read in and apply the properties specified on the command line for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.indexOf("-D") != -1) { String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("=")); String val = arg.substring(arg.indexOf("=") + 1); System.setProperty(prop, val); } else { argsList.add(arg); } } args = (String[]) argsList.toArray(new String[argsList.size()]); return args; } //DMB: TODO: Delete me public static Enumeration<URL> doFindCommands() throws IOException { return Thread.currentThread().getContextClassLoader().getResources(BASE_PATH); } private static void help() { help(true); } private static void help(boolean printHeader) { // Here we are using commons-cli to create the list of available commands // We actually use a different Options object to parse the 'openejb' command try { Options options = new Options(); ResourceFinder commandFinder = new ResourceFinder("META-INF"); Map<String, Properties> commands = commandFinder.mapAvailableProperties("org.apache.openejb.cli"); for (Map.Entry<String, Properties> command : commands.entrySet()) { if (command.getKey().contains(".")) continue; Properties p = command.getValue(); String description = p.getProperty(descriptionI18n, p.getProperty(descriptionBase)); options.addOption(command.getKey(), false, description); } HelpFormatter formatter = new HelpFormatter(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String syntax = "openejb <command> [options] [args]"; String header = "\nAvailable commands:"; String footer = "\n" + "Try 'openejb <command> --help' for help on a specific command.\n" + "For example 'openejb deploy --help'.\n" + "\n" + "Apache OpenEJB -- EJB Container System and Server.\n" + "For additional information, see http://openejb.apache.org\n" + "Bug Reports to <[email protected]>"; if (!printHeader){ pw.append(header).append("\n\n"); formatter.printOptions(pw, 74, options, 1, 3); } else { formatter.printHelp(pw, 74, syntax, header, options, 1, 3, footer, false); } pw.flush(); // Fix up the commons-cli output to our liking. String text = sw.toString().replaceAll("\n -", "\n "); text = text.replace("\nApache OpenEJB","\n\nApache OpenEJB"); System.out.print(text); } catch (IOException e) { e.printStackTrace(); } } }
false
true
public void main(String[] args) { args = processSystemProperties(args); finder = new ResourceFinder(BASE_PATH); locale = Locale.getDefault().getLanguage(); descriptionI18n = descriptionBase + "." + locale; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(null, "version", false, ""); options.addOption("h", "help", false, ""); CommandLine line = null; String commandName = null; try { // parse the arguments up until the first // command, then let the rest fall into // the arguments array. line = parser.parse(options, args, true); // Get and remove the commandName (first arg) List<String> list = line.getArgList(); if (list.size() > 0){ commandName = list.get(0); list.remove(0); } // The rest of the args will be passed to the command args = line.getArgs(); } catch (ParseException exp) { exp.printStackTrace(); System.exit(-1); } if (line.hasOption("version")) { OpenEjbVersion.get().print(System.out); System.exit(0); } else if (line.hasOption("help") || commandName == null || commandName.equals("help")) { help(); System.exit(0); } Properties props = null; try { props = finder.findProperties(commandName); } catch (IOException e1) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } if (props == null) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } // Shift the command name itself off the args list String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME); if (mainClass == null) { throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property"); } Class<?> clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass); } catch (ClassNotFoundException cnfe) { throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe); } Method mainMethod = null; try { mainMethod = clazz.getMethod("main", String[].class); } catch (Exception e) { throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e); } try { // WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args' mainMethod.invoke(clazz, new Object[]{args}); } catch (Throwable e) { e.printStackTrace(); System.exit(-10); } }
public void main(String[] args) { args = processSystemProperties(args); finder = new ResourceFinder(BASE_PATH); locale = Locale.getDefault().getLanguage(); descriptionI18n = descriptionBase + "." + locale; CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(null, "version", false, ""); options.addOption("h", "help", false, ""); options.addOption("e", "errors", false, "Produce execution error messages"); CommandLine line = null; String commandName = null; try { // parse the arguments up until the first // command, then let the rest fall into // the arguments array. line = parser.parse(options, args, true); // Get and remove the commandName (first arg) List<String> list = line.getArgList(); if (list.size() > 0){ commandName = list.get(0); list.remove(0); } // The rest of the args will be passed to the command args = line.getArgs(); } catch (ParseException exp) { exp.printStackTrace(); System.exit(-1); } if (line.hasOption("version")) { OpenEjbVersion.get().print(System.out); System.exit(0); } else if (line.hasOption("help") || commandName == null || commandName.equals("help")) { help(); System.exit(0); } Properties props = null; try { props = finder.findProperties(commandName); } catch (IOException e1) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } if (props == null) { System.out.println("Unavailable command: " + commandName); help(false); System.exit(1); } // Shift the command name itself off the args list String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME); if (mainClass == null) { throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property"); } Class<?> clazz = null; try { clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass); } catch (ClassNotFoundException cnfe) { throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe); } Method mainMethod = null; try { mainMethod = clazz.getMethod("main", String[].class); } catch (Exception e) { throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e); } try { // WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args' mainMethod.invoke(clazz, new Object[]{args}); } catch (Throwable e) { if (line.hasOption("errors")) { e.printStackTrace(); } System.exit(-10); } }
diff --git a/src/ru/spbau/bioinf/tagfinder/GraphUtil.java b/src/ru/spbau/bioinf/tagfinder/GraphUtil.java index 356d2bf..0cb4d25 100644 --- a/src/ru/spbau/bioinf/tagfinder/GraphUtil.java +++ b/src/ru/spbau/bioinf/tagfinder/GraphUtil.java @@ -1,137 +1,139 @@ package ru.spbau.bioinf.tagfinder; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class GraphUtil { public static final double EPSILON = 0.1; public static void generateEdges(Configuration conf, List<Peak> peaks) { int n = peaks.size(); for (int i = 0; i < n; i++) { Peak peak = peaks.get(i); for (int j = i+1; j < n; j++) { Peak next = peaks.get(j); double[] limits = conf.getEdgeLimits(peak, next); for (Acid acid : Acid.values()) { if (acid.match(limits)) { peak.addNext(next); break; } } } } } public static Peak[] findBestTag(List<Peak> peaks) { initMaxPrefix(peaks); Peak[] bestTag; bestTag = new Peak[]{}; for (Peak peak : peaks) { bestTag = findBestTag(peak, bestTag, 0, new Peak[500]); } return bestTag; } public static void initMaxPrefix(List<Peak> peaks) { for (Peak peak : peaks) { peak.setMaxPrefix(-1); } } public static Peak[] findBestTag(Peak peak, Peak[] best, int len, Peak[] prefix) { if (peak.getMaxPrefix() >= len) { return best; } prefix[len] = peak; if (len >= best.length) { best = new Peak[len +1]; System.arraycopy(prefix, 0, best, 0, len + 1); } for (Peak next : peak.getNext()) { best = findBestTag(next, best, len + 1, prefix); } peak.setMaxPrefix(len); return best; } - public static void generateGapEdges(Configuration conf, List<Peak> peaks, int allow) { + public static void generateGapEdges(Configuration conf, List<Peak> peaks, int gap) { int n = peaks.size(); List<Double> masses = new ArrayList<Double>(); Acid[] values = Acid.values(); for (Acid acid : values) { masses.add(acid.getMass()); } for (int i = 0; i < values.length; i++) { Acid a1 = values[i]; - for (int j = i + 1; j < values.length; j++) { - Acid a2 = values[j]; - masses.add(a1.getMass() + a2.getMass()); - if (allow > 2) { - for (int k = j + 1; k < values.length; k++) { - Acid a3 = values[k]; - masses.add(a1.getMass() + a2.getMass() + a3.getMass()); + if (gap > 1) { + for (int j = i + 1; j < values.length; j++) { + Acid a2 = values[j]; + masses.add(a1.getMass() + a2.getMass()); + if (gap > 2) { + for (int k = j + 1; k < values.length; k++) { + Acid a3 = values[k]; + masses.add(a1.getMass() + a2.getMass() + a3.getMass()); + } } } } } for (int i = 0; i < n; i++) { Peak peak = peaks.get(i); for (int j = i+1; j < n; j++) { Peak next = peaks.get(j); double[] limits = conf.getEdgeLimits(peak, next); for (double mass : masses) { if (limits[0] < mass && limits[1] > mass) { peak.addNext(next); break; } } } } } public static Set<String> generateTags(Configuration conf, List<Peak> peaks) { Set<String> tags = new HashSet<String>(); for (Peak peak : peaks) { generateTags(conf, tags, "", peak); } return tags; } public static void generateTags(Configuration conf, Set<String> tags, String prefix, Peak peak) { tags.add(prefix); for (Peak next : peak.getNext()) { for (Acid acid : Acid.values()) { if (acid.match(conf.getEdgeLimits(peak, next))){ generateTags(conf, tags, prefix + acid.name(), next); } } } } public static boolean tagStartsAtPos(double pos, String tag, List<Peak> peaks) { int i; for (i = 0; i < tag.length(); i++) { pos += Acid.getAcid(tag.charAt(i)).getMass(); boolean found = false; for (Peak p2 : peaks) { if (Math.abs(p2.getValue() - pos) < EPSILON) { found = true; break; } } if (!found) { break; } } return i == tag.length(); } }
false
true
public static void generateGapEdges(Configuration conf, List<Peak> peaks, int allow) { int n = peaks.size(); List<Double> masses = new ArrayList<Double>(); Acid[] values = Acid.values(); for (Acid acid : values) { masses.add(acid.getMass()); } for (int i = 0; i < values.length; i++) { Acid a1 = values[i]; for (int j = i + 1; j < values.length; j++) { Acid a2 = values[j]; masses.add(a1.getMass() + a2.getMass()); if (allow > 2) { for (int k = j + 1; k < values.length; k++) { Acid a3 = values[k]; masses.add(a1.getMass() + a2.getMass() + a3.getMass()); } } } } for (int i = 0; i < n; i++) { Peak peak = peaks.get(i); for (int j = i+1; j < n; j++) { Peak next = peaks.get(j); double[] limits = conf.getEdgeLimits(peak, next); for (double mass : masses) { if (limits[0] < mass && limits[1] > mass) { peak.addNext(next); break; } } } } }
public static void generateGapEdges(Configuration conf, List<Peak> peaks, int gap) { int n = peaks.size(); List<Double> masses = new ArrayList<Double>(); Acid[] values = Acid.values(); for (Acid acid : values) { masses.add(acid.getMass()); } for (int i = 0; i < values.length; i++) { Acid a1 = values[i]; if (gap > 1) { for (int j = i + 1; j < values.length; j++) { Acid a2 = values[j]; masses.add(a1.getMass() + a2.getMass()); if (gap > 2) { for (int k = j + 1; k < values.length; k++) { Acid a3 = values[k]; masses.add(a1.getMass() + a2.getMass() + a3.getMass()); } } } } } for (int i = 0; i < n; i++) { Peak peak = peaks.get(i); for (int j = i+1; j < n; j++) { Peak next = peaks.get(j); double[] limits = conf.getEdgeLimits(peak, next); for (double mass : masses) { if (limits[0] < mass && limits[1] > mass) { peak.addNext(next); break; } } } } }
diff --git a/roborumble/roborumble/RoboRumbleAtHome.java b/roborumble/roborumble/RoboRumbleAtHome.java index 4c8a3a69e..735376453 100644 --- a/roborumble/roborumble/RoboRumbleAtHome.java +++ b/roborumble/roborumble/RoboRumbleAtHome.java @@ -1,152 +1,152 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Albert P�rez and RoboRumble contributors * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://robocode.sourceforge.net/license/cpl-v10.html * * Contributors: * Albert P�rez * - Initial API and implementation * Flemming N. Larsen * - Properties are now read using PropertiesUtil.getProperties() * - Renamed UpdateRatings() into updateRatings() *******************************************************************************/ package roborumble; import roborumble.battlesengine.*; import roborumble.netengine.*; import java.util.*; import static roborumble.util.PropertiesUtil.getProperties; /** * Implements the client side of RoboRumble@Home. * Controlled by properties files. * * @author Albert P�rez (original) * @author Flemming N. Larsen (contributor) */ public class RoboRumbleAtHome { public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { - System.out.println("Uloading results ..."); + System.out.println("Uploading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); // With Java 5 this causes a IllegalThreadStateException, but not in Java 6 // System.exit(0); } }
true
true
public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { System.out.println("Uloading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); // With Java 5 this causes a IllegalThreadStateException, but not in Java 6 // System.exit(0); }
public static void main(String args[]) { // get the associated parameters file String parameters = "./roborumble/roborumble.txt"; try { parameters = args[0]; } catch (Exception e) { System.out.println("No argument found specifying properties file. \"roborumble.txt\" assumed."); } // Read parameters for running the app Properties param = getProperties(parameters); String downloads = param.getProperty("DOWNLOAD", "NOT"); String executes = param.getProperty("EXECUTE", "NOT"); String uploads = param.getProperty("UPLOAD", "NOT"); String iterates = param.getProperty("ITERATE", "NOT"); String runonly = param.getProperty("RUNONLY", "GENERAL"); String melee = param.getProperty("MELEE", "NOT"); int iterations = 0; long lastdownload = 0; boolean ratingsdownloaded = false; boolean participantsdownloaded = false; do { System.out.println("Iteration number " + iterations); // Download data from internet if downloads is YES and it has not beeen download for two hours if (downloads.equals("YES") && (System.currentTimeMillis() - lastdownload) > 2 * 3600 * 1000) { BotsDownload download = new BotsDownload(parameters); System.out.println("Downloading participants list ..."); participantsdownloaded = download.downloadParticipantsList(); System.out.println("Downloading missing bots ..."); download.downloadMissingBots(); download.updateCodeSize(); if (runonly.equals("SERVER")) { // download rating files and update ratings downloaded System.out.println("Downloading rating files ..."); ratingsdownloaded = download.downloadRatings(); } // send the order to the server to remove old participants from the ratings file if (ratingsdownloaded && participantsdownloaded) { System.out.println("Removing old participants from server ..."); // send unwanted participants to the server download.notifyServerForOldParticipants(); } download = null; lastdownload = System.currentTimeMillis(); } // create battles file (and delete old ones), and execute battles if (executes.equals("YES")) { boolean ready = false; PrepareBattles battles = new PrepareBattles(parameters); if (melee.equals("YES")) { System.out.println("Preparing melee battles list ..."); ready = battles.createMeleeBattlesList(); } else { System.out.println( "Preparing battles list ... Using smart battles is " + (ratingsdownloaded && runonly.equals("SERVER"))); if (ratingsdownloaded && runonly.equals("SERVER")) { ready = battles.createSmartBattlesList(); } // create the smart lists else { ready = battles.createBattlesList(); } // create the normal lists } battles = null; // execute battles if (ready) { if (melee.equals("YES")) { System.out.println("Executing melee battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runMeleeBattles(); engine = null; } else { System.out.println("Executing battles ..."); BattlesRunner engine = new BattlesRunner(parameters); engine.runBattles(); engine = null; } } } // upload results if (uploads.equals("YES")) { System.out.println("Uploading results ..."); ResultsUpload upload = new ResultsUpload(parameters); // uploads the results to the server upload.uploadResults(); upload = null; // updates the number of battles from the info received from the server System.out.println("Updating number of battles fought ..."); UpdateRatingFiles updater = new UpdateRatingFiles(parameters); ratingsdownloaded = updater.updateRatings(); // if (!ok) ratingsdownloaded = false; updater = null; } iterations++; } while (iterates.equals("YES")); // With Java 5 this causes a IllegalThreadStateException, but not in Java 6 // System.exit(0); }
diff --git a/Common/src/main/java/au/gov/ga/worldwind/common/layers/sun/SunLayer.java b/Common/src/main/java/au/gov/ga/worldwind/common/layers/sun/SunLayer.java index db751cd9..5a15de89 100644 --- a/Common/src/main/java/au/gov/ga/worldwind/common/layers/sun/SunLayer.java +++ b/Common/src/main/java/au/gov/ga/worldwind/common/layers/sun/SunLayer.java @@ -1,387 +1,387 @@ /******************************************************************************* * Copyright 2014 Geoscience Australia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package au.gov.ga.worldwind.common.layers.sun; import gov.nasa.worldwind.View; import gov.nasa.worldwind.geom.Angle; import gov.nasa.worldwind.geom.Matrix; import gov.nasa.worldwind.geom.Vec4; import gov.nasa.worldwind.layers.AbstractLayer; import gov.nasa.worldwind.render.DrawContext; import gov.nasa.worldwind.util.OGLStackHandler; import java.awt.Color; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; import javax.media.opengl.GL2; import au.gov.ga.worldwind.common.layers.atmosphere.Atmosphere; import au.gov.ga.worldwind.common.render.FrameBufferStack; import au.gov.ga.worldwind.common.sun.SunPositionService; import au.gov.ga.worldwind.common.view.delegate.IDelegateView; import com.jogamp.opengl.util.texture.Texture; import com.jogamp.opengl.util.texture.TextureData; import com.jogamp.opengl.util.texture.TextureIO; import com.jogamp.opengl.util.texture.awt.AWTTextureIO; /** * Layer that renders a sun, with lens flare, glow, halo, and dirty lens * effects. * <p/> * Based on the code by Michal Belanec <a * href="http://www.belanecbn.sk/3dtutorials/index.php?id=7">here</a>. * * @author Michael de Hoog ([email protected]) */ public class SunLayer extends AbstractLayer { protected final float sunSize = 20; protected boolean inited = false; protected Dimension size; protected Dimension stageTextureSize; protected Texture circleTexture; protected Texture dirtTexture; protected final int[] depthTexture = new int[1]; protected final int[] stageTextures = new int[3]; protected final int[] fbo = new int[1]; protected final SunDepthTestShader sunDepthTestShader = new SunDepthTestShader(); protected final SunRaysLensFlareHaloShader sunRaysLensFlareHaloShader = new SunRaysLensFlareHaloShader(); protected final BlurHorizontalShader blurHorizontalShader = new BlurHorizontalShader(); protected final BlurVerticalShader blurVerticalShader = new BlurVerticalShader(); @Override protected void doRender(DrawContext dc) { if (!inited) { init(dc); inited = true; } resize(dc); renderSun(dc); } protected void init(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); //load the textures try { BufferedImage circleImage = ImageIO.read(SunLayer.class.getResourceAsStream("circle.png")); //$NON-NLS-1$ TextureData td = AWTTextureIO.newTextureData(gl.getGLProfile(), circleImage, true); circleTexture = TextureIO.newTexture(td); BufferedImage dirtImage = ImageIO.read(SunLayer.class.getResourceAsStream("dirtylens.jpg")); //$NON-NLS-1$ td = AWTTextureIO.newTextureData(gl.getGLProfile(), dirtImage, false); dirtTexture = TextureIO.newTexture(td); } catch (IOException e) { e.printStackTrace(); } //generate textures and a frame buffer object gl.glGenTextures(depthTexture.length, depthTexture, 0); gl.glGenTextures(stageTextures.length, stageTextures, 0); gl.glGenFramebuffers(fbo.length, fbo, 0); //compile the shaders sunDepthTestShader.create(gl); sunRaysLensFlareHaloShader.create(gl); blurHorizontalShader.create(gl); blurVerticalShader.create(gl); } protected void resize(DrawContext dc) { View view = dc.getView(); Rectangle viewport = view.getViewport(); Dimension size = viewport.getSize(); if (size.equals(this.size)) { return; } this.size = size; GL2 gl = dc.getGL().getGL2(); //generate a depth texture for copying the current scene's depth buffer to gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_NEAREST); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP); gl.glTexImage2D(GL2.GL_TEXTURE_2D, 0, GL2.GL_DEPTH_COMPONENT24, size.width, size.height, 0, GL2.GL_DEPTH_COMPONENT, GL2.GL_FLOAT, null); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); //generate the sun staging textures at half-res stageTextureSize = new Dimension(size.width / 2, size.height / 2); for (int i = 0; i < stageTextures.length; i++) { gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[i]); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_LINEAR); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S, GL2.GL_CLAMP_TO_EDGE); gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T, GL2.GL_CLAMP_TO_EDGE); gl.glTexImage2D(GL2.GL_TEXTURE_2D, 0, GL2.GL_RGBA8, stageTextureSize.width, stageTextureSize.height, 0, GL2.GL_RGBA, GL2.GL_UNSIGNED_BYTE, null); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); } } protected void renderSun(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); //calculate view rotation Vec4 up = dc.getView().getUpVector(); Vec4 f = dc.getView().getForwardVector(); Vec4 s = f.cross3(up); Vec4 u = s.cross3(f); Matrix viewRotation = new Matrix( s.x, s.y, s.z, 0.0, u.x, u.y, u.z, 0.0, -f.x, -f.y, -f.z, 0.0, 0.0, 0.0, 0.0, 1.0); //compute modelview matrix by combining view rotation and light direction rotation Vec4 lightDirection = SunPositionService.INSTANCE.getDirection(dc.getView()); Angle lightAngle = Vec4.UNIT_Z.angleBetween3(lightDirection); Vec4 lightAxis = Vec4.UNIT_Z.cross3(lightDirection); Matrix lightRotation = Matrix.fromAxisAngle(lightAngle, lightAxis); Matrix modelview = viewRotation.multiply(lightRotation); //compute the view's projection matrix IDelegateView view = (IDelegateView) dc.getView(); Matrix projection = view.computeProjection(0.1, 1.5); //project the sun's direction onto the view plane using gluProject Rectangle viewport = view.getViewport(); double[] modelviewArray = new double[16]; double[] projectionArray = new double[16]; modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); - int[] viewportArray = new int[] { viewport.x, viewport.y, viewport.width, viewport.height }; + int[] viewportArray = new int[] { 0, 0, viewport.width, viewport.height }; double[] result = new double[3]; dc.getGLU().gluProject(0.0, 0.0, 1.0, modelviewArray, 0, projectionArray, 0, viewportArray, 0, result, 0); //calculate sun screen position in screen coordinates - double projectedSunPosX = (viewport.x + result[0]) / viewport.width; - double projectedSunPosY = (viewport.y + result[1]) / viewport.height; + double projectedSunPosX = result[0] / viewport.width; + double projectedSunPosY = result[1] / viewport.height; double sunWidth = 0.5 * sunSize / viewport.width; double sunHeight = 0.5 * sunSize / viewport.height; double x1 = projectedSunPosX - sunWidth; double x2 = projectedSunPosX + sunWidth; double y1 = projectedSunPosY - sunHeight; double y2 = projectedSunPosY + sunHeight; if (!(0 <= x2 && x1 <= 1 && 0 <= y2 && y1 <= 1 && 0 <= result[2] && result[2] <= 1)) { //sun not within viewport, so don't render return; } double directionScale = dc.getGlobe().getRadius() * dc.getGlobe().getRadius(); Color sunColor = Atmosphere.getSpaceObjectColor(dc, lightDirection.multiply3(directionScale)); OGLStackHandler ogsh = new OGLStackHandler(); try { //switch to ortho mode ogsh.pushModelviewIdentity(gl); ogsh.pushProjectionIdentity(gl); ogsh.pushAttrib(gl, GL2.GL_TEXTURE_BIT | GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_VIEWPORT_BIT); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glOrthof(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f); //copy depth buffer to texture gl.glActiveTexture(GL2.GL_TEXTURE0); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); - gl.glCopyTexSubImage2D(GL2.GL_TEXTURE_2D, 0, 0, 0, 0, 0, size.width, size.height); + gl.glCopyTexSubImage2D(GL2.GL_TEXTURE_2D, 0, 0, 0, viewport.x, viewport.y, size.width, size.height); //render the sun circle texture gl.glViewport(0, 0, stageTextureSize.width, stageTextureSize.height); FrameBufferStack.push(gl, fbo[0]); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_DEPTH_ATTACHMENT, GL2.GL_TEXTURE_2D, 0, 0); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); //clear the frame buffer gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glColor3d(sunColor.getRed() / 255.0, sunColor.getGreen() / 255.0, sunColor.getBlue() / 255.0); circleTexture.bind(gl); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0, 0); gl.glVertex3d(x1, y1, -1); gl.glTexCoord2f(1, 0); gl.glVertex3d(x2, y1, -1); gl.glTexCoord2f(1, 1); gl.glVertex3d(x2, y2, -1); gl.glTexCoord2f(0, 1); gl.glVertex3d(x1, y2, -1); } gl.glEnd(); gl.glColor3d(1.0, 1.0, 1.0); //test if sun sphere is behind scene geometry gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); sunDepthTestShader.use(gl); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunDepthTestShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //blur sun sphere horizontally (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 1, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[2], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 1, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere horizontally (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 10, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 10, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere radially and calculate lens flare and halo and apply dirt texture gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[2]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); gl.glActiveTexture(GL2.GL_TEXTURE2); gl.glBindTexture(GL2.GL_TEXTURE_2D, dirtTexture.getTextureObject(gl)); sunRaysLensFlareHaloShader.use(gl, (float) projectedSunPosX, (float) projectedSunPosY); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunRaysLensFlareHaloShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //unbind frame buffer and reset viewport FrameBufferStack.pop(gl); gl.glViewport(viewport.x, viewport.y, viewport.width, viewport.height); //render the final composited sun texture to the screen gl.glDepthMask(false); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glBlendFunc(GL2.GL_ONE, GL2.GL_ONE_MINUS_SRC_COLOR); gl.glEnable(GL2.GL_BLEND); gl.glColor3f(1.0f, 1.0f, 1.0f); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex2f(0.0f, 0.0f); gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glTexCoord2f(1.0f, 1.0f); gl.glVertex2f(1.0f, 1.0f); gl.glTexCoord2f(0.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); gl.glDisable(GL2.GL_BLEND); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glDepthMask(true); } finally { ogsh.pop(gl); } } }
false
true
protected void renderSun(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); //calculate view rotation Vec4 up = dc.getView().getUpVector(); Vec4 f = dc.getView().getForwardVector(); Vec4 s = f.cross3(up); Vec4 u = s.cross3(f); Matrix viewRotation = new Matrix( s.x, s.y, s.z, 0.0, u.x, u.y, u.z, 0.0, -f.x, -f.y, -f.z, 0.0, 0.0, 0.0, 0.0, 1.0); //compute modelview matrix by combining view rotation and light direction rotation Vec4 lightDirection = SunPositionService.INSTANCE.getDirection(dc.getView()); Angle lightAngle = Vec4.UNIT_Z.angleBetween3(lightDirection); Vec4 lightAxis = Vec4.UNIT_Z.cross3(lightDirection); Matrix lightRotation = Matrix.fromAxisAngle(lightAngle, lightAxis); Matrix modelview = viewRotation.multiply(lightRotation); //compute the view's projection matrix IDelegateView view = (IDelegateView) dc.getView(); Matrix projection = view.computeProjection(0.1, 1.5); //project the sun's direction onto the view plane using gluProject Rectangle viewport = view.getViewport(); double[] modelviewArray = new double[16]; double[] projectionArray = new double[16]; modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); int[] viewportArray = new int[] { viewport.x, viewport.y, viewport.width, viewport.height }; double[] result = new double[3]; dc.getGLU().gluProject(0.0, 0.0, 1.0, modelviewArray, 0, projectionArray, 0, viewportArray, 0, result, 0); //calculate sun screen position in screen coordinates double projectedSunPosX = (viewport.x + result[0]) / viewport.width; double projectedSunPosY = (viewport.y + result[1]) / viewport.height; double sunWidth = 0.5 * sunSize / viewport.width; double sunHeight = 0.5 * sunSize / viewport.height; double x1 = projectedSunPosX - sunWidth; double x2 = projectedSunPosX + sunWidth; double y1 = projectedSunPosY - sunHeight; double y2 = projectedSunPosY + sunHeight; if (!(0 <= x2 && x1 <= 1 && 0 <= y2 && y1 <= 1 && 0 <= result[2] && result[2] <= 1)) { //sun not within viewport, so don't render return; } double directionScale = dc.getGlobe().getRadius() * dc.getGlobe().getRadius(); Color sunColor = Atmosphere.getSpaceObjectColor(dc, lightDirection.multiply3(directionScale)); OGLStackHandler ogsh = new OGLStackHandler(); try { //switch to ortho mode ogsh.pushModelviewIdentity(gl); ogsh.pushProjectionIdentity(gl); ogsh.pushAttrib(gl, GL2.GL_TEXTURE_BIT | GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_VIEWPORT_BIT); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glOrthof(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f); //copy depth buffer to texture gl.glActiveTexture(GL2.GL_TEXTURE0); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); gl.glCopyTexSubImage2D(GL2.GL_TEXTURE_2D, 0, 0, 0, 0, 0, size.width, size.height); //render the sun circle texture gl.glViewport(0, 0, stageTextureSize.width, stageTextureSize.height); FrameBufferStack.push(gl, fbo[0]); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_DEPTH_ATTACHMENT, GL2.GL_TEXTURE_2D, 0, 0); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); //clear the frame buffer gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glColor3d(sunColor.getRed() / 255.0, sunColor.getGreen() / 255.0, sunColor.getBlue() / 255.0); circleTexture.bind(gl); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0, 0); gl.glVertex3d(x1, y1, -1); gl.glTexCoord2f(1, 0); gl.glVertex3d(x2, y1, -1); gl.glTexCoord2f(1, 1); gl.glVertex3d(x2, y2, -1); gl.glTexCoord2f(0, 1); gl.glVertex3d(x1, y2, -1); } gl.glEnd(); gl.glColor3d(1.0, 1.0, 1.0); //test if sun sphere is behind scene geometry gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); sunDepthTestShader.use(gl); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunDepthTestShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //blur sun sphere horizontally (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 1, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[2], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 1, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere horizontally (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 10, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 10, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere radially and calculate lens flare and halo and apply dirt texture gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[2]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); gl.glActiveTexture(GL2.GL_TEXTURE2); gl.glBindTexture(GL2.GL_TEXTURE_2D, dirtTexture.getTextureObject(gl)); sunRaysLensFlareHaloShader.use(gl, (float) projectedSunPosX, (float) projectedSunPosY); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunRaysLensFlareHaloShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //unbind frame buffer and reset viewport FrameBufferStack.pop(gl); gl.glViewport(viewport.x, viewport.y, viewport.width, viewport.height); //render the final composited sun texture to the screen gl.glDepthMask(false); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glBlendFunc(GL2.GL_ONE, GL2.GL_ONE_MINUS_SRC_COLOR); gl.glEnable(GL2.GL_BLEND); gl.glColor3f(1.0f, 1.0f, 1.0f); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex2f(0.0f, 0.0f); gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glTexCoord2f(1.0f, 1.0f); gl.glVertex2f(1.0f, 1.0f); gl.glTexCoord2f(0.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); gl.glDisable(GL2.GL_BLEND); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glDepthMask(true); } finally { ogsh.pop(gl); } }
protected void renderSun(DrawContext dc) { GL2 gl = dc.getGL().getGL2(); //calculate view rotation Vec4 up = dc.getView().getUpVector(); Vec4 f = dc.getView().getForwardVector(); Vec4 s = f.cross3(up); Vec4 u = s.cross3(f); Matrix viewRotation = new Matrix( s.x, s.y, s.z, 0.0, u.x, u.y, u.z, 0.0, -f.x, -f.y, -f.z, 0.0, 0.0, 0.0, 0.0, 1.0); //compute modelview matrix by combining view rotation and light direction rotation Vec4 lightDirection = SunPositionService.INSTANCE.getDirection(dc.getView()); Angle lightAngle = Vec4.UNIT_Z.angleBetween3(lightDirection); Vec4 lightAxis = Vec4.UNIT_Z.cross3(lightDirection); Matrix lightRotation = Matrix.fromAxisAngle(lightAngle, lightAxis); Matrix modelview = viewRotation.multiply(lightRotation); //compute the view's projection matrix IDelegateView view = (IDelegateView) dc.getView(); Matrix projection = view.computeProjection(0.1, 1.5); //project the sun's direction onto the view plane using gluProject Rectangle viewport = view.getViewport(); double[] modelviewArray = new double[16]; double[] projectionArray = new double[16]; modelview.toArray(modelviewArray, 0, false); projection.toArray(projectionArray, 0, false); int[] viewportArray = new int[] { 0, 0, viewport.width, viewport.height }; double[] result = new double[3]; dc.getGLU().gluProject(0.0, 0.0, 1.0, modelviewArray, 0, projectionArray, 0, viewportArray, 0, result, 0); //calculate sun screen position in screen coordinates double projectedSunPosX = result[0] / viewport.width; double projectedSunPosY = result[1] / viewport.height; double sunWidth = 0.5 * sunSize / viewport.width; double sunHeight = 0.5 * sunSize / viewport.height; double x1 = projectedSunPosX - sunWidth; double x2 = projectedSunPosX + sunWidth; double y1 = projectedSunPosY - sunHeight; double y2 = projectedSunPosY + sunHeight; if (!(0 <= x2 && x1 <= 1 && 0 <= y2 && y1 <= 1 && 0 <= result[2] && result[2] <= 1)) { //sun not within viewport, so don't render return; } double directionScale = dc.getGlobe().getRadius() * dc.getGlobe().getRadius(); Color sunColor = Atmosphere.getSpaceObjectColor(dc, lightDirection.multiply3(directionScale)); OGLStackHandler ogsh = new OGLStackHandler(); try { //switch to ortho mode ogsh.pushModelviewIdentity(gl); ogsh.pushProjectionIdentity(gl); ogsh.pushAttrib(gl, GL2.GL_TEXTURE_BIT | GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT | GL2.GL_VIEWPORT_BIT); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glOrthof(0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f); //copy depth buffer to texture gl.glActiveTexture(GL2.GL_TEXTURE0); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); gl.glCopyTexSubImage2D(GL2.GL_TEXTURE_2D, 0, 0, 0, viewport.x, viewport.y, size.width, size.height); //render the sun circle texture gl.glViewport(0, 0, stageTextureSize.width, stageTextureSize.height); FrameBufferStack.push(gl, fbo[0]); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_DEPTH_ATTACHMENT, GL2.GL_TEXTURE_2D, 0, 0); gl.glClear(GL2.GL_COLOR_BUFFER_BIT); //clear the frame buffer gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glColor3d(sunColor.getRed() / 255.0, sunColor.getGreen() / 255.0, sunColor.getBlue() / 255.0); circleTexture.bind(gl); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0, 0); gl.glVertex3d(x1, y1, -1); gl.glTexCoord2f(1, 0); gl.glVertex3d(x2, y1, -1); gl.glTexCoord2f(1, 1); gl.glVertex3d(x2, y2, -1); gl.glTexCoord2f(0, 1); gl.glVertex3d(x1, y2, -1); } gl.glEnd(); gl.glColor3d(1.0, 1.0, 1.0); //test if sun sphere is behind scene geometry gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, depthTexture[0]); sunDepthTestShader.use(gl); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunDepthTestShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //blur sun sphere horizontally (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 1, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (low) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[2], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 1, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere horizontally (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); blurHorizontalShader.use(gl, 10, 1.0f / stageTextureSize.width); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurHorizontalShader.unuse(gl); //blur sun sphere vertically (high) gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[1], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); blurVerticalShader.use(gl, 10, 1.0f / stageTextureSize.height); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); blurVerticalShader.unuse(gl); //blur sun sphere radially and calculate lens flare and halo and apply dirt texture gl.glFramebufferTexture2D(GL2.GL_FRAMEBUFFER, GL2.GL_COLOR_ATTACHMENT0, GL2.GL_TEXTURE_2D, stageTextures[0], 0); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[2]); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[1]); gl.glActiveTexture(GL2.GL_TEXTURE2); gl.glBindTexture(GL2.GL_TEXTURE_2D, dirtTexture.getTextureObject(gl)); sunRaysLensFlareHaloShader.use(gl, (float) projectedSunPosX, (float) projectedSunPosY); gl.glBegin(GL2.GL_QUADS); { gl.glVertex2f(0.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); sunRaysLensFlareHaloShader.unuse(gl); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE1); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glActiveTexture(GL2.GL_TEXTURE0); //unbind frame buffer and reset viewport FrameBufferStack.pop(gl); gl.glViewport(viewport.x, viewport.y, viewport.width, viewport.height); //render the final composited sun texture to the screen gl.glDepthMask(false); gl.glEnable(GL2.GL_TEXTURE_2D); gl.glBindTexture(GL2.GL_TEXTURE_2D, stageTextures[0]); gl.glBlendFunc(GL2.GL_ONE, GL2.GL_ONE_MINUS_SRC_COLOR); gl.glEnable(GL2.GL_BLEND); gl.glColor3f(1.0f, 1.0f, 1.0f); gl.glBegin(GL2.GL_QUADS); { gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex2f(0.0f, 0.0f); gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex2f(1.0f, 0.0f); gl.glTexCoord2f(1.0f, 1.0f); gl.glVertex2f(1.0f, 1.0f); gl.glTexCoord2f(0.0f, 1.0f); gl.glVertex2f(0.0f, 1.0f); } gl.glEnd(); gl.glDisable(GL2.GL_BLEND); gl.glBindTexture(GL2.GL_TEXTURE_2D, 0); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glDepthMask(true); } finally { ogsh.pop(gl); } }
diff --git a/Locus/src/com/example/locus/MainActivity.java b/Locus/src/com/example/locus/MainActivity.java index d262fe7..d6ffb43 100644 --- a/Locus/src/com/example/locus/MainActivity.java +++ b/Locus/src/com/example/locus/MainActivity.java @@ -1,106 +1,108 @@ package com.example.locus; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import com.example.locus.core.CoreFacade; import com.example.locus.entity.Sex; import com.example.locus.entity.User; public class MainActivity extends Activity { private CoreFacade core; ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CoreFacade.getInstance().setContext(this.getApplicationContext()); Intent intent = getIntent(); if(intent.getExtras() == null){ // SLEEP 2 SECONDS HERE ... iv = (ImageView)findViewById(R.id.mainImageView); iv.setScaleType(ScaleType.FIT_XY); iv.setImageResource(R.drawable.main); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent = new Intent(getApplicationContext(), MyProfile.class); startActivity(intent); } else{ Intent listUser = new Intent(getApplicationContext(), Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); + listUser.putExtra("pic", user.getPic()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } }, 2000); } else{ User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent1 = new Intent(this, MyProfile.class); startActivity(intent1); } else{ Intent listUser = new Intent(this, Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); + listUser.putExtra("pic", user.getPic()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } } }
false
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CoreFacade.getInstance().setContext(this.getApplicationContext()); Intent intent = getIntent(); if(intent.getExtras() == null){ // SLEEP 2 SECONDS HERE ... iv = (ImageView)findViewById(R.id.mainImageView); iv.setScaleType(ScaleType.FIT_XY); iv.setImageResource(R.drawable.main); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent = new Intent(getApplicationContext(), MyProfile.class); startActivity(intent); } else{ Intent listUser = new Intent(getApplicationContext(), Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } }, 2000); } else{ User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent1 = new Intent(this, MyProfile.class); startActivity(intent1); } else{ Intent listUser = new Intent(this, Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CoreFacade.getInstance().setContext(this.getApplicationContext()); Intent intent = getIntent(); if(intent.getExtras() == null){ // SLEEP 2 SECONDS HERE ... iv = (ImageView)findViewById(R.id.mainImageView); iv.setScaleType(ScaleType.FIT_XY); iv.setImageResource(R.drawable.main); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent = new Intent(getApplicationContext(), MyProfile.class); startActivity(intent); } else{ Intent listUser = new Intent(getApplicationContext(), Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); listUser.putExtra("pic", user.getPic()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } }, 2000); } else{ User user = CoreFacade.getInstance().getCurrentUser(); if(user == null){ Intent intent1 = new Intent(this, MyProfile.class); startActivity(intent1); } else{ Intent listUser = new Intent(this, Demo.class); listUser.putExtra("userName", user.getName()); listUser.putExtra("latitude", ""+user.getLatitude()); listUser.putExtra("longitude", ""+user.getLongtitude()); listUser.putExtra("userName", user.getName()); listUser.putExtra("pic", user.getPic()); String ipAdd; try { ipAdd = IPAddress.getIPAddress(true); listUser.putExtra("IP", ipAdd); if(user.getSex() == Sex.Female) listUser.putExtra("sex", "Female"); else listUser.putExtra("sex", "Male"); listUser.putExtra("interests", user.getInterests()); } catch (IOException e) { e.printStackTrace(); } startActivity(listUser); } } }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/files/TARDISInteriorSchematicReader.java b/src/main/java/me/eccentric_nz/TARDIS/files/TARDISInteriorSchematicReader.java index 5d30a721a..e827f6dab 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/files/TARDISInteriorSchematicReader.java +++ b/src/main/java/me/eccentric_nz/TARDIS/files/TARDISInteriorSchematicReader.java @@ -1,162 +1,162 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.TARDISConstants; import org.jnbt.ByteArrayTag; import org.jnbt.CompoundTag; import org.jnbt.NBTInputStream; import org.jnbt.ShortTag; import org.jnbt.Tag; /** * The Ood are a humanoid species with coleoid tentacles on the lower portions * of their faces. They have no vocal cords and instead communicate by * telepathy. * * @author eccentric_nz */ public class TARDISInteriorSchematicReader { private static Tag getChildTag(Map<String, Tag> items, String key, Class<? extends Tag> expected) { Tag tag = items.get(key); return tag; } private TARDIS plugin; public TARDISInteriorSchematicReader(TARDIS plugin) { this.plugin = plugin; } /** * Reads a WorldEdit schematic file and writes the data to a CSV file. The * dimensions of the schematics are also stored for use by the TARDIS and * room builders. * * @param fileStr the path to the schematic file * @param s the schematic name */ public void readAndMakeInteriorCSV(String fileStr, TARDISConstants.SCHEMATIC s) { plugin.debug("Loading schematic: " + fileStr); FileInputStream fis = null; try { File f = new File(fileStr); fis = new FileInputStream(f); NBTInputStream nbt = new NBTInputStream(fis); CompoundTag backuptag = (CompoundTag) nbt.readTag(); Map<String, Tag> tagCollection = backuptag.getValue(); short width = (Short) getChildTag(tagCollection, "Width", ShortTag.class).getValue(); short height = (Short) getChildTag(tagCollection, "Height", ShortTag.class).getValue(); short length = (Short) getChildTag(tagCollection, "Length", ShortTag.class).getValue(); switch (s) { case BUDGET: plugin.budgetdimensions[0] = height; plugin.budgetdimensions[1] = width; plugin.budgetdimensions[2] = length; break; case BIGGER: plugin.biggerdimensions[0] = height; plugin.biggerdimensions[1] = width; plugin.biggerdimensions[2] = length; break; case DELUXE: plugin.deluxedimensions[0] = height; plugin.deluxedimensions[1] = width; plugin.deluxedimensions[2] = length; break; case ELEVENTH: plugin.eleventhdimensions[0] = height; plugin.eleventhdimensions[1] = width; plugin.eleventhdimensions[2] = length; break; case REDSTONE: plugin.redstonedimensions[0] = height; plugin.redstonedimensions[1] = width; plugin.redstonedimensions[2] = length; break; case STEAMPUNK: - plugin.redstonedimensions[0] = height; - plugin.redstonedimensions[1] = width; - plugin.redstonedimensions[2] = length; + plugin.steampunkdimensions[0] = height; + plugin.steampunkdimensions[1] = width; + plugin.steampunkdimensions[2] = length; break; } byte[] blocks = (byte[]) getChildTag(tagCollection, "Blocks", ByteArrayTag.class).getValue(); byte[] data = (byte[]) getChildTag(tagCollection, "Data", ByteArrayTag.class).getValue(); nbt.close(); fis.close(); int i = 0; String[] blockdata = new String[width * height * length]; for (byte b : blocks) { blockdata[i] = b + ":" + data[i]; i++; } int j = 0; List<String[][]> layers = new ArrayList<String[][]>(); for (int h = 0; h < height; h++) { String[][] strarr = new String[width][length]; for (int w = 0; w < width; w++) { for (int l = 0; l < length; l++) { strarr[w][l] = blockdata[j]; j++; } } layers.add(strarr); } try { String csvFile = fileStr + ".csv"; File file = new File(csvFile); BufferedWriter bw = new BufferedWriter(new FileWriter(file, false)); for (String[][] l : layers) { for (String[] lines : l) { StringBuilder buf = new StringBuilder(); for (String bd : lines) { buf.append(bd).append(","); } String commas = buf.toString(); String strCommas = commas.substring(0, (commas.length() - 1)); bw.write(strCommas); bw.newLine(); } } bw.close(); } catch (IOException io) { plugin.console.sendMessage(plugin.pluginName + "Could not save the TARDIS csv file!"); } } catch (IOException e) { plugin.console.sendMessage(plugin.pluginName + "Schematic read error: " + e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } } } } }
true
true
public void readAndMakeInteriorCSV(String fileStr, TARDISConstants.SCHEMATIC s) { plugin.debug("Loading schematic: " + fileStr); FileInputStream fis = null; try { File f = new File(fileStr); fis = new FileInputStream(f); NBTInputStream nbt = new NBTInputStream(fis); CompoundTag backuptag = (CompoundTag) nbt.readTag(); Map<String, Tag> tagCollection = backuptag.getValue(); short width = (Short) getChildTag(tagCollection, "Width", ShortTag.class).getValue(); short height = (Short) getChildTag(tagCollection, "Height", ShortTag.class).getValue(); short length = (Short) getChildTag(tagCollection, "Length", ShortTag.class).getValue(); switch (s) { case BUDGET: plugin.budgetdimensions[0] = height; plugin.budgetdimensions[1] = width; plugin.budgetdimensions[2] = length; break; case BIGGER: plugin.biggerdimensions[0] = height; plugin.biggerdimensions[1] = width; plugin.biggerdimensions[2] = length; break; case DELUXE: plugin.deluxedimensions[0] = height; plugin.deluxedimensions[1] = width; plugin.deluxedimensions[2] = length; break; case ELEVENTH: plugin.eleventhdimensions[0] = height; plugin.eleventhdimensions[1] = width; plugin.eleventhdimensions[2] = length; break; case REDSTONE: plugin.redstonedimensions[0] = height; plugin.redstonedimensions[1] = width; plugin.redstonedimensions[2] = length; break; case STEAMPUNK: plugin.redstonedimensions[0] = height; plugin.redstonedimensions[1] = width; plugin.redstonedimensions[2] = length; break; } byte[] blocks = (byte[]) getChildTag(tagCollection, "Blocks", ByteArrayTag.class).getValue(); byte[] data = (byte[]) getChildTag(tagCollection, "Data", ByteArrayTag.class).getValue(); nbt.close(); fis.close(); int i = 0; String[] blockdata = new String[width * height * length]; for (byte b : blocks) { blockdata[i] = b + ":" + data[i]; i++; } int j = 0; List<String[][]> layers = new ArrayList<String[][]>(); for (int h = 0; h < height; h++) { String[][] strarr = new String[width][length]; for (int w = 0; w < width; w++) { for (int l = 0; l < length; l++) { strarr[w][l] = blockdata[j]; j++; } } layers.add(strarr); } try { String csvFile = fileStr + ".csv"; File file = new File(csvFile); BufferedWriter bw = new BufferedWriter(new FileWriter(file, false)); for (String[][] l : layers) { for (String[] lines : l) { StringBuilder buf = new StringBuilder(); for (String bd : lines) { buf.append(bd).append(","); } String commas = buf.toString(); String strCommas = commas.substring(0, (commas.length() - 1)); bw.write(strCommas); bw.newLine(); } } bw.close(); } catch (IOException io) { plugin.console.sendMessage(plugin.pluginName + "Could not save the TARDIS csv file!"); } } catch (IOException e) { plugin.console.sendMessage(plugin.pluginName + "Schematic read error: " + e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } } } }
public void readAndMakeInteriorCSV(String fileStr, TARDISConstants.SCHEMATIC s) { plugin.debug("Loading schematic: " + fileStr); FileInputStream fis = null; try { File f = new File(fileStr); fis = new FileInputStream(f); NBTInputStream nbt = new NBTInputStream(fis); CompoundTag backuptag = (CompoundTag) nbt.readTag(); Map<String, Tag> tagCollection = backuptag.getValue(); short width = (Short) getChildTag(tagCollection, "Width", ShortTag.class).getValue(); short height = (Short) getChildTag(tagCollection, "Height", ShortTag.class).getValue(); short length = (Short) getChildTag(tagCollection, "Length", ShortTag.class).getValue(); switch (s) { case BUDGET: plugin.budgetdimensions[0] = height; plugin.budgetdimensions[1] = width; plugin.budgetdimensions[2] = length; break; case BIGGER: plugin.biggerdimensions[0] = height; plugin.biggerdimensions[1] = width; plugin.biggerdimensions[2] = length; break; case DELUXE: plugin.deluxedimensions[0] = height; plugin.deluxedimensions[1] = width; plugin.deluxedimensions[2] = length; break; case ELEVENTH: plugin.eleventhdimensions[0] = height; plugin.eleventhdimensions[1] = width; plugin.eleventhdimensions[2] = length; break; case REDSTONE: plugin.redstonedimensions[0] = height; plugin.redstonedimensions[1] = width; plugin.redstonedimensions[2] = length; break; case STEAMPUNK: plugin.steampunkdimensions[0] = height; plugin.steampunkdimensions[1] = width; plugin.steampunkdimensions[2] = length; break; } byte[] blocks = (byte[]) getChildTag(tagCollection, "Blocks", ByteArrayTag.class).getValue(); byte[] data = (byte[]) getChildTag(tagCollection, "Data", ByteArrayTag.class).getValue(); nbt.close(); fis.close(); int i = 0; String[] blockdata = new String[width * height * length]; for (byte b : blocks) { blockdata[i] = b + ":" + data[i]; i++; } int j = 0; List<String[][]> layers = new ArrayList<String[][]>(); for (int h = 0; h < height; h++) { String[][] strarr = new String[width][length]; for (int w = 0; w < width; w++) { for (int l = 0; l < length; l++) { strarr[w][l] = blockdata[j]; j++; } } layers.add(strarr); } try { String csvFile = fileStr + ".csv"; File file = new File(csvFile); BufferedWriter bw = new BufferedWriter(new FileWriter(file, false)); for (String[][] l : layers) { for (String[] lines : l) { StringBuilder buf = new StringBuilder(); for (String bd : lines) { buf.append(bd).append(","); } String commas = buf.toString(); String strCommas = commas.substring(0, (commas.length() - 1)); bw.write(strCommas); bw.newLine(); } } bw.close(); } catch (IOException io) { plugin.console.sendMessage(plugin.pluginName + "Could not save the TARDIS csv file!"); } } catch (IOException e) { plugin.console.sendMessage(plugin.pluginName + "Schematic read error: " + e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } } } }
diff --git a/src/me/blackvein/quests/PlayerListener.java b/src/me/blackvein/quests/PlayerListener.java index c75fda1..43ee395 100644 --- a/src/me/blackvein/quests/PlayerListener.java +++ b/src/me/blackvein/quests/PlayerListener.java @@ -1,839 +1,839 @@ package me.blackvein.quests; import java.io.File; import java.util.HashMap; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.conversations.Conversable; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityTameEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerFishEvent.State; import org.bukkit.event.player.*; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class PlayerListener implements Listener { Quests plugin; public PlayerListener(Quests newPlugin) { plugin = newPlugin; } @EventHandler public void onPlayerInteract(PlayerInteractEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { if (evt.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { final Quester quester = plugin.getQuester(evt.getPlayer().getName()); final Player player = evt.getPlayer(); if (quester.hasObjective("useBlock")) { quester.useBlock(evt.getClickedBlock().getType()); } else { for (final Quest q : plugin.quests) { if (q.blockStart != null) { if (q.blockStart.equals(evt.getClickedBlock().getLocation())) { if (quester.currentQuest != null) { player.sendMessage(ChatColor.YELLOW + "You may only have one active Quest."); } else { if (quester.completedQuests.contains(q.name)) { if (q.redoDelay < 0 || q.redoDelay > -1 && (quester.getDifference(q)) > 0) { player.sendMessage(ChatColor.YELLOW + "You may not take " + ChatColor.AQUA + q.name + ChatColor.YELLOW + " again for another " + ChatColor.DARK_PURPLE + Quests.getTime(quester.getDifference(q)) + ChatColor.YELLOW + "."); return; } } quester.questToTake = q.name; String s = ChatColor.GOLD + "- " + ChatColor.DARK_PURPLE + quester.questToTake + ChatColor.GOLD + " -\n" + "\n" + ChatColor.RESET + plugin.getQuest(quester.questToTake).description + "\n"; player.sendMessage(s); plugin.conversationFactory.buildConversation((Conversable) player).begin(); } break; } } } } } } } @EventHandler public void onBlockDamage(BlockDamageEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.hasObjective("damageBlock")) { quester.damageBlock(evt.getBlock().getType()); } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockPlace(BlockPlaceEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.hasObjective("placeBlock")) { if (evt.isCancelled() == false) { quester.placeBlock(evt.getBlock().getType()); } } } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockBreak(BlockBreakEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { boolean canOpen = true; if (canOpen == true) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.hasObjective("breakBlock")) { if (evt.getPlayer().getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH) == false && evt.isCancelled() == false) { quester.breakBlock(evt.getBlock().getType()); } } if (quester.hasObjective("placeBlock")) { if (quester.blocksPlaced.containsKey(evt.getBlock().getType())) { if (quester.blocksPlaced.get(evt.getBlock().getType()) > 0) { if (evt.isCancelled() == false) { quester.blocksPlaced.put(evt.getBlock().getType(), quester.blocksPlaced.get(evt.getBlock().getType()) - 1); } } } } if (evt.getPlayer().getItemInHand().getType().equals(Material.SHEARS) && quester.hasObjective("cutBlock")) { quester.cutBlock(evt.getBlock().getType()); } } } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.hasObjective("collectItem")) { quester.collectItem(evt.getItem().getItemStack()); } } } @EventHandler public void onPlayerShearEntity(PlayerShearEntityEvent evt) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (evt.getEntity().getType().equals(EntityType.SHEEP) && quester.hasObjective("shearSheep")) { Sheep sheep = (Sheep) evt.getEntity(); quester.shearSheep(sheep.getColor()); } } } @EventHandler public void onEntityTame(EntityTameEvent evt) { if (evt.getOwner() instanceof Player) { Player p = (Player) evt.getOwner(); if (plugin.checkQuester(p.getName()) == false) { Quester quester = plugin.getQuester(p.getName()); if (quester.hasObjective("tameMob")) { quester.tameMob(evt.getEntityType()); } } } } @EventHandler public void onEnchantItem(EnchantItemEvent evt) { if (plugin.checkQuester(evt.getEnchanter().getName()) == false) { Quester quester = plugin.getQuester(evt.getEnchanter().getName()); if (quester.hasObjective("enchantItem")) { for (Enchantment e : evt.getEnchantsToAdd().keySet()) { quester.enchantItem(e, evt.getItem().getType()); } } } } @EventHandler public void onCraftItem(final CraftItemEvent evt) { if (evt.getWhoClicked() instanceof Player) { Player p = (Player) evt.getWhoClicked(); if (plugin.checkQuester(p.getName()) == false) { final Quester quester = plugin.getQuester(p.getName()); if (evt.isShiftClick() == false && quester.hasObjective("craftItem")) { quester.craftItem(evt.getCurrentItem()); }else if(quester.hasObjective("craftItem")){ final int amntBefore = Quests.countInv(evt.getInventory(), evt.getCurrentItem().getType(), evt.getCurrentItem().getAmount()); System.out.println("Amount before: " + amntBefore); final Material mat = evt.getCurrentItem().getType(); final Inventory inv = evt.getWhoClicked().getInventory(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable(){ @Override public void run(){ if(evt.isCancelled() == false){ int amntAfter = Quests.countInv(inv, mat, 0); System.out.println("Amount after: " + amntAfter); quester.craftItem(new ItemStack(mat, amntAfter - amntBefore)); } } }, 5); } } } } @EventHandler public void onInventoryClose(InventoryCloseEvent evt) { if (evt.getPlayer() instanceof Player) { if (plugin.checkQuester(evt.getPlayer().getName()) == false) { Quester quester = plugin.getQuester(((Player) evt.getPlayer()).getName()); if (quester.holdingQuestItemFromStorage) { quester.collectItem(evt.getView().getCursor()); } quester.holdingQuestItemFromStorage = false; } } } /* * * CRAFTING (Player) * * 0 - Crafted Slot 1 - Top-left Craft Slot 2 - Top-right Craft Slot 3 - * Bottom-left Craft Slot 4 - Bottom-right Craft Slot * * 5 - Head Slot 6 - Body Slot 7 - Leg Slot 8 - Boots Slot * * 9-35 - Top-left to Bottom-right inventory slots 36-44 - Left to Right * hotbar slots * * -999 - Drop Slot * * * BREWING * * 0 - Left Potion Slot 1 - Middle Potion Slot 2 - Right Potion Slot 3- * Ingredient Slot * * 4-30 - Top-left to Bottom-right inventory slots 31-39 - Left to Right * hotbar slots * * ENCHANTING * * 0 - Enchant Slot * * 1-27 - Top-left to Bottom-right inventory slots 28-36 - Left to Right * hotbar slots * * ENDER CHEST * * 0-26 - Top-left to Bottom-right chest slots * * 27-53 - Top-left to Bottom-right inventory slots 54-62 - Left to Right * hotbar slots * * DISPENSER * * 0-8 - Top-left to Bottom-right dispenser slots * * 9-35 - Top-left to Bottom-right inventory slots 36-44 - Left to Right * hotbar slots * * FURNACE * * 0 - Furnace Slot 1 - Fuel Slot 2 - Product Slot * * 3-29 - Top-left to Bottom-right inventory slots 30-38 - Left to Right * hotbar slots * * WORKBENCH * * 0 - Product Slot 1-9 - Top-left to Bottom-right crafting slots * * CHEST * * 0-26 - Top-left to Bottom-right chest slots * * 27-53 - Top-left to Bottom-right inventory slots 54-62 - Left to Right * hotbar slots * * CHEST (Double) * * 0-53 - Top-left to Bottom-right chest slots * * 54-80 - Top-left to Bottom-right inventory slots 81-89 - Left to Right * hotbar slots * */ @EventHandler(priority = EventPriority.LOWEST) public void onInventoryClick(InventoryClickEvent evt) { Player player = null; if (evt.getWhoClicked() instanceof Player) { player = (Player) evt.getWhoClicked(); } if (player != null) { if (plugin.checkQuester(player.getName()) == false) { if (evt.isShiftClick() == false) { if (evt.getCursor() != null && evt.getCurrentItem() == null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Placing Quest item in empty slot String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { //Placing Quest item in an allowed player inventory slot if (quester.holdingQuestItemFromStorage) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } else if (evt.getCursor() != null && evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCurrentItem().getType()) || quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Either the cursor item or the slot item (or both) is a Quest item Material cursor = evt.getCursor().getType(); Material slot = evt.getCurrentItem().getType(); if (cursor == slot && quester.currentQuest.questItems.containsKey(cursor)) { //Both are the same item, and quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { ItemStack from = evt.getCursor(); ItemStack to = evt.getCurrentItem(); if ((from.getAmount() + to.getAmount()) <= from.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { quester.collectItem(from); quester.holdingQuestItemFromStorage = false; } } else if ((from.getAmount() + to.getAmount()) > from.getMaxStackSize() && to.getAmount() < to.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { ItemStack difference = to.clone(); difference.setAmount(difference.getMaxStackSize() - difference.getAmount()); quester.collectItem(difference); quester.holdingQuestItemFromStorage = false; } } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(cursor)) { //Cursor is a quest item, item in clicked slot is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(slot)) { //Item in clicked slot is a quest item, cursor is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { quester.holdingQuestItemFromStorage = true; } } else { //Both are different quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } } } else { if (evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); Material mat = evt.getCurrentItem().getType(); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(mat)) { if((evt.getInventory().getType().equals(InventoryType.WORKBENCH) && evt.getRawSlot() == 0) || (evt.getInventory().getType().equals(InventoryType.CRAFTING) && evt.getRawSlot() == 0)){ return; } - List<Integer> changedSlots = Quester.getChangedSlots(evt.getInventory(), evt.getCurrentItem()); + List<Integer> changedSlots = Quester.getChangedSlots(evt.getWhoClicked().getInventory(), evt.getCurrentItem()); System.out.println("Number of changed slots: " + changedSlots.size()); boolean can = true; for (int i : changedSlots) { String s = Quester.checkPlacement(evt.getInventory(), i); if (s != null) { System.out.println("BAD Changed slot: " + i); can = false; break; } } if (!can) { System.out.println("Cannot."); evt.setCancelled(true); player.updateInventory(); } else if (can && Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()) != null) { ItemStack oldStack = evt.getCurrentItem(); Inventory inv = plugin.getServer().createInventory(null, evt.getInventory().getType()); HashMap<Integer, ItemStack> map = inv.addItem(oldStack); if (map.isEmpty() == false) { ItemStack newStack = oldStack.clone(); newStack.setAmount(oldStack.getAmount() - map.get(0).getAmount()); quester.collectItem(newStack); } else { quester.collectItem(oldStack); } } } } } } } } } @EventHandler public void onEntityDeath(EntityDeathEvent evt) { if (evt.getEntity() instanceof Player == false) { if (evt.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) evt.getEntity().getLastDamageCause(); Entity damager = damageEvent.getDamager(); if (damager != null) { if (damager instanceof Projectile) { Projectile p = (Projectile) damager; if (p.getShooter() instanceof Player) { Player player = (Player) p.getShooter(); boolean okay = true; if (plugin.citizens != null) { if (plugin.citizens.getNPCRegistry().isNPC(player)) { okay = false; } } if (okay) { Quester quester = plugin.getQuester(player.getName()); if (quester.hasObjective("killMob")) { quester.killMob(evt.getEntity().getLocation(), evt.getEntity().getType()); } } } } else if (damager instanceof Player) { boolean okay = true; if (plugin.citizens != null) { if (plugin.citizens.getNPCRegistry().isNPC(damager)) { okay = false; } } if (okay) { Player player = (Player) damager; Quester quester = plugin.getQuester(player.getName()); if (quester.hasObjective("killMob")) { quester.killMob(evt.getEntity().getLocation(), evt.getEntity().getType()); } } } } } } } @EventHandler public void onPlayerDeath(PlayerDeathEvent evt) { if (evt.getEntity().getLastDamageCause() instanceof EntityDamageByEntityEvent) { EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) evt.getEntity().getLastDamageCause(); Entity damager = damageEvent.getDamager(); if (damager != null) { if (damager instanceof Projectile) { Projectile p = (Projectile) damager; if (p.getShooter() instanceof Player) { Player player = (Player) p.getShooter(); if (plugin.checkQuester(player.getName()) == false) { boolean okay = true; if (plugin.citizens != null) { if (plugin.citizens.getNPCRegistry().isNPC(player) || plugin.citizens.getNPCRegistry().isNPC(evt.getEntity())) { okay = false; } } if (okay) { Quester quester = plugin.getQuester(player.getName()); if (quester.hasObjective("killPlayer")) { quester.killPlayer(evt.getEntity().getName()); } } } } } else if (damager instanceof Player) { Player player = (Player) damager; if (plugin.checkQuester(player.getName()) == false) { boolean okay = true; if (plugin.citizens != null) { if (plugin.citizens.getNPCRegistry().isNPC(player) || plugin.citizens.getNPCRegistry().isNPC(evt.getEntity())) { okay = false; } } if (okay) { Quester quester = plugin.getQuester(player.getName()); if (quester.hasObjective("killPlayer")) { quester.killPlayer(evt.getEntity().getName()); } } } } } } } @EventHandler public void onPlayerFish(PlayerFishEvent evt) { Player player = evt.getPlayer(); if(plugin.checkQuester(player.getName()) == false){ Quester quester = plugin.getQuester(player.getName()); if (quester.hasObjective("catchFish") && evt.getState().equals(State.CAUGHT_FISH)) { quester.catchFish(); } } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent evt) { if(plugin.checkQuester(evt.getPlayer().getName()) == false){ Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getItemDrop().getItemStack().getType())) { evt.getPlayer().sendMessage(ChatColor.YELLOW + "You may not discard Quest items."); evt.setCancelled(true); } } } } @EventHandler public void onPlayerJoin(PlayerJoinEvent evt) { if(plugin.checkQuester(evt.getPlayer().getName()) == false){ Quester quester = new Quester(plugin); quester.name = evt.getPlayer().getName(); if (new File(plugin.getDataFolder(), "data/" + quester.name + ".yml").exists()) { quester.loadData(); } else { quester.saveData(); } plugin.questers.put(evt.getPlayer().getName(), quester); for (String s : quester.completedQuests) { Quest q = plugin.getQuest(s); if (q != null) { if (quester.completedTimes.containsKey(q.name) == false && q.redoDelay > -1) quester.completedTimes.put(q.name, System.currentTimeMillis()); } } quester.checkQuest(); if(quester.currentQuest != null){ if(quester.currentStage.delay > -1){ quester.startStageTimer(); } } } } @EventHandler public void onPlayerQuit(PlayerQuitEvent evt) { if(plugin.checkQuester(evt.getPlayer().getName()) == false){ Quester quester = plugin.getQuester(evt.getPlayer().getName()); if(quester.currentStage.delay > -1) quester.stopStageTimer(); quester.saveData(); plugin.questers.remove(quester.name); } } @EventHandler public void onPlayerMove(PlayerMoveEvent evt) { if(plugin.checkQuester(evt.getPlayer().getName()) == false){ boolean isPlayer = true; if (plugin.citizens != null) { if (plugin.citizens.getNPCRegistry().isNPC(evt.getPlayer())) { isPlayer = false; } } if (isPlayer) { Quester quester = plugin.getQuester(evt.getPlayer().getName()); if (quester.hasObjective("reachLocation")) { quester.reachLocation(evt.getTo()); } } } } }
true
true
public void onInventoryClick(InventoryClickEvent evt) { Player player = null; if (evt.getWhoClicked() instanceof Player) { player = (Player) evt.getWhoClicked(); } if (player != null) { if (plugin.checkQuester(player.getName()) == false) { if (evt.isShiftClick() == false) { if (evt.getCursor() != null && evt.getCurrentItem() == null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Placing Quest item in empty slot String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { //Placing Quest item in an allowed player inventory slot if (quester.holdingQuestItemFromStorage) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } else if (evt.getCursor() != null && evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCurrentItem().getType()) || quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Either the cursor item or the slot item (or both) is a Quest item Material cursor = evt.getCursor().getType(); Material slot = evt.getCurrentItem().getType(); if (cursor == slot && quester.currentQuest.questItems.containsKey(cursor)) { //Both are the same item, and quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { ItemStack from = evt.getCursor(); ItemStack to = evt.getCurrentItem(); if ((from.getAmount() + to.getAmount()) <= from.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { quester.collectItem(from); quester.holdingQuestItemFromStorage = false; } } else if ((from.getAmount() + to.getAmount()) > from.getMaxStackSize() && to.getAmount() < to.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { ItemStack difference = to.clone(); difference.setAmount(difference.getMaxStackSize() - difference.getAmount()); quester.collectItem(difference); quester.holdingQuestItemFromStorage = false; } } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(cursor)) { //Cursor is a quest item, item in clicked slot is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(slot)) { //Item in clicked slot is a quest item, cursor is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { quester.holdingQuestItemFromStorage = true; } } else { //Both are different quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } } } else { if (evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); Material mat = evt.getCurrentItem().getType(); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(mat)) { if((evt.getInventory().getType().equals(InventoryType.WORKBENCH) && evt.getRawSlot() == 0) || (evt.getInventory().getType().equals(InventoryType.CRAFTING) && evt.getRawSlot() == 0)){ return; } List<Integer> changedSlots = Quester.getChangedSlots(evt.getInventory(), evt.getCurrentItem()); System.out.println("Number of changed slots: " + changedSlots.size()); boolean can = true; for (int i : changedSlots) { String s = Quester.checkPlacement(evt.getInventory(), i); if (s != null) { System.out.println("BAD Changed slot: " + i); can = false; break; } } if (!can) { System.out.println("Cannot."); evt.setCancelled(true); player.updateInventory(); } else if (can && Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()) != null) { ItemStack oldStack = evt.getCurrentItem(); Inventory inv = plugin.getServer().createInventory(null, evt.getInventory().getType()); HashMap<Integer, ItemStack> map = inv.addItem(oldStack); if (map.isEmpty() == false) { ItemStack newStack = oldStack.clone(); newStack.setAmount(oldStack.getAmount() - map.get(0).getAmount()); quester.collectItem(newStack); } else { quester.collectItem(oldStack); } } } } } } } } }
public void onInventoryClick(InventoryClickEvent evt) { Player player = null; if (evt.getWhoClicked() instanceof Player) { player = (Player) evt.getWhoClicked(); } if (player != null) { if (plugin.checkQuester(player.getName()) == false) { if (evt.isShiftClick() == false) { if (evt.getCursor() != null && evt.getCurrentItem() == null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Placing Quest item in empty slot String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { //Placing Quest item in an allowed player inventory slot if (quester.holdingQuestItemFromStorage) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } else if (evt.getCursor() != null && evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(evt.getCurrentItem().getType()) || quester.currentQuest.questItems.containsKey(evt.getCursor().getType())) { //Either the cursor item or the slot item (or both) is a Quest item Material cursor = evt.getCursor().getType(); Material slot = evt.getCurrentItem().getType(); if (cursor == slot && quester.currentQuest.questItems.containsKey(cursor)) { //Both are the same item, and quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { ItemStack from = evt.getCursor(); ItemStack to = evt.getCurrentItem(); if ((from.getAmount() + to.getAmount()) <= from.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { quester.collectItem(from); quester.holdingQuestItemFromStorage = false; } } else if ((from.getAmount() + to.getAmount()) > from.getMaxStackSize() && to.getAmount() < to.getMaxStackSize()) { if (quester.holdingQuestItemFromStorage) { ItemStack difference = to.clone(); difference.setAmount(difference.getMaxStackSize() - difference.getAmount()); quester.collectItem(difference); quester.holdingQuestItemFromStorage = false; } } } else { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(cursor)) { //Cursor is a quest item, item in clicked slot is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } else if (cursor != slot && quester.currentQuest.questItems.containsKey(slot)) { //Item in clicked slot is a quest item, cursor is not String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (s == null) { quester.holdingQuestItemFromStorage = true; } } else { //Both are different quest items String s = Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()); if (quester.holdingQuestItemFromStorage && s == null) { quester.collectItem(evt.getCursor()); quester.holdingQuestItemFromStorage = false; } else if (s != null) { player.sendMessage(ChatColor.YELLOW + s); evt.setCancelled(true); player.updateInventory(); } } } } } } else { if (evt.getCurrentItem() != null) { Quester quester = plugin.getQuester(evt.getWhoClicked().getName()); Material mat = evt.getCurrentItem().getType(); if (quester.currentQuest != null) { if (quester.currentQuest.questItems.containsKey(mat)) { if((evt.getInventory().getType().equals(InventoryType.WORKBENCH) && evt.getRawSlot() == 0) || (evt.getInventory().getType().equals(InventoryType.CRAFTING) && evt.getRawSlot() == 0)){ return; } List<Integer> changedSlots = Quester.getChangedSlots(evt.getWhoClicked().getInventory(), evt.getCurrentItem()); System.out.println("Number of changed slots: " + changedSlots.size()); boolean can = true; for (int i : changedSlots) { String s = Quester.checkPlacement(evt.getInventory(), i); if (s != null) { System.out.println("BAD Changed slot: " + i); can = false; break; } } if (!can) { System.out.println("Cannot."); evt.setCancelled(true); player.updateInventory(); } else if (can && Quester.checkPlacement(evt.getInventory(), evt.getRawSlot()) != null) { ItemStack oldStack = evt.getCurrentItem(); Inventory inv = plugin.getServer().createInventory(null, evt.getInventory().getType()); HashMap<Integer, ItemStack> map = inv.addItem(oldStack); if (map.isEmpty() == false) { ItemStack newStack = oldStack.clone(); newStack.setAmount(oldStack.getAmount() - map.get(0).getAmount()); quester.collectItem(newStack); } else { quester.collectItem(oldStack); } } } } } } } } }
diff --git a/me/Guga/Guga_SERVER_MOD/GugaPort.java b/me/Guga/Guga_SERVER_MOD/GugaPort.java index d8ee754..832e12d 100644 --- a/me/Guga/Guga_SERVER_MOD/GugaPort.java +++ b/me/Guga/Guga_SERVER_MOD/GugaPort.java @@ -1,173 +1,173 @@ package me.Guga.Guga_SERVER_MOD; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import org.bukkit.Location; public abstract class GugaPort { public static void SetPlugin(Guga_SERVER_MOD gugaSM) { plugin = gugaSM; } public static GugaPlace GetPlaceByName(String name) { Iterator<GugaPlace> i = places.iterator(); while (i.hasNext()) { GugaPlace e = i.next(); if (e.GetName().equalsIgnoreCase(name)) { return e; } } return null; } public static void AddPlace(String name, String owner, Location loc) { GugaPlace place = new GugaPlace(name, owner, loc); places.add(place); SavePlaces(); } public static void AddPlace(GugaPlace place) { places.add(place); SavePlaces(); } public static void RemovePlace(GugaPlace place) { places.remove(place); SavePlaces(); } public static void SavePlaces() { plugin.log.info("Saving Places Data..."); File file = new File(placesFile); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { FileWriter fStream = new FileWriter(file, false); BufferedWriter bWriter; bWriter = new BufferedWriter(fStream); String line; Iterator<GugaPlace> i = places.iterator(); while (i.hasNext()) { line = i.next().toString(); bWriter.write(line); bWriter.newLine(); } bWriter.close(); fStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static void LoadPlaces() { plugin.log.info("Loading Places Data..."); File file = new File(placesFile); if (!file.exists()) { try { file.createNewFile(); return; } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream fRead = new FileInputStream(file); DataInputStream inStream = new DataInputStream(fRead); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String line; String []splittedLine; String name; int x; int y; int z; String world; String owner; try { while ((line = bReader.readLine()) != null) { splittedLine = line.split(";"); name = splittedLine[0]; owner = splittedLine[1]; x = Integer.parseInt(splittedLine[2]); y = Integer.parseInt(splittedLine[3]); z = Integer.parseInt(splittedLine[4]); - world = splittedLine[4]; + world = splittedLine[5]; places.add(new GugaPlace(plugin.getServer().getWorld(world),name , owner, x, y, z)); } bReader.close(); inStream.close(); fRead.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } public static ArrayList<GugaPlace> GetPlacesForPlayer(String pName) { @SuppressWarnings("unchecked") ArrayList<GugaPlace> p = (ArrayList<GugaPlace>) places.clone(); Collections.copy(p, places); Iterator<GugaPlace> i = places.iterator(); while (i.hasNext()) { GugaPlace e = i.next(); if (e.GetOwner().equalsIgnoreCase("all")) { // Do nothing } else if (!e.GetOwner().equalsIgnoreCase(pName)) { p.remove(e); } } return p; } public static ArrayList<GugaPlace> GetAllPlaces() { return places; } private static String placesFile = "plugins/Places.dat"; private static ArrayList<GugaPlace> places = new ArrayList<GugaPlace>(); private static Guga_SERVER_MOD plugin; }
true
true
public static void LoadPlaces() { plugin.log.info("Loading Places Data..."); File file = new File(placesFile); if (!file.exists()) { try { file.createNewFile(); return; } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream fRead = new FileInputStream(file); DataInputStream inStream = new DataInputStream(fRead); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String line; String []splittedLine; String name; int x; int y; int z; String world; String owner; try { while ((line = bReader.readLine()) != null) { splittedLine = line.split(";"); name = splittedLine[0]; owner = splittedLine[1]; x = Integer.parseInt(splittedLine[2]); y = Integer.parseInt(splittedLine[3]); z = Integer.parseInt(splittedLine[4]); world = splittedLine[4]; places.add(new GugaPlace(plugin.getServer().getWorld(world),name , owner, x, y, z)); } bReader.close(); inStream.close(); fRead.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
public static void LoadPlaces() { plugin.log.info("Loading Places Data..."); File file = new File(placesFile); if (!file.exists()) { try { file.createNewFile(); return; } catch (IOException e) { e.printStackTrace(); return; } } else { try { FileInputStream fRead = new FileInputStream(file); DataInputStream inStream = new DataInputStream(fRead); BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream)); String line; String []splittedLine; String name; int x; int y; int z; String world; String owner; try { while ((line = bReader.readLine()) != null) { splittedLine = line.split(";"); name = splittedLine[0]; owner = splittedLine[1]; x = Integer.parseInt(splittedLine[2]); y = Integer.parseInt(splittedLine[3]); z = Integer.parseInt(splittedLine[4]); world = splittedLine[5]; places.add(new GugaPlace(plugin.getServer().getWorld(world),name , owner, x, y, z)); } bReader.close(); inStream.close(); fRead.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
diff --git a/QikSMSGenerator/src/com/hashcap/qiksmsgenerator/Generator.java b/QikSMSGenerator/src/com/hashcap/qiksmsgenerator/Generator.java index b296357..33f7762 100644 --- a/QikSMSGenerator/src/com/hashcap/qiksmsgenerator/Generator.java +++ b/QikSMSGenerator/src/com/hashcap/qiksmsgenerator/Generator.java @@ -1,245 +1,245 @@ /* * Copyright (C) 2012-2013 Hashcap Pvt. Ltd. */ package com.hashcap.qiksmsgenerator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import android.content.ContentValues; import android.content.Context; import android.net.Uri; import android.provider.Telephony.Sms; import android.provider.Telephony.Threads; import android.text.TextUtils; import android.util.Log; import com.hashcap.qiksmsgenerator.GeneratorUtils.FolderIndex; import com.hashcap.qiksmsgenerator.GeneratorUtils.FolderName; import com.hashcap.qiksmsgenerator.support.OnGeneratorStartListener; import com.hashcap.qiksmsgenerator.support.OnGeneratorStatusChangedListener; public class Generator { private static String TAG = "Generator"; public static final int MAX_GENERATOR = 5; public static int sTotal = 0; public static int sPosition = 0; private OnGeneratorStartListener mGeneratorStartListener; private Uri mUri; private int mType; private int mGenerated; private DataSettings mDataSettings; private static final Random RANDOM = new Random(); private Context mContext; private static OnGeneratorStatusChangedListener mGeneratorActiveListener; private static boolean mIsGeneratorQueueFull; public Generator(Context context, int type) { mContext = context; mType = type; } public Context getContext() { return mContext; } public DataSettings getDataSettings() { return mDataSettings; } public void setDataSettings(DataSettings dataSettings) { this.mDataSettings = dataSettings; } public int getGenerated() { return mGenerated; } public void setGenerated(int generated) { this.mGenerated = generated; } public void increment() { this.mGenerated++; Generator.sPosition++; } public Uri getUri() { return mUri; } public void setUri(Uri uri) { this.mUri = uri; } public int getType() { return mType; } public void setType(int type) { this.mType = type; } @Override public String toString() { return " mType = " + mType + "[" + FolderName.getName(mType) + "]" + " , mDataSettings = " + getDataSettings(); } public void start() { if (mGeneratorStartListener != null) { mGeneratorStartListener.onGeneratorStart(this); } } public void setOnGeneratorStartListener( OnGeneratorStartListener generatorStartListener) { mGeneratorStartListener = generatorStartListener; } private String getBody() { MessageData data = MessageData.getInstance(getContext()); DataSettings dataSettings = getDataSettings(); String body = dataSettings.getBody(); if (!TextUtils.isEmpty(body)) { return body; } int index = RANDOM.nextInt(6); StringBuilder builder = new StringBuilder(); for (int i = 0; i <= index; i++) { if (dataSettings.isText()) { builder.append(" " + data.getText(i)); } if (dataSettings.isEmail()) { builder.append(" " + data.getEmailAddress(i)); } if (dataSettings.isSmiley()) { builder.append(" " + data.getSmiley()); } if (dataSettings.isPhone()) { builder.append(" " + data.getPhoneNumber(i)); } if (dataSettings.isWeb()) { builder.append(" " + data.getWebAddress(i)); } } return builder.toString(); } public List<String> getAddress() { List<String> list = new ArrayList<String>(); int index = RANDOM.nextInt(10); String[] recipients = mDataSettings.getRecipients(); MessageData data = MessageData.getInstance(getContext()); if (mType == FolderIndex.INBOX) { - if (recipients.length > 0) { + if (recipients != null && recipients.length > 0) { list.add(recipients[0]); } else { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } } else { - if (recipients.length > 0) { + if (recipients != null && recipients.length > 0) { list.addAll(Arrays.asList(recipients)); } else { if (getDataSettings().isSingleRecipient()) { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } else { if (index < 2) { index = 2; } for (int i = 0; i < index; i++) { Long address = Long.parseLong(data.getRecipient(i)) + mGenerated; list.add(Long.toString(address)); } } } } return list; } public static int getTotal() { return sTotal; } public static int getPosition() { return sPosition; } /** * Initialised all recommended fields for SMS, if address is null or empty * auto generated address will assign as address. * * @param address * @return {@link ContentValues} */ public ContentValues getSms(String address) { ContentValues values = initContentValue(address); long now = System.currentTimeMillis(); values.put("date", now); values.put("read", 0); values.put("seen", 0); values.put("reply_path_present", 0); values.put("service_center", "000000000000"); values.put("body", getBody()); if (!values.containsKey(Sms.TYPE)) { values.put(Sms.TYPE, mType == 0 ? RANDOM.nextInt(2) + 1 : mType); } Log.v(TAG, "mTag = " + values.getAsString(Sms.TYPE)); return values; } /** * Init message Content Value, its create threads id using address. * * @param address * @return {@link ContentValues} */ private ContentValues initContentValue(String address) { ContentValues values = new ContentValues(); if (TextUtils.isEmpty(address)) { values.put("address", TextUtils.join(",", getAddress().toArray())); } else { values.put("address", address); } Long threadId = values.getAsLong(Sms.THREAD_ID); address = values.getAsString(Sms.ADDRESS); if (((threadId == null) || (threadId == 0)) && (address != null)) { threadId = Threads.getOrCreateThreadId(getContext(), address); values.put(Sms.THREAD_ID, threadId); } return values; } public static void registerGeneratorActiveListener( OnGeneratorStatusChangedListener generatorActiveListener) { mGeneratorActiveListener = generatorActiveListener; } public static void unregisterGeneratorActiveListener() { mGeneratorActiveListener = null; } public static OnGeneratorStatusChangedListener getGeneratorActiveListener() { return mGeneratorActiveListener; } synchronized public static boolean isGeneratorQueueFull() { return mIsGeneratorQueueFull; } synchronized public static void setGeneratorQueueFull(boolean enabled) { mIsGeneratorQueueFull = enabled; } }
false
true
public List<String> getAddress() { List<String> list = new ArrayList<String>(); int index = RANDOM.nextInt(10); String[] recipients = mDataSettings.getRecipients(); MessageData data = MessageData.getInstance(getContext()); if (mType == FolderIndex.INBOX) { if (recipients.length > 0) { list.add(recipients[0]); } else { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } } else { if (recipients.length > 0) { list.addAll(Arrays.asList(recipients)); } else { if (getDataSettings().isSingleRecipient()) { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } else { if (index < 2) { index = 2; } for (int i = 0; i < index; i++) { Long address = Long.parseLong(data.getRecipient(i)) + mGenerated; list.add(Long.toString(address)); } } } } return list; }
public List<String> getAddress() { List<String> list = new ArrayList<String>(); int index = RANDOM.nextInt(10); String[] recipients = mDataSettings.getRecipients(); MessageData data = MessageData.getInstance(getContext()); if (mType == FolderIndex.INBOX) { if (recipients != null && recipients.length > 0) { list.add(recipients[0]); } else { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } } else { if (recipients != null && recipients.length > 0) { list.addAll(Arrays.asList(recipients)); } else { if (getDataSettings().isSingleRecipient()) { Long address = Long.parseLong(data.getRecipient(index)) + mGenerated; list.add(Long.toString(address)); } else { if (index < 2) { index = 2; } for (int i = 0; i < index; i++) { Long address = Long.parseLong(data.getRecipient(i)) + mGenerated; list.add(Long.toString(address)); } } } } return list; }
diff --git a/src/com/redhat/ceylon/compiler/java/launcher/Main.java b/src/com/redhat/ceylon/compiler/java/launcher/Main.java index 61a5b5a81..747e42cc1 100644 --- a/src/com/redhat/ceylon/compiler/java/launcher/Main.java +++ b/src/com/redhat/ceylon/compiler/java/launcher/Main.java @@ -1,575 +1,577 @@ /* * Copyright (c) 1999, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. */ package com.redhat.ceylon.compiler.java.launcher; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.EnumSet; import java.util.MissingResourceException; import javax.annotation.processing.Processor; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardLocation; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.tools.CeyloncFileManager; import com.redhat.ceylon.compiler.java.tools.LanguageCompiler; import com.redhat.ceylon.compiler.java.util.Timer; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.main.CommandLine; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.main.JavacOption.Option; import com.sun.tools.javac.main.RecognizedOptions; import com.sun.tools.javac.main.RecognizedOptions.OptionHelper; import com.sun.tools.javac.processing.AnnotationProcessingError; import com.sun.tools.javac.util.ClientCodeException; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.FatalError; import com.sun.tools.javac.util.JavacMessages; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Options; import com.sun.tools.javac.util.PropagatedException; /** * This class provides a commandline interface to the GJC compiler. * * <p> * <b>This is NOT part of any supported API. If you write code that depends on * this, you do so at your own risk. This code and its internal interfaces are * subject to change or deletion without notice.</b> */ public class Main extends com.sun.tools.javac.main.Main { /** * The name of the compiler, for use in diagnostics. */ String ownName; /** * The writer to use for diagnostic output. */ PrintWriter out; /** * If true, any command line arg errors will cause an exception. */ boolean fatalErrors; /** * Result codes. */ static final int EXIT_OK = 0, // Compilation completed with no errors. EXIT_ERROR = 1, // Completed but reported errors. EXIT_CMDERR = 2, // Bad command-line arguments EXIT_SYSERR = 3, // System error or resource exhaustion. EXIT_ABNORMAL = 4; // Compiler terminated abnormally private Option[] recognizedOptions = RecognizedOptions.getJavaCompilerOptions(new OptionHelper() { public void setOut(PrintWriter out) { Main.this.out = out; } public void error(String key, Object... args) { Main.this.error(key, args); } public void printVersion() { Log.printLines(out, getLocalizedString("version", ownName, JavaCompiler.version())); } public void printFullVersion() { Log.printLines(out, getLocalizedString("fullVersion", ownName, JavaCompiler.fullVersion())); } public void printHelp() { help(); } public void printXhelp() { xhelp(); } public void addFile(File f) { if (!filenames.contains(f)) filenames.append(f); } public void addClassName(String s) { classnames.append(s); } }); /** * Construct a compiler instance. */ public Main(String name) { this(name, new PrintWriter(System.err, true)); } /** * Construct a compiler instance. */ public Main(String name, PrintWriter out) { super(name, out); this.ownName = name; this.out = out; } /** A table of all options that's passed to the JavaCompiler constructor. */ private Options options = null; /** A timer used to calculate task execution times times */ private Timer timer = null; /** * The list of source files to process */ public ListBuffer<File> filenames = null; // XXX sb protected /** * List of class files names passed on the command line */ public ListBuffer<String> classnames = null; // XXX sb protected /** * Report a usage error. */ void error(String key, Object... args) { if (fatalErrors) { String msg = getLocalizedString(key, args); throw new PropagatedException(new IllegalStateException(msg)); } warning(key, args); Log.printLines(out, getLocalizedString("msg.usage", ownName)); } /** * Report a warning. */ void warning(String key, Object... args) { Log.printLines(out, ownName + ": " + getLocalizedString(key, args)); } public Option getOption(String flag) { for (Option option : recognizedOptions) { if (option.matches(flag)) return option; } return null; } public void setOptions(Options options) { if (options == null) throw new NullPointerException(); this.options = options; } public void setFatalErrors(boolean fatalErrors) { this.fatalErrors = fatalErrors; } /** * Process command line arguments: store all command line options in * `options' table and return all source filenames. * @param flags The array of command line arguments. */ public List<File> processArgs(String[] flags) { // XXX sb protected int ac = 0; while (ac < flags.length) { String flag = flags[ac]; ac++; int j; // quick hack to speed up file processing: // if the option does not begin with '-', there is no need to check // most of the compiler options. int firstOptionToCheck = flag.charAt(0) == '-' ? 0 : recognizedOptions.length - 1; for (j = firstOptionToCheck; j < recognizedOptions.length; j++) if (recognizedOptions[j].matches(flag)) break; if (j == recognizedOptions.length) { error("err.invalid.flag", flag); return null; } Option option = recognizedOptions[j]; if (option.hasArg()) { if (ac == flags.length) { error("err.req.arg", flag); return null; } String operand = flags[ac]; ac++; if (option.process(options, flag, operand)) return null; } else { if (option.process(options, flag)) return null; } } if (!checkDirectoryOrURL("-d")) return null; if (!checkDirectory("-s")) return null; String sourceString = options.get("-source"); Source source = (sourceString != null) ? Source.lookup(sourceString) : Source.DEFAULT; String targetString = options.get("-target"); Target target = (targetString != null) ? Target.lookup(targetString) : Target.DEFAULT; // We don't check source/target consistency for CLDC, as J2ME // profiles are not aligned with J2SE targets; moreover, a // single CLDC target may have many profiles. In addition, // this is needed for the continued functioning of the JSR14 // prototype. if (Character.isDigit(target.name.charAt(0))) { if (target.compareTo(source.requiredTarget()) < 0) { if (targetString != null) { if (sourceString == null) { warning("warn.target.default.source.conflict", targetString, source.requiredTarget().name); } else { warning("warn.source.target.conflict", sourceString, source.requiredTarget().name); } return null; } else { options.put("-target", source.requiredTarget().name); } } else { if (targetString == null && !source.allowGenerics()) { options.put("-target", Target.JDK1_4.name); } } } return filenames.toList(); } // where private boolean checkDirectory(String optName) { String value = options.get(optName); if (value == null) return true; File file = new File(value); if (!file.exists()) { error("err.dir.not.found", value); return false; } if (!file.isDirectory()) { error("err.file.not.directory", value); return false; } return true; } /** * Checker whether optName is a valid URL or directory * @param optName The option name * @return */ private boolean checkDirectoryOrURL(String optName) { String value = options.get(optName); if (value == null) return true; try{ URL url = new URL(value); String scheme = url.getProtocol(); if("http".equals(scheme) || "https".equals(scheme)) return true; error("ceylon.err.output.repo.not.supported", value); return false; }catch(MalformedURLException x){ // not a URL, perhaps a file? } File file = new File(value); if (file.exists() && !file.isDirectory()) { error("err.file.not.directory", value); return false; } return true; } /** * Programmatic interface for main function. * @param args The command line parameters. */ public int compile(String[] args) { Context context = new Context(); CeyloncFileManager.preRegister(context); // can't create it until Log // has been set up CeylonLog.preRegister(context); int result = compile(args, context); if (fileManager instanceof JavacFileManager) { // A fresh context was created above, so jfm must be a // JavacFileManager ((JavacFileManager) fileManager).close(); } return result; } public int compile(String[] args, Context context) { return compile(args, context, List.<JavaFileObject> nil(), null); } /** * Programmatic interface for main function. * @param args The command line parameters. */ public int compile(String[] args, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) { if (options == null) { options = Options.instance(context); // creates a new one } filenames = new ListBuffer<File>(); classnames = new ListBuffer<String>(); JavaCompiler comp = null; /* TODO: Logic below about what is an acceptable command line should be * updated to take annotation processing semantics into account. */ try { if (args.length == 0 && fileObjects.isEmpty()) { help(); return EXIT_CMDERR; } List<File> filenames; try { filenames = processArgs(CommandLine.parse(args)); if (filenames == null) { // null signals an error in options, abort return EXIT_CMDERR; } else if (filenames.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) { // it is allowed to compile nothing if just asking for help // or version info if (options.get("-help") != null || options.get("-jhelp") != null || options.get("-X") != null || options.get("-version") != null || options.get("-fullversion") != null) return EXIT_OK; error("err.no.source.files"); return EXIT_CMDERR; } } catch (java.io.FileNotFoundException e) { Log.printLines(out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage())); return EXIT_SYSERR; } // Set up the timer *after* we've processed to options // because it needs to know if we need logging or not timer = Timer.instance(context); timer.init(); boolean forceStdOut = options.get("stdout") != null; if (forceStdOut) { out.flush(); out = new PrintWriter(System.out, true); } context.put(Log.outKey, out); fileManager = context.get(JavaFileManager.class); comp = LanguageCompiler.instance(context); if (comp == null) return EXIT_SYSERR; if(!classnames.isEmpty()) filenames = addModuleSources(filenames); if (!filenames.isEmpty()) { // add filenames to fileObjects comp = JavaCompiler.instance(context); List<JavaFileObject> otherFiles = List.nil(); JavacFileManager dfm = (JavacFileManager) fileManager; for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(filenames)) otherFiles = otherFiles.prepend(fo); for (JavaFileObject fo : otherFiles) fileObjects = fileObjects.prepend(fo); } if(fileObjects.isEmpty()){ error("err.no.source.files"); return EXIT_CMDERR; } comp.compile(fileObjects, classnames.toList(), processors); if (comp.errorCount() != 0) return EXIT_ERROR; } catch (IOException ex) { ioMessage(ex); return EXIT_SYSERR; } catch (OutOfMemoryError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (StackOverflowError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (FatalError ex) { feMessage(ex); return EXIT_SYSERR; } catch (AnnotationProcessingError ex) { apMessage(ex); return EXIT_SYSERR; } catch (ClientCodeException ex) { // as specified by javax.tools.JavaCompiler#getTask // and javax.tools.JavaCompiler.CompilationTask#call throw new RuntimeException(ex.getCause()); } catch (PropagatedException ex) { throw ex.getCause(); } catch (Throwable ex) { // Nasty. If we've already reported an error, compensate // for buggy compiler error recovery by swallowing thrown // exceptions. if (comp == null || comp.errorCount() == 0 || options == null || options.get("dev") != null) bugMessage(ex); return EXIT_ABNORMAL; } finally { if (comp != null) comp.close(); filenames = null; options = null; - timer.end(); + if (timer != null) { + timer.end(); + } timer = null; } return EXIT_OK; } private List<File> addModuleSources(List<File> filenames) throws IOException { for(String moduleName : classnames){ String path = moduleName.equals("default") ? "" : moduleName; Iterable<JavaFileObject> files = fileManager.list(StandardLocation.SOURCE_PATH, path, EnumSet.of(Kind.SOURCE), true); boolean gotOne = false; for(JavaFileObject file : files){ File f = new File(file.toUri().getPath()); if(!filenames.contains(f)) filenames = filenames.prepend(f); gotOne = true; } if(!gotOne){ warning("ceylon", "Could not find source files for module: "+moduleName); } } classnames.clear(); return filenames; } /** * Print a message reporting an internal error. */ void bugMessage(Throwable ex) { Log.printLines(out, getLocalizedString("msg.bug", JavaCompiler.version())); ex.printStackTrace(out); } /** * Print a message reporting an fatal error. */ void feMessage(Throwable ex) { Log.printLines(out, ex.getMessage()); } /** * Print a message reporting an input/output error. */ void ioMessage(Throwable ex) { Log.printLines(out, getLocalizedString("msg.io")); ex.printStackTrace(out); } /** * Print a message reporting an out-of-resources error. */ void resourceMessage(Throwable ex) { Log.printLines(out, getLocalizedString("msg.resource")); // System.out.println("(name buffer len = " + Name.names.length + " " + // Name.nc);//DEBUG ex.printStackTrace(out); } /** * Print a message reporting an uncaught exception from an annotation * processor. */ void apMessage(AnnotationProcessingError ex) { Log.printLines(out, getLocalizedString("msg.proc.annotation.uncaught.exception")); ex.getCause().printStackTrace(); } private JavaFileManager fileManager; /* ************************************************************************ * Internationalization * *********************************************************************** */ /** * Find a localized string in the resource bundle. * @param key The key for the localized string. */ public static String getLocalizedString(String key, Object... args) { // FIXME // sb // private try { if (messages == null) messages = new JavacMessages(javacBundleName); return messages.getLocalizedString("javac." + key, args); } catch (MissingResourceException e) { throw new Error("Fatal Error: Resource for javac is missing", e); } } public static void useRawMessages(boolean enable) { if (enable) { messages = new JavacMessages(javacBundleName) { @Override public String getLocalizedString(String key, Object... args) { return key; } }; } else { messages = new JavacMessages(javacBundleName); } } private static final String javacBundleName = "com.sun.tools.javac.resources.ceylonc"; private static JavacMessages messages; }
true
true
public int compile(String[] args, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) { if (options == null) { options = Options.instance(context); // creates a new one } filenames = new ListBuffer<File>(); classnames = new ListBuffer<String>(); JavaCompiler comp = null; /* TODO: Logic below about what is an acceptable command line should be * updated to take annotation processing semantics into account. */ try { if (args.length == 0 && fileObjects.isEmpty()) { help(); return EXIT_CMDERR; } List<File> filenames; try { filenames = processArgs(CommandLine.parse(args)); if (filenames == null) { // null signals an error in options, abort return EXIT_CMDERR; } else if (filenames.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) { // it is allowed to compile nothing if just asking for help // or version info if (options.get("-help") != null || options.get("-jhelp") != null || options.get("-X") != null || options.get("-version") != null || options.get("-fullversion") != null) return EXIT_OK; error("err.no.source.files"); return EXIT_CMDERR; } } catch (java.io.FileNotFoundException e) { Log.printLines(out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage())); return EXIT_SYSERR; } // Set up the timer *after* we've processed to options // because it needs to know if we need logging or not timer = Timer.instance(context); timer.init(); boolean forceStdOut = options.get("stdout") != null; if (forceStdOut) { out.flush(); out = new PrintWriter(System.out, true); } context.put(Log.outKey, out); fileManager = context.get(JavaFileManager.class); comp = LanguageCompiler.instance(context); if (comp == null) return EXIT_SYSERR; if(!classnames.isEmpty()) filenames = addModuleSources(filenames); if (!filenames.isEmpty()) { // add filenames to fileObjects comp = JavaCompiler.instance(context); List<JavaFileObject> otherFiles = List.nil(); JavacFileManager dfm = (JavacFileManager) fileManager; for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(filenames)) otherFiles = otherFiles.prepend(fo); for (JavaFileObject fo : otherFiles) fileObjects = fileObjects.prepend(fo); } if(fileObjects.isEmpty()){ error("err.no.source.files"); return EXIT_CMDERR; } comp.compile(fileObjects, classnames.toList(), processors); if (comp.errorCount() != 0) return EXIT_ERROR; } catch (IOException ex) { ioMessage(ex); return EXIT_SYSERR; } catch (OutOfMemoryError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (StackOverflowError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (FatalError ex) { feMessage(ex); return EXIT_SYSERR; } catch (AnnotationProcessingError ex) { apMessage(ex); return EXIT_SYSERR; } catch (ClientCodeException ex) { // as specified by javax.tools.JavaCompiler#getTask // and javax.tools.JavaCompiler.CompilationTask#call throw new RuntimeException(ex.getCause()); } catch (PropagatedException ex) { throw ex.getCause(); } catch (Throwable ex) { // Nasty. If we've already reported an error, compensate // for buggy compiler error recovery by swallowing thrown // exceptions. if (comp == null || comp.errorCount() == 0 || options == null || options.get("dev") != null) bugMessage(ex); return EXIT_ABNORMAL; } finally { if (comp != null) comp.close(); filenames = null; options = null; timer.end(); timer = null; } return EXIT_OK; }
public int compile(String[] args, Context context, List<JavaFileObject> fileObjects, Iterable<? extends Processor> processors) { if (options == null) { options = Options.instance(context); // creates a new one } filenames = new ListBuffer<File>(); classnames = new ListBuffer<String>(); JavaCompiler comp = null; /* TODO: Logic below about what is an acceptable command line should be * updated to take annotation processing semantics into account. */ try { if (args.length == 0 && fileObjects.isEmpty()) { help(); return EXIT_CMDERR; } List<File> filenames; try { filenames = processArgs(CommandLine.parse(args)); if (filenames == null) { // null signals an error in options, abort return EXIT_CMDERR; } else if (filenames.isEmpty() && fileObjects.isEmpty() && classnames.isEmpty()) { // it is allowed to compile nothing if just asking for help // or version info if (options.get("-help") != null || options.get("-jhelp") != null || options.get("-X") != null || options.get("-version") != null || options.get("-fullversion") != null) return EXIT_OK; error("err.no.source.files"); return EXIT_CMDERR; } } catch (java.io.FileNotFoundException e) { Log.printLines(out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage())); return EXIT_SYSERR; } // Set up the timer *after* we've processed to options // because it needs to know if we need logging or not timer = Timer.instance(context); timer.init(); boolean forceStdOut = options.get("stdout") != null; if (forceStdOut) { out.flush(); out = new PrintWriter(System.out, true); } context.put(Log.outKey, out); fileManager = context.get(JavaFileManager.class); comp = LanguageCompiler.instance(context); if (comp == null) return EXIT_SYSERR; if(!classnames.isEmpty()) filenames = addModuleSources(filenames); if (!filenames.isEmpty()) { // add filenames to fileObjects comp = JavaCompiler.instance(context); List<JavaFileObject> otherFiles = List.nil(); JavacFileManager dfm = (JavacFileManager) fileManager; for (JavaFileObject fo : dfm.getJavaFileObjectsFromFiles(filenames)) otherFiles = otherFiles.prepend(fo); for (JavaFileObject fo : otherFiles) fileObjects = fileObjects.prepend(fo); } if(fileObjects.isEmpty()){ error("err.no.source.files"); return EXIT_CMDERR; } comp.compile(fileObjects, classnames.toList(), processors); if (comp.errorCount() != 0) return EXIT_ERROR; } catch (IOException ex) { ioMessage(ex); return EXIT_SYSERR; } catch (OutOfMemoryError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (StackOverflowError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (FatalError ex) { feMessage(ex); return EXIT_SYSERR; } catch (AnnotationProcessingError ex) { apMessage(ex); return EXIT_SYSERR; } catch (ClientCodeException ex) { // as specified by javax.tools.JavaCompiler#getTask // and javax.tools.JavaCompiler.CompilationTask#call throw new RuntimeException(ex.getCause()); } catch (PropagatedException ex) { throw ex.getCause(); } catch (Throwable ex) { // Nasty. If we've already reported an error, compensate // for buggy compiler error recovery by swallowing thrown // exceptions. if (comp == null || comp.errorCount() == 0 || options == null || options.get("dev") != null) bugMessage(ex); return EXIT_ABNORMAL; } finally { if (comp != null) comp.close(); filenames = null; options = null; if (timer != null) { timer.end(); } timer = null; } return EXIT_OK; }
diff --git a/core/src/visad/trunk/RealType.java b/core/src/visad/trunk/RealType.java index bb28cdb52..fe24d2a75 100644 --- a/core/src/visad/trunk/RealType.java +++ b/core/src/visad/trunk/RealType.java @@ -1,1212 +1,1212 @@ // // RealType.java // /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2009 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ package visad; import java.util.*; import java.rmi.*; /** RealType is the VisAD scalar data type for real number variables.<P> */ public class RealType extends ScalarType { private Unit DefaultUnit; // default Unit of RealType /** if not null, this sampling is used as a default when this type is used as the domain or range of a field; null unless explicitly set */ private Set DefaultSet; private boolean DefaultSetEverAccessed; /** * The attribute mask of this RealType. * @serial */ private final int attrMask; /** * The interval attribute. This attribute should be used during construction * of a RealType if the RealType refers to an interval (e.g. length * difference, delta temperature). In general, RealType-s that are temporal * in nature should have this attribute because the "time" variable in most * formulae actually refer to time differences (e.g. "time since the * beginning of the experiment"). One obvious exception to this lies with * cosmology, where "time" is absolute rather than an interval. */ public static final int INTERVAL = 1; /** * Monotonically-increasing counter for creating new, unique names. */ private static int count; /** Cartesian spatial coordinate - X axis */ public final static RealType XAxis = new RealType("XAxis", null, true); /** Cartesian spatial coordinate - Y axis */ public final static RealType YAxis = new RealType("YAxis", null, true); /** Cartesian spatial coordinate - Z axis */ public final static RealType ZAxis = new RealType("ZAxis", null, true); /** Spherical spatial coordinate for Latitude*/ public final static RealType Latitude = new RealType("Latitude", CommonUnit.degree, true); /** Spherical spatial coordinate for Longitude*/ public final static RealType Longitude = new RealType("Longitude", CommonUnit.degree, true); public final static RealType Altitude = new RealType("Altitude", CommonUnit.meter, true); public final static RealType Radius = new RealType("Radius", null, true); /** Temporal-interval coordinate */ public final static RealType TimeInterval = new RealType("TimeInterval", CommonUnit.second, INTERVAL, true); /** Timestamp coordinate */ public final static RealType Time = new RealType("Time", CommonUnit.secondsSinceTheEpoch, true); /** astronomical coordinates */ public final static RealType Declination = new RealType("Declination", CommonUnit.degree, true); public final static RealType RightAscension = new RealType("RightAscension", CommonUnit.degree, true); /** generic RealType */ public final static RealType Generic = new RealType("GENERIC_REAL", CommonUnit.promiscuous, true); /** * Constructs from a name (two RealTypes are equal if their names are equal). * Assumes <code>null</code> for the default Unit and default Set and that * the RealType does <em>not</em> refer to an interval. * @param name The name for the RealType. * @throws VisADException Couldn't create necessary VisAD object. * @deprecated Use {@link #getRealType(String)} */ public RealType(String name) throws VisADException { this(name, 0); } /** * Constructs from a name (two RealTypes are equal if their names are equal) * and whether or not the RealType refers to an interval (e.g. length * difference, delta temperature). Assumes <code>null</code> for the default * Unit and default Set. * @param name The name for the RealType. * @param attrMask The attribute mask. 0 or INTERVAL. * @throws VisADException Couldn't create necessary VisAD object. * @deprecated Use {@link #getRealType(String, int)} */ public RealType(String name, int attrMask) throws VisADException { this(name, null, null, attrMask); } /** * Constructs from a name (two RealTypes are equal if their names are equal) * a default Unit, and a default Set. Assumes that the RealType does * <em>not</em> refer to an interval. * @param name The name for the RealType. * @param u The default unit for the RealType. May be * <code>null</code>. * @param set The default sampling set for the RealType. * Used when this type is a FunctionType domain. * May be <code>null</code>. * @throws VisADException Couldn't create necessary VisAD object. * @deprecated Use {@link #getRealType(String, Unit, Set)} */ public RealType(String name, Unit u, Set set) throws VisADException { this(name, u, set, 0); } /** * Constructs from a name (two RealTypes are equal if their names are equal) * and a default Unit. Assumes the default Set, and that the * RealType does <em>not</em> refer to an interval. * @param name The name for the RealType. * @param u The default unit for the RealType. May be * <code>null</code>. * @throws VisADException Couldn't create necessary VisAD object. * @deprecated Use {@link #getRealType(String, Unit)} */ public RealType(String name, Unit u) throws VisADException { this(name, u, null, 0); } /** * Constructs from a name (two RealTypes are equal if their names are equal) * a default Unit, a default Set, and whether or not the RealType refers to * an interval (e.g. length difference, delta temperature). This is the most * general, public constructor. * @param name The name for the RealType. * @param u The default unit for the RealType. May be * <code>null</code>. If non-<code>null</code> * and the RealType refers to an interval, * then the default unit will actually be * <code>u.getAbsoluteUnit()</code>. * @param set The default sampling set for the RealType. * Used when this type is a FunctionType domain. * May be <code>null</code>. * @param attrMask The attribute mask. 0 or INTERVAL. * @throws VisADException Couldn't create necessary VisAD object. * @deprecated Use {@link #getRealType(String, Unit, Set, int)} */ public RealType(String name, Unit u, Set set, int attrMask) throws VisADException { super(name); if (set != null && set.getDimension() != 1) { throw new SetException("RealType: default set dimension != 1"); } DefaultUnit = u != null && isSet(attrMask, INTERVAL) ? u.getAbsoluteUnit() : u; DefaultSet = set; DefaultSetEverAccessed = false; if (DefaultUnit != null && DefaultSet != null) { Unit[] us = {DefaultUnit}; if (!Unit.canConvertArray(us, DefaultSet.getSetUnits())) { throw new UnitException("RealType: default Unit must be convertable " + "with Set default Unit"); } } this.attrMask = attrMask; } /** trusted constructor for initializers */ protected RealType(String name, Unit u, boolean b) { this(name, u, 0, b); } /** trusted constructor for initializers */ protected RealType(String name, Unit u, int attrMask, boolean b) { super(name, b); DefaultUnit = u != null && isSet(attrMask, INTERVAL) ? u.getAbsoluteUnit() : u; DefaultSet = null; DefaultSetEverAccessed = false; this.attrMask = attrMask; } /** trusted constructor for initializers */ protected RealType(String name, Unit u, Set s, int attrMask, boolean b) throws SetException { super(name, b); if (s != null && s.getDimension() != 1) { throw new SetException("RealType: default set dimension != 1"); } DefaultUnit = u != null && isSet(attrMask, INTERVAL) ? u.getAbsoluteUnit() : u; DefaultSet = s; DefaultSetEverAccessed = false; this.attrMask = attrMask; } /** * Gets the attribute mask of this RealType. * @return The attribute mask of this RealType. */ public final int getAttributeMask() { return attrMask; } /** * Indicates whether or not this RealType refers to an interval (e.g. * length difference, delta temperature). * @return Whether or not this RealType refers to an * interval. */ public final boolean isInterval() { return isSet(getAttributeMask(), INTERVAL); } /** * Indicates if the given bits are set in an integer. */ private static boolean isSet(int value, int mask) { return (value & mask) == mask; } /** get default Unit */ public Unit getDefaultUnit() { return DefaultUnit; } /** get default Set*/ public synchronized Set getDefaultSet() { DefaultSetEverAccessed = true; return DefaultSet; } /** set the default Set; this is a violation of MathType immutability to allow a a RealType to be an argument (directly or through a SetType) to the constructor of its default Set; this method throws an Exception if getDefaultSet has previously been invoked */ public synchronized void setDefaultSet(Set sampling) throws VisADException { if (sampling.getDimension() != 1) { throw new SetException( "RealType.setDefaultSet: default set dimension != 1"); } if (DefaultSetEverAccessed) { throw new TypeException("RealType: DefaultSet already accessed" + " so cannot change"); } DefaultSet = sampling; if (DefaultUnit != null && DefaultSet != null) { Unit[] us = {DefaultUnit}; if (!Unit.canConvertArray(us, DefaultSet.getSetUnits())) { throw new UnitException("RealType: default Unit must be convertable " + "with Set default Unit"); } } } /** * Check the equality of type with this RealType; * two RealType-s are equal if they have the same name, * convertible DefaultUnit-s, same DefaultSet and attrMask; * a RealType copied from a remote Java virtual machine may have * the same name but different values for other fields * @param type object in question * @return true if type is a RealType and the conditions above are met */ public boolean equals(Object type) { if (!(type instanceof RealType)) return false; // WLH 26 Aug 2001 // return Name.equals(((RealType) type).Name); if (!Name.equals(((RealType) type).Name)) return false; if (DefaultUnit == null) { if (((RealType) type).DefaultUnit != null) return false; } else { // DRM 30 Nov 2001 - make less strict //if (!DefaultUnit.equals(((RealType) type).DefaultUnit)) return false; if (!Unit.canConvert(DefaultUnit, ((RealType) type).DefaultUnit)) return false; } if (DefaultSet == null) { if (((RealType) type).DefaultSet != null) return false; } else { if (!DefaultSet.equals(((RealType) type).DefaultSet)) return false; } return attrMask == ((RealType) type).attrMask; } /** any two RealType-s are equal except Name */ public boolean equalsExceptName(MathType type) { if (type instanceof RealTupleType) { try { return (((RealTupleType) type).getDimension() == 1 && ((RealTupleType) type).getComponent(0) instanceof RealType); } catch (VisADException e) { return false; } } return (type instanceof RealType); } /*- TDR May 1998 */ /** * Check to see if type has convertible units with this RealType. * @param type MathType to check * @return true if type is a RealType or a RealTupleType of dimension * 1 AND the units are convertible with this RealType's * default Unit. */ public boolean equalsExceptNameButUnits(MathType type) { try { if (type instanceof RealTupleType && ((RealTupleType) type).getDimension() == 1 && ((RealTupleType) type).getComponent(0) instanceof RealType) { RealType rt = (RealType) ((RealTupleType) type).getComponent(0); return Unit.canConvert( this.getDefaultUnit(), ((RealType)rt).getDefaultUnit() ); } } catch (VisADException e) { return false; } if (!(type instanceof RealType)) { return false; } else { return Unit.canConvert( this.getDefaultUnit(), ((RealType)type).getDefaultUnit() ); } } /*- TDR June 1998 */ public MathType cloneDerivative( RealType d_partial ) throws VisADException { String newName = "d_"+this.getName()+"_"+ "d_"+d_partial.getName(); RealType newType = null; Unit R_unit = this.DefaultUnit; Unit D_unit = d_partial.getDefaultUnit(); Unit u = null; if ( R_unit != null && D_unit != null ) { u = R_unit.divide( D_unit ); } newType = getRealType(newName, u); return newType; } /*- TDR July 1998 */ public MathType binary( MathType type, int op, Vector names ) throws VisADException { /* WLH 10 Sept 98 */ if (type == null) { throw new TypeException("TupleType.binary: type may not be null" ); } Unit newUnit = null; MathType newType = null; String newName; if (type instanceof RealType) { RealType that = (RealType)type; Unit unit = ((RealType)type).getDefaultUnit(); Unit thisUnit = DefaultUnit; int newAttrMask = 0; /* * Determine the attributes of the RealType that will result from the * operation. */ switch (op) { case Data.SUBTRACT: case Data.INV_SUBTRACT: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.ADD: case Data.MAX: case Data.MIN: if (isInterval() && that.isInterval()) newAttrMask |= INTERVAL; break; case Data.MULTIPLY: case Data.DIVIDE: case Data.REMAINDER: case Data.INV_DIVIDE: case Data.INV_REMAINDER: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.POW: newAttrMask = getAttributeMask(); break; case Data.INV_POW: newAttrMask = that.getAttributeMask(); break; case Data.ATAN2: case Data.INV_ATAN2: case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: default: } /* * Determine the RealType that will result from the operation. Use the * previously-determined attributes. */ switch (op) { case Data.ADD: case Data.SUBTRACT: case Data.INV_SUBTRACT: case Data.MAX: case Data.MIN: if (CommonUnit.promiscuous.equals(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit)) { newType = type; } else { if (thisUnit == null || unit == null) { newUnit = null; if (thisUnit == null && unit == null) { newName = Name; } else { newName = getUniqueGenericName(names, newUnit); } } else { if (!thisUnit.isConvertible(unit)) { throw new UnitException(); } newUnit = thisUnit; newName = Name; } newType = getRealType(newName, newUnit, newAttrMask); if (newType == null) { /* * The new RealType can't be created -- possibly because the * attribute mask differs from an extant RealType. Create a new * RealType from a new name. */ newType = getRealType(newName(newUnit), newUnit, newAttrMask); } } break; case Data.MULTIPLY: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.multiply(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.DIVIDE: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.divide(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.INV_DIVIDE: if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? unit.divide(thisUnit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.POW: - if (thisUnit.equals(CommonUnit.dimensionless)) { + if (thisUnit != null && CommonUnit.dimensionless.equals(thisUnit)) { newUnit = CommonUnit.dimensionless; } else { - newUnit = CommonUnit.promiscuous; + newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.INV_POW: - if (unit.equals(CommonUnit.dimensionless)) { + if (unit != null && unit.equals(CommonUnit.dimensionless)) { newUnit = CommonUnit.dimensionless; } else { - newUnit = CommonUnit.promiscuous; + newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2: case Data.INV_ATAN2: newUnit = CommonUnit.radian; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: newUnit = CommonUnit.degree; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.REMAINDER: newType = this; break; case Data.INV_REMAINDER: newType = type; break; default: throw new ArithmeticException("RealType.binary: illegal operation"); } } else if ( type instanceof TextType ) { throw new TypeException("RealType.binary: types don't match"); } else if ( type instanceof TupleType ) { return type.binary( this, DataImpl.invertOp(op), names ); } else if ( type instanceof FunctionType ) { return type.binary( this, DataImpl.invertOp(op), names ); } /* WLH 10 Sept 98 - not necessary else if (type instanceof RealTupleType) { int n_comps = ((TupleType) type).getDimension(); RealType[] new_types = new RealType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (RealType) (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new RealTupleType( new_types ); } else if (type instanceof TupleType) { int n_comps = ((TupleType) type).getDimension(); MathType[] new_types = new MathType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new TupleType( new_types ); } else if (type instanceof FunctionType) { return new FunctionType(((FunctionType) type).getDomain(), ((FunctionType) type).getRange().binary(this, DataImpl.invertOp(op), names)); } else { throw new TypeException("RealType.binary: types don't match" ); } */ return newType; } private static String newName(Unit unit) { return "RealType_" + Integer.toString(++count) + "_" + (unit == null ? "nullUnit" : unit.toString()); } /*- TDR July 1998 */ public MathType unary( int op, Vector names ) throws VisADException { MathType newType; Unit newUnit; String newName; /* * Determine the attributes of the RealType that will result from the * operation. */ int newAttrMask; switch (op) { case Data.CEIL: case Data.FLOOR: case Data.RINT: case Data.ROUND: case Data.NOP: case Data.ABS: case Data.NEGATE: newAttrMask = getAttributeMask(); break; case Data.ACOS: case Data.ASIN: case Data.ATAN: case Data.ACOS_DEGREES: case Data.ASIN_DEGREES: case Data.ATAN_DEGREES: case Data.COS: case Data.COS_DEGREES: case Data.SIN: case Data.SIN_DEGREES: case Data.TAN: case Data.TAN_DEGREES: case Data.SQRT: case Data.EXP: case Data.LOG: default: newAttrMask = 0; // clear all attributes } /* * Determine the RealType that will result from the operation. Use the * previously-determined attributes. */ switch (op) { case Data.ABS: case Data.CEIL: case Data.FLOOR: case Data.NEGATE: case Data.NOP: case Data.RINT: case Data.ROUND: newType = this; break; case Data.ACOS: case Data.ASIN: case Data.ATAN: newUnit = CommonUnit.radian; newName = getUniqueGenericName( names, newUnit ); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ACOS_DEGREES: case Data.ASIN_DEGREES: case Data.ATAN_DEGREES: newUnit = CommonUnit.degree; newName = getUniqueGenericName( names, newUnit ); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.COS: case Data.COS_DEGREES: case Data.SIN: case Data.SIN_DEGREES: case Data.TAN: case Data.TAN_DEGREES: case Data.EXP: case Data.LOG: newUnit = Unit.canConvert(CommonUnit.dimensionless, DefaultUnit) ? CommonUnit.dimensionless : null; newName = getUniqueGenericName( names, newUnit ); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.SQRT: newUnit = Unit.canConvert(CommonUnit.dimensionless, DefaultUnit) ? CommonUnit.dimensionless : (DefaultUnit == null) ? null : DefaultUnit.sqrt(); newName = getUniqueGenericName( names, newUnit ); newType = getRealType(newName, newUnit, newAttrMask); break; default: throw new ArithmeticException("RealType.unary: illegal operation"); } return newType; } private static String getUniqueGenericName( Vector names, String ext ) { String name = null; /* * Ensure that the name is acceptable as a RealType name. */ if (ext.indexOf(".") > -1) ext = ext.replace('.', '_'); if (ext.indexOf(" ") > -1) ext = ext.replace(' ', '_'); if (ext.indexOf("(") > -1) ext = ext.replace('(', '_'); if (ext.indexOf(")") > -1) ext = ext.replace(')', '_'); for ( int ii = 1; ; ii++ ) { name = "Generic_"+ii +"_"+ext; if ( !names.contains(name) ) { names.addElement(name); break; } } return name; } private static String getUniqueGenericName(Vector names, Unit unit) { return getUniqueGenericName( names, unit == null ? "nullUnit" : unit.toString()); } public Data missingData() throws VisADException { return new Real(this); } /** * Returns a RealType corresponding to a name. If a RealType with the given * name doesn't exist, then it's created (with default unit, representational * set, and attribute mask) and returned; otherwise, the previously existing * RealType is returned if it is compatible with the input arguments (the * unit, representational set, and attribute mask are ignored in the * comparison); otherwise <code>null</code> is returned. * * @param name The name for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static final RealType getRealType(String name) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt == null) { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name); } catch (VisADException e) { rt = getRealTypeByName(name); } } return rt; } /** * Returns a RealType corresponding to a name and unit. If a RealType * with the given name doesn't exist, then it's created (with default * representational set and attribute mask) and returned; otherwise, the * previously existing RealType is returned if it is compatible with the input * arguments (the representational set and attribute mask are ignored in the * comparison); otherwise <code>null</code> is returned. Note that the unit * of the returned RealType will be convertible with the unit argument but * might not equal it. * * @param name The name for the RealType. * @param unit The unit for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static final RealType getRealType(String name, Unit u) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt != null) { /* * Ensure that the previously-created instance conforms to the input * arguments. */ if (!Unit.canConvert(u, rt.DefaultUnit)) { // System.out.println("getRealType " + name + " unit mismatchA " + u + " " + rt.DefaultUnit); rt = null; } } else { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name, u); } catch (VisADException e) { rt = getRealTypeByName(name); if (rt != null) { if (!Unit.canConvert(u, rt.DefaultUnit)) { // System.out.println("getRealType " + name + " unit mismatchB " + u + " " + rt.DefaultUnit); rt = null; } } } } return rt; } /** * Returns a RealType corresponding to a name and attribute mask. If a * RealType with the given name doesn't exist, then it's created (with * default unit and representational set) and returned; otherwise, the * previously existing RealType is returned if it is compatible with the * input arguments (the unit and representational set are ignored in the * comparison); otherwise <code>null</code> is returned. Note that the unit * of the returned RealType will be convertible with the unit argument but * might not equal it. * * @param name The name for the RealType. * @param attrMask The attribute mask for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static RealType getRealType(String name, int attrMask) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt != null) { /* * Ensure that the previously-created instance conforms to the input * arguments. */ if (attrMask != rt.attrMask) rt = null; } else { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name, attrMask); } catch (VisADException e) { rt = getRealTypeByName(name); if (rt != null) { if (attrMask != rt.attrMask) { rt = null; } } } } return rt; } /** * Returns a RealType corresponding to a name, unit, and representational set. * If a RealType with the given name doesn't exist, then it's created (with a * default attribute mask) and returned; otherwise, the previously existing * RealType is returned if it is compatible with the input arguments (the * attribute mask is ignored in the comparison); otherwise <code>null</code> * is returned. Note that the unit of the returned RealType will be * convertible with the unit argument but might not equal it. * * @param name The name for the RealType. * @param unit The unit for the RealType. * @param set The representational set for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static RealType getRealType(String name, Unit u, Set set) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt != null) { /* * Ensure that the previously-created instance conforms to the input * arguments. */ if (!Unit.canConvert(u, rt.DefaultUnit) || (set == null ? rt.DefaultSet != null : !set.equals(rt.DefaultSet))) { rt = null; } } else { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name, u, set); } catch (VisADException e) { rt = getRealTypeByName(name); if (rt != null) { if (!Unit.canConvert(u, rt.DefaultUnit) || (set == null ? rt.DefaultSet != null : !set.equals(rt.DefaultSet))) { rt = null; } } } } return rt; } /** * Returns a RealType corresponding to a name, unit, and attribute mask. If * a RealType with the given name doesn't exist, then it's created (with a * default representational set) and returned; otherwise, the previously * existing RealType is returned if it is compatible with the input arguments * (the representational set is ignored in the comparison); otherwise * <code>null</code> is returned. Note that the unit of the returned RealType * will be convertible with the unit argument but might not equal it. * * @param name The name for the RealType. * @param unit The unit for the RealType. * @param attrMask The attribute mask for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static final RealType getRealType(String name, Unit u, int attrMask) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt != null) { /* * Ensure that the previously-created instance conforms to the input * arguments. */ if (!Unit.canConvert(u, rt.DefaultUnit) || rt.attrMask != attrMask) rt = null; } else { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name, u, null, attrMask); } catch (VisADException e) { rt = getRealTypeByName(name); if (rt != null) { if (!Unit.canConvert(u, rt.DefaultUnit) || rt.attrMask != attrMask) { rt = null; } } } } return rt; } /** * Returns a RealType corresponding to a name, unit, representational set, * and attribute mask. If a RealType with the given name doesn't exist, then * it's created and returned; otherwise, the previously existing RealType * is returned if it is compatible with the input arguments; otherwise * <code>null</code> is returned. Note that the unit of the returned RealType * will be convertible with the unit argument but might not equal it. * * @param name The name for the RealType. * @param unit The unit for the RealType. * @param set The representational set for the RealType. * @param attrMask The attribute mask for the RealType. * @return A RealType corresponding to the input * arguments or <code>null</code>. * @throws NullPointerException if the name is <code>null</code>. */ public static final RealType getRealType(String name, Unit u, Set set, int attrMask) { if (name == null) throw new NullPointerException(); /* * The following should catch most of the times that an instance with the * given name was previously-created -- without the performance-hit of * catching an exception. */ RealType rt = getRealTypeByName(name); if (rt != null) { /* * Ensure that the previously-created instance conforms to the input * arguments. */ if (!Unit.canConvert(u, rt.DefaultUnit) || (set == null ? rt.DefaultSet != null : !set.equals(rt.DefaultSet)) || rt.attrMask != attrMask) { rt = null; } } else { /* * An instance with the given name didn't exist but might have just been * created by another thread -- so we have to invoke the constructor * inside a try-block. */ try { rt = new RealType(name, u, set, attrMask); } catch (VisADException e) { rt = getRealTypeByName(name); if (rt != null) { if (!Unit.canConvert(u, rt.DefaultUnit) || (set == null ? rt.DefaultSet != null : !set.equals(rt.DefaultSet)) || rt.attrMask != attrMask) { rt = null; } } } } return rt; } /** return any RealType constructed in this JVM with name, or null */ public static RealType getRealTypeByName(String name) { ScalarType real = ScalarType.getScalarTypeByName(name); if (!(real instanceof RealType)) { return null; } return (RealType) real; } public ShadowType buildShadowType(DataDisplayLink link, ShadowType parent) throws VisADException, RemoteException { return link.getRenderer().makeShadowRealType(this, link, parent); } /* WLH 5 Jan 2000 public String toString() { return getName(); } */ public String prettyString(int indent) { // return toString(); WLH 5 Jan 2000 return getName(); } public static void main( String[] args ) throws VisADException { //- Tests for unary --* MathType m_type; RealType real_R = new RealType( "Red_Brightness", null, null ); RealType real_G = new RealType( "Green_Brightness", null, null ); RealType real_B = new RealType( "Blue_Brightness", null, null ); RealType[] reals = { real_R, real_G, real_B }; RealTupleType RGBtuple = new RealTupleType( reals ); m_type = RGBtuple.unary( Data.COS, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.unary( Data.COS_DEGREES, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.unary( Data.ABS, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.unary( Data.ACOS, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.unary( Data.ACOS_DEGREES, new Vector() ); System.out.println( m_type.toString() ); RealType real_A = new RealType( "distance", SI.meter, null ); m_type = real_A.unary( Data.EXP, new Vector() ); System.out.println( m_type.toString() ); //- Tests for binary --* real_A = RealType.Generic; // real_A = new RealType( "temperature", SI.kelvin, null ); m_type = RGBtuple.binary( real_A, Data.ADD, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.binary( real_A, Data.MULTIPLY, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.binary( real_A, Data.POW, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.binary( real_A, Data.ATAN2, new Vector() ); System.out.println( m_type.toString() ); m_type = RGBtuple.binary( real_A, Data.ATAN2_DEGREES, new Vector() ); System.out.println( m_type.toString() ); // and finally, force an Exception System.out.println("force a TypeException:"); RealType r = new RealType("a.b"); } }
false
true
public MathType binary( MathType type, int op, Vector names ) throws VisADException { /* WLH 10 Sept 98 */ if (type == null) { throw new TypeException("TupleType.binary: type may not be null" ); } Unit newUnit = null; MathType newType = null; String newName; if (type instanceof RealType) { RealType that = (RealType)type; Unit unit = ((RealType)type).getDefaultUnit(); Unit thisUnit = DefaultUnit; int newAttrMask = 0; /* * Determine the attributes of the RealType that will result from the * operation. */ switch (op) { case Data.SUBTRACT: case Data.INV_SUBTRACT: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.ADD: case Data.MAX: case Data.MIN: if (isInterval() && that.isInterval()) newAttrMask |= INTERVAL; break; case Data.MULTIPLY: case Data.DIVIDE: case Data.REMAINDER: case Data.INV_DIVIDE: case Data.INV_REMAINDER: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.POW: newAttrMask = getAttributeMask(); break; case Data.INV_POW: newAttrMask = that.getAttributeMask(); break; case Data.ATAN2: case Data.INV_ATAN2: case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: default: } /* * Determine the RealType that will result from the operation. Use the * previously-determined attributes. */ switch (op) { case Data.ADD: case Data.SUBTRACT: case Data.INV_SUBTRACT: case Data.MAX: case Data.MIN: if (CommonUnit.promiscuous.equals(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit)) { newType = type; } else { if (thisUnit == null || unit == null) { newUnit = null; if (thisUnit == null && unit == null) { newName = Name; } else { newName = getUniqueGenericName(names, newUnit); } } else { if (!thisUnit.isConvertible(unit)) { throw new UnitException(); } newUnit = thisUnit; newName = Name; } newType = getRealType(newName, newUnit, newAttrMask); if (newType == null) { /* * The new RealType can't be created -- possibly because the * attribute mask differs from an extant RealType. Create a new * RealType from a new name. */ newType = getRealType(newName(newUnit), newUnit, newAttrMask); } } break; case Data.MULTIPLY: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.multiply(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.DIVIDE: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.divide(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.INV_DIVIDE: if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? unit.divide(thisUnit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.POW: if (thisUnit.equals(CommonUnit.dimensionless)) { newUnit = CommonUnit.dimensionless; } else { newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.INV_POW: if (unit.equals(CommonUnit.dimensionless)) { newUnit = CommonUnit.dimensionless; } else { newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2: case Data.INV_ATAN2: newUnit = CommonUnit.radian; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: newUnit = CommonUnit.degree; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.REMAINDER: newType = this; break; case Data.INV_REMAINDER: newType = type; break; default: throw new ArithmeticException("RealType.binary: illegal operation"); } } else if ( type instanceof TextType ) { throw new TypeException("RealType.binary: types don't match"); } else if ( type instanceof TupleType ) { return type.binary( this, DataImpl.invertOp(op), names ); } else if ( type instanceof FunctionType ) { return type.binary( this, DataImpl.invertOp(op), names ); } /* WLH 10 Sept 98 - not necessary else if (type instanceof RealTupleType) { int n_comps = ((TupleType) type).getDimension(); RealType[] new_types = new RealType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (RealType) (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new RealTupleType( new_types ); } else if (type instanceof TupleType) { int n_comps = ((TupleType) type).getDimension(); MathType[] new_types = new MathType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new TupleType( new_types ); } else if (type instanceof FunctionType) { return new FunctionType(((FunctionType) type).getDomain(), ((FunctionType) type).getRange().binary(this, DataImpl.invertOp(op), names)); } else { throw new TypeException("RealType.binary: types don't match" ); } */ return newType; }
public MathType binary( MathType type, int op, Vector names ) throws VisADException { /* WLH 10 Sept 98 */ if (type == null) { throw new TypeException("TupleType.binary: type may not be null" ); } Unit newUnit = null; MathType newType = null; String newName; if (type instanceof RealType) { RealType that = (RealType)type; Unit unit = ((RealType)type).getDefaultUnit(); Unit thisUnit = DefaultUnit; int newAttrMask = 0; /* * Determine the attributes of the RealType that will result from the * operation. */ switch (op) { case Data.SUBTRACT: case Data.INV_SUBTRACT: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.ADD: case Data.MAX: case Data.MIN: if (isInterval() && that.isInterval()) newAttrMask |= INTERVAL; break; case Data.MULTIPLY: case Data.DIVIDE: case Data.REMAINDER: case Data.INV_DIVIDE: case Data.INV_REMAINDER: if (isInterval() != that.isInterval()) newAttrMask |= INTERVAL; break; case Data.POW: newAttrMask = getAttributeMask(); break; case Data.INV_POW: newAttrMask = that.getAttributeMask(); break; case Data.ATAN2: case Data.INV_ATAN2: case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: default: } /* * Determine the RealType that will result from the operation. Use the * previously-determined attributes. */ switch (op) { case Data.ADD: case Data.SUBTRACT: case Data.INV_SUBTRACT: case Data.MAX: case Data.MIN: if (CommonUnit.promiscuous.equals(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit)) { newType = type; } else { if (thisUnit == null || unit == null) { newUnit = null; if (thisUnit == null && unit == null) { newName = Name; } else { newName = getUniqueGenericName(names, newUnit); } } else { if (!thisUnit.isConvertible(unit)) { throw new UnitException(); } newUnit = thisUnit; newName = Name; } newType = getRealType(newName, newUnit, newAttrMask); if (newType == null) { /* * The new RealType can't be created -- possibly because the * attribute mask differs from an extant RealType. Create a new * RealType from a new name. */ newType = getRealType(newName(newUnit), newUnit, newAttrMask); } } break; case Data.MULTIPLY: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.multiply(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.DIVIDE: if (CommonUnit.promiscuous.equals(unit) || CommonUnit.dimensionless.isConvertible(unit)) { newType = this; } else { newUnit = (unit != null && thisUnit != null) ? thisUnit.divide(unit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.INV_DIVIDE: if (CommonUnit.promiscuous.equals(thisUnit) || CommonUnit.dimensionless.isConvertible(thisUnit)) { newType = type; } else { newUnit = (unit != null && thisUnit != null) ? unit.divide(thisUnit) : null; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); } break; case Data.POW: if (thisUnit != null && CommonUnit.dimensionless.equals(thisUnit)) { newUnit = CommonUnit.dimensionless; } else { newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.INV_POW: if (unit != null && unit.equals(CommonUnit.dimensionless)) { newUnit = CommonUnit.dimensionless; } else { newUnit = CommonUnit.promiscuous; } newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2: case Data.INV_ATAN2: newUnit = CommonUnit.radian; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.ATAN2_DEGREES: case Data.INV_ATAN2_DEGREES: newUnit = CommonUnit.degree; newName = getUniqueGenericName(names, newUnit); newType = getRealType(newName, newUnit, newAttrMask); break; case Data.REMAINDER: newType = this; break; case Data.INV_REMAINDER: newType = type; break; default: throw new ArithmeticException("RealType.binary: illegal operation"); } } else if ( type instanceof TextType ) { throw new TypeException("RealType.binary: types don't match"); } else if ( type instanceof TupleType ) { return type.binary( this, DataImpl.invertOp(op), names ); } else if ( type instanceof FunctionType ) { return type.binary( this, DataImpl.invertOp(op), names ); } /* WLH 10 Sept 98 - not necessary else if (type instanceof RealTupleType) { int n_comps = ((TupleType) type).getDimension(); RealType[] new_types = new RealType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (RealType) (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new RealTupleType( new_types ); } else if (type instanceof TupleType) { int n_comps = ((TupleType) type).getDimension(); MathType[] new_types = new MathType[ n_comps ]; for ( int ii = 0; ii < n_comps; ii++ ) { new_types[ii] = (((TupleType) type).getComponent(ii)).binary(this, DataImpl.invertOp(op), names); } return new TupleType( new_types ); } else if (type instanceof FunctionType) { return new FunctionType(((FunctionType) type).getDomain(), ((FunctionType) type).getRange().binary(this, DataImpl.invertOp(op), names)); } else { throw new TypeException("RealType.binary: types don't match" ); } */ return newType; }
diff --git a/src/sockthing/JobInfo.java b/src/sockthing/JobInfo.java index a268fb4..95800f5 100644 --- a/src/sockthing/JobInfo.java +++ b/src/sockthing/JobInfo.java @@ -1,399 +1,402 @@ package sockthing; import org.json.JSONObject; import org.json.JSONArray; import com.google.bitcoin.core.Coinbase; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.Block; import java.math.BigInteger; import org.apache.commons.codec.binary.Hex; import com.google.bitcoin.core.Sha256Hash; import java.util.ArrayList; import java.util.LinkedList; import java.security.MessageDigest; import java.util.HashSet; public class JobInfo { private NetworkParameters network_params; private StratumServer server; private String job_id; private JSONObject block_template; private byte[] extranonce1; private PoolUser pool_user; private HashSet<String> submits; private Sha256Hash share_target; private double difficulty; private long value; private Coinbase coinbase; public JobInfo(StratumServer server, PoolUser pool_user, String job_id, JSONObject block_template, byte[] extranonce1) throws org.json.JSONException { this.pool_user = pool_user; this.server = server; this.network_params = network_params; this.job_id = job_id; this.block_template = block_template; this.extranonce1 = extranonce1; this.value = block_template.getLong("coinbasevalue"); this.difficulty = server.getBlockDifficulty(); int height = block_template.getInt("height"); submits = new HashSet<String>(); coinbase = new Coinbase(server, pool_user, height, BigInteger.valueOf(value), getFeeTotal(), extranonce1); share_target = DiffMath.getTargetForDifficulty(pool_user.getDifficulty()); } public int getHeight() throws org.json.JSONException { return block_template.getInt("height"); } private BigInteger getFeeTotal() throws org.json.JSONException { long fee_total = 0; JSONArray transactions = block_template.getJSONArray("transactions"); for(int i=0; i<transactions.length(); i++) { JSONObject tx = transactions.getJSONObject(i); long fee = tx.getLong("fee"); fee_total += fee; } return BigInteger.valueOf(fee_total); } public JSONObject getMiningNotifyMessage(boolean clean) throws org.json.JSONException { JSONObject msg = new JSONObject(); msg.put("id", JSONObject.NULL); msg.put("method", "mining.notify"); JSONArray roots= new JSONArray(); /*for(int i=0; i<5; i++) { byte[] root = new byte[32]; rnd.nextBytes(root); roots.put(Hex.encodeHexString(root)); }*/ String protocol="00000002"; String diffbits=block_template.getString("bits"); int ntime = (int)System.currentTimeMillis()/1000; String ntime_str= HexUtil.getIntAsHex(ntime); JSONArray params = new JSONArray(); params.put(job_id); params.put(HexUtil.swapBytesInsideWord(HexUtil.swapEndianHexString(block_template.getString("previousblockhash")))); //correct params.put(Hex.encodeHexString(coinbase.getCoinbase1())); params.put(Hex.encodeHexString(coinbase.getCoinbase2())); params.put(getMerkleRoots()); params.put(protocol); //correct params.put(block_template.getString("bits")); //correct params.put(HexUtil.getIntAsHex(block_template.getInt("curtime"))); //correct params.put(clean); msg.put("params", params); return msg; } public void validateSubmit(JSONArray params, SubmitResult submit_result) { String unique_id = HexUtil.sha256(params.toString()); try { validateSubmitInternal(params, submit_result); } catch(Throwable t) { submit_result.our_result="N"; submit_result.reason="Exception: " + t; } finally { try { server.getShareSaver().saveShare(pool_user,submit_result, "sockthing/" + server.getInstanceId(), unique_id, difficulty, value); } catch(ShareSaveException e) { submit_result.our_result="N"; submit_result.reason="Exception: " + e; } } } public void validateSubmitInternal(JSONArray params, SubmitResult submit_result) throws org.json.JSONException, org.apache.commons.codec.DecoderException, ShareSaveException { String user = params.getString(0); String job_id = params.getString(1); byte[] extranonce2 = Hex.decodeHex(params.getString(2).toCharArray()); String ntime = params.getString(3); String nonce = params.getString(4); - String submit_cannonical_string = params.getString(2) + params.getString(3) + params.getString(4); + String submit_cannonical_string = params.getString(2).trim() + + params.getString(3).trim() + + params.getString(4).trim(); + submit_cannonical_string = submit_cannonical_string.toLowerCase(); synchronized(submits) { if (submits.contains(submit_cannonical_string)) { submit_result.our_result="N"; submit_result.reason="duplicate"; return; } submits.add(submit_cannonical_string); } int stale = server.checkStale(getHeight()); if (stale >= 2) { submit_result.our_result="N"; submit_result.reason="quite stale"; return; } if (stale==1) { submit_result.reason="slightly stale"; } //nonce = HexUtil.swapEndianHexString(nonce); //System.out.println("nonce: " + nonce); //System.out.println("extra2: " + params.getString(2)); /*extranonce2[0]=1; extranonce2[1]=0; extranonce2[2]=0; extranonce2[3]=0; nonce="00000000";*/ Sha256Hash coinbase_hash; synchronized(coinbase) { coinbase.setExtranonce2(extranonce2); coinbase_hash = coinbase.genTx().getHash(); Sha256Hash merkle_root = new Sha256Hash(HexUtil.swapEndianHexString(coinbase_hash.toString())); JSONArray branches = getMerkleRoots(); for(int i=0; i<branches.length(); i++) { Sha256Hash br= new Sha256Hash(branches.getString(i)); //System.out.println("Merkle " + merkle_root + " " + br); merkle_root = HexUtil.treeHash(merkle_root, br); } try { StringBuilder header = new StringBuilder(); header.append("00000002"); header.append(HexUtil.swapBytesInsideWord(HexUtil.swapEndianHexString(block_template.getString("previousblockhash")))); header.append(HexUtil.swapBytesInsideWord(merkle_root.toString())); header.append(ntime); header.append(block_template.getString("bits")); header.append(nonce); //header.append("000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"); String header_str = header.toString(); header_str = HexUtil.swapBytesInsideWord(header_str); System.out.println("Header: " + header_str); System.out.println("Header bytes: " + header_str.length()); //header_str = HexUtil.swapWordHexString(header_str); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(Hex.decodeHex(header_str.toCharArray())); byte[] pass = md.digest(); md.reset(); md.update(pass); Sha256Hash blockhash = new Sha256Hash(HexUtil.swapEndianHexString(new Sha256Hash(md.digest()).toString())); System.out.println("Found block hash: " + blockhash); submit_result.hash = blockhash; if (blockhash.toString().compareTo(share_target.toString()) < 0) { submit_result.our_result="Y"; server.getEventLog().log("Share " + pool_user.getName() + " " + getHeight() + " " + blockhash ); } else { submit_result.our_result="N"; submit_result.reason="H-not-zero"; return; } String upstream_result=null; if (blockhash.toString().compareTo(block_template.getString("target")) < 0) { submit_result.upstream_result = buildAndSubmitBlock(params, merkle_root); submit_result.height = getHeight(); } } catch(java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } } } public String buildAndSubmitBlock(JSONArray params, Sha256Hash merkleRoot) throws org.json.JSONException, org.apache.commons.codec.DecoderException { System.out.println("WE CAN BUILD A BLOCK. WE HAVE THE TECHNOLOGY."); String user = params.getString(0); String job_id = params.getString(1); byte[] extranonce2 = Hex.decodeHex(params.getString(2).toCharArray()); String ntime = params.getString(3); String nonce = params.getString(4); long time = Long.parseLong(ntime,16); long target = Long.parseLong(block_template.getString("bits"),16); long nonce_l = Long.parseLong(nonce,16); LinkedList<Transaction> lst = new LinkedList<Transaction>(); lst.add(coinbase.genTx()); JSONArray transactions = block_template.getJSONArray("transactions"); for(int i=0; i<transactions.length(); i++) { JSONObject tx = transactions.getJSONObject(i); try { Transaction tx_obj = new Transaction(network_params, Hex.decodeHex(tx.getString("data").toCharArray())); lst.add(tx_obj); } catch(com.google.bitcoin.core.ProtocolException e) { throw new RuntimeException(e); } } Block block = new Block( network_params, 2, new Sha256Hash(block_template.getString("previousblockhash")), new Sha256Hash(HexUtil.swapEndianHexString(merkleRoot.toString())), time, target, nonce_l, lst); System.out.println("Constructed block hash: " + block.getHash()); try { block.verifyTransactions(); System.out.println("Block VERIFIED"); byte[] blockbytes = block.bitcoinSerialize(); System.out.println("Bytes: " + blockbytes.length); String ret = server.submitBlock(block); if (ret.equals("Y")) { coinbase.markRemark(); } server.getEventLog().log("BLOCK SUBMITTED: "+ getHeight() + " " + block.getHash() ); return ret; } catch(com.google.bitcoin.core.VerificationException e) { e.printStackTrace(); return "N"; } } public JSONArray getMerkleRoots() throws org.json.JSONException { ArrayList<Sha256Hash> hashes = new ArrayList<Sha256Hash>(); JSONArray transactions = block_template.getJSONArray("transactions"); for(int i=0; i<transactions.length(); i++) { JSONObject tx = transactions.getJSONObject(i); Sha256Hash hash = new Sha256Hash(HexUtil.swapEndianHexString(tx.getString("hash"))); hashes.add(hash); } JSONArray roots = new JSONArray(); while(hashes.size() > 0) { ArrayList<Sha256Hash> next_lst = new ArrayList<Sha256Hash>(); roots.put(hashes.get(0).toString()); for(int i=1; i<hashes.size(); i+=2) { if (i+1==hashes.size()) { next_lst.add(HexUtil.treeHash(hashes.get(i), hashes.get(i))); } else { next_lst.add(HexUtil.treeHash(hashes.get(i), hashes.get(i+1))); } } hashes=next_lst; } return roots; } }
true
true
public void validateSubmitInternal(JSONArray params, SubmitResult submit_result) throws org.json.JSONException, org.apache.commons.codec.DecoderException, ShareSaveException { String user = params.getString(0); String job_id = params.getString(1); byte[] extranonce2 = Hex.decodeHex(params.getString(2).toCharArray()); String ntime = params.getString(3); String nonce = params.getString(4); String submit_cannonical_string = params.getString(2) + params.getString(3) + params.getString(4); synchronized(submits) { if (submits.contains(submit_cannonical_string)) { submit_result.our_result="N"; submit_result.reason="duplicate"; return; } submits.add(submit_cannonical_string); } int stale = server.checkStale(getHeight()); if (stale >= 2) { submit_result.our_result="N"; submit_result.reason="quite stale"; return; } if (stale==1) { submit_result.reason="slightly stale"; } //nonce = HexUtil.swapEndianHexString(nonce); //System.out.println("nonce: " + nonce); //System.out.println("extra2: " + params.getString(2)); /*extranonce2[0]=1; extranonce2[1]=0; extranonce2[2]=0; extranonce2[3]=0; nonce="00000000";*/ Sha256Hash coinbase_hash; synchronized(coinbase) { coinbase.setExtranonce2(extranonce2); coinbase_hash = coinbase.genTx().getHash(); Sha256Hash merkle_root = new Sha256Hash(HexUtil.swapEndianHexString(coinbase_hash.toString())); JSONArray branches = getMerkleRoots(); for(int i=0; i<branches.length(); i++) { Sha256Hash br= new Sha256Hash(branches.getString(i)); //System.out.println("Merkle " + merkle_root + " " + br); merkle_root = HexUtil.treeHash(merkle_root, br); } try { StringBuilder header = new StringBuilder(); header.append("00000002"); header.append(HexUtil.swapBytesInsideWord(HexUtil.swapEndianHexString(block_template.getString("previousblockhash")))); header.append(HexUtil.swapBytesInsideWord(merkle_root.toString())); header.append(ntime); header.append(block_template.getString("bits")); header.append(nonce); //header.append("000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"); String header_str = header.toString(); header_str = HexUtil.swapBytesInsideWord(header_str); System.out.println("Header: " + header_str); System.out.println("Header bytes: " + header_str.length()); //header_str = HexUtil.swapWordHexString(header_str); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(Hex.decodeHex(header_str.toCharArray())); byte[] pass = md.digest(); md.reset(); md.update(pass); Sha256Hash blockhash = new Sha256Hash(HexUtil.swapEndianHexString(new Sha256Hash(md.digest()).toString())); System.out.println("Found block hash: " + blockhash); submit_result.hash = blockhash; if (blockhash.toString().compareTo(share_target.toString()) < 0) { submit_result.our_result="Y"; server.getEventLog().log("Share " + pool_user.getName() + " " + getHeight() + " " + blockhash ); } else { submit_result.our_result="N"; submit_result.reason="H-not-zero"; return; } String upstream_result=null; if (blockhash.toString().compareTo(block_template.getString("target")) < 0) { submit_result.upstream_result = buildAndSubmitBlock(params, merkle_root); submit_result.height = getHeight(); } } catch(java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }
public void validateSubmitInternal(JSONArray params, SubmitResult submit_result) throws org.json.JSONException, org.apache.commons.codec.DecoderException, ShareSaveException { String user = params.getString(0); String job_id = params.getString(1); byte[] extranonce2 = Hex.decodeHex(params.getString(2).toCharArray()); String ntime = params.getString(3); String nonce = params.getString(4); String submit_cannonical_string = params.getString(2).trim() + params.getString(3).trim() + params.getString(4).trim(); submit_cannonical_string = submit_cannonical_string.toLowerCase(); synchronized(submits) { if (submits.contains(submit_cannonical_string)) { submit_result.our_result="N"; submit_result.reason="duplicate"; return; } submits.add(submit_cannonical_string); } int stale = server.checkStale(getHeight()); if (stale >= 2) { submit_result.our_result="N"; submit_result.reason="quite stale"; return; } if (stale==1) { submit_result.reason="slightly stale"; } //nonce = HexUtil.swapEndianHexString(nonce); //System.out.println("nonce: " + nonce); //System.out.println("extra2: " + params.getString(2)); /*extranonce2[0]=1; extranonce2[1]=0; extranonce2[2]=0; extranonce2[3]=0; nonce="00000000";*/ Sha256Hash coinbase_hash; synchronized(coinbase) { coinbase.setExtranonce2(extranonce2); coinbase_hash = coinbase.genTx().getHash(); Sha256Hash merkle_root = new Sha256Hash(HexUtil.swapEndianHexString(coinbase_hash.toString())); JSONArray branches = getMerkleRoots(); for(int i=0; i<branches.length(); i++) { Sha256Hash br= new Sha256Hash(branches.getString(i)); //System.out.println("Merkle " + merkle_root + " " + br); merkle_root = HexUtil.treeHash(merkle_root, br); } try { StringBuilder header = new StringBuilder(); header.append("00000002"); header.append(HexUtil.swapBytesInsideWord(HexUtil.swapEndianHexString(block_template.getString("previousblockhash")))); header.append(HexUtil.swapBytesInsideWord(merkle_root.toString())); header.append(ntime); header.append(block_template.getString("bits")); header.append(nonce); //header.append("000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000"); String header_str = header.toString(); header_str = HexUtil.swapBytesInsideWord(header_str); System.out.println("Header: " + header_str); System.out.println("Header bytes: " + header_str.length()); //header_str = HexUtil.swapWordHexString(header_str); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(Hex.decodeHex(header_str.toCharArray())); byte[] pass = md.digest(); md.reset(); md.update(pass); Sha256Hash blockhash = new Sha256Hash(HexUtil.swapEndianHexString(new Sha256Hash(md.digest()).toString())); System.out.println("Found block hash: " + blockhash); submit_result.hash = blockhash; if (blockhash.toString().compareTo(share_target.toString()) < 0) { submit_result.our_result="Y"; server.getEventLog().log("Share " + pool_user.getName() + " " + getHeight() + " " + blockhash ); } else { submit_result.our_result="N"; submit_result.reason="H-not-zero"; return; } String upstream_result=null; if (blockhash.toString().compareTo(block_template.getString("target")) < 0) { submit_result.upstream_result = buildAndSubmitBlock(params, merkle_root); submit_result.height = getHeight(); } } catch(java.security.NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }
diff --git a/src/edgruberman/bukkit/obituaries/Coroner.java b/src/edgruberman/bukkit/obituaries/Coroner.java index 7efa42c..0587b72 100644 --- a/src/edgruberman/bukkit/obituaries/Coroner.java +++ b/src/edgruberman/bukkit/obituaries/Coroner.java @@ -1,224 +1,226 @@ package edgruberman.bukkit.obituaries; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityCombustByBlockEvent; import org.bukkit.event.entity.EntityCombustByEntityEvent; import org.bukkit.event.entity.EntityCombustEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; /** tracks damages for a specific player to report on death */ public class Coroner implements Listener { private static final double PLAYER_WIDTH = 0.6D; private static final double PLAYER_HEIGHT = 1.8D; private static final double ENTITY_NON_FLAMMABLE = 0.001D; private static final int EXPIRATION_LIVING = 300; // 15s private static final int EXPIRATION_ENVIRONMENT = 100; // 5s private final UUID playerId; private final List<Damage> damages = new ArrayList<Damage>(); private int consumptionOccurred = -1; private ItemStack consumed = null; private String combusterAsKiller = null; private Object combuster = null; Coroner(final Player player) { this.playerId = player.getUniqueId(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) // give everything else a chance to finalize what really happened public void onPlayerDamaged(final EntityDamageEvent event) { if (!(event.getEntity().getUniqueId().equals(this.playerId))) return; if (event.getEntity().isDead()) return; final Player player = (Player) event.getEntity(); if (player.getGameMode() == GameMode.CREATIVE) return; // TODO submit ticket and fix why ENTITY_ATTACK is thrown right after ENTITY&&BLOCK_EXPLOSION if (event.getCause() == DamageCause.ENTITY_ATTACK) { final Damage last = this.getLastDamage(); if (last != null) { if (last.getCause() == DamageCause.BLOCK_EXPLOSION || last.getCause() == DamageCause.ENTITY_EXPLOSION) return; } } this.clearOldCombat(); try { final Damage damage = Damage.create(this, event); this.damages.add(damage); } catch (final Exception e) { e.printStackTrace(); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onConsumption(final PlayerItemConsumeEvent consume) { if (!(consume.getPlayer().getUniqueId().equals(this.playerId))) return; this.consumed = consume.getItem(); this.consumptionOccurred = consume.getPlayer().getTicksLived(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCombustion(final EntityCombustEvent combustion) { if (!(combustion.getEntity().getUniqueId().equals(this.playerId))) return; if (combustion instanceof EntityCombustByEntityEvent) { // combustible PROJECTILE (fireball), lightning, fire enchanted item (sword), a burning entity (zombie, arrow) final EntityCombustByEntityEvent combustByEntity = (EntityCombustByEntityEvent) combustion; final Entity combuster = combustByEntity.getCombuster(); this.combusterAsKiller = Attack.describeEntity(combuster); if (combuster instanceof Projectile) { final LivingEntity shooter = ((Projectile) combuster).getShooter(); this.combuster = ( shooter != null ? shooter.getUniqueId() : null ); } else { this.combuster = combuster.getUniqueId(); } if (combuster instanceof LivingEntity) { final LivingEntity living = (LivingEntity) combuster; final ItemStack weapon = living.getEquipment().getItemInHand(); if (weapon != null && weapon.getTypeId() != Material.AIR.getId()) this.combusterAsKiller = Main.courier.format("weapon.format", this.combusterAsKiller, Translator.formatItem(weapon)); } return; } if (combustion instanceof EntityCombustByBlockEvent) { // so far, only LAVA final EntityCombustByBlockEvent combustByBlock = (EntityCombustByBlockEvent) combustion; final Block combuster = combustByBlock.getCombuster(); if (combuster == null) { + this.combuster = null; this.combusterAsKiller = Translator.describeMaterial(Material.LAVA); return; } + this.combuster = combuster.getState(); this.combusterAsKiller = Translator.describeMaterial(combuster); return; } // simple EntityCombustEvent for fire or lava final Material source = Coroner.combustionSource(combustion.getEntity()); this.combusterAsKiller = ( source != null ? Translator.describeMaterial(source) : null ); } /** @return first combustion source found within vanilla logic of determination */ private static Material combustionSource(final Entity entity) { final Location location = entity.getLocation(); // Entity.move shrinks bounding box to determine if in contact "enough" with combustion source final int minX = (int) Math.floor(location.getX() - (Coroner.PLAYER_WIDTH / 2D) + Coroner.ENTITY_NON_FLAMMABLE); final int maxX = (int) Math.floor(location.getX() + (Coroner.PLAYER_WIDTH / 2D) - Coroner.ENTITY_NON_FLAMMABLE); final int minY = (int) Math.floor(location.getY() - (Coroner.PLAYER_HEIGHT / 2D) + Coroner.ENTITY_NON_FLAMMABLE); final int maxY = (int) Math.floor(location.getY() + (Coroner.PLAYER_HEIGHT / 2D) - Coroner.ENTITY_NON_FLAMMABLE); final int minZ = (int) Math.floor(location.getZ() - (Coroner.PLAYER_WIDTH / 2D) + Coroner.ENTITY_NON_FLAMMABLE); final int maxZ = (int) Math.floor(location.getZ() + (Coroner.PLAYER_WIDTH / 2D) - Coroner.ENTITY_NON_FLAMMABLE); for (int x = minX; x <= maxX; ++x) { for (int y = minY; y <= maxY; ++y) { for (int z = minZ; z <= maxZ; ++z) { final Material source = Material.getMaterial(entity.getWorld().getBlockTypeIdAt(x, y, z)); if (source == Material.FIRE || source == Material.LAVA || source == Material.STATIONARY_LAVA) return source; } } } return null; } @EventHandler public void onPlayerDeath(final PlayerDeathEvent death) { if (!death.getEntity().getUniqueId().equals(this.playerId)) return; final String message = this.getLastDamage().formatDeath(); // forcibly clear old combat this.damages.clear(); this.combusterAsKiller = null; if (message == null) return; // allow default death message if no format specified death.setDeathMessage(message); } @EventHandler public void onPlayerQuit(final PlayerQuitEvent quit) { if (!quit.getPlayer().getUniqueId().equals(this.playerId)) return; HandlerList.unregisterAll(this); } private void clearOldCombat() { if (this.damages.isEmpty()) return; final Damage last = this.getLastDamage(); final int expiration = ( last.isDamagerLiving() ? Coroner.EXPIRATION_LIVING : Coroner.EXPIRATION_ENVIRONMENT ); final int age = this.getPlayer().getTicksLived() - last.getRecorded(); if (age < expiration) return; this.damages.clear(); this.combusterAsKiller = null; } public Damage getLastDamage() { if (this.damages.isEmpty()) return null; return this.damages.get(this.damages.size() - 1); } public List<Damage> getDamages() { return this.damages; } public Player getPlayer() { for (final Player player : Bukkit.getServer().getOnlinePlayers()) { if (player.getUniqueId().equals(this.playerId)) return player; } return null; } public UUID getPlayerId() { return this.playerId; } // TODO theoretically some other entity carrying some applied effect could occur at same tick as consumption does public ItemStack getConsumed(final int ticks) { return this.consumptionOccurred == ticks ? this.consumed : null; } public String getCombusterAsKiller() { return this.combusterAsKiller; } public Object getCombuster() { return this.combuster; } }
false
true
public void onCombustion(final EntityCombustEvent combustion) { if (!(combustion.getEntity().getUniqueId().equals(this.playerId))) return; if (combustion instanceof EntityCombustByEntityEvent) { // combustible PROJECTILE (fireball), lightning, fire enchanted item (sword), a burning entity (zombie, arrow) final EntityCombustByEntityEvent combustByEntity = (EntityCombustByEntityEvent) combustion; final Entity combuster = combustByEntity.getCombuster(); this.combusterAsKiller = Attack.describeEntity(combuster); if (combuster instanceof Projectile) { final LivingEntity shooter = ((Projectile) combuster).getShooter(); this.combuster = ( shooter != null ? shooter.getUniqueId() : null ); } else { this.combuster = combuster.getUniqueId(); } if (combuster instanceof LivingEntity) { final LivingEntity living = (LivingEntity) combuster; final ItemStack weapon = living.getEquipment().getItemInHand(); if (weapon != null && weapon.getTypeId() != Material.AIR.getId()) this.combusterAsKiller = Main.courier.format("weapon.format", this.combusterAsKiller, Translator.formatItem(weapon)); } return; } if (combustion instanceof EntityCombustByBlockEvent) { // so far, only LAVA final EntityCombustByBlockEvent combustByBlock = (EntityCombustByBlockEvent) combustion; final Block combuster = combustByBlock.getCombuster(); if (combuster == null) { this.combusterAsKiller = Translator.describeMaterial(Material.LAVA); return; } this.combusterAsKiller = Translator.describeMaterial(combuster); return; } // simple EntityCombustEvent for fire or lava final Material source = Coroner.combustionSource(combustion.getEntity()); this.combusterAsKiller = ( source != null ? Translator.describeMaterial(source) : null ); }
public void onCombustion(final EntityCombustEvent combustion) { if (!(combustion.getEntity().getUniqueId().equals(this.playerId))) return; if (combustion instanceof EntityCombustByEntityEvent) { // combustible PROJECTILE (fireball), lightning, fire enchanted item (sword), a burning entity (zombie, arrow) final EntityCombustByEntityEvent combustByEntity = (EntityCombustByEntityEvent) combustion; final Entity combuster = combustByEntity.getCombuster(); this.combusterAsKiller = Attack.describeEntity(combuster); if (combuster instanceof Projectile) { final LivingEntity shooter = ((Projectile) combuster).getShooter(); this.combuster = ( shooter != null ? shooter.getUniqueId() : null ); } else { this.combuster = combuster.getUniqueId(); } if (combuster instanceof LivingEntity) { final LivingEntity living = (LivingEntity) combuster; final ItemStack weapon = living.getEquipment().getItemInHand(); if (weapon != null && weapon.getTypeId() != Material.AIR.getId()) this.combusterAsKiller = Main.courier.format("weapon.format", this.combusterAsKiller, Translator.formatItem(weapon)); } return; } if (combustion instanceof EntityCombustByBlockEvent) { // so far, only LAVA final EntityCombustByBlockEvent combustByBlock = (EntityCombustByBlockEvent) combustion; final Block combuster = combustByBlock.getCombuster(); if (combuster == null) { this.combuster = null; this.combusterAsKiller = Translator.describeMaterial(Material.LAVA); return; } this.combuster = combuster.getState(); this.combusterAsKiller = Translator.describeMaterial(combuster); return; } // simple EntityCombustEvent for fire or lava final Material source = Coroner.combustionSource(combustion.getEntity()); this.combusterAsKiller = ( source != null ? Translator.describeMaterial(source) : null ); }
diff --git a/control-interface/control-modules/tctoken/src/main/java/org/openecard/control/module/tctoken/GenericTCTokenHandler.java b/control-interface/control-modules/tctoken/src/main/java/org/openecard/control/module/tctoken/GenericTCTokenHandler.java index 18b769a2..f0a2dda0 100644 --- a/control-interface/control-modules/tctoken/src/main/java/org/openecard/control/module/tctoken/GenericTCTokenHandler.java +++ b/control-interface/control-modules/tctoken/src/main/java/org/openecard/control/module/tctoken/GenericTCTokenHandler.java @@ -1,445 +1,445 @@ /**************************************************************************** * Copyright (C) 2012 HS Coburg. * All rights reserved. * Contact: ecsec GmbH ([email protected]) * * This file is part of the Open eCard App. * * GNU General Public License Usage * This file may be used under the terms of the GNU General Public * License version 3.0 as published by the Free Software Foundation * and appearing in the file LICENSE.GPL included in the packaging of * this file. Please review the following information to ensure the * GNU General Public License version 3.0 requirements will be met: * http://www.gnu.org/copyleft/gpl.html. * * Other Usage * Alternatively, this file may be used in accordance with the terms * and conditions contained in a signed written agreement between * you and ecsec GmbH. * ***************************************************************************/ package org.openecard.control.module.tctoken; import generated.TCTokenType; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPath; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType; import iso.std.iso_iec._24727.tech.schema.StartPAOSResponse; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import org.openecard.apache.http.HttpException; import org.openecard.bouncycastle.crypto.tls.Certificate; import org.openecard.common.DynamicContext; import org.openecard.common.ECardConstants; import org.openecard.common.I18n; import org.openecard.common.TR03112Keys; import org.openecard.common.WSHelper; import org.openecard.common.WSHelper.WSException; import org.openecard.common.interfaces.Dispatcher; import org.openecard.common.interfaces.DispatcherException; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.util.HttpRequestLineUtils; import org.openecard.common.util.Pair; import org.openecard.control.module.tctoken.gui.InsertCardDialog; import org.openecard.gui.UserConsent; import org.openecard.recognition.CardRecognition; import org.openecard.transport.paos.PAOSException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Transport binding agnostic TCToken handler. <br/> * This handler supports the following transports: * <ul> * <li>PAOS</li> * </ul> * <p> * This handler supports the following security protocols: * <ul> * <li>TLS</li> * <li>TLS-PSK</li> * <li>PLS-PSK-RSA</li> * </ul> * * @author Dirk Petrautzki <[email protected]> * @author Moritz Horsch <[email protected]> */ public class GenericTCTokenHandler { private static final Logger logger = LoggerFactory.getLogger(GenericTCTokenHandler.class); private final I18n lang = I18n.getTranslation("tctoken"); private final CardStateMap cardStates; private final Dispatcher dispatcher; private final UserConsent gui; private final CardRecognition rec; /** * Creates a TCToken handler instances and initializes it with the given parameters. * * @param cardStates Instance of the card states managed by the application. * @param dispatcher The dispatcher used to deliver the messages to the webservice interface implementations. * @param gui The implementation of the user consent interface. * @param rec The card recognition engine. */ public GenericTCTokenHandler(CardStateMap cardStates, Dispatcher dispatcher, UserConsent gui, CardRecognition rec) { this.cardStates = cardStates; this.dispatcher = dispatcher; this.gui = gui; this.rec = rec; } /** * Processes the activation request sent via the localhost binding. * * @param requestURI The request URI of the localhost server. This is not the tcTokenURL but the complete request * URI. * @return A TCToken request for further processing in the TCToken handler. * @throws UnsupportedEncodingException If the URI contains an invalid query string. * @throws TCTokenException If the TCToken could not be fetched. That means either the URL is invalid, the server * was not reachable or the returned value was not a TCToken or TCToken like structure. */ public TCTokenRequest parseRequestURI(URI requestURI) throws UnsupportedEncodingException, TCTokenException { String queryStr = requestURI.getRawQuery(); Map<String, String> queries = HttpRequestLineUtils.transform(queryStr); TCTokenRequest result; if (queries.containsKey("tcTokenURL")) { result = parseTCTokenRequestURI(queries); result.setTokenFromObject(false); return result; } else if (queries.containsKey("activationObject")) { result = parseObjectURI(queries); result.setTokenFromObject(true); return result; } throw new TCTokenException("No suitable set of parameters given in the request."); } private TCTokenRequest parseTCTokenRequestURI(Map<String, String> queries) throws TCTokenException { TCTokenRequest tcTokenRequest = new TCTokenRequest(); for (Map.Entry<String, String> next : queries.entrySet()) { String k = next.getKey(); String v = next.getValue(); if (k.equals("tcTokenURL")) { if (v != null && ! v.isEmpty()) { try { URL tcTokenURL = new URL(v); Pair<TCTokenType, List<Pair<URL, Certificate>>> token = TCTokenFactory.generateTCToken(tcTokenURL); tcTokenRequest.setTCToken(token.p1); tcTokenRequest.setCertificates(token.p2); tcTokenRequest.setTCTokenURL(tcTokenURL); } catch (MalformedURLException ex) { String msg = "The tcTokenURL parameter contains an invalid URL: " + v; throw new TCTokenException(msg, ex); } catch (IOException ex) { throw new TCTokenException("Failed to fetch TCToken.", ex); } } else { throw new TCTokenException("Parameter tcTokenURL contains no value."); } } else if (k.equals("ifdName")) { if (v != null && ! v.isEmpty()) { tcTokenRequest.setIFDName(v); } else { throw new TCTokenException("Parameter ifdName contains no value."); } } else if (k.equals("contextHandle")) { if (v != null && ! v.isEmpty()) { tcTokenRequest.setContextHandle(v); } else { throw new TCTokenException("Parameter contextHandle contains no value."); } } else if (k.equals("slotIndex")) { if (v != null && ! v.isEmpty()) { tcTokenRequest.setSlotIndex(v); } else { throw new TCTokenException("Parameter slotIndex contains no value."); } } else if (k.equals("cardType")) { if (v != null && ! v.isEmpty()) { tcTokenRequest.setCardType(v); } else { throw new TCTokenException("Parameter cardType contains no value."); } } else { logger.info("Unknown query element: {}", k); } } return tcTokenRequest; } private TCTokenRequest parseObjectURI(Map<String, String> queries) throws TCTokenException { TCTokenRequest tcTokenRequest = new TCTokenRequest(); for (Map.Entry<String, String> next : queries.entrySet()) { String k = next.getKey(); String v = next.getValue(); if ("activationObject".equals(k)) { TCTokenType token = TCTokenFactory.generateTCToken(v); tcTokenRequest.setTCToken(token); } else if ("serverCertificate".equals(k)) { // TODO: convert base64 and url encoded certificate to Certificate object } } return tcTokenRequest; } /** * Gets the first handle of the given card type. * * @param type The card type to get the first handle for. * @return Handle describing the given card type or null if none is present. */ private ConnectionHandleType getFirstHandle(String type) { String cardName = rec.getTranslatedCardName(type); ConnectionHandleType conHandle = new ConnectionHandleType(); ConnectionHandleType.RecognitionInfo recInfo = new ConnectionHandleType.RecognitionInfo(); recInfo.setCardType(type); conHandle.setRecognitionInfo(recInfo); Set<CardStateEntry> entries = cardStates.getMatchingEntries(conHandle); if (entries.isEmpty()) { InsertCardDialog uc = new InsertCardDialog(gui, cardStates, type, cardName); return uc.show(); } else { return entries.iterator().next().handleCopy(); } } /** * Performs the actual PAOS procedure. * Connects the given card, establishes the HTTP channel and talks to the server. Afterwards disconnects the card. * * @param token The TCToken containing the connection parameters. * @param connectionHandle The handle of the card that will be used. * @return A TCTokenResponse indicating success or failure. * @throws DispatcherException If there was a problem dispatching a request from the server. * @throws PAOSException If there was a transport error. */ private TCTokenResponse doPAOS(TCTokenRequest tokenRequest, ConnectionHandleType connectionHandle) throws PAOSException, DispatcherException { TCTokenType token = tokenRequest.getTCToken(); try { // Perform a CardApplicationPath and CardApplicationConnect to connect to the card application CardApplicationPath appPath = new CardApplicationPath(); appPath.setCardAppPathRequest(connectionHandle); CardApplicationPathResponse appPathRes = (CardApplicationPathResponse) dispatcher.deliver(appPath); // Check CardApplicationPathResponse WSHelper.checkResult(appPathRes); CardApplicationConnect appConnect = new CardApplicationConnect(); List<CardApplicationPathType> pathRes; pathRes = appPathRes.getCardAppPathResultSet().getCardApplicationPathResult(); appConnect.setCardApplicationPath(pathRes.get(0)); CardApplicationConnectResponse appConnectRes; appConnectRes = (CardApplicationConnectResponse) dispatcher.deliver(appConnect); // Update ConnectionHandle. It now includes a SlotHandle. connectionHandle = appConnectRes.getConnectionHandle(); // Check CardApplicationConnectResponse WSHelper.checkResult(appConnectRes); // send StartPAOS PAOSTask task = new PAOSTask(dispatcher, connectionHandle, tokenRequest); FutureTask<StartPAOSResponse> paosTask = new FutureTask<StartPAOSResponse>(task); Thread paosThread = new Thread(paosTask, "PAOS"); paosThread.start(); if (! tokenRequest.isTokenFromObject()) { // wait for computation to finish waitForTask(paosTask); } TCTokenResponse response = new TCTokenResponse(); response.setRefreshAddress(new URL(token.getRefreshAddress())); response.setPAOSTask(paosTask); response.setResult(WSHelper.makeResultOK()); return response; } catch (WSException ex) { String msg = "Failed to connect to card."; logger.error(msg, ex); throw new DispatcherException(msg, ex); } catch (InvocationTargetException ex) { logger.error(ex.getMessage(), ex); throw new DispatcherException(ex); } catch (MalformedURLException ex) { logger.error(ex.getMessage(), ex); throw new PAOSException(ex); } } /** * Activates the client according to the received TCToken. * * @param request The activation request containing the TCToken. * @return The response containing the result of the activation process. */ public TCTokenResponse handleActivate(TCTokenRequest request) { final DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY); boolean performChecks = TCTokenHacks.isPerformTR03112Checks(request); if (! performChecks) { logger.warn("Checks according to BSI TR03112 3.4.2, 3.4.4 (TCToken specific) and 3.4.5 are disabled."); } boolean isObjectActivation = request.getTCTokenURL() == null; if (isObjectActivation) { logger.warn("Checks according to BSI TR03112 3.4.4 (TCToken specific) are disabled."); } dynCtx.put(TR03112Keys.TCTOKEN_CHECKS, performChecks); dynCtx.put(TR03112Keys.OBJECT_ACTIVATION, isObjectActivation); dynCtx.put(TR03112Keys.TCTOKEN_SERVER_CERTIFICATES, request.getCertificates()); dynCtx.put(TR03112Keys.TCTOKEN_URL, request.getTCTokenURL()); ConnectionHandleType connectionHandle = null; TCTokenResponse response = new TCTokenResponse(); byte[] requestedContextHandle = request.getContextHandle(); String ifdName = request.getIFDName(); BigInteger requestedSlotIndex = request.getSlotIndex(); if (requestedContextHandle == null || ifdName == null || requestedSlotIndex == null) { // use dumb activation without explicitly specifying the card and terminal // see TR-03112-7 v 1.1.2 (2012-02-28) sec. 3.2 connectionHandle = getFirstHandle(request.getCardType()); } else { // we know exactly which card we want ConnectionHandleType requestedHandle = new ConnectionHandleType(); requestedHandle.setContextHandle(requestedContextHandle); requestedHandle.setIFDName(ifdName); requestedHandle.setSlotIndex(requestedSlotIndex); Set<CardStateEntry> matchingHandles = cardStates.getMatchingEntries(requestedHandle); if (! matchingHandles.isEmpty()) { connectionHandle = matchingHandles.toArray(new CardStateEntry[] {})[0].handleCopy(); } } if (connectionHandle == null) { - String msg = "No card available for the given ConnectionHandle."; + String msg = lang.translationForKey("cancel"); logger.error(msg); response.setResult(WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, msg)); return response; } try { // perform PAOS and correct redirect address afterwards response = doPAOS(request, connectionHandle); response = determineRefreshURL(request, response); // in case of an object activation we have to wait until the job is done, the future takes care of that waitForTask(response.getPAOSTask()); return response; } catch (IOException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultUnknownError(w.getMessage())); return response; } catch (DispatcherException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); return response; } catch (PAOSException w) { logger.error(w.getMessage(), w); Throwable innerException = w.getCause(); if (innerException instanceof WSException) { response.setResult(((WSException) innerException).getResult()); } else { // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); } return response; } } private static void waitForTask(Future<?> task) throws PAOSException, DispatcherException { try { task.get(); } catch (InterruptedException ex) { logger.error(ex.getMessage(), ex); throw new PAOSException(ex); } catch (ExecutionException ex) { logger.error(ex.getMessage(), ex); // perform conversion of ExecutionException from the Future to the really expected exceptions if (ex.getCause() instanceof PAOSException) { throw (PAOSException) ex.getCause(); } else if (ex.getCause() instanceof DispatcherException) { throw (DispatcherException) ex.getCause(); } else { throw new PAOSException(ex); } } } /** * Follow the URL in the RefreshAddress of the TCToken as long as it is a redirect (302, 303 or 307) AND is a * https-URL AND the hash of the retrieved server certificate is contained in the CertificateDescrioption, else * return 400. If the URL and the subjectURL in the CertificateDescription conform to the SOP we reached our final * destination. * * @param endpoint current Redirect location * @return HTTP redirect to the final address the browser should be redirected to * @throws HttpException * @throws IOException * @throws URISyntaxException */ private TCTokenResponse determineRefreshURL(TCTokenRequest request, TCTokenResponse response) throws IOException { try { URL endpoint = response.getRefreshAddress(); DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY); // disable certificate checks according to BSI TR03112-7 in some situations boolean redirectChecks = TCTokenHacks.isPerformTR03112Checks(request); RedirectCertificateVerifier verifier = new RedirectCertificateVerifier(redirectChecks); Pair<InputStream, List<Pair<URL, Certificate>>> result = TCTokenGrabber.getStream(endpoint, verifier); // determine redirect List<Pair<URL, Certificate>> resultPoints = result.p2; Pair<URL, Certificate> last = resultPoints.get(resultPoints.size() - 1); endpoint = last.p1; // we finally found the refresh URL; redirect the browser to this location // but first clear context if it is not needed elsewhere (i hope this bullcrap can be removed very soon) Object objectActivation = dynCtx.get(TR03112Keys.OBJECT_ACTIVATION); if (objectActivation instanceof Boolean && ((Boolean) objectActivation).booleanValue() == false) { dynCtx.clear(); DynamicContext.remove(); } logger.debug("Setting redirect address to '{}'.", endpoint); response.setRefreshAddress(endpoint); return response; } catch (HttpException ex) { throw new IOException(ex); } catch (URISyntaxException ex) { throw new IOException(ex); } } }
true
true
public TCTokenResponse handleActivate(TCTokenRequest request) { final DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY); boolean performChecks = TCTokenHacks.isPerformTR03112Checks(request); if (! performChecks) { logger.warn("Checks according to BSI TR03112 3.4.2, 3.4.4 (TCToken specific) and 3.4.5 are disabled."); } boolean isObjectActivation = request.getTCTokenURL() == null; if (isObjectActivation) { logger.warn("Checks according to BSI TR03112 3.4.4 (TCToken specific) are disabled."); } dynCtx.put(TR03112Keys.TCTOKEN_CHECKS, performChecks); dynCtx.put(TR03112Keys.OBJECT_ACTIVATION, isObjectActivation); dynCtx.put(TR03112Keys.TCTOKEN_SERVER_CERTIFICATES, request.getCertificates()); dynCtx.put(TR03112Keys.TCTOKEN_URL, request.getTCTokenURL()); ConnectionHandleType connectionHandle = null; TCTokenResponse response = new TCTokenResponse(); byte[] requestedContextHandle = request.getContextHandle(); String ifdName = request.getIFDName(); BigInteger requestedSlotIndex = request.getSlotIndex(); if (requestedContextHandle == null || ifdName == null || requestedSlotIndex == null) { // use dumb activation without explicitly specifying the card and terminal // see TR-03112-7 v 1.1.2 (2012-02-28) sec. 3.2 connectionHandle = getFirstHandle(request.getCardType()); } else { // we know exactly which card we want ConnectionHandleType requestedHandle = new ConnectionHandleType(); requestedHandle.setContextHandle(requestedContextHandle); requestedHandle.setIFDName(ifdName); requestedHandle.setSlotIndex(requestedSlotIndex); Set<CardStateEntry> matchingHandles = cardStates.getMatchingEntries(requestedHandle); if (! matchingHandles.isEmpty()) { connectionHandle = matchingHandles.toArray(new CardStateEntry[] {})[0].handleCopy(); } } if (connectionHandle == null) { String msg = "No card available for the given ConnectionHandle."; logger.error(msg); response.setResult(WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, msg)); return response; } try { // perform PAOS and correct redirect address afterwards response = doPAOS(request, connectionHandle); response = determineRefreshURL(request, response); // in case of an object activation we have to wait until the job is done, the future takes care of that waitForTask(response.getPAOSTask()); return response; } catch (IOException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultUnknownError(w.getMessage())); return response; } catch (DispatcherException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); return response; } catch (PAOSException w) { logger.error(w.getMessage(), w); Throwable innerException = w.getCause(); if (innerException instanceof WSException) { response.setResult(((WSException) innerException).getResult()); } else { // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); } return response; } }
public TCTokenResponse handleActivate(TCTokenRequest request) { final DynamicContext dynCtx = DynamicContext.getInstance(TR03112Keys.INSTANCE_KEY); boolean performChecks = TCTokenHacks.isPerformTR03112Checks(request); if (! performChecks) { logger.warn("Checks according to BSI TR03112 3.4.2, 3.4.4 (TCToken specific) and 3.4.5 are disabled."); } boolean isObjectActivation = request.getTCTokenURL() == null; if (isObjectActivation) { logger.warn("Checks according to BSI TR03112 3.4.4 (TCToken specific) are disabled."); } dynCtx.put(TR03112Keys.TCTOKEN_CHECKS, performChecks); dynCtx.put(TR03112Keys.OBJECT_ACTIVATION, isObjectActivation); dynCtx.put(TR03112Keys.TCTOKEN_SERVER_CERTIFICATES, request.getCertificates()); dynCtx.put(TR03112Keys.TCTOKEN_URL, request.getTCTokenURL()); ConnectionHandleType connectionHandle = null; TCTokenResponse response = new TCTokenResponse(); byte[] requestedContextHandle = request.getContextHandle(); String ifdName = request.getIFDName(); BigInteger requestedSlotIndex = request.getSlotIndex(); if (requestedContextHandle == null || ifdName == null || requestedSlotIndex == null) { // use dumb activation without explicitly specifying the card and terminal // see TR-03112-7 v 1.1.2 (2012-02-28) sec. 3.2 connectionHandle = getFirstHandle(request.getCardType()); } else { // we know exactly which card we want ConnectionHandleType requestedHandle = new ConnectionHandleType(); requestedHandle.setContextHandle(requestedContextHandle); requestedHandle.setIFDName(ifdName); requestedHandle.setSlotIndex(requestedSlotIndex); Set<CardStateEntry> matchingHandles = cardStates.getMatchingEntries(requestedHandle); if (! matchingHandles.isEmpty()) { connectionHandle = matchingHandles.toArray(new CardStateEntry[] {})[0].handleCopy(); } } if (connectionHandle == null) { String msg = lang.translationForKey("cancel"); logger.error(msg); response.setResult(WSHelper.makeResultError(ECardConstants.Minor.SAL.CANCELLATION_BY_USER, msg)); return response; } try { // perform PAOS and correct redirect address afterwards response = doPAOS(request, connectionHandle); response = determineRefreshURL(request, response); // in case of an object activation we have to wait until the job is done, the future takes care of that waitForTask(response.getPAOSTask()); return response; } catch (IOException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultUnknownError(w.getMessage())); return response; } catch (DispatcherException w) { logger.error(w.getMessage(), w); // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); return response; } catch (PAOSException w) { logger.error(w.getMessage(), w); Throwable innerException = w.getCause(); if (innerException instanceof WSException) { response.setResult(((WSException) innerException).getResult()); } else { // TODO: check for better matching minor type response.setResult(WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, w.getMessage())); } return response; } }
diff --git a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java index cab7756b..9f6a556d 100644 --- a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java +++ b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java @@ -1,125 +1,126 @@ package ch.cern.atlas.apvs.ptu.server; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.cern.atlas.apvs.domain.Event; import ch.cern.atlas.apvs.domain.Measurement; import ch.cern.atlas.apvs.domain.Message; import com.cedarsoftware.util.io.JsonReader; public class PtuJsonReader extends JsonReader { private Logger log = LoggerFactory.getLogger(getClass().getName()); public PtuJsonReader(InputStream in) { super(in); } public PtuJsonReader(InputStream in, boolean noObjects) { super(in, noObjects); } @Override public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { // FIXME #4 String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = Double.parseDouble((String) msg.get("Value")); - Number low = Double.parseDouble((String) msg.get("DownThreshold")); - Number high = Double.parseDouble((String) msg.get("UpThreshold")); + Number low = Double.parseDouble((String) msg + .get("DownThreshold")); + Number high = Double.parseDouble((String) msg + .get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt((String) msg.get("SamplingRate")), convertToDate(msg.get("Time")))); } else if (type.equals("Event")) { - // FIXME #231 result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg - .get("Threshold")), "", convertToDate(msg - .get("Time")))); + .get("Threshold")), (String) msg.get("Unit"), + convertToDate(msg.get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; } private Double convertToDouble(Object number) { if ((number == null) || !(number instanceof String)) { return null; } try { return Double.parseDouble((String) number); } catch (NumberFormatException e) { return null; } } @Override protected Date convertToDate(Object rhs) { try { return PtuServerConstants.dateFormat.parse((String) rhs); } catch (ParseException e) { return null; } } public static List<Message> jsonToJava(String json) throws IOException { ByteArrayInputStream ba = new ByteArrayInputStream( json.getBytes("UTF-8")); PtuJsonReader jr = new PtuJsonReader(ba, false); @SuppressWarnings("unchecked") List<Message> result = (List<Message>) jr.readObject(); jr.close(); return result; } public static List<Message> toJava(String json) { try { return jsonToJava(json); } catch (Exception ignored) { return null; } } }
false
true
public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { // FIXME #4 String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = Double.parseDouble((String) msg.get("Value")); Number low = Double.parseDouble((String) msg.get("DownThreshold")); Number high = Double.parseDouble((String) msg.get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt((String) msg.get("SamplingRate")), convertToDate(msg.get("Time")))); } else if (type.equals("Event")) { // FIXME #231 result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg .get("Threshold")), "", convertToDate(msg .get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; }
public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { // FIXME #4 String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = Double.parseDouble((String) msg.get("Value")); Number low = Double.parseDouble((String) msg .get("DownThreshold")); Number high = Double.parseDouble((String) msg .get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt((String) msg.get("SamplingRate")), convertToDate(msg.get("Time")))); } else if (type.equals("Event")) { result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg .get("Threshold")), (String) msg.get("Unit"), convertToDate(msg.get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; }
diff --git a/src/com/yahoo/platform/yui/compressor/CssCompressor.java b/src/com/yahoo/platform/yui/compressor/CssCompressor.java index 134681c..7205eab 100644 --- a/src/com/yahoo/platform/yui/compressor/CssCompressor.java +++ b/src/com/yahoo/platform/yui/compressor/CssCompressor.java @@ -1,149 +1,149 @@ /* * YUI Compressor * Author: Julien Lecomte <[email protected]> * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt * * This code is a port of Isaac Schlueter's cssmin utility. */ package com.yahoo.platform.yui.compressor; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.regex.Pattern; import java.util.regex.Matcher; public class CssCompressor { private StringBuffer srcsb = new StringBuffer(); public CssCompressor(Reader in) throws IOException { // Read the stream... int c; while ((c = in.read()) != -1) { srcsb.append((char) c); } } public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*")) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex >= startIndex + 2) sb.delete(startIndex, endIndex + 2); } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6 - css = css.replaceAll("[^\\d]0+\\.(\\d+)", ".$1"); + css = css.replaceAll("([^\\d])0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC p = Pattern.compile("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(1).equalsIgnoreCase(m.group(2)) && m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))) { m.appendReplacement(sb, "#" + m.group(1) + m.group(3) + m.group(5)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); } }
true
true
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*")) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex >= startIndex + 2) sb.delete(startIndex, endIndex + 2); } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6 css = css.replaceAll("[^\\d]0+\\.(\\d+)", ".$1"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC p = Pattern.compile("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(1).equalsIgnoreCase(m.group(2)) && m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))) { m.appendReplacement(sb, "#" + m.group(1) + m.group(3) + m.group(5)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
public void compress(Writer out, int linebreakpos) throws IOException { Pattern p; Matcher m; String css; StringBuffer sb; int startIndex, endIndex; // Remove all comment blocks... sb = new StringBuffer(srcsb.toString()); while ((startIndex = sb.indexOf("/*")) >= 0) { endIndex = sb.indexOf("*/", startIndex + 2); if (endIndex >= startIndex + 2) sb.delete(startIndex, endIndex + 2); } css = sb.toString(); // Normalize all whitespace strings to single spaces. Easier to work with that way. css = css.replaceAll("\\s+", " "); // Remove the spaces before the things that should not have spaces before them. // But, be careful not to turn "p :link {...}" into "p:link{...}" // Swap out any pseudo-class colons with the token, and then swap back. sb = new StringBuffer(); p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)"); m = p.matcher(css); while (m.find()) { String s = m.group(); s = s.replaceAll(":", "___PSEUDOCLASSCOLON___"); m.appendReplacement(sb, s); } m.appendTail(sb); css = sb.toString(); css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1"); css = css.replaceAll("___PSEUDOCLASSCOLON___", ":"); // Remove the spaces after the things that should not have spaces after them. css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1"); // Add the semicolon where it's missing. css = css.replaceAll("([^;\\}])}", "$1;}"); // Replace 0(px,em,%) with 0. css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2"); // Replace 0 0 0 0; with 0. css = css.replaceAll(":0 0 0 0;", ":0;"); css = css.replaceAll(":0 0 0;", ":0;"); css = css.replaceAll(":0 0;", ":0;"); // Replace background-position:0; with background-position:0 0; css = css.replaceAll("background-position:0;", "background-position:0 0;"); // Replace 0.6 to .6 css = css.replaceAll("([^\\d])0+\\.(\\d+)", "$1.$2"); // Shorten colors from rgb(51,102,153) to #336699 // This makes it more likely that it'll get further compressed in the next step. p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { String[] rgbcolors = m.group(1).split(","); StringBuffer hexcolor = new StringBuffer("#"); for (int i = 0; i < rgbcolors.length; i++) { int val = Integer.parseInt(rgbcolors[i]); hexcolor.append(Integer.toHexString(val)); } m.appendReplacement(sb, hexcolor.toString()); } m.appendTail(sb); css = sb.toString(); // Shorten colors from #AABBCC to #ABC p = Pattern.compile("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])"); m = p.matcher(css); sb = new StringBuffer(); while (m.find()) { // Test for AABBCC pattern if (m.group(1).equalsIgnoreCase(m.group(2)) && m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))) { m.appendReplacement(sb, "#" + m.group(1) + m.group(3) + m.group(5)); } else { m.appendReplacement(sb, m.group()); } } m.appendTail(sb); css = sb.toString(); // Remove empty rules. css = css.replaceAll("[^\\}]+\\{;\\}", ""); if (linebreakpos >= 0) { // Some source control tools don't like it when files containing lines longer // than, say 8000 characters, are checked in. The linebreak option is used in // that case to split long lines after a specific column. int i = 0; int linestartpos = 0; sb = new StringBuffer(css); while (i < sb.length()) { char c = sb.charAt(i++); if (c == '}' && i - linestartpos > linebreakpos) { sb.insert(i, '\n'); linestartpos = i; } } css = sb.toString(); } // Trim the final string (for any leading or trailing white spaces) css = css.trim(); // Write the output... out.write(css); }
diff --git a/CompleteMyTask/src/ca/ualberta/cs/completemytask/activities/CommentActivity.java b/CompleteMyTask/src/ca/ualberta/cs/completemytask/activities/CommentActivity.java index d08ad71..dbee688 100644 --- a/CompleteMyTask/src/ca/ualberta/cs/completemytask/activities/CommentActivity.java +++ b/CompleteMyTask/src/ca/ualberta/cs/completemytask/activities/CommentActivity.java @@ -1,170 +1,171 @@ package ca.ualberta.cs.completemytask.activities; import ca.ualberta.cs.completemytask.R; import ca.ualberta.cs.completemytask.background.BackgroundTask; import ca.ualberta.cs.completemytask.background.HandleInBackground; import ca.ualberta.cs.completemytask.database.DatabaseManager; import ca.ualberta.cs.completemytask.saving.LocalSaving; import ca.ualberta.cs.completemytask.settings.Settings; import ca.ualberta.cs.completemytask.userdata.Comment; import ca.ualberta.cs.completemytask.userdata.Task; import ca.ualberta.cs.completemytask.userdata.TaskManager; import ca.ualberta.cs.completemytask.userdata.User; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; /** * Handles the adding of a comment. The user * enters their comment into the EditText * "Comment" and it is added to the task with * the button "SendButton". * * @author * */ public class CommentActivity extends Activity { private static final String TAG = "CommentActivity"; private EditText commentEditText; private TextView commentsTextView; private Task task; public LocalSaving saver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); saver = new LocalSaving(); int position = TaskManager.getInstance().getCurrentTaskPosition(); task = TaskManager.getInstance().getTaskAt(position); commentsTextView = (TextView) findViewById(R.id.commentsView); BackgroundTask bg = new BackgroundTask(); bg.runInBackGround(new HandleInBackground() { public void onPreExecute() { } public void onPostExecute(int response) { int numberOfComments = task.getNumberOfComments(); for (int i = 0; i < numberOfComments; i++) { Comment comment = task.getCommentAt(i); User user = comment.getUser(); String commentsString = commentsTextView.getText().toString(); commentsString += user.getUserName() + "\n\n\t" + comment.getContent() + "\n\n\n"; commentsTextView.setText(commentsString); } } public void onUpdate(int response) { } public boolean handleInBackground(Object o) { - return DatabaseManager.getInstance().syncDatabaseComments(task); + DatabaseManager.getInstance().getComments(task); + return true; } }); commentEditText = (EditText) findViewById(R.id.Comment); commentEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { // Send the user message send(null); handled = true; } return handled; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_comment, menu); return true; } /** * Send a text to the current task. * @param A view */ public void send(View view) { Log.v(TAG, "Sent Comment"); String commentString = commentEditText.getText().toString(); commentEditText.setText(""); if (task == null) return; if (commentString.length() > 0) { Comment comment = new Comment(commentString); User user = null; if (Settings.getInstance().hasUser()) { user = Settings.getInstance().getUser(); } else { user = new User("Unknown"); } comment.setUser(user); comment.setParentId(task.getId()); sync(comment); String commentsString = commentsTextView.getText().toString(); commentsString += user.getUserName() + "\n\n\t" + comment.getContent() + "\n\n\n"; commentsTextView.setText(commentsString); } } public void sync(final Comment comment) { BackgroundTask bg = new BackgroundTask(); bg.runInBackGround(new HandleInBackground() { public void onPreExecute() { } public void onPostExecute(int response) { } public void onUpdate(int response) { } public boolean handleInBackground(Object o) { DatabaseManager.getInstance().syncComment(comment); task.addComment(comment); if (task.isLocal()) { saver.open(); saver.saveComment(comment); saver.close(); } return true; } }); } /** * Close activity. * * @param A view */ public void close(View view) { this.finish(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); saver = new LocalSaving(); int position = TaskManager.getInstance().getCurrentTaskPosition(); task = TaskManager.getInstance().getTaskAt(position); commentsTextView = (TextView) findViewById(R.id.commentsView); BackgroundTask bg = new BackgroundTask(); bg.runInBackGround(new HandleInBackground() { public void onPreExecute() { } public void onPostExecute(int response) { int numberOfComments = task.getNumberOfComments(); for (int i = 0; i < numberOfComments; i++) { Comment comment = task.getCommentAt(i); User user = comment.getUser(); String commentsString = commentsTextView.getText().toString(); commentsString += user.getUserName() + "\n\n\t" + comment.getContent() + "\n\n\n"; commentsTextView.setText(commentsString); } } public void onUpdate(int response) { } public boolean handleInBackground(Object o) { return DatabaseManager.getInstance().syncDatabaseComments(task); } }); commentEditText = (EditText) findViewById(R.id.Comment); commentEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { // Send the user message send(null); handled = true; } return handled; } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_comment); saver = new LocalSaving(); int position = TaskManager.getInstance().getCurrentTaskPosition(); task = TaskManager.getInstance().getTaskAt(position); commentsTextView = (TextView) findViewById(R.id.commentsView); BackgroundTask bg = new BackgroundTask(); bg.runInBackGround(new HandleInBackground() { public void onPreExecute() { } public void onPostExecute(int response) { int numberOfComments = task.getNumberOfComments(); for (int i = 0; i < numberOfComments; i++) { Comment comment = task.getCommentAt(i); User user = comment.getUser(); String commentsString = commentsTextView.getText().toString(); commentsString += user.getUserName() + "\n\n\t" + comment.getContent() + "\n\n\n"; commentsTextView.setText(commentsString); } } public void onUpdate(int response) { } public boolean handleInBackground(Object o) { DatabaseManager.getInstance().getComments(task); return true; } }); commentEditText = (EditText) findViewById(R.id.Comment); commentEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { // Send the user message send(null); handled = true; } return handled; } }); }
diff --git a/src/wikitopdf/WikiProcessor.java b/src/wikitopdf/WikiProcessor.java index 6c8d5fb..9fde2f8 100755 --- a/src/wikitopdf/WikiProcessor.java +++ b/src/wikitopdf/WikiProcessor.java @@ -1,281 +1,281 @@ package wikitopdf; import wikitopdf.utils.ByteFormatter; import wikitopdf.utils.WikiSettings; import wikitopdf.utils.WikiLogger; import com.lowagie.text.DocumentException; import java.io.IOException; import java.io.File; import java.sql.SQLException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import wikitopdf.pdf.PdfPageWrapper; import wikitopdf.pdf.PdfStamp; import wikitopdf.wiki.WikiPage; /** * * @author Denis Lunev <[email protected]> */ public class WikiProcessor { /** * */ public void createPdf() { int pageBunch = WikiSettings.getInstance().getArticleBunch(); int pdfPageLimit = WikiSettings.getInstance().getPageLimit(); String pageInfo = ""; int startLimit = WikiSettings.getInstance().getStartPage(); boolean isInProggress = true; int cPageNum = 0; int artWritten = 0; int numArt = 0; int cVolNum = 1; Date newTime = new Date(); Date oldTime; String tempName; String outputName = ""; File oldFile; File newFile; SQLProcessor sqlReader = null; PdfPageWrapper pdfWrapper = null; Runtime runtime = Runtime.getRuntime(); //while (isInProggress) { try { //i want this to get built and broken down with each iteration to ensure no memory leaking in it. sqlReader = new SQLProcessor(); int artCount = sqlReader.getArticlesCount();// Counts total from database sqlReader = null; while (isInProggress) { pdfWrapper = new PdfPageWrapper(startLimit); // Start with page ID indicated in settings - tempName = "output\\" + pdfWrapper.getOutputFileName(); // Added Wednesday May 22 by CE For file rename + tempName = "./output/" + pdfWrapper.getOutputFileName(); // Added Wednesday May 22 by CE For file rename sqlReader = new SQLProcessor(); // While still pages in database and still writing pages to this volume // This inner while loop creates a single pdf volume while (pdfWrapper.getPageNumb() < pdfPageLimit && isInProggress) { // Get all article entries from the database ArrayList<WikiPage> pages = sqlReader.getBunch(startLimit, pageBunch, 1); //for (WikiPage page : pages) { // pdfWrapper.writePage(page); //} // Added May 23 by CE to stop writing articles when page limit is reached outputName = pages.get(0).getTitle(); Iterator<WikiPage> i = pages.iterator(); for(; i.hasNext() && pdfWrapper.getPageNumb() < pdfPageLimit; ) { WikiPage page = i.next(); pdfWrapper.writePage(page); artWritten++; } outputName = outputName + "-" + pages.get(artWritten - 1).getTitle(); isInProggress = sqlReader.isInProggres(); // checks to see if there is still database entries //TODO change from test value //isInProggress = false; if (isInProggress) { //startLimit += pageBunch; //auto-incraments start based on a database query bunch startLimit += artWritten; // Added May 23 by CE incraments by the number of articles written } numArt = artWritten; artWritten = 0; // Added May 23 by CE resets incramentor so that it doesn't skip articles next loop through pages = null; //System.out.println("starting PDF, page number: " + pdfWrapper.getPageNumb()); // the number that is being printed //pdfWrapper.closeColumn(); } // End of Volume cPageNum = pdfWrapper.getPageNumb(); pdfWrapper.close(); //Renaming Added May 24 by CE, renames outputfile - outputName = "output\\Vol_" + cVolNum + "-" + outputName + "-" + (cPageNum - 1) + ".pdf"; + outputName = "./output/Vol_" + cVolNum + "-" + outputName + "-" + (cPageNum - 1) + ".pdf"; oldFile = new File(tempName); newFile = new File(outputName); if(newFile.exists()){ newFile.delete(); } if(!(oldFile.renameTo(newFile))){ System.out.println("File not renamed"); } //Timing oldTime = newTime; newTime = new Date(); //Print time for last volume in seconds, as well as the number of articles used to write it. System.out.println("Time for Vol_" + cVolNum + ": " + ((newTime.getTime() - oldTime.getTime()) / 1000) + ", articles written: " + numArt); //Print out current time //System.out.println("Current Time: " + newTime.getTime()); cVolNum++; //Info pageInfo = "([" + pdfWrapper.getCurrentArticleID() + "] " + pdfWrapper.getCurrentTitle() + ")"; WikiLogger.getLogger().fine("Retrieved " + startLimit + "/" + artCount + " articles " + pageInfo); WikiLogger.getLogger().info("Free memory: " + ByteFormatter.format(runtime.freeMemory())); //here's some closing code at the end of each volume pdfWrapper = null; sqlReader = null; } //End of all volumes/PDFs //Stamping all page numbers PdfStamp stamp = new PdfStamp(); WikiLogger.getLogger().info("Stamping page numbers..."); stamp.stampDir(cPageNum); WikiLogger.getLogger().fine("Stamping done"); } catch (Exception ex) { WikiLogger.getLogger().severe(ex.getMessage() + pageInfo); } finally { sqlReader.close(); } WikiLogger.getLogger().fine("Finished (" + startLimit + " pages)"); } } /* * THIS IS RAM'S CODE FROM THE AKKA BRANCH * IS THIS A GENERAL PURPOSE WIKIPROCESSOR? * OR IS IT SPECIFICALLY REWRITTEN FOR THE AKKA BRANCH? * IF AKKA BRANCH, IT SHOULD BE GIVEN A NEW NAME * E.G. AkkaWikiProcessor * SO THE TWO CAN COEXIST. public class WikiProcessor { public int createPdf(int startLimit) { String pageInfo = ""; int cPageNum = 0; int pageBunch = WikiSettings.getInstance().getArticleBunch(); SQLProcessor sqlReader = null; int pdfPageLimit = WikiSettings.getInstance().getPageLimit(); Runtime runtime = Runtime.getRuntime(); int artCount = 0; try { PdfPageWrapper pdfWrapper = new PdfPageWrapper(startLimit); sqlReader = new SQLProcessor(); artCount = sqlReader.getArticlesCount(); while (pdfWrapper.getPageNumb() < pdfPageLimit) { ArrayList<WikiPage> pages = sqlReader.getBunch(startLimit, pageBunch, 1); for (WikiPage page : pages) { pdfWrapper.writePage(page); } startLimit += pageBunch; } cPageNum = pdfWrapper.getPageNumb(); pdfWrapper.close(); pageInfo = "([" + pdfWrapper.getCurrentArticleID() + "] " + pdfWrapper.getCurrentTitle() + ")"; WikiLogger.getLogger().fine( "Retrieved " + startLimit + "/" + artCount + " articles " + pageInfo); WikiLogger.getLogger().info( "Free memory: " + ByteFormatter.format(runtime.freeMemory())); PdfStamp stamp = new PdfStamp(); WikiLogger.getLogger().info("Stamping page numbers..."); stamp.stampDir(cPageNum); WikiLogger.getLogger().fine("Stamping done"); } catch (Exception ex) { WikiLogger.getLogger().severe(ex.getMessage() + pageInfo); } finally { sqlReader.close(); } WikiLogger.getLogger().fine("Finished (" + startLimit + " pages)"); return artCount; } public void createPdf() { int pageBunch = WikiSettings.getInstance().getArticleBunch(); int pdfPageLimit = WikiSettings.getInstance().getPageLimit(); String pageInfo = ""; int startLimit = WikiSettings.getInstance().getStartPage(); boolean isInProggress = true; int cPageNum = 0; SQLProcessor sqlReader = null; PdfPageWrapper pdfWrapper = null; Runtime runtime = Runtime.getRuntime(); try { sqlReader = new SQLProcessor(); int artCount = sqlReader.getArticlesCount(); while (isInProggress) { pdfWrapper = new PdfPageWrapper(startLimit); while (pdfWrapper.getPageNumb() < pdfPageLimit && isInProggress) { ArrayList<WikiPage> pages = sqlReader.getBunch(startLimit, pageBunch, 1); for (WikiPage page : pages) { pdfWrapper.writePage(page); } // cPageNum += isInProggress = sqlReader.isInProggres(); // TODO change from test value // isInProggress = false; if (isInProggress) { startLimit += pageBunch; } System.out.println(pdfWrapper.getPageNumb()); // pdfWrapper.closeColumn(); } cPageNum = pdfWrapper.getPageNumb(); pdfWrapper.close(); // Info pageInfo = "([" + pdfWrapper.getCurrentArticleID() + "] " + pdfWrapper.getCurrentTitle() + ")"; WikiLogger.getLogger().fine( "Retrieved " + startLimit + "/" + artCount + " articles " + pageInfo); WikiLogger.getLogger().info( "Free memory: " + ByteFormatter.format(runtime.freeMemory())); } // Stamping all page numbers PdfStamp stamp = new PdfStamp(); WikiLogger.getLogger().info("Stamping page numbers..."); stamp.stampDir(cPageNum); WikiLogger.getLogger().fine("Stamping done"); } catch (Exception ex) { WikiLogger.getLogger().severe(ex.getMessage() + pageInfo); } finally { sqlReader.close(); } WikiLogger.getLogger().fine("Finished (" + startLimit + " pages)"); } } * */
false
true
public void createPdf() { int pageBunch = WikiSettings.getInstance().getArticleBunch(); int pdfPageLimit = WikiSettings.getInstance().getPageLimit(); String pageInfo = ""; int startLimit = WikiSettings.getInstance().getStartPage(); boolean isInProggress = true; int cPageNum = 0; int artWritten = 0; int numArt = 0; int cVolNum = 1; Date newTime = new Date(); Date oldTime; String tempName; String outputName = ""; File oldFile; File newFile; SQLProcessor sqlReader = null; PdfPageWrapper pdfWrapper = null; Runtime runtime = Runtime.getRuntime(); //while (isInProggress) { try { //i want this to get built and broken down with each iteration to ensure no memory leaking in it. sqlReader = new SQLProcessor(); int artCount = sqlReader.getArticlesCount();// Counts total from database sqlReader = null; while (isInProggress) { pdfWrapper = new PdfPageWrapper(startLimit); // Start with page ID indicated in settings tempName = "output\\" + pdfWrapper.getOutputFileName(); // Added Wednesday May 22 by CE For file rename sqlReader = new SQLProcessor(); // While still pages in database and still writing pages to this volume // This inner while loop creates a single pdf volume while (pdfWrapper.getPageNumb() < pdfPageLimit && isInProggress) { // Get all article entries from the database ArrayList<WikiPage> pages = sqlReader.getBunch(startLimit, pageBunch, 1); //for (WikiPage page : pages) { // pdfWrapper.writePage(page); //} // Added May 23 by CE to stop writing articles when page limit is reached outputName = pages.get(0).getTitle(); Iterator<WikiPage> i = pages.iterator(); for(; i.hasNext() && pdfWrapper.getPageNumb() < pdfPageLimit; ) { WikiPage page = i.next(); pdfWrapper.writePage(page); artWritten++; } outputName = outputName + "-" + pages.get(artWritten - 1).getTitle(); isInProggress = sqlReader.isInProggres(); // checks to see if there is still database entries //TODO change from test value //isInProggress = false; if (isInProggress) { //startLimit += pageBunch; //auto-incraments start based on a database query bunch startLimit += artWritten; // Added May 23 by CE incraments by the number of articles written } numArt = artWritten; artWritten = 0; // Added May 23 by CE resets incramentor so that it doesn't skip articles next loop through pages = null; //System.out.println("starting PDF, page number: " + pdfWrapper.getPageNumb()); // the number that is being printed //pdfWrapper.closeColumn(); } // End of Volume cPageNum = pdfWrapper.getPageNumb(); pdfWrapper.close(); //Renaming Added May 24 by CE, renames outputfile outputName = "output\\Vol_" + cVolNum + "-" + outputName + "-" + (cPageNum - 1) + ".pdf"; oldFile = new File(tempName); newFile = new File(outputName); if(newFile.exists()){ newFile.delete(); } if(!(oldFile.renameTo(newFile))){ System.out.println("File not renamed"); } //Timing oldTime = newTime; newTime = new Date(); //Print time for last volume in seconds, as well as the number of articles used to write it. System.out.println("Time for Vol_" + cVolNum + ": " + ((newTime.getTime() - oldTime.getTime()) / 1000) + ", articles written: " + numArt); //Print out current time //System.out.println("Current Time: " + newTime.getTime()); cVolNum++; //Info pageInfo = "([" + pdfWrapper.getCurrentArticleID() + "] " + pdfWrapper.getCurrentTitle() + ")"; WikiLogger.getLogger().fine("Retrieved " + startLimit + "/" + artCount + " articles " + pageInfo); WikiLogger.getLogger().info("Free memory: " + ByteFormatter.format(runtime.freeMemory())); //here's some closing code at the end of each volume pdfWrapper = null; sqlReader = null; } //End of all volumes/PDFs //Stamping all page numbers PdfStamp stamp = new PdfStamp(); WikiLogger.getLogger().info("Stamping page numbers..."); stamp.stampDir(cPageNum); WikiLogger.getLogger().fine("Stamping done"); } catch (Exception ex) { WikiLogger.getLogger().severe(ex.getMessage() + pageInfo); } finally { sqlReader.close(); } WikiLogger.getLogger().fine("Finished (" + startLimit + " pages)"); }
public void createPdf() { int pageBunch = WikiSettings.getInstance().getArticleBunch(); int pdfPageLimit = WikiSettings.getInstance().getPageLimit(); String pageInfo = ""; int startLimit = WikiSettings.getInstance().getStartPage(); boolean isInProggress = true; int cPageNum = 0; int artWritten = 0; int numArt = 0; int cVolNum = 1; Date newTime = new Date(); Date oldTime; String tempName; String outputName = ""; File oldFile; File newFile; SQLProcessor sqlReader = null; PdfPageWrapper pdfWrapper = null; Runtime runtime = Runtime.getRuntime(); //while (isInProggress) { try { //i want this to get built and broken down with each iteration to ensure no memory leaking in it. sqlReader = new SQLProcessor(); int artCount = sqlReader.getArticlesCount();// Counts total from database sqlReader = null; while (isInProggress) { pdfWrapper = new PdfPageWrapper(startLimit); // Start with page ID indicated in settings tempName = "./output/" + pdfWrapper.getOutputFileName(); // Added Wednesday May 22 by CE For file rename sqlReader = new SQLProcessor(); // While still pages in database and still writing pages to this volume // This inner while loop creates a single pdf volume while (pdfWrapper.getPageNumb() < pdfPageLimit && isInProggress) { // Get all article entries from the database ArrayList<WikiPage> pages = sqlReader.getBunch(startLimit, pageBunch, 1); //for (WikiPage page : pages) { // pdfWrapper.writePage(page); //} // Added May 23 by CE to stop writing articles when page limit is reached outputName = pages.get(0).getTitle(); Iterator<WikiPage> i = pages.iterator(); for(; i.hasNext() && pdfWrapper.getPageNumb() < pdfPageLimit; ) { WikiPage page = i.next(); pdfWrapper.writePage(page); artWritten++; } outputName = outputName + "-" + pages.get(artWritten - 1).getTitle(); isInProggress = sqlReader.isInProggres(); // checks to see if there is still database entries //TODO change from test value //isInProggress = false; if (isInProggress) { //startLimit += pageBunch; //auto-incraments start based on a database query bunch startLimit += artWritten; // Added May 23 by CE incraments by the number of articles written } numArt = artWritten; artWritten = 0; // Added May 23 by CE resets incramentor so that it doesn't skip articles next loop through pages = null; //System.out.println("starting PDF, page number: " + pdfWrapper.getPageNumb()); // the number that is being printed //pdfWrapper.closeColumn(); } // End of Volume cPageNum = pdfWrapper.getPageNumb(); pdfWrapper.close(); //Renaming Added May 24 by CE, renames outputfile outputName = "./output/Vol_" + cVolNum + "-" + outputName + "-" + (cPageNum - 1) + ".pdf"; oldFile = new File(tempName); newFile = new File(outputName); if(newFile.exists()){ newFile.delete(); } if(!(oldFile.renameTo(newFile))){ System.out.println("File not renamed"); } //Timing oldTime = newTime; newTime = new Date(); //Print time for last volume in seconds, as well as the number of articles used to write it. System.out.println("Time for Vol_" + cVolNum + ": " + ((newTime.getTime() - oldTime.getTime()) / 1000) + ", articles written: " + numArt); //Print out current time //System.out.println("Current Time: " + newTime.getTime()); cVolNum++; //Info pageInfo = "([" + pdfWrapper.getCurrentArticleID() + "] " + pdfWrapper.getCurrentTitle() + ")"; WikiLogger.getLogger().fine("Retrieved " + startLimit + "/" + artCount + " articles " + pageInfo); WikiLogger.getLogger().info("Free memory: " + ByteFormatter.format(runtime.freeMemory())); //here's some closing code at the end of each volume pdfWrapper = null; sqlReader = null; } //End of all volumes/PDFs //Stamping all page numbers PdfStamp stamp = new PdfStamp(); WikiLogger.getLogger().info("Stamping page numbers..."); stamp.stampDir(cPageNum); WikiLogger.getLogger().fine("Stamping done"); } catch (Exception ex) { WikiLogger.getLogger().severe(ex.getMessage() + pageInfo); } finally { sqlReader.close(); } WikiLogger.getLogger().fine("Finished (" + startLimit + " pages)"); }
diff --git a/melati/src/main/java/org/melati/admin/Admin.java b/melati/src/main/java/org/melati/admin/Admin.java index 5463c8a33..3125ab0cc 100644 --- a/melati/src/main/java/org/melati/admin/Admin.java +++ b/melati/src/main/java/org/melati/admin/Admin.java @@ -1,428 +1,428 @@ /* * $Source$ * $Revision$ * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * ------------------------------------- * Copyright (C) 2000 William Chesters * ------------------------------------- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * A copy of the GPL should be in the file org/melati/COPYING in this tree. * Or see http://melati.org/License.html. * * Contact details for copyright holder: * * William Chesters <[email protected]> * http://paneris.org/~williamc * Obrechtstraat 114, 2517VX Den Haag, The Netherlands * * * ------ * Note * ------ * * I will assign copyright to PanEris (http://paneris.org) as soon as * we have sorted out what sort of legal existence we need to have for * that to make sense. When WebMacro's "Simple Public License" is * finalised, we'll offer it as an alternative license for Melati. * In the meantime, if you want to use Melati on non-GPL terms, * contact me! */ package org.melati.admin; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.melati.*; import org.melati.util.*; import org.melati.poem.*; import org.webmacro.*; import org.webmacro.util.*; import org.webmacro.servlet.*; import org.webmacro.engine.*; import org.webmacro.resource.*; import org.webmacro.broker.*; /** * FIXME getting a bit big, wants breaking up */ public class Admin extends MelatiServlet { protected Persistent create(Table table, final WebContext context) { return table.create( new Initialiser() { public void init(Persistent object) throws AccessPoemException, ValidationPoemException { Melati.extractFields(context, object); } }); } protected final Template adminTemplate(WebContext context, String name) throws NotFoundException, InvalidTypeException { return getTemplate("admin/" + name); } // return the 'Main' admin page protected Template mainTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { context.put("database", PoemThread.database()); return adminTemplate(context, "Main.wm"); } // return the 'LowerFrame' admin page protected Template lowerFrameTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { context.put("database", PoemThread.database()); final Table table = melati.getTable(); context.put("table", table); return adminTemplate(context, "LowerFrame.wm"); } protected Template tablesViewTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { context.put("database", PoemThread.database()); return adminTemplate(context, "Tables.wm"); } protected Template tableCreateTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { Database database = melati.getDatabase(); // Compose field for naming the TROID column: the display name and // description are redundant, since they not used in the template Field troidNameField = new Field( "id", new BaseFieldAttributes( "troidName", "Troid column", "Name of TROID column", database.getColumnInfoTable().getNameColumn().getType(), null)); context.put("troidNameField", troidNameField); Table tit = database.getTableInfoTable(); Enumeration tableInfoFields = new MappedEnumeration(tit.columns()) { public Object mapped(Object column) { return new Field((Object)null, (Column)column); } }; context.put("tableInfoFields", tableInfoFields); return adminTemplate(context, "CreateTable.wm"); } protected Template tableCreate_doitTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { Database database = melati.getDatabase(); database.addTableAndCommit( (TableInfo)create(database.getTableInfoTable(), context), context.getForm("field-troidName")); return adminTemplate(context, "CreateTable_doit.wm"); } protected Template tableListTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { return adminTemplate(tableList(context,melati), "Select.wm"); } protected Template popupTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { return adminTemplate(tableList(context,melati), "PopupSelect.wm"); } protected WebContext tableList(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { final Table table = melati.getTable(); context.put("table", table); final Database database = table.getDatabase(); context.put("database", database); // sort out search criteria final Persistent criteria = table.newPersistent(); for (Enumeration c = table.columns(); c.hasMoreElements();) { Column column = (Column)c.nextElement(); String string = context.getForm("field-" + column.getName()); if (string != null && !string.equals("")) column.setRaw_unsafe(criteria, column.getType().rawOfString(string)); } - MappedEnumeration criteria = + MappedEnumeration criterias = new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object c) { Column column = (Column)c; final PoemType nullable = column.getType().withNullable(true); return new Field(column.getRaw(criteria), column) { public PoemType getType() { return nullable; } }; } }; - context.put("criteria", EnumUtils.vectorOf(criteria)); + context.put("criteria", EnumUtils.vectorOf(criterias)); // sort out ordering (FIXME this is a bit out of control) PoemType searchColumnsType = new ReferencePoemType(database.getColumnInfoTable(), true) { protected Enumeration _possibleRaws() { return new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object column) { return ((Column)column).getColumnInfo().getTroid(); } }; } }; Vector orderingNames = new Vector(); Vector orderings = new Vector(); for (int o = 1; o <= 2; ++o) { String name = "order-" + o; String orderColumnIDString = context.getForm("field-" + name); Integer orderColumnID = null; if (orderColumnIDString != null && !orderColumnIDString.equals("")) { orderColumnID = (Integer)searchColumnsType.rawOfString(orderColumnIDString); ColumnInfo info = (ColumnInfo)searchColumnsType.cookedOfRaw(orderColumnID); orderingNames.addElement(database.quotedName(info.getName())); } orderings.addElement( new Field(orderColumnID, new BaseFieldAttributes(name, searchColumnsType))); } context.put("orderings", orderings); String orderByClause = EnumUtils.concatenated(", ", orderingNames.elements()); int start = 0; String startString = context.getForm("start"); if (startString != null) { try { start = Math.max(0, Integer.parseInt(startString)); } catch (NumberFormatException e) { throw new HandlerException("`start' param to `List' must be a number"); } } context.put("objects", table.selection(table.whereClause(criteria), orderByClause, false, start, 20)); return context; } protected Template columnCreateTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { final ColumnInfoTable cit = melati.getDatabase().getColumnInfoTable(); final Column tic = cit.getTableinfoColumn(); final Column typeColumn = cit.getTypeColumn(); Enumeration columnInfoFields = new MappedEnumeration(cit.columns()) { public Object mapped(Object column) { /* if (column == tic) // What does this do??! return new Field( (Object)null, new BaseFieldAttributes( tic.getName(), tic.getDisplayName(), tic.getDescription(), tic.getType(), tic.getRenderInfo())); else */ if (column == typeColumn) return new Field(PoemTypeFactory.STRING.getCode(), typeColumn); else return new Field((Object)null, (FieldAttributes)column); } }; context.put("columnInfoFields", columnInfoFields); return adminTemplate(context, "CreateColumn.wm"); } protected Template columnCreate_doitTemplate(final WebContext context, final Melati melati) throws NotFoundException, InvalidTypeException, PoemException { ColumnInfo columnInfo = (ColumnInfo)melati.getDatabase().getColumnInfoTable().create( new Initialiser() { public void init(Persistent object) throws AccessPoemException, ValidationPoemException { ((ColumnInfo)object).setTableinfoTroid( melati.getTable().tableInfoID()); Melati.extractFields(context, object); } }); melati.getTable().addColumnAndCommit(columnInfo); return adminTemplate(context, "CreateTable_doit.wm"); } protected Template editTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { melati.getObject().assertCanRead(); context.put("object", melati.getObject()); Database database = melati.getDatabase(); context.put("database", database); return adminTemplate(context, "Edit.wm"); } protected Template addTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { context.put("table", melati.getTable()); Enumeration fields = new MappedEnumeration(melati.getTable().columns()) { public Object mapped(Object column) { return new Field((Object)null, (Column)column); } }; context.put("fields", fields); return adminTemplate(context, "Add.wm"); } protected Template updateTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { Melati.extractFields(context, melati.getObject()); return adminTemplate(context, "Update.wm"); } protected Template addUpdateTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { create(melati.getTable(), context); return adminTemplate(context, "Update.wm"); } protected Template deleteTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { try { melati.getObject().deleteAndCommit(); return adminTemplate(context, "Update.wm"); } catch (DeletionIntegrityPoemException e) { context.put("object", e.object); context.put("references", e.references); return adminTemplate(context, "DeleteFailure.wm"); } } protected Template duplicateTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException { // FIXME the ORIGINAL object is the one that will get edited when the // update comes in from Edit.wm, because it will be identified from // the path info! melati.getObject().duplicated(); context.put("object", melati.getObject()); return adminTemplate(context, "Update.wm"); } protected Template modifyTemplate(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { String action = context.getRequest().getParameter("action"); if ("Update".equals(action)) return updateTemplate(context, melati); else if ("Delete".equals(action)) return deleteTemplate(context, melati); else if ("Duplicate".equals(action)) return duplicateTemplate(context, melati); else throw new HandlerException("bad action from Edit.wm: " + action); } protected Template handle(WebContext context, Melati melati) throws PoemException, HandlerException { try { context.put("admin", new AdminUtils(context.getRequest().getServletPath(), melati.getLogicalDatabaseName())); if (melati.getObject() != null) { if (melati.getMethod().equals("Edit")) return editTemplate(context, melati); else if (melati.getMethod().equals("Update")) return modifyTemplate(context, melati); } else if (melati.getTable() != null) { if (melati.getMethod().equals("View")) return tableListTemplate(context, melati); if (melati.getMethod().equals("LowerFrame")) return lowerFrameTemplate(context, melati); if (melati.getMethod().equals("PopUp")) return popupTemplate(context, melati); else if (melati.getMethod().equals("Add")) return addTemplate(context, melati); else if (melati.getMethod().equals("AddUpdate")) return addUpdateTemplate(context, melati); } else { if (melati.getMethod().equals("Main")) return mainTemplate(context, melati); if (melati.getMethod().equals("View")) return tablesViewTemplate(context, melati); else if (melati.getMethod().equals("Create")) return tableCreateTemplate(context, melati); else if (melati.getMethod().equals("Create_doit")) return tableCreate_doitTemplate(context, melati); else if (melati.getMethod().equals("CreateColumn")) return columnCreateTemplate(context, melati); else if (melati.getMethod().equals("CreateColumn_doit")) return columnCreate_doitTemplate(context, melati); } throw new InvalidUsageException(this, melati.getContext()); } catch (PoemException e) { // we want to let these through untouched, since MelatiServlet handles // AccessPoemException specially ... throw e; } catch (Exception e) { e.printStackTrace(); throw new HandlerException("Bollocks: " + e); } } }
false
true
protected WebContext tableList(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { final Table table = melati.getTable(); context.put("table", table); final Database database = table.getDatabase(); context.put("database", database); // sort out search criteria final Persistent criteria = table.newPersistent(); for (Enumeration c = table.columns(); c.hasMoreElements();) { Column column = (Column)c.nextElement(); String string = context.getForm("field-" + column.getName()); if (string != null && !string.equals("")) column.setRaw_unsafe(criteria, column.getType().rawOfString(string)); } MappedEnumeration criteria = new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object c) { Column column = (Column)c; final PoemType nullable = column.getType().withNullable(true); return new Field(column.getRaw(criteria), column) { public PoemType getType() { return nullable; } }; } }; context.put("criteria", EnumUtils.vectorOf(criteria)); // sort out ordering (FIXME this is a bit out of control) PoemType searchColumnsType = new ReferencePoemType(database.getColumnInfoTable(), true) { protected Enumeration _possibleRaws() { return new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object column) { return ((Column)column).getColumnInfo().getTroid(); } }; } }; Vector orderingNames = new Vector(); Vector orderings = new Vector(); for (int o = 1; o <= 2; ++o) { String name = "order-" + o; String orderColumnIDString = context.getForm("field-" + name); Integer orderColumnID = null; if (orderColumnIDString != null && !orderColumnIDString.equals("")) { orderColumnID = (Integer)searchColumnsType.rawOfString(orderColumnIDString); ColumnInfo info = (ColumnInfo)searchColumnsType.cookedOfRaw(orderColumnID); orderingNames.addElement(database.quotedName(info.getName())); } orderings.addElement( new Field(orderColumnID, new BaseFieldAttributes(name, searchColumnsType))); } context.put("orderings", orderings); String orderByClause = EnumUtils.concatenated(", ", orderingNames.elements()); int start = 0; String startString = context.getForm("start"); if (startString != null) { try { start = Math.max(0, Integer.parseInt(startString)); } catch (NumberFormatException e) { throw new HandlerException("`start' param to `List' must be a number"); } } context.put("objects", table.selection(table.whereClause(criteria), orderByClause, false, start, 20)); return context; }
protected WebContext tableList(WebContext context, Melati melati) throws NotFoundException, InvalidTypeException, PoemException, HandlerException { final Table table = melati.getTable(); context.put("table", table); final Database database = table.getDatabase(); context.put("database", database); // sort out search criteria final Persistent criteria = table.newPersistent(); for (Enumeration c = table.columns(); c.hasMoreElements();) { Column column = (Column)c.nextElement(); String string = context.getForm("field-" + column.getName()); if (string != null && !string.equals("")) column.setRaw_unsafe(criteria, column.getType().rawOfString(string)); } MappedEnumeration criterias = new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object c) { Column column = (Column)c; final PoemType nullable = column.getType().withNullable(true); return new Field(column.getRaw(criteria), column) { public PoemType getType() { return nullable; } }; } }; context.put("criteria", EnumUtils.vectorOf(criterias)); // sort out ordering (FIXME this is a bit out of control) PoemType searchColumnsType = new ReferencePoemType(database.getColumnInfoTable(), true) { protected Enumeration _possibleRaws() { return new MappedEnumeration(table.getSearchCriterionColumns()) { public Object mapped(Object column) { return ((Column)column).getColumnInfo().getTroid(); } }; } }; Vector orderingNames = new Vector(); Vector orderings = new Vector(); for (int o = 1; o <= 2; ++o) { String name = "order-" + o; String orderColumnIDString = context.getForm("field-" + name); Integer orderColumnID = null; if (orderColumnIDString != null && !orderColumnIDString.equals("")) { orderColumnID = (Integer)searchColumnsType.rawOfString(orderColumnIDString); ColumnInfo info = (ColumnInfo)searchColumnsType.cookedOfRaw(orderColumnID); orderingNames.addElement(database.quotedName(info.getName())); } orderings.addElement( new Field(orderColumnID, new BaseFieldAttributes(name, searchColumnsType))); } context.put("orderings", orderings); String orderByClause = EnumUtils.concatenated(", ", orderingNames.elements()); int start = 0; String startString = context.getForm("start"); if (startString != null) { try { start = Math.max(0, Integer.parseInt(startString)); } catch (NumberFormatException e) { throw new HandlerException("`start' param to `List' must be a number"); } } context.put("objects", table.selection(table.whereClause(criteria), orderByClause, false, start, 20)); return context; }
diff --git a/openFaces/source/org/openfaces/util/ResourceUtil.java b/openFaces/source/org/openfaces/util/ResourceUtil.java index acb9ea2c3..dbaa12d83 100644 --- a/openFaces/source/org/openfaces/util/ResourceUtil.java +++ b/openFaces/source/org/openfaces/util/ResourceUtil.java @@ -1,503 +1,503 @@ /* * OpenFaces - JSF Component Library 2.0 * Copyright (C) 2007-2009, TeamDev Ltd. * [email protected] * Unless agreed in writing the contents of this file are subject to * the GNU Lesser General Public License Version 2.1 (the "LGPL" License). * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * Please visit http://openfaces.org/licensing/ for more details. */ package org.openfaces.util; import org.w3c.dom.Node; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.ajax4jsf.renderkit.RendererUtils; import javax.faces.application.ViewHandler; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.FacesException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; import java.util.Locale; /** * @author Dmitry Pikhulya */ public class ResourceUtil { public static final String HEADER_JS_LIBRARIES = "OF:js_file_included"; public static final String RENDERED_JS_LINKS = "org.openfaces.util.RenderingUtil.renderedJsLinks"; public static final String POSTPONE_JS_LINK_RENDERING = "org.openfaces.util.ResourceUtil.postponeJsLinkRendering"; public static final String JSON_JS_LIB_NAME = "json2.js"; private static final String OPENFACES_VERSION = "/META-INF/openFacesVersion.txt"; private static final String VERSION_PLACEHOLDER_STR = "version"; private static String SCRIPT = RendererUtils.HTML.SCRIPT_ELEM; private static String SCRIPT_UC = SCRIPT.toUpperCase(Locale.US); private static String SRC = RendererUtils.HTML.src_ATTRIBUTE; private static String SRC_UC = SRC.toUpperCase(Locale.US); private ResourceUtil() { } /** * This method returns the URL string ready for rendering into HTML based on the URL specified by the user. If * URL is not specified by the user explicitly then URL to a default internal resource is returned instead. * * @param userSpecifiedUrl optional resource url as specified by the user. This can be a relative URL, or an absolute URL * @param defaultResourceFileName file name for a resource which should be provided if userSpecifiedUrl is null or empty string * @param defaultResourceBaseClassName the class relatively to which defaultResourceFileName is specified * @return */ public static String getResourceURL(FacesContext context, String userSpecifiedUrl, Class defaultResourceBaseClassName, String defaultResourceFileName) { return getResourceURL(context, userSpecifiedUrl, defaultResourceBaseClassName, defaultResourceFileName, true); } /** * @param userSpecifiedUrl optional resource url as specified by the user. This can be a relative URL, or an absolute URL * @param defaultResourceFileName file name for a resource which should be provided if userSpecifiedUrl is null (or empty string). * Empty string is also considered as signal for returning the default resource here because null * is auto-converted to an empty string when passed through a string binding * @param defaultResourceBaseClassName the class relatively to which defaultResourceFileName is specified * @param prependContextPath use true here if you render the attribute yourself, and false if you use pass this URL to HtmlGraphicImage or similar component */ public static String getResourceURL( FacesContext context, String userSpecifiedUrl, Class defaultResourceBaseClassName, String defaultResourceFileName, boolean prependContextPath) { boolean returnDefaultResource = userSpecifiedUrl == null || userSpecifiedUrl.length() == 0; String result = returnDefaultResource ? getInternalResourceURL(context, defaultResourceBaseClassName, defaultResourceFileName, prependContextPath) : (prependContextPath ? getApplicationResourceURL(context, userSpecifiedUrl) : userSpecifiedUrl); return result; } /** * Get path to application resource according to contex and resource path * * @param context faces contex provided by application * @param resourcePath path to resource - either absolute (starting with a slash) in the scope of application context, * or relative to the current page * @return full URL to resource ready for rendering as <code>src</code> or <code>href</code> attribute's value. */ public static String getApplicationResourceURL(FacesContext context, String resourcePath) { if (resourcePath == null || resourcePath.length() == 0) return ""; ViewHandler viewHandler = context.getApplication().getViewHandler(); String resourceUrl = viewHandler.getResourceURL(context, resourcePath); String encodedResourceUrl = context.getExternalContext().encodeResourceURL(resourceUrl); return encodedResourceUrl; } public static String getInternalResourceURL(FacesContext context, Class componentClass, String resourceName) { return getInternalResourceURL(context, componentClass, resourceName, true); } /** * @param context Current FacesContext * @param componentClass Class, relative to which the resourcePath is specified * @param resourcePath Path to the resource file * @param prependContextPath true means that the resulting url should be prefixed with context root. This is the case * when the returned URL is rendered without any modifications. Passing false to this * parameter is required in cases when the returned URL is passed to some component which * expects application URL, so the component will prepend the URL with context root tself. * @return The requested URL */ public static String getInternalResourceURL( FacesContext context, Class componentClass, String resourcePath, boolean prependContextPath) { if (context == null) throw new NullPointerException("context"); if (resourcePath == null) throw new NullPointerException("resourcePath"); String packageName = componentClass == null ? "" : getPackageName(componentClass); String packagePath = packageName.replace('.', '/'); if (packagePath.length() > 0) { packagePath += "/"; } String versionString = getVersionString(); int extensionIndex = resourcePath.lastIndexOf("."); String urlRelativeToContextRoot = ResourceFilter.INTERNAL_RESOURCE_PATH + packagePath + resourcePath.substring(0, extensionIndex) + "-" + versionString + resourcePath.substring(extensionIndex); if (!prependContextPath) return urlRelativeToContextRoot; return getApplicationResourceURL(context, urlRelativeToContextRoot); } private static String versionString; /** * Return version of OpenFaces * * @return requested version of OpenFaces */ public static String getVersionString() { if (versionString != null) return versionString; InputStream versionStream = ResourceUtil.class.getResourceAsStream(OPENFACES_VERSION); String version = ""; if (versionStream != null) { BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(versionStream)); String buildInfo = bufferedReader.readLine(); if (buildInfo != null) { version = buildInfo.substring(0, buildInfo.indexOf(",")).trim(); } } catch (IOException e) { Log.log("Couldn't read version string", e); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { // } } } } if (VERSION_PLACEHOLDER_STR.equals(version)) { long startTime = System.currentTimeMillis() / 1000; version = Long.toString(startTime, 36); } versionString = version; return version; } /** * Return URL of util.js file * * @param context {@link FacesContext} for the current request * @return requested URL of util.js file */ public static String getUtilJsURL(FacesContext context) { return getInternalResourceURL(context, ResourceUtil.class, "util.js"); } /** * Return URL of util.js file. Keep in mind, that ajaxUtil.js depends on util.js. * Don't forget to include util.js as well before including this URL. * * @param context {@link FacesContext} for the current request * @return requested URL of ajaxUtil.js file */ public static String getAjaxUtilJsURL(FacesContext context) { return ResourceUtil.getInternalResourceURL(context, ResourceUtil.class, "ajaxUtil.js"); } /** * Return URL of json javascript file * * @param context {@link FacesContext} for the current request * @return requested URL of json javascript file */ public static String getJsonJsURL(FacesContext context) { return ResourceUtil.getInternalResourceURL(context, ResourceUtil.class, JSON_JS_LIB_NAME); } /** * Return full package name for Class * * @param aClass The Class object * @return full package name for given Class */ public static String getPackageName(Class aClass) { String className = aClass.getName(); int lastIndexOfDot = className.lastIndexOf('.'); if (lastIndexOfDot == -1) { return ""; } else { return className.substring(0, lastIndexOfDot); } } /** * Register javascript library to future adding to response * * @param context {@link FacesContext} for the current request * @param baseClass Class, relative to which the resourcePath is specified * @param relativeJsPath Path to the javascript file */ public static void registerJavascriptLibrary(FacesContext context, Class baseClass, String relativeJsPath) { String jsFileUrl = getInternalResourceURL(context, baseClass, relativeJsPath); registerJavascriptLibrary(context, jsFileUrl); } /** * Register javascript library to future adding to response * * @param facesContext {@link FacesContext} for the current request * @param jsFileUrl Url for the javascript file */ public static void registerJavascriptLibrary(FacesContext facesContext, String jsFileUrl) { Map<String, Object> requestMap = facesContext.getExternalContext().getRequestMap(); List<String> libraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); if (libraries == null) { libraries = new ArrayList<String>(); requestMap.put(HEADER_JS_LIBRARIES, libraries); } if (libraries.contains(jsFileUrl)) return; libraries.add(jsFileUrl); } public static void processHeadResources(FacesContext context) { Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Class richfacesContextClass = null; try { richfacesContextClass = Class.forName("org.ajax4jsf.context.AjaxContext"); } catch (ClassNotFoundException e) { // Just checking for class presense. It's normal that a class can be absent. } String ajax4jsfScriptParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "SCRIPTS_PARAMETER"); String ajax4jsfStylesParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "STYLES_PARAMETER"); String headEventsParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "HEAD_EVENTS_PARAMETER"); if (ajax4jsfStylesParameter != null) { Set<String> styles = (Set<String>) requestMap.get(ajax4jsfStylesParameter); String defaultCssUrl = ((HttpServletRequest) context.getExternalContext().getRequest()).getContextPath() + ResourceFilter.INTERNAL_RESOURCE_PATH + "org/openfaces/renderkit/default" + "-" + getVersionString() + ".css"; if (styles == null) { styles = new LinkedHashSet<String>(); } styles.add(defaultCssUrl); requestMap.put(ajax4jsfStylesParameter, styles); } if (ajax4jsfScriptParameter != null) { Set<String> libraries = (Set<String>) requestMap.get(ajax4jsfScriptParameter); List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); if (libraries == null) { libraries = new LinkedHashSet<String>(); } if (ourLibraries != null) { libraries.addAll(ourLibraries); } requestMap.put(ajax4jsfScriptParameter, libraries); } if (headEventsParameter != null) { List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); final Node[] headerResources = (Node[]) requestMap.get(headEventsParameter); - final Node[] ourHeaderNodes = prepareHeaderNodes(ourLibraries); - if (headerResources != null) { + if (headerResources != null && ourLibraries != null) { + final Node[] ourHeaderNodes = prepareHeaderNodes(ourLibraries); final Node[] mergedNodes = mergeHeadResourceNodes(ourHeaderNodes, headerResources); requestMap.put(headEventsParameter, mergedNodes); } } } private static void mergeHeadResourceNode(List<Node> nodes, Set renderedScripts, Node node) { boolean shouldAdd = true; String nodeName = node.getNodeName(); if (SCRIPT.equals(nodeName) || SCRIPT_UC.equals(nodeName)) { if (node.getFirstChild() == null) { //no text content etc. NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { Node item = attributes.getNamedItem(SRC); if (item == null) { attributes.getNamedItem(SRC_UC); } if (item != null) { String src = item.getNodeValue(); if (src != null) { if (renderedScripts.contains(src)) { shouldAdd = false; } else { renderedScripts.add(src); } } } } } } if (shouldAdd) { nodes.add(node); } } private static Node[] mergeHeadResourceNodes(Node[] headerJsNodes, Node[] richFacesHeaderNodes) { List<Node> result = new ArrayList<Node>(); Set scripts = new HashSet(); for (Node node : richFacesHeaderNodes) { mergeHeadResourceNode(result, scripts, node); } for (Node node : headerJsNodes) { mergeHeadResourceNode(result, scripts, node); } return result.toArray(new Node[result.size()]); } private static Node[] prepareHeaderNodes(List<String> headerLibraries) { try { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Node node = document.createElement("head"); document.appendChild(node); for (String headerLibrary : headerLibraries) { Element element = document.createElement("script"); element.setAttribute("type", "text/javascript"); element.setAttribute("src", headerLibrary); node.appendChild(element); } NodeList childNodes = node.getChildNodes(); Node[] list = new Node[childNodes.getLength()]; for (int i = 0; i < list.length; i++) { list[i] = childNodes.item(i); } return list; } catch (ParserConfigurationException e) { throw new FacesException(e.getLocalizedMessage(), e); } } /** * Register OpenFaces javascript library util.js to future adding to response * * @param facesContext {@link FacesContext} for the current request */ public static void registerUtilJs(FacesContext facesContext) { registerJavascriptLibrary(facesContext, RenderingUtil.class, "util.js"); } public static boolean isHeaderIncludesRegistered(ServletRequest servletRequest) { if (AjaxUtil.isAjaxRequest(RequestFacade.getInstance(servletRequest))) return false; for (Iterator<String> iterator = StyleUtil.getClassKeyIterator(); iterator.hasNext();) { String key = iterator.next(); if (servletRequest.getAttribute(key) != null) { return true; } } return servletRequest.getAttribute(RenderingUtil.ON_LOAD_SCRIPTS_KEY) != null || servletRequest.getAttribute(HEADER_JS_LIBRARIES) != null || servletRequest.getAttribute(StyleUtil.DEFAULT_CSS_REQUESTED) != null; } // public static void registerJavascriptLibrary(RequestFacade servletRequest, String relativeJsPath) { // // List libraries = (List) servletRequest.getAttribute(ResourceFilter.HEADER_JS_LIBRARIES); // if (libraries == null) { // libraries = new ArrayList(); // libraries.add(relativeJsPath); // } /* if (AjaxUtil.isAjax4jsfRequest((HttpServletRequest) facesContext.getExternalContext().getRequest())) { ResponseWriter writer = facesContext.getResponseWriter(); try { writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.writeAttribute("src", jsFileUrl, null); writer.endElement("script"); } catch (IOException e) { e.printStackTrace(); } } else { */ // if (libraries.contains(relativeJsPath)) return; // libraries.add(relativeJsPath); // // } /** * Render javascript file link, if not rendered early * * @param jsFile Javascript file to include * @param context {@link FacesContext} for the current request * @throws IOException if an input/output error occurs */ public static void renderJSLinkIfNeeded(String jsFile, FacesContext context) throws IOException { ResponseWriter writer = context.getResponseWriter(); List<String> renderedJsLinks = getRenderedJsLinks(context); if (renderedJsLinks.contains(jsFile)) { return; } renderedJsLinks.add(jsFile); Boolean postponeJsLinkRendering = (Boolean) context.getExternalContext().getRequestMap().get(POSTPONE_JS_LINK_RENDERING); if (postponeJsLinkRendering != null && postponeJsLinkRendering) return; if (AjaxUtil.isAjaxRequest(context)) { registerJavascriptLibrary(context, jsFile); } else if (AjaxUtil.isAjax4jsfRequest()) { registerJavascriptLibrary(context, jsFile); } else { writer.startElement("script", null); writer.writeAttribute("type", "text/javascript", null); writer.writeAttribute("src", jsFile, null); // write white-space to avoid creating self-closing <script/> tags // under certain servers, which are not correctly interpreted by browsers (JSFC-2303) writer.writeText(" ", null); writer.endElement("script"); } } /** * Return list of already rendered javascript links * * @param context {@link FacesContext} for the current request * @return list of already rendered javascript links */ public static List<String> getRenderedJsLinks(FacesContext context) { Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); List<String> renderedJsLinks = (List<String>) requestMap.get(RENDERED_JS_LINKS); if (renderedJsLinks == null) { renderedJsLinks = new ArrayList<String>(); requestMap.put(RENDERED_JS_LINKS, renderedJsLinks); } return renderedJsLinks; } }
false
true
public static void processHeadResources(FacesContext context) { Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Class richfacesContextClass = null; try { richfacesContextClass = Class.forName("org.ajax4jsf.context.AjaxContext"); } catch (ClassNotFoundException e) { // Just checking for class presense. It's normal that a class can be absent. } String ajax4jsfScriptParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "SCRIPTS_PARAMETER"); String ajax4jsfStylesParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "STYLES_PARAMETER"); String headEventsParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "HEAD_EVENTS_PARAMETER"); if (ajax4jsfStylesParameter != null) { Set<String> styles = (Set<String>) requestMap.get(ajax4jsfStylesParameter); String defaultCssUrl = ((HttpServletRequest) context.getExternalContext().getRequest()).getContextPath() + ResourceFilter.INTERNAL_RESOURCE_PATH + "org/openfaces/renderkit/default" + "-" + getVersionString() + ".css"; if (styles == null) { styles = new LinkedHashSet<String>(); } styles.add(defaultCssUrl); requestMap.put(ajax4jsfStylesParameter, styles); } if (ajax4jsfScriptParameter != null) { Set<String> libraries = (Set<String>) requestMap.get(ajax4jsfScriptParameter); List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); if (libraries == null) { libraries = new LinkedHashSet<String>(); } if (ourLibraries != null) { libraries.addAll(ourLibraries); } requestMap.put(ajax4jsfScriptParameter, libraries); } if (headEventsParameter != null) { List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); final Node[] headerResources = (Node[]) requestMap.get(headEventsParameter); final Node[] ourHeaderNodes = prepareHeaderNodes(ourLibraries); if (headerResources != null) { final Node[] mergedNodes = mergeHeadResourceNodes(ourHeaderNodes, headerResources); requestMap.put(headEventsParameter, mergedNodes); } } }
public static void processHeadResources(FacesContext context) { Map<String, Object> requestMap = context.getExternalContext().getRequestMap(); Class richfacesContextClass = null; try { richfacesContextClass = Class.forName("org.ajax4jsf.context.AjaxContext"); } catch (ClassNotFoundException e) { // Just checking for class presense. It's normal that a class can be absent. } String ajax4jsfScriptParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "SCRIPTS_PARAMETER"); String ajax4jsfStylesParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "STYLES_PARAMETER"); String headEventsParameter = (String) ReflectionUtil.getStaticFieldValue(richfacesContextClass, "HEAD_EVENTS_PARAMETER"); if (ajax4jsfStylesParameter != null) { Set<String> styles = (Set<String>) requestMap.get(ajax4jsfStylesParameter); String defaultCssUrl = ((HttpServletRequest) context.getExternalContext().getRequest()).getContextPath() + ResourceFilter.INTERNAL_RESOURCE_PATH + "org/openfaces/renderkit/default" + "-" + getVersionString() + ".css"; if (styles == null) { styles = new LinkedHashSet<String>(); } styles.add(defaultCssUrl); requestMap.put(ajax4jsfStylesParameter, styles); } if (ajax4jsfScriptParameter != null) { Set<String> libraries = (Set<String>) requestMap.get(ajax4jsfScriptParameter); List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); if (libraries == null) { libraries = new LinkedHashSet<String>(); } if (ourLibraries != null) { libraries.addAll(ourLibraries); } requestMap.put(ajax4jsfScriptParameter, libraries); } if (headEventsParameter != null) { List<String> ourLibraries = (List<String>) requestMap.get(HEADER_JS_LIBRARIES); final Node[] headerResources = (Node[]) requestMap.get(headEventsParameter); if (headerResources != null && ourLibraries != null) { final Node[] ourHeaderNodes = prepareHeaderNodes(ourLibraries); final Node[] mergedNodes = mergeHeadResourceNodes(ourHeaderNodes, headerResources); requestMap.put(headEventsParameter, mergedNodes); } } }
diff --git a/src/model/Select_Allgemein.java b/src/model/Select_Allgemein.java index 808fe19..1d0429d 100644 --- a/src/model/Select_Allgemein.java +++ b/src/model/Select_Allgemein.java @@ -1,100 +1,100 @@ /* * To change this template, choose Tools | Templates and open the template in * the editor. */ package model; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; /** * * @author felix * * In dieser Klasse */ public class Select_Allgemein { Datenbankverbindung db = new Datenbankverbindung(); /** * * @param tabelle * @return * @throws ClassNotFoundException */ public static String create_select_ganze_tabelle(String tabelle) throws ClassNotFoundException { String query = "SELECT * FROM " + tabelle + ";"; return query; } /** * * @param tabelle * @param spaltenwerte * @return */ public static String create_select_teile_suchen(String[][] suchwerte) { String query = "SELECT * FROM Teilestammdaten"; int i = 0; for (String[] wert : suchwerte) { // Wenn der Suchwert leer ist soll nichts zu dem Select hinzugefügt werden if (!wert[1].equals("")) { // Wenn es der erste Wert ist muss im Select WHERE vorher eingefügt werden nicht AND if (i == 0) { // IDs sollen exakt gesucht werden if (wert[0].equals("id")) { query = query + " WHERE " + wert[0] + "=" + wert[1]; } // Es soll nach allen Teilen gesucht werden die in ein Fach reinpassen else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anzahl_mittel") || wert[0].equals("max_anz_gross")) { query = query + " WHERE " + wert[0] + "<=" + wert[1]; } else { query = query + " WHERE " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } i++; } else { if (wert[0].equals("id")) { query = query + " AND " + wert[0] + "=" + wert[1]; - } else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anzahl_mittel") + } else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anz_mittel") || wert[0].equals("max_anz_gross")) { query = query + " AND " + wert[0] + "<=" + wert[1]; } else { query = query + " AND " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } } } } return query + ";"; } public void test_rmsd() throws SQLException, ClassNotFoundException { db.basic_connect("SELECT * FROM Teilestammdaten"); ResultSetMetaData rmsd = db.rs.getMetaData(); ArrayList<ArrayList> teilestammdaten = db.resultset_to_arraylist(); System.out.println(teilestammdaten); //int columnType = rmsd.getColumnType(4); //String columnname = rmsd.getColumnName(4); //while (db.rs.next()) { //String value = db.rs.getString(1); // System.out.println(value); //} //System.out.println(columnname + ": " + columnType); db.disconnect(); } public static void main(String[] args) throws SQLException, ClassNotFoundException { Select_Allgemein sa = new Select_Allgemein(); sa.test_rmsd(); } }
true
true
public static String create_select_teile_suchen(String[][] suchwerte) { String query = "SELECT * FROM Teilestammdaten"; int i = 0; for (String[] wert : suchwerte) { // Wenn der Suchwert leer ist soll nichts zu dem Select hinzugefügt werden if (!wert[1].equals("")) { // Wenn es der erste Wert ist muss im Select WHERE vorher eingefügt werden nicht AND if (i == 0) { // IDs sollen exakt gesucht werden if (wert[0].equals("id")) { query = query + " WHERE " + wert[0] + "=" + wert[1]; } // Es soll nach allen Teilen gesucht werden die in ein Fach reinpassen else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anzahl_mittel") || wert[0].equals("max_anz_gross")) { query = query + " WHERE " + wert[0] + "<=" + wert[1]; } else { query = query + " WHERE " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } i++; } else { if (wert[0].equals("id")) { query = query + " AND " + wert[0] + "=" + wert[1]; } else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anzahl_mittel") || wert[0].equals("max_anz_gross")) { query = query + " AND " + wert[0] + "<=" + wert[1]; } else { query = query + " AND " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } } } } return query + ";"; }
public static String create_select_teile_suchen(String[][] suchwerte) { String query = "SELECT * FROM Teilestammdaten"; int i = 0; for (String[] wert : suchwerte) { // Wenn der Suchwert leer ist soll nichts zu dem Select hinzugefügt werden if (!wert[1].equals("")) { // Wenn es der erste Wert ist muss im Select WHERE vorher eingefügt werden nicht AND if (i == 0) { // IDs sollen exakt gesucht werden if (wert[0].equals("id")) { query = query + " WHERE " + wert[0] + "=" + wert[1]; } // Es soll nach allen Teilen gesucht werden die in ein Fach reinpassen else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anzahl_mittel") || wert[0].equals("max_anz_gross")) { query = query + " WHERE " + wert[0] + "<=" + wert[1]; } else { query = query + " WHERE " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } i++; } else { if (wert[0].equals("id")) { query = query + " AND " + wert[0] + "=" + wert[1]; } else if (wert[0].equals("max_anz_klein") || wert[0].equals("max_anz_mittel") || wert[0].equals("max_anz_gross")) { query = query + " AND " + wert[0] + "<=" + wert[1]; } else { query = query + " AND " + wert[0] + " LIKE \"%" + wert[1] + "%\""; } } } } return query + ";"; }
diff --git a/HttpRequest.java b/HttpRequest.java index e45617f..2a07deb 100644 --- a/HttpRequest.java +++ b/HttpRequest.java @@ -1,259 +1,262 @@ import java.io.* ; import java.net.* ; import java.util.* ; import com.google.gson.*; final class HttpRequest implements Runnable { Socket socket; Map<String, String> header = new HashMap<String, String>(); private Queue<String> request = new LinkedList<String>(); static Map<String, Integer> agents = new HashMap<String, Integer>(); private HttpResponse response; private InputStream is; private BufferedReader br; // Constructor public HttpRequest(Socket socket) throws Exception { this.socket = socket; } // Implement the run() method of the Runnable interface. public void run() { processRequest(); } private void processRequest() { try { // Get a reference to the socket's input stream. is = new DataInputStream(socket.getInputStream()); br = new BufferedReader(new InputStreamReader(is, "UTF8")); // Process the request try { String headerLine; String cookiestr = null; String requestLine = null; while ((headerLine = br.readLine()) != null) { if (headerLine.length() < 1) break; if (requestLine == null) requestLine = headerLine; int jj = headerLine.indexOf(':'); if (jj == -1) continue; String field = headerLine.substring(0, jj).trim(); String value = headerLine.substring(jj+1).trim(); if (field.equals("Cookie")) { cookiestr = value; } } // If there's no requestline, then just ignore it as a bad request if (requestLine == null) { tidyUp(); return; } // Extract the path from the request line. StringTokenizer tokens = new StringTokenizer(requestLine); String method = tokens.nextToken().trim(); String path = tokens.nextToken().trim(); // Extract the get paramters from the path Map<String, String> get = new HashMap<String, String>(); int ii = path.indexOf('?'); if (ii > -1) { String[] getstring = path.substring(ii+1).split("&"); for (String key : getstring) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8"); field = URLDecoder.decode(field, "UTF-8"); get.put(key, field); } path = path.substring(0, ii); } path = URLDecoder.decode(path, "UTF-8"); // Extract the cookies from the request Map<String, String> cookies = new HashMap<String, String>(); if (cookiestr != null) { String[] cookiestrs = cookiestr.split(";"); for (String key : cookiestrs) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8").trim(); field = URLDecoder.decode(field, "UTF-8").trim(); cookies.put(key, field); } } // Get a reference to the socket and create a response. final Socket socket = this.socket; response = new HttpResponse(socket); // Authenticate the request String token = get.get("token"); if (token == null) token = cookies.get("token"); // An agentid of null means the user hasn't authenticated - an agentid of zero indicates a problem retrieving the agentid from the authentication service Integer agentid = null; if (token != null) { agentid = agents.get(token); if (agentid == null && Manager.authRunning()) { String authurl = "http://"+Manager.authDomain()+"/data?token="+URLEncoder.encode(token, "utf8"); try{ URL dataurl = new URL(authurl); Gson gson = new Gson(); BufferedReader datain = new BufferedReader(new InputStreamReader(dataurl.openStream())); String data = ""; String datastr; while ((datastr = datain.readLine()) != null) { data += datastr; } datain.close(); AuthData ad = gson.fromJson(data, AuthData.class); agentid = ad.getId(); if (agentid > 0) { agents.put(token, agentid); response.setHeader("Set-Cookie", "token=" + URLEncoder.encode(token, "utf8")); } } catch (FileNotFoundException e) { Manager.logErr("Auth Error: Can't connect to "+authurl); } catch (IOException e) { // Sometimes these errors can get the user stuck in an endless loop, so output them. Manager.logErr(e); } } } String[] pathParts = path.split("\\/"); if (pathParts.length < 2 || path.equals("/services")) { response.redirect("/services/"); } else if (pathParts[1].equals("services")) { if (isAuthorised(agentid, method, "http://"+Manager.servicesDomain()+path)) { if (pathParts.length == 2) { response.setBody(Service.getIndexTemplate()); } else { Service service = null; String id = pathParts[2]; if (id.length() > 0) { try { service = Service.getById(id); if (pathParts.length == 3) { response.setBody(service.getFullTemplate()); } else { if (method.equalsIgnoreCase("POST")) { service.execCommand(pathParts[3]); + response.redirect("/services/"+service.getId()); + } else { + response.setError(405, "Not Allowed."); + response.setHeader("Allow", "POST"); } - response.redirect("/services/"+service.getId()); } } catch (RuntimeException e) { response.notFound("Service"); } } } } } else if (pathParts[1].equals("api")) { if (pathParts.length == 2) { response.setJson("// TODO: write some API documentation"); } else if (pathParts[2].equals("hosts")) { response.setJson(Service.getHosts()); } else { response.notFound(); } } else { if (path.equals("/icon")) path = "/icon.png"; String fileName = "./data" + path; fileName.replaceAll("/\\.\\./",""); // Open the requested file. FileInputStream fis = null; try { response.setBody(new FileInputStream(fileName)); } catch (FileNotFoundException e) { response.notFound(); } } response.send(); tidyUp(); } catch (SocketException e) { // Don't do anything if there's a socketexception - it's probably just the client disconnecting before it's received the full response } catch (Exception e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } } catch (IOException e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } } private boolean isAuthorised(Integer agentid, String method, String uri) throws Exception { // Luke is authorised if (agentid != null && agentid.intValue() == 2) return true; // If the auth service is running then make sure the user has authenticated if (Manager.authRunning() && agentid == null) { response.redirect("http://"+Manager.authDomain()+"/authenticate?redirect_uri="+URLEncoder.encode(uri, "utf8")); return false; } // If the user has successfully authenticated, but isn't authorised, return a 403 if (agentid != null && agentid > 0) { response.setError(403, "Permission Denied"); return false; } /* Ideally never go past this point - this means either the authentication server isn't running or has returned an invalid agentid */ if (!Manager.authRunning()) Manager.logErr("Auth service isn't running, using fallback auth rules"); else Manager.logErr("Auth service returned invalid agentid, using fallback auth rules"); // Allow GET requests so that whatever is causing the problem can be debugged if (method.equalsIgnoreCase("GET")) return true; // Don't allow any other requests as the user hasn't been authenticated response.setError(403, "Authentication Error"); return false; } static class AuthData { private int id; public AuthData() { } public int getId() { return id; } } private void tidyUp() { try { br.close(); is.close(); socket.close(); } catch (IOException e) { } } }
false
true
private void processRequest() { try { // Get a reference to the socket's input stream. is = new DataInputStream(socket.getInputStream()); br = new BufferedReader(new InputStreamReader(is, "UTF8")); // Process the request try { String headerLine; String cookiestr = null; String requestLine = null; while ((headerLine = br.readLine()) != null) { if (headerLine.length() < 1) break; if (requestLine == null) requestLine = headerLine; int jj = headerLine.indexOf(':'); if (jj == -1) continue; String field = headerLine.substring(0, jj).trim(); String value = headerLine.substring(jj+1).trim(); if (field.equals("Cookie")) { cookiestr = value; } } // If there's no requestline, then just ignore it as a bad request if (requestLine == null) { tidyUp(); return; } // Extract the path from the request line. StringTokenizer tokens = new StringTokenizer(requestLine); String method = tokens.nextToken().trim(); String path = tokens.nextToken().trim(); // Extract the get paramters from the path Map<String, String> get = new HashMap<String, String>(); int ii = path.indexOf('?'); if (ii > -1) { String[] getstring = path.substring(ii+1).split("&"); for (String key : getstring) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8"); field = URLDecoder.decode(field, "UTF-8"); get.put(key, field); } path = path.substring(0, ii); } path = URLDecoder.decode(path, "UTF-8"); // Extract the cookies from the request Map<String, String> cookies = new HashMap<String, String>(); if (cookiestr != null) { String[] cookiestrs = cookiestr.split(";"); for (String key : cookiestrs) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8").trim(); field = URLDecoder.decode(field, "UTF-8").trim(); cookies.put(key, field); } } // Get a reference to the socket and create a response. final Socket socket = this.socket; response = new HttpResponse(socket); // Authenticate the request String token = get.get("token"); if (token == null) token = cookies.get("token"); // An agentid of null means the user hasn't authenticated - an agentid of zero indicates a problem retrieving the agentid from the authentication service Integer agentid = null; if (token != null) { agentid = agents.get(token); if (agentid == null && Manager.authRunning()) { String authurl = "http://"+Manager.authDomain()+"/data?token="+URLEncoder.encode(token, "utf8"); try{ URL dataurl = new URL(authurl); Gson gson = new Gson(); BufferedReader datain = new BufferedReader(new InputStreamReader(dataurl.openStream())); String data = ""; String datastr; while ((datastr = datain.readLine()) != null) { data += datastr; } datain.close(); AuthData ad = gson.fromJson(data, AuthData.class); agentid = ad.getId(); if (agentid > 0) { agents.put(token, agentid); response.setHeader("Set-Cookie", "token=" + URLEncoder.encode(token, "utf8")); } } catch (FileNotFoundException e) { Manager.logErr("Auth Error: Can't connect to "+authurl); } catch (IOException e) { // Sometimes these errors can get the user stuck in an endless loop, so output them. Manager.logErr(e); } } } String[] pathParts = path.split("\\/"); if (pathParts.length < 2 || path.equals("/services")) { response.redirect("/services/"); } else if (pathParts[1].equals("services")) { if (isAuthorised(agentid, method, "http://"+Manager.servicesDomain()+path)) { if (pathParts.length == 2) { response.setBody(Service.getIndexTemplate()); } else { Service service = null; String id = pathParts[2]; if (id.length() > 0) { try { service = Service.getById(id); if (pathParts.length == 3) { response.setBody(service.getFullTemplate()); } else { if (method.equalsIgnoreCase("POST")) { service.execCommand(pathParts[3]); } response.redirect("/services/"+service.getId()); } } catch (RuntimeException e) { response.notFound("Service"); } } } } } else if (pathParts[1].equals("api")) { if (pathParts.length == 2) { response.setJson("// TODO: write some API documentation"); } else if (pathParts[2].equals("hosts")) { response.setJson(Service.getHosts()); } else { response.notFound(); } } else { if (path.equals("/icon")) path = "/icon.png"; String fileName = "./data" + path; fileName.replaceAll("/\\.\\./",""); // Open the requested file. FileInputStream fis = null; try { response.setBody(new FileInputStream(fileName)); } catch (FileNotFoundException e) { response.notFound(); } } response.send(); tidyUp(); } catch (SocketException e) { // Don't do anything if there's a socketexception - it's probably just the client disconnecting before it's received the full response } catch (Exception e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } } catch (IOException e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } }
private void processRequest() { try { // Get a reference to the socket's input stream. is = new DataInputStream(socket.getInputStream()); br = new BufferedReader(new InputStreamReader(is, "UTF8")); // Process the request try { String headerLine; String cookiestr = null; String requestLine = null; while ((headerLine = br.readLine()) != null) { if (headerLine.length() < 1) break; if (requestLine == null) requestLine = headerLine; int jj = headerLine.indexOf(':'); if (jj == -1) continue; String field = headerLine.substring(0, jj).trim(); String value = headerLine.substring(jj+1).trim(); if (field.equals("Cookie")) { cookiestr = value; } } // If there's no requestline, then just ignore it as a bad request if (requestLine == null) { tidyUp(); return; } // Extract the path from the request line. StringTokenizer tokens = new StringTokenizer(requestLine); String method = tokens.nextToken().trim(); String path = tokens.nextToken().trim(); // Extract the get paramters from the path Map<String, String> get = new HashMap<String, String>(); int ii = path.indexOf('?'); if (ii > -1) { String[] getstring = path.substring(ii+1).split("&"); for (String key : getstring) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8"); field = URLDecoder.decode(field, "UTF-8"); get.put(key, field); } path = path.substring(0, ii); } path = URLDecoder.decode(path, "UTF-8"); // Extract the cookies from the request Map<String, String> cookies = new HashMap<String, String>(); if (cookiestr != null) { String[] cookiestrs = cookiestr.split(";"); for (String key : cookiestrs) { int jj = key.indexOf('='); String field; if ( jj > -1) { field = key.substring(jj+1); key = key.substring(0, jj); } else { field = "true"; } key = URLDecoder.decode(key, "UTF-8").trim(); field = URLDecoder.decode(field, "UTF-8").trim(); cookies.put(key, field); } } // Get a reference to the socket and create a response. final Socket socket = this.socket; response = new HttpResponse(socket); // Authenticate the request String token = get.get("token"); if (token == null) token = cookies.get("token"); // An agentid of null means the user hasn't authenticated - an agentid of zero indicates a problem retrieving the agentid from the authentication service Integer agentid = null; if (token != null) { agentid = agents.get(token); if (agentid == null && Manager.authRunning()) { String authurl = "http://"+Manager.authDomain()+"/data?token="+URLEncoder.encode(token, "utf8"); try{ URL dataurl = new URL(authurl); Gson gson = new Gson(); BufferedReader datain = new BufferedReader(new InputStreamReader(dataurl.openStream())); String data = ""; String datastr; while ((datastr = datain.readLine()) != null) { data += datastr; } datain.close(); AuthData ad = gson.fromJson(data, AuthData.class); agentid = ad.getId(); if (agentid > 0) { agents.put(token, agentid); response.setHeader("Set-Cookie", "token=" + URLEncoder.encode(token, "utf8")); } } catch (FileNotFoundException e) { Manager.logErr("Auth Error: Can't connect to "+authurl); } catch (IOException e) { // Sometimes these errors can get the user stuck in an endless loop, so output them. Manager.logErr(e); } } } String[] pathParts = path.split("\\/"); if (pathParts.length < 2 || path.equals("/services")) { response.redirect("/services/"); } else if (pathParts[1].equals("services")) { if (isAuthorised(agentid, method, "http://"+Manager.servicesDomain()+path)) { if (pathParts.length == 2) { response.setBody(Service.getIndexTemplate()); } else { Service service = null; String id = pathParts[2]; if (id.length() > 0) { try { service = Service.getById(id); if (pathParts.length == 3) { response.setBody(service.getFullTemplate()); } else { if (method.equalsIgnoreCase("POST")) { service.execCommand(pathParts[3]); response.redirect("/services/"+service.getId()); } else { response.setError(405, "Not Allowed."); response.setHeader("Allow", "POST"); } } } catch (RuntimeException e) { response.notFound("Service"); } } } } } else if (pathParts[1].equals("api")) { if (pathParts.length == 2) { response.setJson("// TODO: write some API documentation"); } else if (pathParts[2].equals("hosts")) { response.setJson(Service.getHosts()); } else { response.notFound(); } } else { if (path.equals("/icon")) path = "/icon.png"; String fileName = "./data" + path; fileName.replaceAll("/\\.\\./",""); // Open the requested file. FileInputStream fis = null; try { response.setBody(new FileInputStream(fileName)); } catch (FileNotFoundException e) { response.notFound(); } } response.send(); tidyUp(); } catch (SocketException e) { // Don't do anything if there's a socketexception - it's probably just the client disconnecting before it's received the full response } catch (Exception e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } } catch (IOException e) { Manager.logErr("Server Error (HttpRequest):"); Manager.logErr(e); } }
diff --git a/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java b/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java index 4cd15ac9..e2d6146c 100644 --- a/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java +++ b/src/org/red5/server/jetty/Red5WebPropertiesConfiguration.java @@ -1,69 +1,72 @@ package org.red5.server.jetty; import java.util.EventListener; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.resource.Resource; public class Red5WebPropertiesConfiguration implements Configuration, EventListener { // Initialize Logging protected static Log log = LogFactory.getLog(Red5WebPropertiesConfiguration.class.getName()); protected static WebAppContext _context; public void setWebAppContext(WebAppContext context) { _context = context; } public WebAppContext getWebAppContext() { return _context; } public void configureClassLoader() throws Exception { // TODO Auto-generated method stub } public void configureDefaults() throws Exception { // TODO Auto-generated method stub } public void configureWebApp () throws Exception{ if (getWebAppContext().isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf= getWebAppContext().getWebInf(); if(webInf!=null&&webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); - if(hostnames[i].equals("*")){ - hostnames[i] = ""; + if(hostnames[i].equals("*")) { + // A virtual host "null" must be used so requests for any host + // will be server. + hostnames = null; + break; } } getWebAppContext().setVirtualHosts(hostnames); getWebAppContext().setContextPath(contextPath); } } } public void deconfigureWebApp() throws Exception { // TODO Auto-generated method stub } }
true
true
public void configureWebApp () throws Exception{ if (getWebAppContext().isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf= getWebAppContext().getWebInf(); if(webInf!=null&&webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if(hostnames[i].equals("*")){ hostnames[i] = ""; } } getWebAppContext().setVirtualHosts(hostnames); getWebAppContext().setContextPath(contextPath); } } }
public void configureWebApp () throws Exception{ if (getWebAppContext().isStarted()) { log.debug("Cannot configure webapp after it is started"); return; } Resource webInf= getWebAppContext().getWebInf(); if(webInf!=null&&webInf.isDirectory()){ Resource config = webInf.addPath("red5-web.properties"); if(config.exists()){ log.debug("Configuring red5-web.properties"); Properties props = new Properties(); props.load(config.getInputStream()); String contextPath = props.getProperty("webapp.contextPath"); String virtualHosts = props.getProperty("webapp.virtualHosts"); String[] hostnames = virtualHosts.split(","); for (int i = 0; i < hostnames.length; i++) { hostnames[i] = hostnames[i].trim(); if(hostnames[i].equals("*")) { // A virtual host "null" must be used so requests for any host // will be server. hostnames = null; break; } } getWebAppContext().setVirtualHosts(hostnames); getWebAppContext().setContextPath(contextPath); } } }
diff --git a/com.github.usrprops_xtext/src/com/github/usrprops_xtext/formatting/UsrpropsDslFormatter.java b/com.github.usrprops_xtext/src/com/github/usrprops_xtext/formatting/UsrpropsDslFormatter.java index a607222..503407c 100644 --- a/com.github.usrprops_xtext/src/com/github/usrprops_xtext/formatting/UsrpropsDslFormatter.java +++ b/com.github.usrprops_xtext/src/com/github/usrprops_xtext/formatting/UsrpropsDslFormatter.java @@ -1,155 +1,157 @@ /* * Copyright 2012 Barrie Treloar <[email protected]> * * This file is part of USRPROPS Xtext Editor. * * USRPROPS Xtext Editor is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * USRPROPS Xtext Editor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with USRPROPS Xtext Editor. If not, see <http://www.gnu.org/licenses/>. */ package com.github.usrprops_xtext.formatting; import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter; import org.eclipse.xtext.formatting.impl.FormattingConfig; import com.github.usrprops_xtext.services.UsrpropsDslGrammarAccess; /** * This class contains custom formatting description. * * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting * on how and when to use it * * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an * example */ public class UsrpropsDslFormatter extends AbstractDeclarativeFormatter { /** * Formatter for Usrprops * <p> * It does not make sense to blanket wrap around all keywords. The output of * this is not very pretty. * </p> * <p> * There does not appear to be an easy way to programmatically loop through * a grammar rule to set values. e.g. Property rule in this code should all * be on one line (including sub-rules). See * http://www.eclipse.org/forums/index.php/m/988459/#msg_988459 * </p> * <p> * Notes: * <ul> * <li>grammar.get*Rule() is used to specify line wrapping for most DSL * rules * <li>grammar.get*Access().getBeginAssignment* (and .getEndAssignment*) are * used to overwrite line wrapping around sub-rule begin/end statements when * needed. * </ul> * </p> */ @Override protected void configureFormatting(FormattingConfig c) { UsrpropsDslGrammarAccess grammar = (UsrpropsDslGrammarAccess) getGrammarAccess(); c.setAutoLinewrap(300); // BEGIN/END Blocks are indented c.setIndentationIncrement().after(grammar.getBeginRule()); c.setIndentationDecrement().before(grammar.getEndRule()); c.setLinewrap().around(grammar.getBeginRule()); c.setLinewrap().around(grammar.getEndRule()); // Top level rule are on their own lines // Major rules get an extra whitespace between them. // Everything else can have betwen 1 and 5 newlines between them c.setLinewrap(1, 1, 5).before(grammar.getIncludeRule()); c.setLinewrap(1, 1, 5).before(grammar.getRenameRule()); c.setLinewrap(2).before(grammar.getListRule()); c.setLinewrap(2).before(grammar.getDiagramRule()); c.setLinewrap(2).before(grammar.getSymbolRule()); c.setLinewrap(2).before(grammar.getDefinitionRule()); c.setLinewrap(1, 2, 2).before(grammar.getAssignInToRule()); // REM can have 0 to 5 newlines, defaults to 1. c.setLinewrap(0, 1, 10).before(grammar.getREMRule()); c.setLinewrap(0, 1, 10).after(grammar.getREMRule()); // Addressable is on its own line. c.setLinewrap().after(grammar.getAddressableRule()); // Hierarchical is on its own line. c.setLinewrap().after(grammar.getHierachicalRule()); // Chapter is on its own line. c.setLinewrap(2).before(grammar.getChapterRule()); c.setLinewrap().after(grammar.getChapterRule()); // Property and its sub-rules are on one line. c.setNoLinewrap().around(grammar.getPropertyAccess().getBeginAssignment_2()); c.setNoLinewrap().around(grammar.getEditRule()); c.setNoLinewrap().around(grammar.getPropertyAccess().getOptionsPropertyOptionParserRuleCall_3_0()); c.setNoLinewrap().around(grammar.getDisplayAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getDisplayAccess().getEndAssignment_4()); c.setNoLinewrap().around(grammar.getBordersAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getBordersAccess().getEndAssignment_9()); c.setNoLinewrap().around(grammar.getDepictionsAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getDepictionsAccess().getEndAssignment_3()); c.setLinewrap(0, 1, 1).after(grammar.getDepictionsAccess().getEndAssignment_3()); c.setNoLinewrap().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoSpace().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_3()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_5()); c.setNoSpace().before(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getEndAssignment_4()); c.setNoSpace().around(grammar.getKeyedByClauseAccess().getColonKeyword_1_1_0()); c.setNoSpace().before(grammar.getKeyedByAccess().getCommaKeyword_3_0()); c.setNoLinewrap().around(grammar.getPlacementAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getPlacementAccess().getEndAssignment_5()); c.setNoSpace().around(grammar.getLabelPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getLabelPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getLabelPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertyPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertySizeAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertySizeAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertySizeAccess().getRightParenthesisKeyword_5()); c.setNoLinewrap().around(grammar.getLayoutAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getLayoutAccess().getEndAssignment_3()); + c.setNoLinewrap().around(grammar.getBrowserShowHideAccess().getBeginAssignment_1()); + c.setNoLinewrap().around(grammar.getBrowserShowHideAccess().getEndAssignment_3()); // LIST Value are on own line c.setLinewrap().before(grammar.getValueRule()); c.setNoLinewrap().between(grammar.getValueRule(), grammar.getDepictionsRule()); // CONTROL c.setNoLinewrap().around(grammar.getControlAccess().getBeginAssignment_2()); c.setNoLinewrap().before(grammar.getControlAccess().getEndAssignment_5()); // TESTPROC c.setLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringBeginAssignment_6()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringEndAssignment_8()); c.setNoLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); c.setLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); // Symbol rules are on their own line c.setLinewrap().before(grammar.getDefinedByRule()); c.setLinewrap().before(grammar.getAssignToRule()); c.setLinewrap().before(grammar.getDepictLikeRule()); c.setLinewrap().before(grammar.getDepictionsRule()); } }
true
true
protected void configureFormatting(FormattingConfig c) { UsrpropsDslGrammarAccess grammar = (UsrpropsDslGrammarAccess) getGrammarAccess(); c.setAutoLinewrap(300); // BEGIN/END Blocks are indented c.setIndentationIncrement().after(grammar.getBeginRule()); c.setIndentationDecrement().before(grammar.getEndRule()); c.setLinewrap().around(grammar.getBeginRule()); c.setLinewrap().around(grammar.getEndRule()); // Top level rule are on their own lines // Major rules get an extra whitespace between them. // Everything else can have betwen 1 and 5 newlines between them c.setLinewrap(1, 1, 5).before(grammar.getIncludeRule()); c.setLinewrap(1, 1, 5).before(grammar.getRenameRule()); c.setLinewrap(2).before(grammar.getListRule()); c.setLinewrap(2).before(grammar.getDiagramRule()); c.setLinewrap(2).before(grammar.getSymbolRule()); c.setLinewrap(2).before(grammar.getDefinitionRule()); c.setLinewrap(1, 2, 2).before(grammar.getAssignInToRule()); // REM can have 0 to 5 newlines, defaults to 1. c.setLinewrap(0, 1, 10).before(grammar.getREMRule()); c.setLinewrap(0, 1, 10).after(grammar.getREMRule()); // Addressable is on its own line. c.setLinewrap().after(grammar.getAddressableRule()); // Hierarchical is on its own line. c.setLinewrap().after(grammar.getHierachicalRule()); // Chapter is on its own line. c.setLinewrap(2).before(grammar.getChapterRule()); c.setLinewrap().after(grammar.getChapterRule()); // Property and its sub-rules are on one line. c.setNoLinewrap().around(grammar.getPropertyAccess().getBeginAssignment_2()); c.setNoLinewrap().around(grammar.getEditRule()); c.setNoLinewrap().around(grammar.getPropertyAccess().getOptionsPropertyOptionParserRuleCall_3_0()); c.setNoLinewrap().around(grammar.getDisplayAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getDisplayAccess().getEndAssignment_4()); c.setNoLinewrap().around(grammar.getBordersAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getBordersAccess().getEndAssignment_9()); c.setNoLinewrap().around(grammar.getDepictionsAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getDepictionsAccess().getEndAssignment_3()); c.setLinewrap(0, 1, 1).after(grammar.getDepictionsAccess().getEndAssignment_3()); c.setNoLinewrap().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoSpace().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_3()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_5()); c.setNoSpace().before(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getEndAssignment_4()); c.setNoSpace().around(grammar.getKeyedByClauseAccess().getColonKeyword_1_1_0()); c.setNoSpace().before(grammar.getKeyedByAccess().getCommaKeyword_3_0()); c.setNoLinewrap().around(grammar.getPlacementAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getPlacementAccess().getEndAssignment_5()); c.setNoSpace().around(grammar.getLabelPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getLabelPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getLabelPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertyPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertySizeAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertySizeAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertySizeAccess().getRightParenthesisKeyword_5()); c.setNoLinewrap().around(grammar.getLayoutAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getLayoutAccess().getEndAssignment_3()); // LIST Value are on own line c.setLinewrap().before(grammar.getValueRule()); c.setNoLinewrap().between(grammar.getValueRule(), grammar.getDepictionsRule()); // CONTROL c.setNoLinewrap().around(grammar.getControlAccess().getBeginAssignment_2()); c.setNoLinewrap().before(grammar.getControlAccess().getEndAssignment_5()); // TESTPROC c.setLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringBeginAssignment_6()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringEndAssignment_8()); c.setNoLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); c.setLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); // Symbol rules are on their own line c.setLinewrap().before(grammar.getDefinedByRule()); c.setLinewrap().before(grammar.getAssignToRule()); c.setLinewrap().before(grammar.getDepictLikeRule()); c.setLinewrap().before(grammar.getDepictionsRule()); }
protected void configureFormatting(FormattingConfig c) { UsrpropsDslGrammarAccess grammar = (UsrpropsDslGrammarAccess) getGrammarAccess(); c.setAutoLinewrap(300); // BEGIN/END Blocks are indented c.setIndentationIncrement().after(grammar.getBeginRule()); c.setIndentationDecrement().before(grammar.getEndRule()); c.setLinewrap().around(grammar.getBeginRule()); c.setLinewrap().around(grammar.getEndRule()); // Top level rule are on their own lines // Major rules get an extra whitespace between them. // Everything else can have betwen 1 and 5 newlines between them c.setLinewrap(1, 1, 5).before(grammar.getIncludeRule()); c.setLinewrap(1, 1, 5).before(grammar.getRenameRule()); c.setLinewrap(2).before(grammar.getListRule()); c.setLinewrap(2).before(grammar.getDiagramRule()); c.setLinewrap(2).before(grammar.getSymbolRule()); c.setLinewrap(2).before(grammar.getDefinitionRule()); c.setLinewrap(1, 2, 2).before(grammar.getAssignInToRule()); // REM can have 0 to 5 newlines, defaults to 1. c.setLinewrap(0, 1, 10).before(grammar.getREMRule()); c.setLinewrap(0, 1, 10).after(grammar.getREMRule()); // Addressable is on its own line. c.setLinewrap().after(grammar.getAddressableRule()); // Hierarchical is on its own line. c.setLinewrap().after(grammar.getHierachicalRule()); // Chapter is on its own line. c.setLinewrap(2).before(grammar.getChapterRule()); c.setLinewrap().after(grammar.getChapterRule()); // Property and its sub-rules are on one line. c.setNoLinewrap().around(grammar.getPropertyAccess().getBeginAssignment_2()); c.setNoLinewrap().around(grammar.getEditRule()); c.setNoLinewrap().around(grammar.getPropertyAccess().getOptionsPropertyOptionParserRuleCall_3_0()); c.setNoLinewrap().around(grammar.getDisplayAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getDisplayAccess().getEndAssignment_4()); c.setNoLinewrap().around(grammar.getBordersAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getBordersAccess().getEndAssignment_9()); c.setNoLinewrap().around(grammar.getDepictionsAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getDepictionsAccess().getEndAssignment_3()); c.setLinewrap(0, 1, 1).after(grammar.getDepictionsAccess().getEndAssignment_3()); c.setNoLinewrap().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoSpace().around(grammar.getFillColorAccess().getBeginAssignment_1()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_3()); c.setNoSpace().around(grammar.getFillColorAccess().getCommaKeyword_5()); c.setNoSpace().before(grammar.getFillColorAccess().getEndAssignment_7()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getKeyedByAccess().getEndAssignment_4()); c.setNoSpace().around(grammar.getKeyedByClauseAccess().getColonKeyword_1_1_0()); c.setNoSpace().before(grammar.getKeyedByAccess().getCommaKeyword_3_0()); c.setNoLinewrap().around(grammar.getPlacementAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getPlacementAccess().getEndAssignment_5()); c.setNoSpace().around(grammar.getLabelPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getLabelPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getLabelPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertyPositionAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertyPositionAccess().getRightParenthesisKeyword_5()); c.setNoSpace().around(grammar.getPropertySizeAccess().getLeftParenthesisKeyword_1()); c.setNoSpace().around(grammar.getPropertySizeAccess().getCommaKeyword_3()); c.setNoSpace().before(grammar.getPropertySizeAccess().getRightParenthesisKeyword_5()); c.setNoLinewrap().around(grammar.getLayoutAccess().getBeginAssignment_1()); c.setNoLinewrap().before(grammar.getLayoutAccess().getEndAssignment_3()); c.setNoLinewrap().around(grammar.getBrowserShowHideAccess().getBeginAssignment_1()); c.setNoLinewrap().around(grammar.getBrowserShowHideAccess().getEndAssignment_3()); // LIST Value are on own line c.setLinewrap().before(grammar.getValueRule()); c.setNoLinewrap().between(grammar.getValueRule(), grammar.getDepictionsRule()); // CONTROL c.setNoLinewrap().around(grammar.getControlAccess().getBeginAssignment_2()); c.setNoLinewrap().before(grammar.getControlAccess().getEndAssignment_5()); // TESTPROC c.setLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getBeginAssignment_0()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringBeginAssignment_6()); c.setNoLinewrap().around(grammar.getConditionalCapabilityCommandGroupAccess().getStringEndAssignment_8()); c.setNoLinewrap().before(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); c.setLinewrap().after(grammar.getConditionalCapabilityCommandGroupAccess().getEndAssignment_9()); // Symbol rules are on their own line c.setLinewrap().before(grammar.getDefinedByRule()); c.setLinewrap().before(grammar.getAssignToRule()); c.setLinewrap().before(grammar.getDepictLikeRule()); c.setLinewrap().before(grammar.getDepictionsRule()); }
diff --git a/app/src/com/jackandjason/voter.java b/app/src/com/jackandjason/voter.java index 4b8e05b..703781a 100644 --- a/app/src/com/jackandjason/voter.java +++ b/app/src/com/jackandjason/voter.java @@ -1,47 +1,47 @@ package com.jackandjason; import java.io.IOException; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.webkit.WebView; import android.webkit.WebViewClient; import android.view.KeyEvent; public class voter extends Activity { /** Called when the activity is first created. */ WebView webview; private class VoteViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webview = new WebView(this); setContentView(webview); - webview.loadUrl("http://141.212.237.39:8888/vote"); + webview.loadUrl("http://192.168.1.126:8888/vote"); webview.getSettings().setJavaScriptEnabled(true); webview.setVerticalScrollBarEnabled(false); webview.setHorizontalScrollBarEnabled(false); webview.setWebViewClient(new VoteViewClient()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) { webview.goBack(); return true; } return super.onKeyDown(keyCode, event); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webview = new WebView(this); setContentView(webview); webview.loadUrl("http://141.212.237.39:8888/vote"); webview.getSettings().setJavaScriptEnabled(true); webview.setVerticalScrollBarEnabled(false); webview.setHorizontalScrollBarEnabled(false); webview.setWebViewClient(new VoteViewClient()); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webview = new WebView(this); setContentView(webview); webview.loadUrl("http://192.168.1.126:8888/vote"); webview.getSettings().setJavaScriptEnabled(true); webview.setVerticalScrollBarEnabled(false); webview.setHorizontalScrollBarEnabled(false); webview.setWebViewClient(new VoteViewClient()); }
diff --git a/src/newsrack/web/BrowseAction.java b/src/newsrack/web/BrowseAction.java index c5e72a2..47fd318 100644 --- a/src/newsrack/web/BrowseAction.java +++ b/src/newsrack/web/BrowseAction.java @@ -1,286 +1,286 @@ package newsrack.web; import newsrack.GlobalConstants; import newsrack.filter.Category; import newsrack.filter.Issue; import newsrack.archiver.Source; import newsrack.user.User; import newsrack.archiver.DownloadNewsTask; import newsrack.database.NewsItem; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Collection; import java.util.LinkedList; import java.util.ArrayList; import java.io.IOException; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * class <code>BrowseAction</code> implements the functionality * browsing through news archives of a particular user as well * as other public archives */ public class BrowseAction extends BaseAction { private static final ThreadLocal<SimpleDateFormat> DATE_PARSER = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy.MM.dd"); } }; private static final ThreadLocal<SimpleDateFormat> SDF = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("MMM dd yyyy kk:mm z"); } }; private static final Log _log = LogFactory.getLog(BrowseAction.class); /* Logger for this action class */ // FIXME: Pick some other view scheme than this! private static Date _lastUpdateTime = null; private static List<Issue> _updatesMostRecent = null; private static List<Issue> _updatesLast24Hrs = null; private static List<Issue> _updatesMoreThan24Hrs = null; private static final int DEF_NUM_ARTS_PER_PAGE = 20; private static final int MIN_NUM_ARTS_PER_PAGE = 5; private static final int MAX_NUM_ARTS_PER_PAGE = 200; // Caching! public static void setIssueUpdateLists() { List<Issue> l1 = new ArrayList<Issue>(); List<Issue> l2 = new ArrayList<Issue>(); List<Issue> l3 = new ArrayList<Issue>(); List<Issue> issues = User.getAllValidatedIssues(); for (Issue i: issues) { int n = i.getNumItemsSinceLastDownload(); if ((n > 0) && (_lastUpdateTime != null) && (i.getLastUpdateTime() != null) && i.getLastUpdateTime().after(_lastUpdateTime)) l1.add(i); else if (i.updatedWithinLastNHours(24)) l2.add(i); else l3.add(i); } _updatesMostRecent = l1; _updatesLast24Hrs = l2; _updatesMoreThan24Hrs = l3; _lastUpdateTime = new Date(); } private String _lastDownloadTime; /* These 4 params are for the common browse case: * top-level browse; user browse; issue browse */ private User _issueOwner; private Issue _issue; private Category _cat; private List<Category> _catAncestors; private int _numArts; private int _start; private int _count; /* These 4 params are for the uncommon browse case: * for browsing news by source */ private Source _src; private String _d; private String _m; private String _y; /* News list to be displayed */ private Collection<NewsItem> _news; public String getLastDownloadTime() { return _lastDownloadTime; } public Date getLastUpdateTime() { return _lastUpdateTime; } public int getNumArts() { return _numArts; } public int getStart() { return _start; } public int getCount() { return _count; } public Collection<NewsItem> getNews() { return _news; } public User getOwner() { return _issueOwner; } public Issue getIssue() { return _issue; } public Category getCat() { return _cat; } public List<Category> getCatAncestors() { return _catAncestors; } public String getDate() { return _d; } public String getMonth() { return _m; } public String getYear() { return _y; } public Source getSource() { return _src; } public List<Issue> getMostRecentUpdates() { return _updatesMostRecent; } public List<Issue> getLast24HourUpdates() { return _updatesLast24Hrs; } public List<Issue> getOldestUpdates() { return _updatesMoreThan24Hrs; } public String execute() { /* Do some error checking, fetch the issue, and the referenced category * and pass control to the news display routine */ Date ldt = DownloadNewsTask.getLastDownloadTime(); _lastDownloadTime = SDF.get().format(ldt); String uid = getParam("owner"); if (uid == null) { // No uid, -- send them to the top-level browse page! if ((_updatesMostRecent == null) || _lastUpdateTime.before(ldt)) setIssueUpdateLists(); return "browse.main"; } else { _issueOwner = User.getUser(uid); if (_issueOwner == null) { // Bad uid given! Send the user to the top-level browse page _log.info("Browse: No user with uid: " + uid); return "browse.main"; } String issueName = getParam("issue"); if (issueName == null) { // No issue parameter for the user. Send them to a issue listing page for that user! return "browse.user"; } _issue = _issueOwner.getIssue(issueName); if (_issue == null) { // Bad issue-name parameter. Send them to a issue listing page for that user! _log.info("Browse: No issue with name: " + issueName + " defined for user: " + uid); return "browse.user"; } String catId = getParam("catID"); if (catId == null) { // No cat specified -- browse the issue! return "browse.issue"; } _cat = _issue.getCategory(Integer.parseInt(catId)); if (_cat == null) { // Bad category! Send them to a listing page for the issue! _log.info("Browse: Category with id " + catId + " not defined in issue " + issueName + " for user: " + uid); return "browse.issue"; } // Set up the ancestor list for the category Category c = _cat; LinkedList<Category> ancestors = new LinkedList<Category>(); while (c != null) { c = c.getParent(); if (c != null) ancestors.addFirst(c); } _catAncestors = ancestors; // Display news in the current category in the current issue if (!_cat.isLeafCategory()) { return "browse.cat"; } else { _numArts = _cat.getNumArticles(); // Start String startVal = getParam("start"); if (startVal == null) { _start = 0; } else { - _start = Integer.parseInt(startVal); + _start = Integer.parseInt(startVal)-1; if (_start < 0) _start = 0; else if (_start > _numArts) _start = _numArts; } // Count String countVal = getParam("count"); if (countVal == null) { _count = DEF_NUM_ARTS_PER_PAGE; } else { _count = Integer.parseInt(countVal); if (_count < MIN_NUM_ARTS_PER_PAGE) _count = MIN_NUM_ARTS_PER_PAGE; else if (_count > MAX_NUM_ARTS_PER_PAGE) _count = MAX_NUM_ARTS_PER_PAGE; } // Filter by source String srcTag = getParam("source_tag"); Source src = null; if ((srcTag != null) && (srcTag != "")) src = _issue.getSourceByTag(srcTag); Date startDate = null; String sdStr = getParam("start_date"); if (sdStr != null) { try { startDate = DATE_PARSER.get().parse(sdStr); } catch (Exception e) { addActionError(getText("bad.date", sdStr)); _log.info("Error parsing date: " + sdStr + e); } } // Filter by start & end dates Date endDate = null; String edStr = getParam("end_date"); if (edStr != null) { try { endDate = DATE_PARSER.get().parse(edStr); } catch (Exception e) { addActionError(getText("bad.date", edStr)); _log.info("Error parsing date: " + edStr + e); } } //_log.info("Browse: owner uid - " + uid + "; issue name - " + issueName + "; catID - " + catId + "; start - " + _start + "; count - " + _count + "; start - " + startDate + "; end - " + endDate + "; srcTag - " + srcTag + "; src - " + (src != null ? src.getKey() : null)); // Fetch news! _news = _cat.getNews(startDate, endDate, src, _start, _count); return "browse.news"; } } } public String browseSource() { // If there is no valid session, send them to the generic browse page! if (_user == null) { _log.error("Expired session!"); return "browse.main"; } // Fetch source String srcId = getParam("srcId"); if (srcId == null) { _log.error("No source id provided!"); return Action.INPUT; } _src = _user.getSourceByTag(srcId); if (_src == null) { _log.error("Unknown source: " + srcId); return Action.INPUT; } _d = getParam("d"); _m = getParam("m"); _y = getParam("y"); if ((_d == null) || (_m == null) && (_y == null)) { _log.error("Bad date params: d- " + _d + ", m- " + _m + ", y- " + _y); return Action.INPUT; } // Fetch news for the source for the requested date _news = _src.getArchivedNews(_y, _m, _d); if (_news == null) _news = new ArrayList<NewsItem>(); return Action.SUCCESS; } }
true
true
public String execute() { /* Do some error checking, fetch the issue, and the referenced category * and pass control to the news display routine */ Date ldt = DownloadNewsTask.getLastDownloadTime(); _lastDownloadTime = SDF.get().format(ldt); String uid = getParam("owner"); if (uid == null) { // No uid, -- send them to the top-level browse page! if ((_updatesMostRecent == null) || _lastUpdateTime.before(ldt)) setIssueUpdateLists(); return "browse.main"; } else { _issueOwner = User.getUser(uid); if (_issueOwner == null) { // Bad uid given! Send the user to the top-level browse page _log.info("Browse: No user with uid: " + uid); return "browse.main"; } String issueName = getParam("issue"); if (issueName == null) { // No issue parameter for the user. Send them to a issue listing page for that user! return "browse.user"; } _issue = _issueOwner.getIssue(issueName); if (_issue == null) { // Bad issue-name parameter. Send them to a issue listing page for that user! _log.info("Browse: No issue with name: " + issueName + " defined for user: " + uid); return "browse.user"; } String catId = getParam("catID"); if (catId == null) { // No cat specified -- browse the issue! return "browse.issue"; } _cat = _issue.getCategory(Integer.parseInt(catId)); if (_cat == null) { // Bad category! Send them to a listing page for the issue! _log.info("Browse: Category with id " + catId + " not defined in issue " + issueName + " for user: " + uid); return "browse.issue"; } // Set up the ancestor list for the category Category c = _cat; LinkedList<Category> ancestors = new LinkedList<Category>(); while (c != null) { c = c.getParent(); if (c != null) ancestors.addFirst(c); } _catAncestors = ancestors; // Display news in the current category in the current issue if (!_cat.isLeafCategory()) { return "browse.cat"; } else { _numArts = _cat.getNumArticles(); // Start String startVal = getParam("start"); if (startVal == null) { _start = 0; } else { _start = Integer.parseInt(startVal); if (_start < 0) _start = 0; else if (_start > _numArts) _start = _numArts; } // Count String countVal = getParam("count"); if (countVal == null) { _count = DEF_NUM_ARTS_PER_PAGE; } else { _count = Integer.parseInt(countVal); if (_count < MIN_NUM_ARTS_PER_PAGE) _count = MIN_NUM_ARTS_PER_PAGE; else if (_count > MAX_NUM_ARTS_PER_PAGE) _count = MAX_NUM_ARTS_PER_PAGE; } // Filter by source String srcTag = getParam("source_tag"); Source src = null; if ((srcTag != null) && (srcTag != "")) src = _issue.getSourceByTag(srcTag); Date startDate = null; String sdStr = getParam("start_date"); if (sdStr != null) { try { startDate = DATE_PARSER.get().parse(sdStr); } catch (Exception e) { addActionError(getText("bad.date", sdStr)); _log.info("Error parsing date: " + sdStr + e); } } // Filter by start & end dates Date endDate = null; String edStr = getParam("end_date"); if (edStr != null) { try { endDate = DATE_PARSER.get().parse(edStr); } catch (Exception e) { addActionError(getText("bad.date", edStr)); _log.info("Error parsing date: " + edStr + e); } } //_log.info("Browse: owner uid - " + uid + "; issue name - " + issueName + "; catID - " + catId + "; start - " + _start + "; count - " + _count + "; start - " + startDate + "; end - " + endDate + "; srcTag - " + srcTag + "; src - " + (src != null ? src.getKey() : null)); // Fetch news! _news = _cat.getNews(startDate, endDate, src, _start, _count); return "browse.news"; } } }
public String execute() { /* Do some error checking, fetch the issue, and the referenced category * and pass control to the news display routine */ Date ldt = DownloadNewsTask.getLastDownloadTime(); _lastDownloadTime = SDF.get().format(ldt); String uid = getParam("owner"); if (uid == null) { // No uid, -- send them to the top-level browse page! if ((_updatesMostRecent == null) || _lastUpdateTime.before(ldt)) setIssueUpdateLists(); return "browse.main"; } else { _issueOwner = User.getUser(uid); if (_issueOwner == null) { // Bad uid given! Send the user to the top-level browse page _log.info("Browse: No user with uid: " + uid); return "browse.main"; } String issueName = getParam("issue"); if (issueName == null) { // No issue parameter for the user. Send them to a issue listing page for that user! return "browse.user"; } _issue = _issueOwner.getIssue(issueName); if (_issue == null) { // Bad issue-name parameter. Send them to a issue listing page for that user! _log.info("Browse: No issue with name: " + issueName + " defined for user: " + uid); return "browse.user"; } String catId = getParam("catID"); if (catId == null) { // No cat specified -- browse the issue! return "browse.issue"; } _cat = _issue.getCategory(Integer.parseInt(catId)); if (_cat == null) { // Bad category! Send them to a listing page for the issue! _log.info("Browse: Category with id " + catId + " not defined in issue " + issueName + " for user: " + uid); return "browse.issue"; } // Set up the ancestor list for the category Category c = _cat; LinkedList<Category> ancestors = new LinkedList<Category>(); while (c != null) { c = c.getParent(); if (c != null) ancestors.addFirst(c); } _catAncestors = ancestors; // Display news in the current category in the current issue if (!_cat.isLeafCategory()) { return "browse.cat"; } else { _numArts = _cat.getNumArticles(); // Start String startVal = getParam("start"); if (startVal == null) { _start = 0; } else { _start = Integer.parseInt(startVal)-1; if (_start < 0) _start = 0; else if (_start > _numArts) _start = _numArts; } // Count String countVal = getParam("count"); if (countVal == null) { _count = DEF_NUM_ARTS_PER_PAGE; } else { _count = Integer.parseInt(countVal); if (_count < MIN_NUM_ARTS_PER_PAGE) _count = MIN_NUM_ARTS_PER_PAGE; else if (_count > MAX_NUM_ARTS_PER_PAGE) _count = MAX_NUM_ARTS_PER_PAGE; } // Filter by source String srcTag = getParam("source_tag"); Source src = null; if ((srcTag != null) && (srcTag != "")) src = _issue.getSourceByTag(srcTag); Date startDate = null; String sdStr = getParam("start_date"); if (sdStr != null) { try { startDate = DATE_PARSER.get().parse(sdStr); } catch (Exception e) { addActionError(getText("bad.date", sdStr)); _log.info("Error parsing date: " + sdStr + e); } } // Filter by start & end dates Date endDate = null; String edStr = getParam("end_date"); if (edStr != null) { try { endDate = DATE_PARSER.get().parse(edStr); } catch (Exception e) { addActionError(getText("bad.date", edStr)); _log.info("Error parsing date: " + edStr + e); } } //_log.info("Browse: owner uid - " + uid + "; issue name - " + issueName + "; catID - " + catId + "; start - " + _start + "; count - " + _count + "; start - " + startDate + "; end - " + endDate + "; srcTag - " + srcTag + "; src - " + (src != null ? src.getKey() : null)); // Fetch news! _news = _cat.getNews(startDate, endDate, src, _start, _count); return "browse.news"; } } }
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java index 720317808..604254f81 100644 --- a/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java +++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxClassReader.java @@ -1,596 +1,596 @@ /* * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.comp; import java.util.IdentityHashMap; import javax.tools.JavaFileObject; import com.sun.tools.javac.jvm.ClassReader; import com.sun.tools.javac.code.*; import com.sun.tools.javac.code.Type.*; import com.sun.tools.javac.code.Symbol.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.List; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.Kinds.*; import static com.sun.tools.javac.code.TypeTags.*; import com.sun.tools.javafx.code.JavafxClassSymbol; import com.sun.tools.javafx.code.JavafxSymtab; import com.sun.tools.javafx.code.JavafxFlags; import com.sun.tools.javafx.main.JavafxCompiler; import static com.sun.tools.javafx.code.JavafxVarSymbol.*; /** Provides operations to read a classfile into an internal * representation. The internal representation is anchored in a * JavafxClassSymbol which contains in its scope symbol representations * for all other definitions in the classfile. Top-level Classes themselves * appear as members of the scopes of PackageSymbols. * * We delegate actual classfile-reading to javac's ClassReader, and then * translates the resulting ClassSymbol to JavafxClassSymbol, doing some * renaming etc to make the resulting Symbols and Types match those produced * by the parser. This munging is incomplete, and there are still places * where the compiler needs to know of a class comes from the parser or a * classfile; those places will hopefully become fewer. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class JavafxClassReader extends ClassReader { protected static final Context.Key<ClassReader> backendClassReaderKey = new Context.Key<ClassReader>(); private final JavafxDefs defs; /** The raw class-reader, shared by the back-end. */ public ClassReader jreader; private final Name functionClassPrefixName; private Context ctx; public static void registerBackendReader(final Context context, final ClassReader jreader) { context.put(backendClassReaderKey, jreader); } public static void preRegister(final Context context, final ClassReader jreader) { registerBackendReader(context, jreader); preRegister(context); } public static void preRegister(final Context context) { context.put(classReaderKey, new Context.Factory<ClassReader>() { public JavafxClassReader make() { JavafxClassReader reader = new JavafxClassReader(context, true); reader.jreader = context.get(backendClassReaderKey); return reader; } }); } public static JavafxClassReader instance(Context context) { JavafxClassReader instance = (JavafxClassReader) context.get(classReaderKey); if (instance == null) instance = new JavafxClassReader(context, true); return instance; } /** Construct a new class reader, optionally treated as the * definitive classreader for this invocation. */ protected JavafxClassReader(Context context, boolean definitive) { super(context, definitive); defs = JavafxDefs.instance(context); functionClassPrefixName = names.fromString(JavafxSymtab.functionClassPrefix); ctx = context; } public Name.Table getNames() { return names; } /** Reassign names of classes that might have been loaded with * their flat names. */ void fixupFullname (JavafxClassSymbol cSym, ClassSymbol jsymbol) { if (cSym.fullname != jsymbol.fullname && cSym.owner.kind == PCK && jsymbol.owner.kind == TYP) { cSym.owner.members().remove(cSym); cSym.name = jsymbol.name; ClassSymbol owner = enterClass(((ClassSymbol) jsymbol.owner).flatname); cSym.owner = owner; cSym.fullname = ClassSymbol.formFullName(cSym.name, owner); } } public JavafxClassSymbol enterClass(ClassSymbol jsymbol) { Name className = jsymbol.flatname; boolean compound = className.endsWith(defs.interfaceSuffixName); if (compound) className = className.subName(0, className.len - defs.interfaceSuffixName.len); JavafxClassSymbol cSym = (JavafxClassSymbol) enterClass(className); //cSym.flags_field |= jsymbol.flags_field; if (compound) cSym.flags_field |= JavafxFlags.COMPOUND_CLASS; else { fixupFullname(cSym, jsymbol); cSym.jsymbol = jsymbol; } return cSym; } /** Define a new class given its name and owner. */ @Override public ClassSymbol defineClass(Name name, Symbol owner) { ClassSymbol c = new JavafxClassSymbol(0, name, owner); if (owner.kind == PCK) assert classes.get(c.flatname) == null : c; c.completer = this; return c; } /* FIXME: The re-written class-reader doesn't translate annotations yet. protected void attachAnnotations(final Symbol sym) { int numAttributes = nextChar(); if (numAttributes != 0) { ListBuffer<CompoundAnnotationProxy> proxies = new ListBuffer<CompoundAnnotationProxy>(); for (int i = 0; i<numAttributes; i++) { CompoundAnnotationProxy proxy = readCompoundAnnotation(); if (proxy.type.tsym == syms.proprietaryType.tsym) sym.flags_field |= PROPRIETARY; else { proxies.append(proxy); } } annotate.later(new JavafxAnnotationCompleter(sym, proxies.toList(), this)); } } static public class JavafxAnnotationCompleter extends AnnotationCompleter { JavafxClassReader classReader; public JavafxAnnotationCompleter(Symbol sym, List<CompoundAnnotationProxy> l, ClassReader classReader) { super(sym, l, classReader); this.classReader = (JavafxClassReader)classReader; } // implement Annotate.Annotator.enterAnnotation() public void enterAnnotation() { JavaFileObject previousClassFile = classReader.currentClassFile; try { classReader.currentClassFile = classFile; List<Attribute.Compound> newList = deproxyCompoundList(l); JavafxSymtab javafxSyms = (JavafxSymtab)classReader.syms; for (Attribute.Compound comp : newList) { } sym.attributes_field = ((sym.attributes_field == null) ? newList : newList.prependList(sym.attributes_field)); } finally { classReader.currentClassFile = previousClassFile; } } } */ /** Map javac Type/Symbol to javafx Type/Symbol. */ IdentityHashMap<Object,Object> typeMap = new IdentityHashMap<Object,Object>(); /** Translate a List of raw JVM types to Javafx types. */ List<Type> translateTypes (List<Type> types) { if (types == null) return null; List<Type> ts = (List<Type>) typeMap.get(types); if (ts != null) return ts; ListBuffer<Type> rs = new ListBuffer<Type>(); for (List<Type> t = types; t.tail != null; t = t.tail) rs.append(translateType(t.head)); ts = rs.toList(); typeMap.put(types, ts); return ts; } /** Translate raw JVM type to Javafx type. */ Type translateType (Type type) { if (type == null) return null; Type t = (Type) typeMap.get(type); if (t != null) return t; switch (type.tag) { case VOID: t = syms.voidType; break; case BOOLEAN: t = syms.booleanType; break; case CHAR: t = syms.charType; break; case BYTE: t = syms.byteType; break; case SHORT: t = syms.shortType; break; case INT: t = syms.intType; break; case LONG: t = syms.longType; break; case DOUBLE: t = syms.doubleType; break; case FLOAT: t = syms.floatType; break; case TYPEVAR: TypeVar tv = (TypeVar) type; TypeVar tx = new TypeVar(null, (Type) null, (Type) null); typeMap.put(type, tx); // In case of a cycle. tx.bound = translateType(tv.bound); tx.lower = translateType(tv.lower); tx.tsym = new TypeSymbol(0, tv.tsym.name, tx, translateSymbol(tv.tsym.owner)); return tx; case FORALL: ForAll tf = (ForAll) type; t = new ForAll(translateTypes(tf.tvars), translateType(tf.qtype)); break; case WILDCARD: WildcardType wt = (WildcardType) type; t = new WildcardType(translateType(wt.type), wt.kind, translateTypeSymbol(wt.tsym)); break; case CLASS: TypeSymbol tsym = type.tsym; if (tsym instanceof ClassSymbol) { if (tsym.name.endsWith(defs.interfaceSuffixName)) { t = enterClass((ClassSymbol) tsym).type; break; } final ClassType ctype = (ClassType) type; if (ctype.isCompound()) { t = types.makeCompoundType(translateTypes(ctype.interfaces_field), translateType(ctype.supertype_field)); break; } Name flatname = ((ClassSymbol) tsym).flatname; Type deloc = defs.delocationize(flatname); if (deloc != null) { if (deloc == syms.intType || deloc == syms.doubleType || deloc == syms.booleanType) { return deloc; } if (ctype.typarams_field != null && ctype.typarams_field.size() == 1) { if (deloc == syms.objectType) { return translateType(ctype.typarams_field.head); } if (deloc == ((JavafxSymtab) syms).javafx_SequenceType) { Type tparam = translateType(ctype.typarams_field.head); WildcardType tpType = new WildcardType(tparam, BoundKind.EXTENDS, tparam.tsym); t = new ClassType(Type.noType, List.<Type>of(tpType), ((JavafxSymtab) syms).javafx_SequenceType.tsym); break; } } } if (flatname.startsWith(functionClassPrefixName) && flatname != functionClassPrefixName) { t = ((JavafxSymtab) syms).makeFunctionType(translateTypes(ctype.typarams_field)); break; } TypeSymbol sym = translateTypeSymbol(tsym); ClassType ntype; if (tsym.type == type) ntype = (ClassType) sym.type; else ntype = new ClassType(Type.noType, List.<Type>nil(), sym) { boolean completed = false; @Override public Type getEnclosingType() { if (!completed) { completed = true; tsym.complete(); super.setEnclosingType(translateType(ctype.getEnclosingType())); } return super.getEnclosingType(); } @Override public void setEnclosingType(Type outer) { throw new UnsupportedOperationException(); } @Override public boolean equals(Object t) { return super.equals(t); } @Override public int hashCode() { return super.hashCode(); } }; typeMap.put(type, ntype); // In case of a cycle. ntype.typarams_field = translateTypes(type.getTypeArguments()); return ntype; } break; case ARRAY: t = new ArrayType(translateType(((ArrayType) type).elemtype), syms.arrayClass); break; case METHOD: t = new MethodType(translateTypes(type.getParameterTypes()), translateType(type.getReturnType()), translateTypes(type.getThrownTypes()), syms.methodClass); break; default: t = type; // FIXME } typeMap.put(type, t); return t; } TypeSymbol translateTypeSymbol(TypeSymbol tsym) { if (tsym == syms.predefClass) return tsym; ClassSymbol csym = (ClassSymbol) tsym; // FIXME return enterClass(csym); } Symbol translateSymbol(Symbol sym) { if (sym == null) return null; Symbol s = (Symbol) typeMap.get(sym); if (s != null) return s; if (sym instanceof PackageSymbol) s = enterPackage(((PackageSymbol) sym).fullname); else if (sym instanceof MethodSymbol) { Name name = sym.name; long flags = sym.flags_field; Symbol owner = translateSymbol(sym.owner); Type type = translateType(sym.type); String nameString = name.toString(); int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix); if (boundStringIndex != -1) { // this is a bound function // remove the bound suffix, and mark as bound name = names.fromString(nameString.substring(0, boundStringIndex)); flags |= JavafxFlags.BOUND; } MethodSymbol m = new MethodSymbol(flags, name, type, owner); ((ClassSymbol) owner).members_field.enter(m); s = m; } else s = translateTypeSymbol((TypeSymbol) sym); typeMap.put(sym, s); return s; } @Override public void complete(Symbol sym) throws CompletionFailure { if (jreader.sourceCompleter == null) jreader.sourceCompleter = JavafxCompiler.instance(ctx); if (sym instanceof PackageSymbol) { PackageSymbol psym = (PackageSymbol) sym; PackageSymbol jpackage; if (psym == syms.unnamedPackage) jpackage = jreader.syms.unnamedPackage; else jpackage = jreader.enterPackage(psym.fullname); jpackage.complete(); if (psym.members_field == null) psym.members_field = new Scope(psym); for (Scope.Entry e = jpackage.members_field.elems; e != null; e = e.sibling) { if (e.sym instanceof ClassSymbol) { ClassSymbol jsym = (ClassSymbol) e.sym; if (jsym.name.endsWith(defs.interfaceSuffixName)) continue; JavafxClassSymbol csym = enterClass(jsym); psym.members_field.enter(csym); csym.classfile = jsym.classfile; csym.jsymbol = jsym; } } if (jpackage.exists()) psym.flags_field |= EXISTS; } else { sym.owner.complete(); JavafxClassSymbol csym = (JavafxClassSymbol) sym; ClassSymbol jsymbol = csym.jsymbol; if (jsymbol != null && jsymbol.classfile != null && jsymbol.classfile.getKind() == JavaFileObject.Kind.SOURCE && jsymbol.classfile.getName().endsWith(".fx")) { SourceCompleter fxSourceCompleter = JavafxCompiler.instance(ctx); fxSourceCompleter.complete(csym); return; } else { csym.jsymbol = jsymbol = jreader.loadClass(csym.flatname); } fixupFullname(csym, jsymbol); typeMap.put(jsymbol, csym); jsymbol.classfile = ((ClassSymbol) sym).classfile; ClassType ct = (ClassType)csym.type; ClassType jt = (ClassType)jsymbol.type; csym.members_field = new Scope(csym); // flags are derived from flag bits and access modifier annoations csym.flags_field = flagsFromAnnotationsAndFlags(jsymbol); ct.typarams_field = translateTypes(jt.typarams_field); ct.setEnclosingType(translateType(jt.getEnclosingType())); ct.supertype_field = translateType(jt.supertype_field); ListBuffer<Type> interfaces = new ListBuffer<Type>(); Type iface = null; if (jt.interfaces_field != null) { // true for ErrorType for (List<Type> it = jt.interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; - else if (itype.tsym.name.endsWith(defs.interfaceSuffixName)) { + else if ((csym.fullname.len + defs.interfaceSuffixName.len == + ((ClassSymbol) itype.tsym).fullname.len) && + ((ClassSymbol) itype.tsym).fullname.startsWith(csym.fullname) && + itype.tsym.name.endsWith(defs.interfaceSuffixName)) { iface = itype; iface.tsym.complete(); - assert (csym.fullname.len + defs.interfaceSuffixName.len == - ((ClassSymbol) itype.tsym).fullname.len) && - ((ClassSymbol) itype.tsym).fullname.startsWith(csym.fullname); csym.flags_field |= JavafxFlags.COMPOUND_CLASS; } else { itype = translateType(itype); interfaces.append(itype); } } } if (iface != null) { for (List<Type> it = ((ClassType) iface.tsym.type).interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; else { itype = translateType(itype); interfaces.append(itype); csym.addSuperType(itype); } } } ct.interfaces_field = interfaces.toList(); // Now translate the members. // Do an initial "reverse" pass so we copy the order. List<Symbol> syms = List.nil(); for (Scope.Entry e = jsymbol.members_field.elems; e != null; e = e.sibling) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; syms = syms.prepend(e.sym); } handleSyms: for (List<Symbol> l = syms; l.nonEmpty(); l=l.tail) { Name name = l.head.name; long flags = flagsFromAnnotationsAndFlags(l.head); if ((flags & PRIVATE) != 0) continue; boolean sawSourceNameAnnotation = false; JavafxSymtab javafxSyms = (JavafxSymtab) this.syms; for (Attribute.Compound a : l.head.getAnnotationMirrors()) { if (a.type.tsym.flatName() == javafxSyms.javafx_staticAnnotationType.tsym.flatName()) { flags |= Flags.STATIC; } else if (a.type.tsym.flatName() == javafxSyms.javafx_defAnnotationType.tsym.flatName()) { flags |= JavafxFlags.IS_DEF; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicInitAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_INIT; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicReadAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_READ; } else if (a.type.tsym.flatName() == javafxSyms.javafx_inheritedAnnotationType.tsym.flatName()) { continue handleSyms; } else if (a.type.tsym.flatName() == javafxSyms.javafx_sourceNameAnnotationType.tsym.flatName()) { Attribute aa = a.member(name.table.value); Object sourceName = aa.getValue(); if (sourceName instanceof String) { name = names.fromString((String) sourceName); sawSourceNameAnnotation = true; } } } if (l.head instanceof MethodSymbol) { if (! sawSourceNameAnnotation && (name == defs.internalRunFunctionName || name == defs.initializeName || name == defs.postInitName || name == defs.userInitName || name == defs.addTriggersName || name == names.clinit || name.startsWith(defs.attributeGetPrefixName) || name.startsWith(defs.applyDefaultsPrefixName) || name.endsWith(defs.implFunctionSuffixName))) continue; // This should be merged with translateSymbol. // But that doesn't work for some unknown reason. FIXME Type type = translateType(l.head.type); String nameString = name.toString(); int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix); if (boundStringIndex != -1) { // this is a bound function // remove the bound suffix, and mark as bound name = names.fromString(nameString.substring(0, boundStringIndex)); flags |= JavafxFlags.BOUND; } MethodSymbol m = new MethodSymbol(flags, name, type, csym); csym.members_field.enter(m); } else if (l.head instanceof VarSymbol) { Type otype = l.head.type; if (otype.tag == CLASS) { TypeSymbol tsym = otype.tsym; Name flatname = ((ClassSymbol) tsym).flatname; Type deloc = defs.delocationize(flatname); if (deloc != null) { flags |= JavafxFlags.VARUSE_NEED_LOCATION; } } flags |= JavafxFlags.VARUSE_NEED_LOCATION_DETERMINED; Type type = translateType(otype); VarSymbol v = new VarSymbol(flags, name, type, csym); csym.members_field.enter(v); } else { l.head.flags_field = flags; csym.members_field.enter(translateSymbol(l.head)); } } } } private long flagsFromAnnotationsAndFlags(Symbol sym) { long initialFlags = sym.flags_field; long nonAccessFlags = initialFlags & ~JavafxFlags.JavafxAccessFlags; long accessFlags = initialFlags & JavafxFlags.JavafxAccessFlags; JavafxSymtab javafxSyms = (JavafxSymtab) this.syms; for (Attribute.Compound a : sym.getAnnotationMirrors()) { if (a.type.tsym.flatName() == javafxSyms.javafx_privateAnnotationType.tsym.flatName()) { accessFlags = Flags.PRIVATE; } else if (a.type.tsym.flatName() == javafxSyms.javafx_protectedAnnotationType.tsym.flatName()) { accessFlags = Flags.PROTECTED; } else if (a.type.tsym.flatName() == javafxSyms.javafx_packageAnnotationType.tsym.flatName()) { accessFlags = 0L; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicAnnotationType.tsym.flatName()) { accessFlags = Flags.PUBLIC; } else if (a.type.tsym.flatName() == javafxSyms.javafx_scriptPrivateAnnotationType.tsym.flatName()) { accessFlags = JavafxFlags.SCRIPT_PRIVATE; } } if (accessFlags == 0L) { accessFlags = JavafxFlags.PACKAGE_ACCESS; } return nonAccessFlags | accessFlags; } }
false
true
public void complete(Symbol sym) throws CompletionFailure { if (jreader.sourceCompleter == null) jreader.sourceCompleter = JavafxCompiler.instance(ctx); if (sym instanceof PackageSymbol) { PackageSymbol psym = (PackageSymbol) sym; PackageSymbol jpackage; if (psym == syms.unnamedPackage) jpackage = jreader.syms.unnamedPackage; else jpackage = jreader.enterPackage(psym.fullname); jpackage.complete(); if (psym.members_field == null) psym.members_field = new Scope(psym); for (Scope.Entry e = jpackage.members_field.elems; e != null; e = e.sibling) { if (e.sym instanceof ClassSymbol) { ClassSymbol jsym = (ClassSymbol) e.sym; if (jsym.name.endsWith(defs.interfaceSuffixName)) continue; JavafxClassSymbol csym = enterClass(jsym); psym.members_field.enter(csym); csym.classfile = jsym.classfile; csym.jsymbol = jsym; } } if (jpackage.exists()) psym.flags_field |= EXISTS; } else { sym.owner.complete(); JavafxClassSymbol csym = (JavafxClassSymbol) sym; ClassSymbol jsymbol = csym.jsymbol; if (jsymbol != null && jsymbol.classfile != null && jsymbol.classfile.getKind() == JavaFileObject.Kind.SOURCE && jsymbol.classfile.getName().endsWith(".fx")) { SourceCompleter fxSourceCompleter = JavafxCompiler.instance(ctx); fxSourceCompleter.complete(csym); return; } else { csym.jsymbol = jsymbol = jreader.loadClass(csym.flatname); } fixupFullname(csym, jsymbol); typeMap.put(jsymbol, csym); jsymbol.classfile = ((ClassSymbol) sym).classfile; ClassType ct = (ClassType)csym.type; ClassType jt = (ClassType)jsymbol.type; csym.members_field = new Scope(csym); // flags are derived from flag bits and access modifier annoations csym.flags_field = flagsFromAnnotationsAndFlags(jsymbol); ct.typarams_field = translateTypes(jt.typarams_field); ct.setEnclosingType(translateType(jt.getEnclosingType())); ct.supertype_field = translateType(jt.supertype_field); ListBuffer<Type> interfaces = new ListBuffer<Type>(); Type iface = null; if (jt.interfaces_field != null) { // true for ErrorType for (List<Type> it = jt.interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; else if (itype.tsym.name.endsWith(defs.interfaceSuffixName)) { iface = itype; iface.tsym.complete(); assert (csym.fullname.len + defs.interfaceSuffixName.len == ((ClassSymbol) itype.tsym).fullname.len) && ((ClassSymbol) itype.tsym).fullname.startsWith(csym.fullname); csym.flags_field |= JavafxFlags.COMPOUND_CLASS; } else { itype = translateType(itype); interfaces.append(itype); } } } if (iface != null) { for (List<Type> it = ((ClassType) iface.tsym.type).interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; else { itype = translateType(itype); interfaces.append(itype); csym.addSuperType(itype); } } } ct.interfaces_field = interfaces.toList(); // Now translate the members. // Do an initial "reverse" pass so we copy the order. List<Symbol> syms = List.nil(); for (Scope.Entry e = jsymbol.members_field.elems; e != null; e = e.sibling) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; syms = syms.prepend(e.sym); } handleSyms: for (List<Symbol> l = syms; l.nonEmpty(); l=l.tail) { Name name = l.head.name; long flags = flagsFromAnnotationsAndFlags(l.head); if ((flags & PRIVATE) != 0) continue; boolean sawSourceNameAnnotation = false; JavafxSymtab javafxSyms = (JavafxSymtab) this.syms; for (Attribute.Compound a : l.head.getAnnotationMirrors()) { if (a.type.tsym.flatName() == javafxSyms.javafx_staticAnnotationType.tsym.flatName()) { flags |= Flags.STATIC; } else if (a.type.tsym.flatName() == javafxSyms.javafx_defAnnotationType.tsym.flatName()) { flags |= JavafxFlags.IS_DEF; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicInitAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_INIT; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicReadAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_READ; } else if (a.type.tsym.flatName() == javafxSyms.javafx_inheritedAnnotationType.tsym.flatName()) { continue handleSyms; } else if (a.type.tsym.flatName() == javafxSyms.javafx_sourceNameAnnotationType.tsym.flatName()) { Attribute aa = a.member(name.table.value); Object sourceName = aa.getValue(); if (sourceName instanceof String) { name = names.fromString((String) sourceName); sawSourceNameAnnotation = true; } } } if (l.head instanceof MethodSymbol) { if (! sawSourceNameAnnotation && (name == defs.internalRunFunctionName || name == defs.initializeName || name == defs.postInitName || name == defs.userInitName || name == defs.addTriggersName || name == names.clinit || name.startsWith(defs.attributeGetPrefixName) || name.startsWith(defs.applyDefaultsPrefixName) || name.endsWith(defs.implFunctionSuffixName))) continue; // This should be merged with translateSymbol. // But that doesn't work for some unknown reason. FIXME Type type = translateType(l.head.type); String nameString = name.toString(); int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix); if (boundStringIndex != -1) { // this is a bound function // remove the bound suffix, and mark as bound name = names.fromString(nameString.substring(0, boundStringIndex)); flags |= JavafxFlags.BOUND; } MethodSymbol m = new MethodSymbol(flags, name, type, csym); csym.members_field.enter(m); } else if (l.head instanceof VarSymbol) { Type otype = l.head.type; if (otype.tag == CLASS) { TypeSymbol tsym = otype.tsym; Name flatname = ((ClassSymbol) tsym).flatname; Type deloc = defs.delocationize(flatname); if (deloc != null) { flags |= JavafxFlags.VARUSE_NEED_LOCATION; } } flags |= JavafxFlags.VARUSE_NEED_LOCATION_DETERMINED; Type type = translateType(otype); VarSymbol v = new VarSymbol(flags, name, type, csym); csym.members_field.enter(v); } else { l.head.flags_field = flags; csym.members_field.enter(translateSymbol(l.head)); } } } }
public void complete(Symbol sym) throws CompletionFailure { if (jreader.sourceCompleter == null) jreader.sourceCompleter = JavafxCompiler.instance(ctx); if (sym instanceof PackageSymbol) { PackageSymbol psym = (PackageSymbol) sym; PackageSymbol jpackage; if (psym == syms.unnamedPackage) jpackage = jreader.syms.unnamedPackage; else jpackage = jreader.enterPackage(psym.fullname); jpackage.complete(); if (psym.members_field == null) psym.members_field = new Scope(psym); for (Scope.Entry e = jpackage.members_field.elems; e != null; e = e.sibling) { if (e.sym instanceof ClassSymbol) { ClassSymbol jsym = (ClassSymbol) e.sym; if (jsym.name.endsWith(defs.interfaceSuffixName)) continue; JavafxClassSymbol csym = enterClass(jsym); psym.members_field.enter(csym); csym.classfile = jsym.classfile; csym.jsymbol = jsym; } } if (jpackage.exists()) psym.flags_field |= EXISTS; } else { sym.owner.complete(); JavafxClassSymbol csym = (JavafxClassSymbol) sym; ClassSymbol jsymbol = csym.jsymbol; if (jsymbol != null && jsymbol.classfile != null && jsymbol.classfile.getKind() == JavaFileObject.Kind.SOURCE && jsymbol.classfile.getName().endsWith(".fx")) { SourceCompleter fxSourceCompleter = JavafxCompiler.instance(ctx); fxSourceCompleter.complete(csym); return; } else { csym.jsymbol = jsymbol = jreader.loadClass(csym.flatname); } fixupFullname(csym, jsymbol); typeMap.put(jsymbol, csym); jsymbol.classfile = ((ClassSymbol) sym).classfile; ClassType ct = (ClassType)csym.type; ClassType jt = (ClassType)jsymbol.type; csym.members_field = new Scope(csym); // flags are derived from flag bits and access modifier annoations csym.flags_field = flagsFromAnnotationsAndFlags(jsymbol); ct.typarams_field = translateTypes(jt.typarams_field); ct.setEnclosingType(translateType(jt.getEnclosingType())); ct.supertype_field = translateType(jt.supertype_field); ListBuffer<Type> interfaces = new ListBuffer<Type>(); Type iface = null; if (jt.interfaces_field != null) { // true for ErrorType for (List<Type> it = jt.interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; else if ((csym.fullname.len + defs.interfaceSuffixName.len == ((ClassSymbol) itype.tsym).fullname.len) && ((ClassSymbol) itype.tsym).fullname.startsWith(csym.fullname) && itype.tsym.name.endsWith(defs.interfaceSuffixName)) { iface = itype; iface.tsym.complete(); csym.flags_field |= JavafxFlags.COMPOUND_CLASS; } else { itype = translateType(itype); interfaces.append(itype); } } } if (iface != null) { for (List<Type> it = ((ClassType) iface.tsym.type).interfaces_field; it.tail != null; it = it.tail) { Type itype = it.head; if (((ClassSymbol) itype.tsym).flatname == defs.fxObjectName) csym.flags_field |= JavafxFlags.FX_CLASS; else { itype = translateType(itype); interfaces.append(itype); csym.addSuperType(itype); } } } ct.interfaces_field = interfaces.toList(); // Now translate the members. // Do an initial "reverse" pass so we copy the order. List<Symbol> syms = List.nil(); for (Scope.Entry e = jsymbol.members_field.elems; e != null; e = e.sibling) { if ((e.sym.flags_field & SYNTHETIC) != 0) continue; syms = syms.prepend(e.sym); } handleSyms: for (List<Symbol> l = syms; l.nonEmpty(); l=l.tail) { Name name = l.head.name; long flags = flagsFromAnnotationsAndFlags(l.head); if ((flags & PRIVATE) != 0) continue; boolean sawSourceNameAnnotation = false; JavafxSymtab javafxSyms = (JavafxSymtab) this.syms; for (Attribute.Compound a : l.head.getAnnotationMirrors()) { if (a.type.tsym.flatName() == javafxSyms.javafx_staticAnnotationType.tsym.flatName()) { flags |= Flags.STATIC; } else if (a.type.tsym.flatName() == javafxSyms.javafx_defAnnotationType.tsym.flatName()) { flags |= JavafxFlags.IS_DEF; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicInitAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_INIT; } else if (a.type.tsym.flatName() == javafxSyms.javafx_publicReadAnnotationType.tsym.flatName()) { flags |= JavafxFlags.PUBLIC_READ; } else if (a.type.tsym.flatName() == javafxSyms.javafx_inheritedAnnotationType.tsym.flatName()) { continue handleSyms; } else if (a.type.tsym.flatName() == javafxSyms.javafx_sourceNameAnnotationType.tsym.flatName()) { Attribute aa = a.member(name.table.value); Object sourceName = aa.getValue(); if (sourceName instanceof String) { name = names.fromString((String) sourceName); sawSourceNameAnnotation = true; } } } if (l.head instanceof MethodSymbol) { if (! sawSourceNameAnnotation && (name == defs.internalRunFunctionName || name == defs.initializeName || name == defs.postInitName || name == defs.userInitName || name == defs.addTriggersName || name == names.clinit || name.startsWith(defs.attributeGetPrefixName) || name.startsWith(defs.applyDefaultsPrefixName) || name.endsWith(defs.implFunctionSuffixName))) continue; // This should be merged with translateSymbol. // But that doesn't work for some unknown reason. FIXME Type type = translateType(l.head.type); String nameString = name.toString(); int boundStringIndex = nameString.indexOf(JavafxDefs.boundFunctionDollarSuffix); if (boundStringIndex != -1) { // this is a bound function // remove the bound suffix, and mark as bound name = names.fromString(nameString.substring(0, boundStringIndex)); flags |= JavafxFlags.BOUND; } MethodSymbol m = new MethodSymbol(flags, name, type, csym); csym.members_field.enter(m); } else if (l.head instanceof VarSymbol) { Type otype = l.head.type; if (otype.tag == CLASS) { TypeSymbol tsym = otype.tsym; Name flatname = ((ClassSymbol) tsym).flatname; Type deloc = defs.delocationize(flatname); if (deloc != null) { flags |= JavafxFlags.VARUSE_NEED_LOCATION; } } flags |= JavafxFlags.VARUSE_NEED_LOCATION_DETERMINED; Type type = translateType(otype); VarSymbol v = new VarSymbol(flags, name, type, csym); csym.members_field.enter(v); } else { l.head.flags_field = flags; csym.members_field.enter(translateSymbol(l.head)); } } } }
diff --git a/src/com/dmdirc/ui/swing/textpane/TextPaneCanvas.java b/src/com/dmdirc/ui/swing/textpane/TextPaneCanvas.java index 570bed493..6e4831228 100644 --- a/src/com/dmdirc/ui/swing/textpane/TextPaneCanvas.java +++ b/src/com/dmdirc/ui/swing/textpane/TextPaneCanvas.java @@ -1,876 +1,876 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.ui.swing.textpane; import com.dmdirc.ui.messages.IRCTextAttribute; import com.dmdirc.ui.swing.textpane.TextPane.ClickType; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Toolkit; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextHitInfo; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.event.MouseInputListener; /** Canvas object to draw text. */ class TextPaneCanvas extends JPanel implements MouseInputListener, ComponentListener { /** * A version number for this class. It should be changed whenever the * class structure is changed (or anything else that would prevent * serialized objects being unserialized with the new class). */ private static final long serialVersionUID = 8; /** Hand cursor. */ private static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR); /** IRCDocument. */ private final IRCDocument document; /** parent textpane. */ private final TextPane textPane; /** Position -> TextLayout. */ private final Map<Rectangle, TextLayout> positions; /** TextLayout -> Line numbers. */ private final Map<TextLayout, LineInfo> textLayouts; /** Line height. */ private final int lineHeight; /** Selection event types. */ protected enum MouseEventType { /** Mouse clicked. */ CLICK, /** Mouse dragged. */ DRAG, /** Mouse released. */ RELEASE, } /** position of the scrollbar. */ private int scrollBarPosition; /** Start line of the selection. */ private int selStartLine; /** Start character of the selection. */ private int selStartChar; /** End line of the selection. */ private int selEndLine; /** End character of the selection. */ private int selEndChar; /** First visible line. */ private int firstVisibleLine; /** Last visible line. */ private int lastVisibleLine; /** Line wrapping cache. */ private final Map<Integer, Integer> lineWrap; /** * Creates a new text pane canvas. * * @param parent parent text pane for the canvas * @param document IRCDocument to be displayed */ public TextPaneCanvas(final TextPane parent, final IRCDocument document) { super(); this.document = document; scrollBarPosition = 0; lineHeight = getFont().getSize() + 2; textPane = parent; setDoubleBuffered(true); setOpaque(true); textLayouts = new HashMap<TextLayout, LineInfo>(); positions = new HashMap<Rectangle, TextLayout>(); lineWrap = new HashMap<Integer, Integer>(); addMouseListener(this); addMouseMotionListener(this); addComponentListener(this); } /** * Paints the text onto the canvas. * * @param graphics graphics object to draw onto */ @Override public void paintComponent(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final Map desktopHints = (Map) Toolkit.getDefaultToolkit(). getDesktopProperty("awt.font.desktophints"); if (desktopHints != null) { g.addRenderingHints(desktopHints); } final float formatWidth = getWidth() - 6; final float formatHeight = getHeight(); float drawPosY = formatHeight; int startLine = scrollBarPosition; int useStartLine; int useStartChar; int useEndLine; int useEndChar; int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; g.setColor(textPane.getBackground()); g.fill(g.getClipBounds()); textLayouts.clear(); positions.clear(); //check theres something to draw if (document.getNumLines() == 0) { setCursor(Cursor.getDefaultCursor()); return; } //check there is some space to draw in if (formatWidth < 1) { setCursor(Cursor.getDefaultCursor()); return; } // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } //sets the last visible line lastVisibleLine = startLine; firstVisibleLine = startLine; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines for (int i = startLine; i >= 0; i--) { float drawPosX; final AttributedCharacterIterator iterator = document.getLine(i). getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, g.getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); final int wrappedLine; //do we have the line wrapping in the cache? if (lineWrap.containsKey(i)) { //use it wrappedLine = lineWrap.get(i); } else { //get it and populate the cache wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart, paragraphEnd, formatWidth); lineWrap.put(i, wrappedLine); } if (wrappedLine > 1) { drawPosY -= lineHeight * wrappedLine; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= lineHeight; } else if (j != 0) { drawPosY += lineHeight; } // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 3; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY >= 0 || drawPosY <= formatHeight) { g.setColor(textPane.getForeground()); layout.draw(g, drawPosX, drawPosY + lineHeight / 2f); doHighlight(i, useStartLine, useEndLine, useStartChar, useEndChar, chars, layout, g, drawPosY, drawPosX); firstVisibleLine = i; textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle(0, (int) drawPosY, (int) formatWidth + 6, lineHeight), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= lineHeight * (wrappedLine - 1); } if (drawPosY <= 0) { - checkForLink(); break; } } + checkForLink(); } /** * Returns the number of timesa line will wrap. * * @param lineMeasurer LineBreakMeasurer to work out wrapping for * @param paragraphStart Start index of the paragraph * @param paragraphEnd End index of the paragraph * @param formatWidth Width to wrap at * * @return Number of times the line wraps */ private int getNumWrappedLines(final LineBreakMeasurer lineMeasurer, final int paragraphStart, final int paragraphEnd, final float formatWidth) { int wrappedLine = 0; while (lineMeasurer.getPosition() < paragraphEnd) { lineMeasurer.nextLayout(formatWidth); wrappedLine++; } lineMeasurer.setPosition(paragraphStart); return wrappedLine; } /** * Redraws the text that has been highlighted. * * @param line Line number * @param startLine Selection start line * @param endLine Selection end line * @param startChar Selection start char * @param endChar Selection end char * @param chars Number of characters so far in the line * @param layout Current line textlayout * @param g Graphics surface to draw highlight on * @param drawPosY current y location of the line * @param drawPosX current x location of the line */ private void doHighlight(final int line, final int startLine, final int endLine, final int startChar, final int endChar, final int chars, final TextLayout layout, final Graphics2D g, final float drawPosY, final float drawPosX) { //Does this line need highlighting? if (startLine <= line && endLine >= line) { int firstChar; int lastChar; // Determine the first char we care about if (startLine < line || startChar < chars) { firstChar = chars; } else { firstChar = startChar; } // ... And the last if (endLine > line || endChar > chars + layout.getCharacterCount()) { lastChar = chars + layout.getCharacterCount(); } else { lastChar = endChar; } // If the selection includes the chars we're showing if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) { final String text = textPane.getTextFromLine(line).substring(firstChar, lastChar); if (text.isEmpty()) { return; } final int trans = (int) (lineHeight / 2f + drawPosY); final AttributedString as = new AttributedString( textPane.getLine(line).getIterator(), firstChar, lastChar); as.addAttribute(TextAttribute.FOREGROUND, textPane.getBackground()); as.addAttribute(TextAttribute.BACKGROUND, textPane.getForeground()); final TextLayout newLayout = new TextLayout(as.getIterator(), g.getFontRenderContext()); final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars); if (firstChar != 0) { g.translate(shape.getBounds().getX(), 0); } newLayout.draw(g, drawPosX, trans); if (firstChar != 0) { g.translate(-1 * shape.getBounds().getX(), 0); } } } } /** * sets the position of the scroll bar, and repaints if required. * @param position scroll bar position */ protected void setScrollBarPosition(final int position) { if (scrollBarPosition != position) { scrollBarPosition = position; if (textPane.isVisible()) { repaint(); } } } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseClicked(final MouseEvent e) { String clickedText = ""; final int start; final int end; final LineInfo lineInfo = getClickPosition(getMousePosition()); if (lineInfo.getLine() != -1) { clickedText = textPane.getTextFromLine(lineInfo.getLine()); if (lineInfo.getIndex() == -1) { start = -1; end = -1; } else { final int[] extent = getSurroundingWordIndexes(clickedText, lineInfo.getIndex()); start = extent[0]; end = extent[1]; } if (e.getClickCount() == 2) { selStartLine = lineInfo.getLine(); selEndLine = lineInfo.getLine(); selStartChar = start; selEndChar = end; } else if (e.getClickCount() == 3) { selStartLine = lineInfo.getLine(); selEndLine = lineInfo.getLine(); selStartChar = 0; selEndChar = clickedText.length(); } } e.setSource(textPane); textPane.dispatchEvent(e); } /** * Returns the type of text this click represents. * * @param lineInfo Line info of click. * * @return Click type for specified position */ public ClickType getClickType(final LineInfo lineInfo) { if (lineInfo.getLine() != -1) { final AttributedCharacterIterator iterator = document.getLine(lineInfo.getLine()). getIterator(); iterator.setIndex(lineInfo.getIndex()); Object linkattr = iterator.getAttributes().get(IRCTextAttribute.HYPERLINK); if (linkattr instanceof String) { return ClickType.HYPERLINK; } linkattr = iterator.getAttributes().get(IRCTextAttribute.CHANNEL); if (linkattr instanceof String) { return ClickType.CHANNEL; } linkattr = iterator.getAttributes().get(IRCTextAttribute.NICKNAME); if (linkattr instanceof String) { return ClickType.NICKNAME; } } return ClickType.NORMAL; } /** * Returns the atrriute value for the specified location. * * @param lineInfo Specified location * * @return Specified value */ public Object getAttributeValueAtPoint(LineInfo lineInfo) { if (lineInfo.getLine() != -1) { final AttributedCharacterIterator iterator = document.getLine(lineInfo.getLine()). getIterator(); iterator.setIndex(lineInfo.getIndex()); Object linkattr = iterator.getAttributes().get(IRCTextAttribute.HYPERLINK); if (linkattr instanceof String) { return linkattr; } linkattr = iterator.getAttributes().get(IRCTextAttribute.CHANNEL); if (linkattr instanceof String) { return linkattr; } linkattr = iterator.getAttributes().get(IRCTextAttribute.NICKNAME); if (linkattr instanceof String) { return linkattr; } } return null; } /** * Returns the indexes for the word surrounding the index in the specified * string. * * @param text Text to get word from * @param index Index to get surrounding word * * @return Indexes of the word surrounding the index (start, end) */ protected int[] getSurroundingWordIndexes(final String text, final int index) { final int start = getSurroundingWordStart(text, index); final int end = getSurroundingWordEnd(text, index); if (start < 0 || end > text.length() || start > end) { return new int[]{0, 0}; } return new int[]{start, end}; } /** * Returns the start index for the word surrounding the index in the * specified string. * * @param text Text to get word from * @param index Index to get surrounding word * * @return Start index of the word surrounding the index */ private int getSurroundingWordStart(final String text, final int index) { int start = index; // Traverse backwards while (start > 0 && start < text.length() && text.charAt(start) != ' ') { start--; } if (start + 1 < text.length() && text.charAt(start) == ' ') { start++; } return start; } /** * Returns the end index for the word surrounding the index in the * specified string. * * @param text Text to get word from * @param index Index to get surrounding word * * @return End index of the word surrounding the index */ private int getSurroundingWordEnd(final String text, final int index) { int end = index; // And forwards while (end < text.length() && end > 0 && text.charAt(end) != ' ') { end++; } return end; } /** * {@inheritDoc} * * @param e Mouse event */ public void mousePressed(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { highlightEvent(MouseEventType.CLICK, e); } e.setSource(textPane); textPane.dispatchEvent(e); } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseReleased(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { highlightEvent(MouseEventType.RELEASE, e); } e.setSource(textPane); textPane.dispatchEvent(e); } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseDragged(final MouseEvent e) { if (e.getModifiersEx() == MouseEvent.BUTTON1_DOWN_MASK) { highlightEvent(MouseEventType.DRAG, e); } e.setSource(textPane); textPane.dispatchEvent(e); } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseEntered(final MouseEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseExited(final MouseEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Mouse event */ public void mouseMoved(final MouseEvent e) { checkForLink(); } /** Checks for a link under the cursor and sets appropriately. */ private void checkForLink() { final LineInfo info = getClickPosition(getMousePosition()); if (info.getLine() != -1 && document.getLine(info.getLine()) != null) { final AttributedCharacterIterator iterator = document.getLine(info.getLine()). getIterator(); if (info.getIndex() < iterator.getBeginIndex() || info.getIndex() > iterator.getEndIndex()) { return; } iterator.setIndex(info.getIndex()); Object linkattr = iterator.getAttributes().get(IRCTextAttribute.HYPERLINK); if (linkattr instanceof String) { setCursor(HAND_CURSOR); return; } linkattr = iterator.getAttributes().get(IRCTextAttribute.CHANNEL); if (linkattr instanceof String) { setCursor(HAND_CURSOR); return; } linkattr = iterator.getAttributes().get(IRCTextAttribute.NICKNAME); if (linkattr instanceof String) { setCursor(HAND_CURSOR); return; } } if (getCursor() == HAND_CURSOR) { setCursor(Cursor.getDefaultCursor()); } } /** * Sets the selection for the given event. * * @param type mouse event type * @param e responsible mouse event */ protected void highlightEvent(final MouseEventType type, final MouseEvent e) { if (isVisible()) { Point point = e.getLocationOnScreen(); SwingUtilities.convertPointFromScreen(point, this); if (!contains(point)) { final Rectangle bounds = getBounds(); final Point mousePos = e.getPoint(); if (mousePos.getX() < bounds.getX()) { point.setLocation(bounds.getX() + 3, point.getY()); } else if (mousePos.getX() > (bounds.getX() + bounds.getWidth())) { point.setLocation(bounds.getX() + bounds.getWidth() - 3, point.getY()); } if (mousePos.getY() < bounds.getY()) { point.setLocation(point.getX(), bounds.getY() + 6); } else if (mousePos.getY() > (bounds.getY() + bounds.getHeight())) { //Nice text selection behaviour //point.setLocation(point.getX(), bounds.getY() + // bounds.getHeight() - 6); point.setLocation(bounds.getX() + bounds.getWidth() - 3, bounds.getY() + bounds.getHeight() - 6); } } final LineInfo info = getClickPosition(point); if (info.getLine() == -1 && info.getPart() == -1 && contains(point)) { info.setLine(0); info.setPart(0); //Nice text selection behaviour //info.setIndex(getHitPosition(info.getLine(), info.getPart(), // point.x, 0)); info.setIndex(0); } if (info.getLine() != -1 && info.getPart() != -1) { if (type == MouseEventType.CLICK) { selStartLine = info.getLine(); selStartChar = info.getIndex(); } selEndLine = info.getLine(); selEndChar = info.getIndex(); repaint(); } } } /** * * Returns the line information from a mouse click inside the textpane. * * @param point mouse position * * @return line number, line part, position in whole line */ public LineInfo getClickPosition(final Point point) { int lineNumber = -1; int linePart = -1; int pos = 0; if (point != null) { for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (entry.getKey().contains(point)) { lineNumber = textLayouts.get(entry.getValue()).getLine(); linePart = textLayouts.get(entry.getValue()).getPart(); } } pos = getHitPosition(lineNumber, linePart, (int) point.getX(), (int) point.getY()); } return new LineInfo(lineNumber, linePart, pos); } /** * Returns the character index for a specified line and part for a specific hit position. * * @param lineNumber Line number * @param linePart Line part * @param x X position * @param y Y position * * @return Hit position */ private int getHitPosition(final int lineNumber, final int linePart, final int x, final int y) { int pos = 0; for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) { if (textLayouts.get(entry.getValue()).getLine() == lineNumber) { if (textLayouts.get(entry.getValue()).getPart() < linePart) { pos += entry.getValue().getCharacterCount(); } else if (textLayouts.get(entry.getValue()).getPart() == linePart) { final TextHitInfo hit = entry.getValue().hitTestChar(x - 6, y); pos += hit.getInsertionIndex(); } } } return pos; } /** * Returns the selected range info. * * @return Selected range info */ protected LinePosition getSelectedRange() { if (selStartLine > selEndLine) { // Swap both return new LinePosition(selEndLine, selEndChar, selStartLine, selStartChar); } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars return new LinePosition(selStartLine, selEndChar, selEndLine, selStartChar); } else { // Swap nothing return new LinePosition(selStartLine, selStartChar, selEndLine, selEndChar); } } /** Clears the selection. */ protected void clearSelection() { selEndLine = selStartLine; selEndChar = selStartChar; if (isVisible()) { repaint(); } } /** * Selects the specified region of text. * * @param position Line position */ public void setSelectedRange(final LinePosition position) { selStartLine = position.getStartLine(); selStartChar = position.getStartPos(); selEndLine = position.getEndLine(); selEndChar = position.getEndPos(); if (isVisible()) { repaint(); } } /** * Returns the first visible line. * * @return the line number of the first visible line */ public int getFirstVisibleLine() { return firstVisibleLine; } /** * Returns the last visible line. * * @return the line number of the last visible line */ public int getLastVisibleLine() { return lastVisibleLine; } /** * {@inheritDoc} * * @param e Component event */ public void componentResized(final ComponentEvent e) { //line wrap cache now invalid, clear and repaint lineWrap.clear(); if (isVisible()) { repaint(); } } /** * {@inheritDoc} * * @param e Component event */ public void componentMoved(final ComponentEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Component event */ public void componentShown(final ComponentEvent e) { //Ignore } /** * {@inheritDoc} * * @param e Component event */ public void componentHidden(final ComponentEvent e) { //Ignore } /** Clears the line wrapping cache. */ protected void clearWrapCache() { lineWrap.clear(); } }
false
true
public void paintComponent(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final Map desktopHints = (Map) Toolkit.getDefaultToolkit(). getDesktopProperty("awt.font.desktophints"); if (desktopHints != null) { g.addRenderingHints(desktopHints); } final float formatWidth = getWidth() - 6; final float formatHeight = getHeight(); float drawPosY = formatHeight; int startLine = scrollBarPosition; int useStartLine; int useStartChar; int useEndLine; int useEndChar; int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; g.setColor(textPane.getBackground()); g.fill(g.getClipBounds()); textLayouts.clear(); positions.clear(); //check theres something to draw if (document.getNumLines() == 0) { setCursor(Cursor.getDefaultCursor()); return; } //check there is some space to draw in if (formatWidth < 1) { setCursor(Cursor.getDefaultCursor()); return; } // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } //sets the last visible line lastVisibleLine = startLine; firstVisibleLine = startLine; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines for (int i = startLine; i >= 0; i--) { float drawPosX; final AttributedCharacterIterator iterator = document.getLine(i). getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, g.getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); final int wrappedLine; //do we have the line wrapping in the cache? if (lineWrap.containsKey(i)) { //use it wrappedLine = lineWrap.get(i); } else { //get it and populate the cache wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart, paragraphEnd, formatWidth); lineWrap.put(i, wrappedLine); } if (wrappedLine > 1) { drawPosY -= lineHeight * wrappedLine; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= lineHeight; } else if (j != 0) { drawPosY += lineHeight; } // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 3; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY >= 0 || drawPosY <= formatHeight) { g.setColor(textPane.getForeground()); layout.draw(g, drawPosX, drawPosY + lineHeight / 2f); doHighlight(i, useStartLine, useEndLine, useStartChar, useEndChar, chars, layout, g, drawPosY, drawPosX); firstVisibleLine = i; textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle(0, (int) drawPosY, (int) formatWidth + 6, lineHeight), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= lineHeight * (wrappedLine - 1); } if (drawPosY <= 0) { checkForLink(); break; } } }
public void paintComponent(final Graphics graphics) { final Graphics2D g = (Graphics2D) graphics; final Map desktopHints = (Map) Toolkit.getDefaultToolkit(). getDesktopProperty("awt.font.desktophints"); if (desktopHints != null) { g.addRenderingHints(desktopHints); } final float formatWidth = getWidth() - 6; final float formatHeight = getHeight(); float drawPosY = formatHeight; int startLine = scrollBarPosition; int useStartLine; int useStartChar; int useEndLine; int useEndChar; int paragraphStart; int paragraphEnd; LineBreakMeasurer lineMeasurer; g.setColor(textPane.getBackground()); g.fill(g.getClipBounds()); textLayouts.clear(); positions.clear(); //check theres something to draw if (document.getNumLines() == 0) { setCursor(Cursor.getDefaultCursor()); return; } //check there is some space to draw in if (formatWidth < 1) { setCursor(Cursor.getDefaultCursor()); return; } // Check the start line is in range if (startLine >= document.getNumLines()) { startLine = document.getNumLines() - 1; } if (startLine <= 0) { startLine = 0; } //sets the last visible line lastVisibleLine = startLine; firstVisibleLine = startLine; if (selStartLine > selEndLine) { // Swap both useStartLine = selEndLine; useStartChar = selEndChar; useEndLine = selStartLine; useEndChar = selStartChar; } else if (selStartLine == selEndLine && selStartChar > selEndChar) { // Just swap the chars useStartLine = selStartLine; useStartChar = selEndChar; useEndLine = selEndLine; useEndChar = selStartChar; } else { // Swap nothing useStartLine = selStartLine; useStartChar = selStartChar; useEndLine = selEndLine; useEndChar = selEndChar; } // Iterate through the lines for (int i = startLine; i >= 0; i--) { float drawPosX; final AttributedCharacterIterator iterator = document.getLine(i). getIterator(); paragraphStart = iterator.getBeginIndex(); paragraphEnd = iterator.getEndIndex(); lineMeasurer = new LineBreakMeasurer(iterator, g.getFontRenderContext()); lineMeasurer.setPosition(paragraphStart); final int wrappedLine; //do we have the line wrapping in the cache? if (lineWrap.containsKey(i)) { //use it wrappedLine = lineWrap.get(i); } else { //get it and populate the cache wrappedLine = getNumWrappedLines(lineMeasurer, paragraphStart, paragraphEnd, formatWidth); lineWrap.put(i, wrappedLine); } if (wrappedLine > 1) { drawPosY -= lineHeight * wrappedLine; } int j = 0; int chars = 0; // Loop through each wrapped line while (lineMeasurer.getPosition() < paragraphEnd) { final TextLayout layout = lineMeasurer.nextLayout(formatWidth); // Calculate the Y offset if (wrappedLine == 1) { drawPosY -= lineHeight; } else if (j != 0) { drawPosY += lineHeight; } // Calculate the initial X position if (layout.isLeftToRight()) { drawPosX = 3; } else { drawPosX = formatWidth - layout.getAdvance(); } // Check if the target is in range if (drawPosY >= 0 || drawPosY <= formatHeight) { g.setColor(textPane.getForeground()); layout.draw(g, drawPosX, drawPosY + lineHeight / 2f); doHighlight(i, useStartLine, useEndLine, useStartChar, useEndChar, chars, layout, g, drawPosY, drawPosX); firstVisibleLine = i; textLayouts.put(layout, new LineInfo(i, j)); positions.put(new Rectangle(0, (int) drawPosY, (int) formatWidth + 6, lineHeight), layout); } j++; chars += layout.getCharacterCount(); } if (j > 1) { drawPosY -= lineHeight * (wrappedLine - 1); } if (drawPosY <= 0) { break; } } checkForLink(); }
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/virtual/CompositeDestinationFilter.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/virtual/CompositeDestinationFilter.java index a61a6a1ba..22f3209e3 100644 --- a/activemq-core/src/main/java/org/apache/activemq/broker/region/virtual/CompositeDestinationFilter.java +++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/virtual/CompositeDestinationFilter.java @@ -1,84 +1,88 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker.region.virtual; import java.util.Collection; import java.util.Iterator; import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.broker.region.Destination; import org.apache.activemq.broker.region.DestinationFilter; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.Message; import org.apache.activemq.filter.MessageEvaluationContext; import org.apache.activemq.filter.NonCachedMessageEvaluationContext; /** * Represents a composite {@link Destination} where send()s are replicated to * each Destination instance. * * @version $Revision$ */ public class CompositeDestinationFilter extends DestinationFilter { private Collection forwardDestinations; private boolean forwardOnly; private boolean copyMessage; public CompositeDestinationFilter(Destination next, Collection forwardDestinations, boolean forwardOnly, boolean copyMessage) { super(next); this.forwardDestinations = forwardDestinations; this.forwardOnly = forwardOnly; this.copyMessage = copyMessage; } public void send(ProducerBrokerExchange context, Message message) throws Exception { MessageEvaluationContext messageContext = null; for (Iterator iter = forwardDestinations.iterator(); iter.hasNext();) { ActiveMQDestination destination = null; Object value = iter.next(); if (value instanceof FilteredDestination) { FilteredDestination filteredDestination = (FilteredDestination)value; if (messageContext == null) { messageContext = new NonCachedMessageEvaluationContext(); messageContext.setMessageReference(message); } messageContext.setDestination(filteredDestination.getDestination()); if (filteredDestination.matches(messageContext)) { destination = filteredDestination.getDestination(); } } else if (value instanceof ActiveMQDestination) { destination = (ActiveMQDestination)value; } if (destination == null) { continue; } + Message forwarded_message; if (copyMessage) { - message = message.copy(); - message.setDestination(destination); + forwarded_message = message.copy(); + forwarded_message.setDestination(destination); + } + else { + forwarded_message = message; } - send(context, message, destination); + send(context, forwarded_message, destination); } if (!forwardOnly) { super.send(context, message); } } }
false
true
public void send(ProducerBrokerExchange context, Message message) throws Exception { MessageEvaluationContext messageContext = null; for (Iterator iter = forwardDestinations.iterator(); iter.hasNext();) { ActiveMQDestination destination = null; Object value = iter.next(); if (value instanceof FilteredDestination) { FilteredDestination filteredDestination = (FilteredDestination)value; if (messageContext == null) { messageContext = new NonCachedMessageEvaluationContext(); messageContext.setMessageReference(message); } messageContext.setDestination(filteredDestination.getDestination()); if (filteredDestination.matches(messageContext)) { destination = filteredDestination.getDestination(); } } else if (value instanceof ActiveMQDestination) { destination = (ActiveMQDestination)value; } if (destination == null) { continue; } if (copyMessage) { message = message.copy(); message.setDestination(destination); } send(context, message, destination); } if (!forwardOnly) { super.send(context, message); } }
public void send(ProducerBrokerExchange context, Message message) throws Exception { MessageEvaluationContext messageContext = null; for (Iterator iter = forwardDestinations.iterator(); iter.hasNext();) { ActiveMQDestination destination = null; Object value = iter.next(); if (value instanceof FilteredDestination) { FilteredDestination filteredDestination = (FilteredDestination)value; if (messageContext == null) { messageContext = new NonCachedMessageEvaluationContext(); messageContext.setMessageReference(message); } messageContext.setDestination(filteredDestination.getDestination()); if (filteredDestination.matches(messageContext)) { destination = filteredDestination.getDestination(); } } else if (value instanceof ActiveMQDestination) { destination = (ActiveMQDestination)value; } if (destination == null) { continue; } Message forwarded_message; if (copyMessage) { forwarded_message = message.copy(); forwarded_message.setDestination(destination); } else { forwarded_message = message; } send(context, forwarded_message, destination); } if (!forwardOnly) { super.send(context, message); } }
diff --git a/CSipSimple/src/com/csipsimple/service/OutgoingCall.java b/CSipSimple/src/com/csipsimple/service/OutgoingCall.java index fa7d0f9f..5c52ba69 100644 --- a/CSipSimple/src/com/csipsimple/service/OutgoingCall.java +++ b/CSipSimple/src/com/csipsimple/service/OutgoingCall.java @@ -1,137 +1,137 @@ /** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.telephony.PhoneNumberUtils; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.api.SipProfile; import com.csipsimple.api.SipUri; import com.csipsimple.models.Filter; import com.csipsimple.ui.outgoingcall.OutgoingCallChooser; import com.csipsimple.utils.CallHandlerPlugin; import com.csipsimple.utils.Log; import com.csipsimple.utils.PreferencesProviderWrapper; import java.util.Map; public class OutgoingCall extends BroadcastReceiver { private static final String THIS_FILE = "Outgoing RCV"; private Context context; private PreferencesProviderWrapper prefsWrapper; private static Long gsmCallHandlerId = null; public static String ignoreNext = ""; @Override public void onReceive(Context aContext, Intent intent) { context = aContext; String action = intent.getAction(); String number = getResultData(); //String full_number = intent.getStringExtra("android.phone.extra.ORIGINAL_URI"); // Escape if no number if (number == null) { return; } // If emergency number transmit as if we were not there if(PhoneNumberUtils.isEmergencyNumber(number)) { ignoreNext = ""; setResultData(number); return; } prefsWrapper = new PreferencesProviderWrapper(context); // If we already passed the outgoing call receiver or we are not integrated, do as if we were not there if ( ignoreNext.equalsIgnoreCase(number) || !prefsWrapper.getPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_DIALER, true) || action == null) { Log.d(THIS_FILE, "Our selector disabled, or Mobile chosen in our selector, send to tel"); ignoreNext = ""; setResultData(number); return; } // If this is an outgoing call with a valid number if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL) ) { //Compute remote apps that could receive the outgoing call itnent through our api Map<String, String> potentialHandlers = CallHandlerPlugin.getAvailableCallHandlers(context); Log.d(THIS_FILE, "We have " + potentialHandlers.size() + " potential handlers"); // If sip is there or there is at least 2 call handlers (if only one we assume that's the embed gsm one !) if(prefsWrapper.isValidConnectionForOutgoing() || potentialHandlers.size() > 1) { // Just to be sure of what is incoming : sanitize phone number (in case of it was not properly done by dialer // Or by a third party app number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); // We can now check that the number that we want to call can be managed by something different than gsm plugin // Note that this is now possible because we cache filters. if(gsmCallHandlerId == null) { gsmCallHandlerId = CallHandlerPlugin.getAccountIdForCallHandler(aContext, (new ComponentName(aContext, com.csipsimple.plugins.telephony.CallHandler.class)).flattenToString()); } if(gsmCallHandlerId != SipProfile.INVALID_ID) { if(Filter.isMustCallNumber(aContext, gsmCallHandlerId, number)) { Log.d(THIS_FILE, "Filtering to force pass number along"); // Pass the call to pstn handle - setResultData(number); + setResultData(Filter.rewritePhoneNumber(aContext, gsmCallHandlerId, number)); return; } } // Launch activity to choose what to do with this call Intent outgoingCallChooserIntent = new Intent(Intent.ACTION_CALL); // Add csipsimple protocol :) outgoingCallChooserIntent.setData(SipUri.forgeSipUri(SipManager.PROTOCOL_SIP, number)); outgoingCallChooserIntent.setClassName(context, OutgoingCallChooser.class.getName()); outgoingCallChooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(THIS_FILE, "Start outgoing call chooser for CSipSimple"); context.startActivity(outgoingCallChooserIntent); // We will treat this by ourselves setResultData(null); return; } } Log.d(THIS_FILE, "Can't use SIP, pass number along"); // Pass the call to pstn handle setResultData(number); return; } }
true
true
public void onReceive(Context aContext, Intent intent) { context = aContext; String action = intent.getAction(); String number = getResultData(); //String full_number = intent.getStringExtra("android.phone.extra.ORIGINAL_URI"); // Escape if no number if (number == null) { return; } // If emergency number transmit as if we were not there if(PhoneNumberUtils.isEmergencyNumber(number)) { ignoreNext = ""; setResultData(number); return; } prefsWrapper = new PreferencesProviderWrapper(context); // If we already passed the outgoing call receiver or we are not integrated, do as if we were not there if ( ignoreNext.equalsIgnoreCase(number) || !prefsWrapper.getPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_DIALER, true) || action == null) { Log.d(THIS_FILE, "Our selector disabled, or Mobile chosen in our selector, send to tel"); ignoreNext = ""; setResultData(number); return; } // If this is an outgoing call with a valid number if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL) ) { //Compute remote apps that could receive the outgoing call itnent through our api Map<String, String> potentialHandlers = CallHandlerPlugin.getAvailableCallHandlers(context); Log.d(THIS_FILE, "We have " + potentialHandlers.size() + " potential handlers"); // If sip is there or there is at least 2 call handlers (if only one we assume that's the embed gsm one !) if(prefsWrapper.isValidConnectionForOutgoing() || potentialHandlers.size() > 1) { // Just to be sure of what is incoming : sanitize phone number (in case of it was not properly done by dialer // Or by a third party app number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); // We can now check that the number that we want to call can be managed by something different than gsm plugin // Note that this is now possible because we cache filters. if(gsmCallHandlerId == null) { gsmCallHandlerId = CallHandlerPlugin.getAccountIdForCallHandler(aContext, (new ComponentName(aContext, com.csipsimple.plugins.telephony.CallHandler.class)).flattenToString()); } if(gsmCallHandlerId != SipProfile.INVALID_ID) { if(Filter.isMustCallNumber(aContext, gsmCallHandlerId, number)) { Log.d(THIS_FILE, "Filtering to force pass number along"); // Pass the call to pstn handle setResultData(number); return; } } // Launch activity to choose what to do with this call Intent outgoingCallChooserIntent = new Intent(Intent.ACTION_CALL); // Add csipsimple protocol :) outgoingCallChooserIntent.setData(SipUri.forgeSipUri(SipManager.PROTOCOL_SIP, number)); outgoingCallChooserIntent.setClassName(context, OutgoingCallChooser.class.getName()); outgoingCallChooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(THIS_FILE, "Start outgoing call chooser for CSipSimple"); context.startActivity(outgoingCallChooserIntent); // We will treat this by ourselves setResultData(null); return; } } Log.d(THIS_FILE, "Can't use SIP, pass number along"); // Pass the call to pstn handle setResultData(number); return; }
public void onReceive(Context aContext, Intent intent) { context = aContext; String action = intent.getAction(); String number = getResultData(); //String full_number = intent.getStringExtra("android.phone.extra.ORIGINAL_URI"); // Escape if no number if (number == null) { return; } // If emergency number transmit as if we were not there if(PhoneNumberUtils.isEmergencyNumber(number)) { ignoreNext = ""; setResultData(number); return; } prefsWrapper = new PreferencesProviderWrapper(context); // If we already passed the outgoing call receiver or we are not integrated, do as if we were not there if ( ignoreNext.equalsIgnoreCase(number) || !prefsWrapper.getPreferenceBooleanValue(SipConfigManager.INTEGRATE_WITH_DIALER, true) || action == null) { Log.d(THIS_FILE, "Our selector disabled, or Mobile chosen in our selector, send to tel"); ignoreNext = ""; setResultData(number); return; } // If this is an outgoing call with a valid number if (action.equals(Intent.ACTION_NEW_OUTGOING_CALL) ) { //Compute remote apps that could receive the outgoing call itnent through our api Map<String, String> potentialHandlers = CallHandlerPlugin.getAvailableCallHandlers(context); Log.d(THIS_FILE, "We have " + potentialHandlers.size() + " potential handlers"); // If sip is there or there is at least 2 call handlers (if only one we assume that's the embed gsm one !) if(prefsWrapper.isValidConnectionForOutgoing() || potentialHandlers.size() > 1) { // Just to be sure of what is incoming : sanitize phone number (in case of it was not properly done by dialer // Or by a third party app number = PhoneNumberUtils.convertKeypadLettersToDigits(number); number = PhoneNumberUtils.stripSeparators(number); // We can now check that the number that we want to call can be managed by something different than gsm plugin // Note that this is now possible because we cache filters. if(gsmCallHandlerId == null) { gsmCallHandlerId = CallHandlerPlugin.getAccountIdForCallHandler(aContext, (new ComponentName(aContext, com.csipsimple.plugins.telephony.CallHandler.class)).flattenToString()); } if(gsmCallHandlerId != SipProfile.INVALID_ID) { if(Filter.isMustCallNumber(aContext, gsmCallHandlerId, number)) { Log.d(THIS_FILE, "Filtering to force pass number along"); // Pass the call to pstn handle setResultData(Filter.rewritePhoneNumber(aContext, gsmCallHandlerId, number)); return; } } // Launch activity to choose what to do with this call Intent outgoingCallChooserIntent = new Intent(Intent.ACTION_CALL); // Add csipsimple protocol :) outgoingCallChooserIntent.setData(SipUri.forgeSipUri(SipManager.PROTOCOL_SIP, number)); outgoingCallChooserIntent.setClassName(context, OutgoingCallChooser.class.getName()); outgoingCallChooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Log.d(THIS_FILE, "Start outgoing call chooser for CSipSimple"); context.startActivity(outgoingCallChooserIntent); // We will treat this by ourselves setResultData(null); return; } } Log.d(THIS_FILE, "Can't use SIP, pass number along"); // Pass the call to pstn handle setResultData(number); return; }
diff --git a/src/org/gridlab/gridsphere/provider/portletui/beans/TableBean.java b/src/org/gridlab/gridsphere/provider/portletui/beans/TableBean.java index 9df795cbd..6eeba0425 100644 --- a/src/org/gridlab/gridsphere/provider/portletui/beans/TableBean.java +++ b/src/org/gridlab/gridsphere/provider/portletui/beans/TableBean.java @@ -1,355 +1,356 @@ /* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.provider.portletui.beans; import org.gridlab.gridsphere.portlet.PortletResponse; import org.gridlab.gridsphere.provider.portletui.model.DefaultTableModel; /** * A <code>TableBean</code> provides a table element */ public class TableBean extends BaseComponentBean implements TagBean { public static final String CURRENT_PAGE = "tablepage"; public static final String SHOW_ALL = "showall"; public static final String SHOW_PAGES = "showpages"; protected DefaultTableModel defaultModel = null; protected String cellSpacing = null; protected String cellPadding = null; protected String border = null; protected String background = null; protected String width = null; protected String align = null; protected String valign = null; protected int currentPage = 0; protected boolean isSortable = false; protected boolean isZebra = false; protected String sortableId = "t1"; private int rowCount = 0; private int maxRows = -1; private boolean showall = false; private boolean isJSR = true; protected PortletResponse res = null; protected String uris = ""; protected String uriString = ""; protected String title = null; protected int numEntries = 0; /** * Constructs a default table bean */ public TableBean() { super(); } /** * Constructs a table bean with a supplied CSS style * * @param cssStyle the CSS style */ public TableBean(String cssStyle) { this.cssClass = cssStyle; } /** * Sets the default table model for this table * * @param defaultModel the table model */ public void setTableModel(DefaultTableModel defaultModel) { this.defaultModel = defaultModel; } /** * Returns the default table model * * @return the default table model */ public DefaultTableModel getTableModel() { return defaultModel; } public int getNumEntries() { return numEntries; } public void setNumEntries(int numEntries) { this.numEntries = numEntries; } /** * Sets the table width * * @param width the table width */ public void setWidth(String width) { this.width = width; } /** * Returns the table width * * @return the table width */ public String getWidth() { return width; } /** * Sets the table alignment e.g. "left", "center" or "right" * * @param align the table alignment */ public void setAlign(String align) { this.align = align; } /** * Returns the table alignment e.g. "left", "center" or "right" * * @return the table alignment */ public String getAlign() { return align; } /** * Returns the table vertical alignment e.g. 'top', 'bottom' * * @return the table vertical alignment */ public String getValign() { return valign; } /** * Sets the table horizontal alignment, e.g. 'top', 'bottom' * * @param valign the tables horizontal alignment */ public void setValign(String valign) { this.valign = valign; } /** * Sets the table cell spacing * * @param cellSpacing the table cell spacing */ public void setCellSpacing(String cellSpacing) { this.cellSpacing = cellSpacing; } /** * Returns the table cell spacing * * @return the table cell spacing */ public String getCellSpacing() { return cellSpacing; } /** * Sets the table cell spacing * * @param cellPadding the table cell padding */ public void setCellPadding(String cellPadding) { this.cellPadding = cellPadding; } /** * Returns the table cell padding * * @return the table cell padding */ public String getCellPadding() { return cellPadding; } /** * Sets the table background * * @param background the table background */ public void setBackground(String background) { this.background = background; } /** * Returns the table background * * @return the table background */ public String getBackground() { return background; } /** * Sets the table border * * @param border the table border */ public void setBorder(String border) { this.border = border; } /** * Returns the tableborder * * @return the table border */ public String getBorder() { return border; } public void setZebra(boolean isZebra) { this.isZebra = isZebra; } public boolean getZebra() { return isZebra; } public void setSortable(boolean isSortable) { this.isSortable = isSortable; } public boolean getSortable() { return isSortable; } public void setSortableID(String sortableId) { this.sortableId = sortableId; } public String getSortableID() { return sortableId; } public void setRowCount(int rowCount) { this.rowCount = rowCount; } public int getRowCount() { return rowCount; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getCurrentPage() { return currentPage; } public void setMaxRows(int maxRows) { this.maxRows = maxRows; } public int getMaxRows() { return maxRows; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isShowall() { return showall; } public void setShowall(boolean showall) { this.showall = showall; } public void setURIString(String uriString) { this.uriString = uriString; } public void setJSR(boolean isJSR) { this.isJSR = isJSR; } public String toStartString() { StringBuffer sb = new StringBuffer(); if (isSortable) { sb.append("<table class=\"sortable\" id=\"" + sortableId + "\" "); } else { sb.append("<table" + getFormattedCss()); } if (cellSpacing != null) sb.append(" cellspacing=\"" + cellSpacing + "\" "); if (cellPadding != null) sb.append(" cellpadding=\"" + cellPadding + "\" "); if (border != null) sb.append(" border=\"" + border + "\" "); if (width != null) sb.append(" width=\"" + width + "\" "); if (align != null) sb.append(" align=\"" + align + "\" "); /// Removed for XHTML 1.0 Strict compliance /* if (valign != null) { sb.append(" valign=\"" + valign + "\" "); } */ sb.append(">"); if (title != null) sb.append("<caption>" + title + "</caption>"); if (defaultModel != null) sb.append(defaultModel.toStartString()); return sb.toString(); } public String toEndString() { StringBuffer sb = new StringBuffer(); sb.append("</table>"); String uri = ""; if (showall) { uri = uriString; sb.append("<p>"); // added for XHTML 1.0 Strict compliance String showPages = TableBean.SHOW_PAGES; if (isJSR) showPages = "rp_" + showPages; sb.append("<a href=\"" + uri + "&amp;" + showPages + "\">" + this.getLocalizedText("SHOW_PAGES") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance } if (maxRows > 0) { - int numpages = (numEntries != 0) ? (numEntries / maxRows + 1) : rowCount / maxRows + 1; + int numpages = (numEntries != 0) ? (numEntries / maxRows + numEntries % maxRows) : rowCount / maxRows + rowCount % maxRows; + System.err.println("numpages = " + numpages); int dispPage = currentPage + 1; if ((dispPage == numpages) && (numpages == 1)) return sb.toString(); int c = 0; //System.err.println("maxrows=" + maxRows + " numEntries=" + numEntries + " rowCount=" + rowCount + " numpages=" + numpages); sb.append("<p>"); // added for XHTML 1.0 Strict compliance sb.append(this.getLocalizedText("PAGE") + dispPage + this.getLocalizedText("OUT_OF_PAGES") + numpages); for (int i = 0; i < numpages; i++) { c = i + 1; if (c == dispPage) { sb.append(" | <b>" + c + "</b>"); } else { // create an actionlink uris = uriString; //System.err.println("uri = " + uris); String curPage = TableBean.CURRENT_PAGE; if (isJSR) curPage = "rp_" + curPage; uri = uris + "&amp;" + curPage + "=" + i; sb.append(" | " + "<a href=\"" + uri + "\">" + c + "</a>"); } } uri = uriString; sb.append(" | "); String showall = TableBean.SHOW_ALL; if (isJSR) showall = "rp_" + TableBean.SHOW_ALL; sb.append("<a href=\"" + uri + "&amp;" + showall + "\">" + this.getLocalizedText("SHOW_ALL") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance rowCount = 0; } return sb.toString(); } }
true
true
public String toEndString() { StringBuffer sb = new StringBuffer(); sb.append("</table>"); String uri = ""; if (showall) { uri = uriString; sb.append("<p>"); // added for XHTML 1.0 Strict compliance String showPages = TableBean.SHOW_PAGES; if (isJSR) showPages = "rp_" + showPages; sb.append("<a href=\"" + uri + "&amp;" + showPages + "\">" + this.getLocalizedText("SHOW_PAGES") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance } if (maxRows > 0) { int numpages = (numEntries != 0) ? (numEntries / maxRows + 1) : rowCount / maxRows + 1; int dispPage = currentPage + 1; if ((dispPage == numpages) && (numpages == 1)) return sb.toString(); int c = 0; //System.err.println("maxrows=" + maxRows + " numEntries=" + numEntries + " rowCount=" + rowCount + " numpages=" + numpages); sb.append("<p>"); // added for XHTML 1.0 Strict compliance sb.append(this.getLocalizedText("PAGE") + dispPage + this.getLocalizedText("OUT_OF_PAGES") + numpages); for (int i = 0; i < numpages; i++) { c = i + 1; if (c == dispPage) { sb.append(" | <b>" + c + "</b>"); } else { // create an actionlink uris = uriString; //System.err.println("uri = " + uris); String curPage = TableBean.CURRENT_PAGE; if (isJSR) curPage = "rp_" + curPage; uri = uris + "&amp;" + curPage + "=" + i; sb.append(" | " + "<a href=\"" + uri + "\">" + c + "</a>"); } } uri = uriString; sb.append(" | "); String showall = TableBean.SHOW_ALL; if (isJSR) showall = "rp_" + TableBean.SHOW_ALL; sb.append("<a href=\"" + uri + "&amp;" + showall + "\">" + this.getLocalizedText("SHOW_ALL") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance rowCount = 0; } return sb.toString(); }
public String toEndString() { StringBuffer sb = new StringBuffer(); sb.append("</table>"); String uri = ""; if (showall) { uri = uriString; sb.append("<p>"); // added for XHTML 1.0 Strict compliance String showPages = TableBean.SHOW_PAGES; if (isJSR) showPages = "rp_" + showPages; sb.append("<a href=\"" + uri + "&amp;" + showPages + "\">" + this.getLocalizedText("SHOW_PAGES") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance } if (maxRows > 0) { int numpages = (numEntries != 0) ? (numEntries / maxRows + numEntries % maxRows) : rowCount / maxRows + rowCount % maxRows; System.err.println("numpages = " + numpages); int dispPage = currentPage + 1; if ((dispPage == numpages) && (numpages == 1)) return sb.toString(); int c = 0; //System.err.println("maxrows=" + maxRows + " numEntries=" + numEntries + " rowCount=" + rowCount + " numpages=" + numpages); sb.append("<p>"); // added for XHTML 1.0 Strict compliance sb.append(this.getLocalizedText("PAGE") + dispPage + this.getLocalizedText("OUT_OF_PAGES") + numpages); for (int i = 0; i < numpages; i++) { c = i + 1; if (c == dispPage) { sb.append(" | <b>" + c + "</b>"); } else { // create an actionlink uris = uriString; //System.err.println("uri = " + uris); String curPage = TableBean.CURRENT_PAGE; if (isJSR) curPage = "rp_" + curPage; uri = uris + "&amp;" + curPage + "=" + i; sb.append(" | " + "<a href=\"" + uri + "\">" + c + "</a>"); } } uri = uriString; sb.append(" | "); String showall = TableBean.SHOW_ALL; if (isJSR) showall = "rp_" + TableBean.SHOW_ALL; sb.append("<a href=\"" + uri + "&amp;" + showall + "\">" + this.getLocalizedText("SHOW_ALL") + "</a>"); sb.append("</p>"); // added for XHTML 1.0 Strict compliance rowCount = 0; } return sb.toString(); }
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryView.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryView.java index c2548a9c3..499a7715b 100644 --- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryView.java +++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/history/GenericHistoryView.java @@ -1,682 +1,687 @@ /******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ui.history; import java.util.*; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.jface.action.*; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.*; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.history.IFileHistoryProvider; import org.eclipse.team.internal.ui.*; import org.eclipse.team.ui.history.*; import org.eclipse.ui.*; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.ide.ResourceUtil; import org.eclipse.ui.part.*; public class GenericHistoryView extends ViewPart implements IHistoryView { class PageContainer { private Page page; private SubActionBars subBars; public PageContainer(Page page) { this.page = page; } public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } public SubActionBars getSubBars() { return subBars; } public void setSubBars(SubActionBars subBars) { this.subBars = subBars; } } /** * The pagebook control, or <code>null</code> if not initialized. */ private PageBook book; /** * View actions */ private Action refreshAction; private Action linkWithEditorAction; private Action pinAction; /** * The page container for the default page. */ private PageContainer defaultPageContainer; /** * The current page container */ PageContainer currentPageContainer; /** * The drop target + drop target listener */ DropTarget dropTarget; GenericHistoryDropAdapter dropAdapter; /** * Keeps track of the last selected element (either by selecting or opening an editor) */ private Object lastSelectedElement; private IPartListener partListener = new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) { if (part == GenericHistoryView.this) editorActivated(getViewSite().getPage().getActiveEditor()); } public void partOpened(IWorkbenchPart part) { if (part == GenericHistoryView.this) editorActivated(getViewSite().getPage().getActiveEditor()); } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } }; private IPartListener2 partListener2 = new IPartListener2() { public void partActivated(IWorkbenchPartReference ref) { } public void partBroughtToTop(IWorkbenchPartReference ref) { } public void partClosed(IWorkbenchPartReference ref) { } public void partDeactivated(IWorkbenchPartReference ref) { } public void partOpened(IWorkbenchPartReference ref) { } public void partHidden(IWorkbenchPartReference ref) { } public void partVisible(IWorkbenchPartReference ref) { if (ref.getPart(true) == GenericHistoryView.this) editorActivated(getViewSite().getPage().getActiveEditor()); } public void partInputChanged(IWorkbenchPartReference ref) { } }; private ISelectionListener selectionListener = new ISelectionListener() { public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structSelection = (IStructuredSelection) selection; //Always take the first element - this is not intended to work with multiple selection //Also, hang on to this selection for future use in case the history view is not visible lastSelectedElement = structSelection.getFirstElement(); if (!isLinkingEnabled() || !checkIfPageIsVisible()) { return; } if (lastSelectedElement != null){ Object resource = Utils.getAdapter(lastSelectedElement, IResource.class); if (resource != null) itemDropped((IResource) resource, false); else itemDropped(lastSelectedElement, false); //reset lastSelectedElement lastSelectedElement = null; } } } }; private boolean linkingEnabled; private boolean viewPinned; /** * Refreshes the global actions for the active page. */ void refreshGlobalActionHandlers() { // Clear old actions. IActionBars bars = getViewSite().getActionBars(); bars.clearGlobalActionHandlers(); // Set new actions. Map newActionHandlers = currentPageContainer.getSubBars().getGlobalActionHandlers(); if (newActionHandlers != null) { Set keys = newActionHandlers.entrySet(); Iterator iter = keys.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); bars.setGlobalActionHandler((String) entry.getKey(), (IAction) entry.getValue()); } } //add refresh action handler from history view bars.setGlobalActionHandler(ActionFactory.REFRESH.getId(), refreshAction); } public void createPartControl(Composite parent) { // Create the page book. book = new PageBook(parent, SWT.NONE); this.linkingEnabled = TeamUIPlugin.getPlugin().getPreferenceStore().getBoolean(IFileHistoryConstants.PREF_GENERIC_HISTORYVIEW_EDITOR_LINKING); // Create the default page rec. defaultPageContainer = createDefaultPage(book); //Contribute toolbars configureToolbars(getViewSite().getActionBars()); //add global action handler getViewSite().getActionBars().setGlobalActionHandler(ActionFactory.REFRESH.getId(), refreshAction); //initialize the drag and drop initDragAndDrop(); // Show the default page showPageRec(defaultPageContainer); // add listener for editor page activation - this is to support editor // linking getSite().getPage().addPartListener(partListener); getSite().getPage().addPartListener(partListener2); // add listener for selections getSite().getPage().addSelectionListener(selectionListener); } private void configureToolbars(IActionBars actionBars) { pinAction = new Action(TeamUIMessages.GenericHistoryView_PinCurrentHistory, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_PINNED)) { public void run() { if (isChecked()) { //uncheck editor linking linkWithEditorAction.setChecked(false); setLinkingEnabled(false); } setViewPinned(isChecked()); } }; pinAction.setChecked(isViewPinned()); pinAction.setToolTipText(TeamUIMessages.GenericHistoryView_0); refreshAction = new Action(TeamUIMessages.GenericHistoryView_Refresh, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_REFRESH)) { public void run() { ((IHistoryPage) currentPageContainer.getPage()).refresh(); } }; refreshAction.setToolTipText(TeamUIMessages.GenericHistoryView_RefreshTooltip); refreshAction.setEnabled(true); linkWithEditorAction = new Action(TeamUIMessages.GenericHistoryView_LinkWithEditor, TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_LINK_WITH)) { public void run() { if (isChecked()) { // uncheck pinned pinAction.setChecked(false); setViewPinned(false); } setLinkingEnabled(isViewPinned() ? false : isChecked()); } }; linkWithEditorAction.setChecked(isLinkingEnabled()); linkWithEditorAction.setToolTipText(TeamUIMessages.GenericHistoryView_LinkWithTooltip); //Create the local tool bar IToolBarManager tbm = actionBars.getToolBarManager(); tbm.add(new Separator("historyView")); //$NON-NLS-1$ tbm.appendToGroup("historyView", refreshAction); //$NON-NLS-1$ tbm.appendToGroup("historyView", linkWithEditorAction); //$NON-NLS-1$ tbm.appendToGroup("historyView", pinAction); //$NON-NLS-1$ tbm.update(false); } boolean isLinkingEnabled() { return linkingEnabled; } /** * Enabled linking to the active editor * @param enabled flag indiciating whether linking is enabled */ public void setLinkingEnabled(boolean enabled) { this.linkingEnabled = enabled; // remember the last setting in the dialog settings TeamUIPlugin.getPlugin().getPreferenceStore().setValue(IFileHistoryConstants.PREF_GENERIC_HISTORYVIEW_EDITOR_LINKING, enabled); // if turning linking on, update the selection to correspond to the active editor if (enabled) { editorActivated(getSite().getPage().getActiveEditor()); } } /** * Sets the current view pinned * @param b */ void setViewPinned(boolean pinned) { this.viewPinned = pinned; } /** * Adds drag and drop support to the history view. */ void initDragAndDrop() { int ops = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; Transfer[] transfers = new Transfer[] {ResourceTransfer.getInstance(), PluginTransfer.getInstance()}; dropTarget = new DropTarget(book, ops); dropTarget.setTransfer(transfers); dropAdapter = new GenericHistoryDropAdapter(this); dropTarget.addDropListener(dropAdapter); } public void setFocus() { if (isLinkingEnabled()){ if (lastSelectedElement != null){ if (lastSelectedElement instanceof IEditorPart){ editorActivated((IEditorPart) lastSelectedElement); } else { Object resource = Utils.getAdapter(lastSelectedElement, IResource.class); if (resource != null) itemDropped((IResource) resource, false); else itemDropped(lastSelectedElement, false); } //reset lastSelectedElement to null to prevent updating history view if it just gets focus lastSelectedElement = null; } } if (currentPageContainer.page instanceof IPage){ ((IPage) currentPageContainer.page).setFocus(); } } /** * Shows page contained in the given page record in this view. The page record must * be one from this pagebook view. * <p> * The <code>PageBookView</code> implementation of this method asks the * pagebook control to show the given page's control, and records that the * given page is now current. Subclasses may extend. * </p> * * @param pageContainer the page record containing the page to show */ protected void showPageRec(PageContainer pageContainer) { // If already showing do nothing if (currentPageContainer == pageContainer) return; // If the page is the same, just set activeRec to pageRec if (currentPageContainer != null && pageContainer != null && currentPageContainer == pageContainer) { currentPageContainer = pageContainer; return; } // Hide old page. if (currentPageContainer != null) { currentPageContainer.getSubBars().deactivate(); //give the current page a chance to dispose currentPageContainer.getPage().dispose(); currentPageContainer.getSubBars().dispose(); } // Show new page. currentPageContainer = pageContainer; Control pageControl = currentPageContainer.getPage().getControl(); if (pageControl != null && !pageControl.isDisposed()) { // Verify that the page control is not disposed // If we are closing, it may have already been disposed book.showPage(pageControl); currentPageContainer.getSubBars().activate(); refreshGlobalActionHandlers(); // Update action bars. getViewSite().getActionBars().updateActionBars(); } } /** * Initializes the given page with a page site. * <p> * Subclasses should call this method after * the page is created but before creating its * controls. * </p> * <p> * Subclasses may override * </p> * @param page The page to initialize */ protected PageSite initPage(IPageBookViewPage page) { try { PageSite site = new PageSite(getViewSite()); page.init(site); return site; } catch (PartInitException e) { TeamUIPlugin.log(e); } return null; } public IHistoryPage itemDropped(Object object, boolean refresh) { //check to see if history view is visible - if it's not, don't bother //going to the trouble of fetching the history if (!this.getSite().getPage().isPartVisible(this)) return null; IResource resource = Utils.getResource(object); if (resource != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, resource.getName(), refresh); if (existingPage != null){ return existingPage; } //now check to see if this view is pinned IHistoryPage pinnedPage = checkForPinnedView(object, resource.getName(), refresh); if (pinnedPage != null) return pinnedPage; //check to see if resource is managed RepositoryProvider teamProvider = RepositoryProvider.getProvider(resource.getProject()); //couldn't find a repo provider; try showing it in a local page Object tempPageSource = null; if (teamProvider == null){ tempPageSource = new LocalHistoryPageSource(); } else { IFileHistoryProvider fileHistory = teamProvider.getFileHistoryProvider(); if (fileHistory != null) { tempPageSource = Utils.getAdapter(fileHistory, IHistoryPageSource.class,true); } if (tempPageSource == null) { tempPageSource = Utils.getAdapter(teamProvider, IHistoryPageSource.class,true); } } if (tempPageSource instanceof IHistoryPageSource) { IHistoryPageSource pageSource = (IHistoryPageSource) tempPageSource; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; - if (!((IHistoryPage) tempPageContainer.getPage()).isValidInput(resource)) { + IHistoryPage page = (IHistoryPage) tempPageContainer.getPage(); + if (!page.isValidInput(resource)) { tempPageContainer = createPage(pageSource, resource); + if (tempPageContainer == null) + page = null; + else + page = (IHistoryPage) tempPageContainer.getPage(); } - if (tempPageContainer != null) { - if (((IHistoryPage) tempPageContainer.getPage()).setInput(resource)){ - ((HistoryPage) tempPageContainer.getPage()).setHistoryView(this); - setContentDescription(resource.getName()); + if (page != null) { + if (page.setInput(resource)){ + ((HistoryPage) page).setHistoryView(this); + setContentDescription(page.getName()); showPageRec(tempPageContainer); - return (IHistoryPage) tempPageContainer.getPage(); + return page; } } else { showPageRec(defaultPageContainer); } } } } else if (object != null){ IHistoryPageSource historyPageSource = (IHistoryPageSource) Utils.getAdapter(object, IHistoryPageSource.class); //Check to see that this object can be adapted to an IHistoryPageSource, else //we don't know how to display it if (historyPageSource == null) return null; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; if (!((IHistoryPage) tempPageContainer.getPage()).isValidInput(object)) { tempPageContainer = createPage(historyPageSource, object); } if (tempPageContainer != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (existingPage != null){ return existingPage; } IHistoryPage pinnedPage = checkForPinnedView(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (pinnedPage != null) return pinnedPage; if (((IHistoryPage) tempPageContainer.getPage()).setInput(object)){ ((HistoryPage) tempPageContainer.getPage()).setHistoryView(this); setContentDescription(((IHistoryPage) tempPageContainer.getPage()).getName()); showPageRec(tempPageContainer); return (IHistoryPage) tempPageContainer.getPage(); } } else { showPageRec(defaultPageContainer); } } } return null; } private IHistoryPage checkForPinnedView(Object object, String objectName, boolean refresh) { if (isViewPinned()) { try { IViewPart view = null; //check to see if a view already contains this object String id = VIEW_ID + System.currentTimeMillis(); IHistoryPage page = searchHistoryViewsForObject(object, refresh); if (page != null) return page; //check to see if an unpinned version of the history view exists GenericHistoryView historyView = findUnpinnedHistoryView(); if (historyView != null){ getSite().getPage().activate(historyView); return historyView.itemDropped(object, refresh); } view = getSite().getPage().showView(VIEW_ID, id, IWorkbenchPage.VIEW_CREATE); getSite().getPage().activate(view); if (view instanceof GenericHistoryView) return ((GenericHistoryView) view).itemDropped(object, refresh); } catch (PartInitException e) { } } return null; } private IHistoryPage checkForExistingPage(Object object, String objectName, boolean refresh) { //first check to see if the main history view contains the current resource if (currentPageContainer != null && ((IHistoryPage)currentPageContainer.getPage()).getInput() != null){ if (((IHistoryPage)currentPageContainer.getPage()).getInput().equals(object)){ //current page contains object, so just refresh it IHistoryPage tempPage =((IHistoryPage)currentPageContainer.getPage()); if (refresh) tempPage.refresh(); return tempPage; } } return searchHistoryViewsForObject(object, refresh); } private IHistoryPage searchHistoryViewsForObject(Object object, boolean refresh) { IWorkbenchPage page = getSite().getPage(); IViewReference[] historyViews = page.getViewReferences(); for (int i = 0; i < historyViews.length; i++) { if (historyViews[i].getId().equals(VIEW_ID)){ IViewPart historyView = historyViews[i].getView(true); if (historyView != null){ IHistoryPage historyPage = ((IHistoryView)historyView).getHistoryPage(); if (historyPage != null){ Object input = historyPage.getInput(); if (input != null && input.equals(object)){ //this view already contains the file, so just reuse it getSite().getPage().bringToTop(historyView); return ((GenericHistoryView) historyView).itemDropped(object, refresh); } } } } } return null; } private GenericHistoryView findUnpinnedHistoryView(){ IWorkbenchPage page = getSite().getPage(); IViewReference[] historyViews = page.getViewReferences(); for (int i = 0; i < historyViews.length; i++) { if (historyViews[i].getId().equals(VIEW_ID)){ IViewPart historyView = historyViews[i].getView(false); if (!((GenericHistoryView)historyView).isViewPinned()) return (GenericHistoryView) historyView; } } return null; } boolean isViewPinned() { return viewPinned; } private PageContainer createPage(IHistoryPageSource participant, Object object) { Page page = participant.createPage(object); PageSite site = initPage(page); ((IHistoryPage) page).setSite(new WorkbenchHistoryPageSite(this, page.getSite())); page.createControl(book); PageContainer container = new PageContainer(page); container.setSubBars((SubActionBars) site.getActionBars()); return container; } protected PageContainer createDefaultPage(PageBook book) { GenericHistoryViewDefaultPage page = new GenericHistoryViewDefaultPage(); PageSite site = initPage(page); page.createControl(book); PageContainer container = new PageContainer(page); container.setSubBars((SubActionBars) site.getActionBars()); return container; } /** * An editor has been activated. Fetch the history if the file is shared and the history view * is visible in the current page. * * @param editor the active editor */ protected void editorActivated(IEditorPart editor) { //If this history view is not visible, keep track of this editor //for future use if (editor != null && !checkIfPageIsVisible()) lastSelectedElement = editor; //Only fetch contents if the view is shown in the current page. if (editor == null || !isLinkingEnabled() || !checkIfPageIsVisible() || isViewPinned()) { return; } IEditorInput input = editor.getEditorInput(); IFile file = ResourceUtil.getFile(input); if (file != null) { itemDropped(file, false); /* don't fetch if already cached */ } //see if it adapts to an IHistoryPageSource Object pageSource = Utils.getAdapter(input, IHistoryPageSource.class); if (pageSource != null) itemDropped(input, false); } private boolean checkIfPageIsVisible() { return getViewSite().getPage().isPartVisible(this); } public void dispose() { super.dispose(); //Remove the drop listener if (dropTarget != null && !dropTarget.isDisposed()) dropTarget.removeDropListener(dropAdapter); //Call dispose on current and default pages currentPageContainer.getPage().dispose(); defaultPageContainer.getPage().dispose(); currentPageContainer = null; defaultPageContainer = null; //Remove the part listeners getSite().getPage().removePartListener(partListener); getSite().getPage().removePartListener(partListener2); //Remove the selection listener getSite().getPage().removeSelectionListener(selectionListener); } public IHistoryPage showHistoryFor(Object object) { return itemDropped(object, true); } public IHistoryPage getHistoryPage() { if (currentPageContainer != null && currentPageContainer.getPage() != null) return (IHistoryPage) currentPageContainer.getPage(); return (IHistoryPage) defaultPageContainer.getPage(); } /** * Updates the content description of the view with the passed * in string. * @param description */ public void updateContentDescription(String description){ setContentDescription(description); } }
false
true
public IHistoryPage itemDropped(Object object, boolean refresh) { //check to see if history view is visible - if it's not, don't bother //going to the trouble of fetching the history if (!this.getSite().getPage().isPartVisible(this)) return null; IResource resource = Utils.getResource(object); if (resource != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, resource.getName(), refresh); if (existingPage != null){ return existingPage; } //now check to see if this view is pinned IHistoryPage pinnedPage = checkForPinnedView(object, resource.getName(), refresh); if (pinnedPage != null) return pinnedPage; //check to see if resource is managed RepositoryProvider teamProvider = RepositoryProvider.getProvider(resource.getProject()); //couldn't find a repo provider; try showing it in a local page Object tempPageSource = null; if (teamProvider == null){ tempPageSource = new LocalHistoryPageSource(); } else { IFileHistoryProvider fileHistory = teamProvider.getFileHistoryProvider(); if (fileHistory != null) { tempPageSource = Utils.getAdapter(fileHistory, IHistoryPageSource.class,true); } if (tempPageSource == null) { tempPageSource = Utils.getAdapter(teamProvider, IHistoryPageSource.class,true); } } if (tempPageSource instanceof IHistoryPageSource) { IHistoryPageSource pageSource = (IHistoryPageSource) tempPageSource; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; if (!((IHistoryPage) tempPageContainer.getPage()).isValidInput(resource)) { tempPageContainer = createPage(pageSource, resource); } if (tempPageContainer != null) { if (((IHistoryPage) tempPageContainer.getPage()).setInput(resource)){ ((HistoryPage) tempPageContainer.getPage()).setHistoryView(this); setContentDescription(resource.getName()); showPageRec(tempPageContainer); return (IHistoryPage) tempPageContainer.getPage(); } } else { showPageRec(defaultPageContainer); } } } } else if (object != null){ IHistoryPageSource historyPageSource = (IHistoryPageSource) Utils.getAdapter(object, IHistoryPageSource.class); //Check to see that this object can be adapted to an IHistoryPageSource, else //we don't know how to display it if (historyPageSource == null) return null; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; if (!((IHistoryPage) tempPageContainer.getPage()).isValidInput(object)) { tempPageContainer = createPage(historyPageSource, object); } if (tempPageContainer != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (existingPage != null){ return existingPage; } IHistoryPage pinnedPage = checkForPinnedView(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (pinnedPage != null) return pinnedPage; if (((IHistoryPage) tempPageContainer.getPage()).setInput(object)){ ((HistoryPage) tempPageContainer.getPage()).setHistoryView(this); setContentDescription(((IHistoryPage) tempPageContainer.getPage()).getName()); showPageRec(tempPageContainer); return (IHistoryPage) tempPageContainer.getPage(); } } else { showPageRec(defaultPageContainer); } } } return null; }
public IHistoryPage itemDropped(Object object, boolean refresh) { //check to see if history view is visible - if it's not, don't bother //going to the trouble of fetching the history if (!this.getSite().getPage().isPartVisible(this)) return null; IResource resource = Utils.getResource(object); if (resource != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, resource.getName(), refresh); if (existingPage != null){ return existingPage; } //now check to see if this view is pinned IHistoryPage pinnedPage = checkForPinnedView(object, resource.getName(), refresh); if (pinnedPage != null) return pinnedPage; //check to see if resource is managed RepositoryProvider teamProvider = RepositoryProvider.getProvider(resource.getProject()); //couldn't find a repo provider; try showing it in a local page Object tempPageSource = null; if (teamProvider == null){ tempPageSource = new LocalHistoryPageSource(); } else { IFileHistoryProvider fileHistory = teamProvider.getFileHistoryProvider(); if (fileHistory != null) { tempPageSource = Utils.getAdapter(fileHistory, IHistoryPageSource.class,true); } if (tempPageSource == null) { tempPageSource = Utils.getAdapter(teamProvider, IHistoryPageSource.class,true); } } if (tempPageSource instanceof IHistoryPageSource) { IHistoryPageSource pageSource = (IHistoryPageSource) tempPageSource; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; IHistoryPage page = (IHistoryPage) tempPageContainer.getPage(); if (!page.isValidInput(resource)) { tempPageContainer = createPage(pageSource, resource); if (tempPageContainer == null) page = null; else page = (IHistoryPage) tempPageContainer.getPage(); } if (page != null) { if (page.setInput(resource)){ ((HistoryPage) page).setHistoryView(this); setContentDescription(page.getName()); showPageRec(tempPageContainer); return page; } } else { showPageRec(defaultPageContainer); } } } } else if (object != null){ IHistoryPageSource historyPageSource = (IHistoryPageSource) Utils.getAdapter(object, IHistoryPageSource.class); //Check to see that this object can be adapted to an IHistoryPageSource, else //we don't know how to display it if (historyPageSource == null) return null; //If a current page exists, see if it can handle the dropped item if (currentPageContainer.getPage() instanceof IHistoryPage) { PageContainer tempPageContainer = currentPageContainer; if (!((IHistoryPage) tempPageContainer.getPage()).isValidInput(object)) { tempPageContainer = createPage(historyPageSource, object); } if (tempPageContainer != null) { //check to see if this resource is alreadu being displayed in another page IHistoryPage existingPage = checkForExistingPage(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (existingPage != null){ return existingPage; } IHistoryPage pinnedPage = checkForPinnedView(object, ((IHistoryPage) tempPageContainer.getPage()).getName(), refresh); if (pinnedPage != null) return pinnedPage; if (((IHistoryPage) tempPageContainer.getPage()).setInput(object)){ ((HistoryPage) tempPageContainer.getPage()).setHistoryView(this); setContentDescription(((IHistoryPage) tempPageContainer.getPage()).getName()); showPageRec(tempPageContainer); return (IHistoryPage) tempPageContainer.getPage(); } } else { showPageRec(defaultPageContainer); } } } return null; }
diff --git a/src/com/android/contacts/widget/PinnedHeaderListView.java b/src/com/android/contacts/widget/PinnedHeaderListView.java index 80db26f18..5893ac661 100644 --- a/src/com/android/contacts/widget/PinnedHeaderListView.java +++ b/src/com/android/contacts/widget/PinnedHeaderListView.java @@ -1,222 +1,221 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.widget; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.AbsListView.OnScrollListener; /** * A ListView that maintains a header pinned at the top of the list. The * pinned header can be pushed up and dissolved as needed. */ public class PinnedHeaderListView extends ListView implements OnScrollListener { /** * Adapter interface. The list adapter must implement this interface. */ public interface PinnedHeaderAdapter { /** * Pinned header state: don't show the header. */ public static final int PINNED_HEADER_GONE = 0; /** * Pinned header state: show the header at the top of the list. */ public static final int PINNED_HEADER_VISIBLE = 1; /** * Pinned header state: show the header. If the header extends beyond * the bottom of the first shown element, push it up and clip. */ public static final int PINNED_HEADER_PUSHED_UP = 2; /** * Creates the pinned header view. */ View createPinnedHeaderView(ViewGroup parent); /** * Computes the desired state of the pinned header for the given * position of the first visible list item. Allowed return values are * {@link #PINNED_HEADER_GONE}, {@link #PINNED_HEADER_VISIBLE} or * {@link #PINNED_HEADER_PUSHED_UP}. */ int getPinnedHeaderState(int position); /** * Configures the pinned header view to match the first visible list item. * * @param header pinned header view. * @param position position of the first visible list item. * @param alpha fading of the header view, between 0 and 255. */ void configurePinnedHeader(View header, int position, int alpha); } private static final int MAX_ALPHA = 255; private PinnedHeaderAdapter mAdapter; private View mHeaderView; private boolean mHeaderViewVisible; private float mHeaderOffset; private int mHeaderViewWidth; private int mHeaderViewHeight; private OnScrollListener mOnScrollListener; private boolean mHeaderViewConfigured; public PinnedHeaderListView(Context context) { super(context); } public PinnedHeaderListView(Context context, AttributeSet attrs) { super(context, attrs); super.setOnScrollListener(this); } public PinnedHeaderListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); super.setOnScrollListener(this); } public void setPinnedHeaderView(View view) { mHeaderView = view; // Disable vertical fading when the pinned header is present // TODO change ListView to allow separate measures for top and bottom fading edge; // in this particular case we would like to disable the top, but not the bottom edge. if (mHeaderView != null) { setFadingEdgeLength(0); } mHeaderViewConfigured = false; requestLayout(); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); mAdapter = (PinnedHeaderAdapter)adapter; View headerView = mAdapter.createPinnedHeaderView(this); setPinnedHeaderView(headerView); } @Override public void setOnScrollListener(OnScrollListener onScrollListener) { mOnScrollListener = onScrollListener; super.setOnScrollListener(this); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); if (mHeaderView != null) { if (!mHeaderViewConfigured) { configureHeaderView(getFirstVisiblePosition() - getHeaderViewsCount()); } measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec); mHeaderViewWidth = mHeaderView.getMeasuredWidth(); mHeaderViewHeight = mHeaderView.getMeasuredHeight(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mHeaderView != null) { if (!mHeaderViewConfigured) { configureHeaderView(getFirstVisiblePosition() - getHeaderViewsCount()); } mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight); } } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { configureHeaderView(firstVisibleItem - getHeaderViewsCount()); if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, firstVisibleItem, visibleItemCount, totalItemCount); } } public void onScrollStateChanged(AbsListView view, int scrollState) { if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(this, scrollState); } } public void configureHeaderView(int position) { if (mHeaderView == null) { return; } int state = mAdapter.getPinnedHeaderState(position); switch (state) { case PinnedHeaderAdapter.PINNED_HEADER_GONE: { mHeaderViewVisible = false; break; } case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: { mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA); mHeaderOffset = 0; mHeaderViewVisible = true; break; } case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: { - View firstView = getChildAt(0); - int bottom = firstView.getBottom(); - int headerHeight = mHeaderViewHeight; - int alpha; - int y; - if (bottom < headerHeight) { - y = (bottom - headerHeight); - alpha = MAX_ALPHA * (headerHeight + y) / headerHeight; - } else { - y = 0; - alpha = MAX_ALPHA; + int y = 0; + int alpha = MAX_ALPHA; + if (getChildCount() != 0) { + View firstView = getChildAt(0); + int bottom = firstView.getBottom(); + int headerHeight = mHeaderViewHeight; + if (bottom < headerHeight) { + y = (bottom - headerHeight); + alpha = MAX_ALPHA * (headerHeight + y) / headerHeight; + } } mAdapter.configurePinnedHeader(mHeaderView, position, alpha); mHeaderOffset = y; mHeaderViewVisible = true; break; } } mHeaderViewConfigured = true; } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); if (mHeaderViewVisible) { canvas.save(); canvas.translate(0, mHeaderOffset); drawChild(canvas, mHeaderView, getDrawingTime()); canvas.restore(); } } }
true
true
public void configureHeaderView(int position) { if (mHeaderView == null) { return; } int state = mAdapter.getPinnedHeaderState(position); switch (state) { case PinnedHeaderAdapter.PINNED_HEADER_GONE: { mHeaderViewVisible = false; break; } case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: { mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA); mHeaderOffset = 0; mHeaderViewVisible = true; break; } case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: { View firstView = getChildAt(0); int bottom = firstView.getBottom(); int headerHeight = mHeaderViewHeight; int alpha; int y; if (bottom < headerHeight) { y = (bottom - headerHeight); alpha = MAX_ALPHA * (headerHeight + y) / headerHeight; } else { y = 0; alpha = MAX_ALPHA; } mAdapter.configurePinnedHeader(mHeaderView, position, alpha); mHeaderOffset = y; mHeaderViewVisible = true; break; } } mHeaderViewConfigured = true; }
public void configureHeaderView(int position) { if (mHeaderView == null) { return; } int state = mAdapter.getPinnedHeaderState(position); switch (state) { case PinnedHeaderAdapter.PINNED_HEADER_GONE: { mHeaderViewVisible = false; break; } case PinnedHeaderAdapter.PINNED_HEADER_VISIBLE: { mAdapter.configurePinnedHeader(mHeaderView, position, MAX_ALPHA); mHeaderOffset = 0; mHeaderViewVisible = true; break; } case PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP: { int y = 0; int alpha = MAX_ALPHA; if (getChildCount() != 0) { View firstView = getChildAt(0); int bottom = firstView.getBottom(); int headerHeight = mHeaderViewHeight; if (bottom < headerHeight) { y = (bottom - headerHeight); alpha = MAX_ALPHA * (headerHeight + y) / headerHeight; } } mAdapter.configurePinnedHeader(mHeaderView, position, alpha); mHeaderOffset = y; mHeaderViewVisible = true; break; } } mHeaderViewConfigured = true; }
diff --git a/components/src/main/java/com/googlecode/wicketelements/components/module/Module.java b/components/src/main/java/com/googlecode/wicketelements/components/module/Module.java index 50ba8b5..d8428b5 100644 --- a/components/src/main/java/com/googlecode/wicketelements/components/module/Module.java +++ b/components/src/main/java/com/googlecode/wicketelements/components/module/Module.java @@ -1,57 +1,57 @@ package com.googlecode.wicketelements.components.module; import com.googlecode.jbp.common.requirements.ParamRequirements; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.markup.html.CSSPackageResource; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.border.Border; import org.apache.wicket.markup.html.link.AbstractLink; import org.apache.wicket.model.AbstractReadOnlyModel; import org.apache.wicket.model.IModel; public class Module extends Border { private boolean expanded = true; private WebMarkupContainer content; public Module(final String id, final IModel<?> titleModelParam) { super(id, titleModelParam); ParamRequirements.INSTANCE.requireNotNull(titleModelParam, "A module must have a title model. Parameter 'titleModelParam' must not be null."); init(titleModelParam); } private void init(final IModel<?> titleModelParam) { add(CSSPackageResource.getHeaderContribution(Module.class, "Module.css", "screen, projection")); setOutputMarkupId(true); content = new WebMarkupContainer("content"); content.add(getBodyContainer()); add(content); final AbstractLink headerLink = new AjaxFallbackLink("header") { @Override public void onClick(final AjaxRequestTarget target) { expanded = !expanded; target.addComponent(Module.this); } }; //do not use setVisible to hide or show the body, as hidden components in forms would not use validation anymore. content.add(new AttributeAppender("class", true, new AbstractReadOnlyModel<Object>() { @Override public Object getObject() { return expanded ? "displayBlock" : "displayNone"; } - }, ";")); + }, " ")); headerLink.add(new Label("title", titleModelParam)); add(headerLink); } public boolean isExpanded() { return expanded; } public void setExpanded(final boolean expandedParam) { expanded = expandedParam; } }
true
true
private void init(final IModel<?> titleModelParam) { add(CSSPackageResource.getHeaderContribution(Module.class, "Module.css", "screen, projection")); setOutputMarkupId(true); content = new WebMarkupContainer("content"); content.add(getBodyContainer()); add(content); final AbstractLink headerLink = new AjaxFallbackLink("header") { @Override public void onClick(final AjaxRequestTarget target) { expanded = !expanded; target.addComponent(Module.this); } }; //do not use setVisible to hide or show the body, as hidden components in forms would not use validation anymore. content.add(new AttributeAppender("class", true, new AbstractReadOnlyModel<Object>() { @Override public Object getObject() { return expanded ? "displayBlock" : "displayNone"; } }, ";")); headerLink.add(new Label("title", titleModelParam)); add(headerLink); }
private void init(final IModel<?> titleModelParam) { add(CSSPackageResource.getHeaderContribution(Module.class, "Module.css", "screen, projection")); setOutputMarkupId(true); content = new WebMarkupContainer("content"); content.add(getBodyContainer()); add(content); final AbstractLink headerLink = new AjaxFallbackLink("header") { @Override public void onClick(final AjaxRequestTarget target) { expanded = !expanded; target.addComponent(Module.this); } }; //do not use setVisible to hide or show the body, as hidden components in forms would not use validation anymore. content.add(new AttributeAppender("class", true, new AbstractReadOnlyModel<Object>() { @Override public Object getObject() { return expanded ? "displayBlock" : "displayNone"; } }, " ")); headerLink.add(new Label("title", titleModelParam)); add(headerLink); }
diff --git a/src/org/startsmall/openalarm/handler/FireAlarm.java b/src/org/startsmall/openalarm/handler/FireAlarm.java index af84830..34ea38c 100755 --- a/src/org/startsmall/openalarm/handler/FireAlarm.java +++ b/src/org/startsmall/openalarm/handler/FireAlarm.java @@ -1,417 +1,417 @@ /** * @file FireAlarm.java * @author josh <yenliangl at gmail dot com> * @date Tue Nov 3 20:33:08 2009 * * @brief An activity that is launched when an alarm goes off. * * */ package org.startsmall.openalarm; import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.ContentValues; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.Vibrator; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.RingtonePreference; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import android.text.method.DigitsKeyListener; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; import java.io.FileDescriptor; import java.util.Calendar; public class FireAlarm extends Activity { // MediaPlayer enters Prepared state and now a // Handler should be setup to stop playback of // ringtone after some period of time. private static class StopPlayback implements Handler.Callback { @Override public boolean handleMessage(Message msg) { FireAlarm handler; if (msg.obj instanceof FireAlarm) { handler = (FireAlarm)msg.obj; } else { return false; } switch (msg.what) { case MESSAGE_ID_STOP_PLAYBACK: // This callback is executed because user doesn't // tell me what to do, i.e., dimiss or snooze. I decide // to snooze it or when the FireAlarm is paused. handler.snoozeAlarm(); handler.finish(); return true; default: break; } return true; } } private static class OnPlaybackErrorListener implements MediaPlayer.OnErrorListener { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.d(TAG, "===> onError(): " + what + "====> " + extra); return true; } } private static final String TAG = "FireAlarm"; private static final String EXTRA_KEY_VIBRATE = "vibrate"; private static final String EXTRA_KEY_RINGTONE = "ringtone"; private static final String EXTRA_KEY_SNOOZE_DURATION = "snooze_duration"; private static final int DEFAULT_SNOOZE_DURATION = 2; // 2 minutes private static final int MESSAGE_ID_STOP_PLAYBACK = 1; private static final float IN_CALL_VOLUME = 0.125f; private static final int PLAYBACK_TIMEOUT = 60000; // 1 minute private MediaPlayer mMediaPlayer; private Vibrator mVibrator; private Handler mHandler; private PowerManager mPowerManager; private TelephonyManager mTelephonyManager; private PowerManager.WakeLock mWakeLock; private KeyguardManager mKeyguardManager; private KeyguardManager.KeyguardLock mKeyguardLock; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "===> onCreate()"); // Wakeup the device and release keylock. mPowerManager = (PowerManager)getSystemService(Context.POWER_SERVICE); mKeyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); mHandler = new Handler(new StopPlayback()); acquireWakeLock(); // requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.fire_alarm); setLabelFromIntent(); setWindowTitleFromIntent(); // Snooze this alarm makes the alarm postponded and saved // as a SharedPreferences. Button snoozeButton = (Button)findViewById(R.id.snooze); snoozeButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { FireAlarm.this.snoozeAlarm(); FireAlarm.this.finish(); } }); // Dismiss the alarm causes the ringtone playback of this // alarm stopped and reschudiling of this alarm happens. Button dismissButton = (Button)findViewById(R.id.dismiss); dismissButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { FireAlarm.this.dismissAlarm(); FireAlarm.this.finish(); } }); // Prepare MediaPlayer for playing ringtone. if (prepareMediaPlayer()) { mMediaPlayer.start(); } startVibration(); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "===> onDestroy()"); if (mHandler != null) { mHandler.removeMessages(MESSAGE_ID_STOP_PLAYBACK, mMediaPlayer); mHandler = null; } // Stop and release MediaPlayer object. if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; Log.d(TAG, "===> MediaPlayer stopped and released"); } releaseWakeLock(); } // FireAlarm comes to the foreground @Override public void onResume() { super.onResume(); Log.d(TAG, "===> onResume()"); // FireAlarm goes back to interact to user. But, Keyguard // may be in front. disableKeyguard(); } @Override public void onPause() { super.onPause(); Log.d(TAG, "===> onPause()"); // Returns to keyguarded mode if the phone was in this // mode. enableKeyguard(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // don't handle BACK key. return true; } return super.onKeyDown(keyCode, event); } @Override public void onNewIntent(Intent newIntent) { Log.v(TAG, "===> onNewIntent()"); // Dismiss the old alarm. dismissAlarm(); // New intent comes. Replace the old one. setIntent(newIntent); // Refresh UI of the existing instance. setLabelFromIntent(); setWindowTitleFromIntent(); // The ringtone uri might be different and timeout of // playback needs to be recounted. if (prepareMediaPlayer()) { mMediaPlayer.start(); } startVibration(); } private void setWindowTitleFromIntent() { Intent i = getIntent(); final String label = i.getStringExtra(Alarms.AlarmColumns.LABEL); setTitle(label); } private void setLabelFromIntent() { Intent i = getIntent(); final int hourOfDay = i.getIntExtra(Alarms.AlarmColumns.HOUR, -1); final int minutes = i.getIntExtra(Alarms.AlarmColumns.MINUTES, -1); Calendar calendar = Alarms.getCalendarInstance(); calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minutes); final String label = DateUtils.formatDateTime(this, calendar.getTimeInMillis(), DateUtils.FORMAT_SHOW_TIME|DateUtils.FORMAT_CAP_AMPM); TextView labelView = (TextView)findViewById(R.id.label); labelView.setText(label); } private void snoozeAlarm() { Intent i = getIntent(); final int alarmId = i.getIntExtra(Alarms.AlarmColumns._ID, -1); final String label = i.getStringExtra(Alarms.AlarmColumns.LABEL); final int repeatOnDays = i.getIntExtra(Alarms.AlarmColumns.REPEAT_DAYS, -1); final String handlerClassName = i.getStringExtra(Alarms.AlarmColumns.HANDLER); final String extraData = i.getStringExtra(Alarms.AlarmColumns.EXTRA); final int snoozeDuration = i.getIntExtra(EXTRA_KEY_SNOOZE_DURATION, -1); Alarms.snoozeAlarm(this, alarmId, label, repeatOnDays, handlerClassName, extraData, snoozeDuration); stopVibration(); } private void dismissAlarm() { // final Intent intent = getIntent(); // final int alarmId = intent.getIntExtra(Alarms.AlarmColumns._ID, -1); // final Uri alarmUri = Alarms.getAlarmUri(alarmId); // // Disable the old alert. The explicit class field of // // the Intent was set to this activity when setting alarm // // in AlarmManager.. // final String handlerClassName = // intent.getStringExtra(Alarms.AlarmColumns.HANDLER); // Alarms.disableAlarm(this, alarmId, handlerClassName); // // Recalculate the new time of the alarm. // final int hourOfDay = intent.getIntExtra(Alarms.AlarmColumns.HOUR, -1); // // If user clicks dimiss button in the same minute as // // this alarm, the calculateAlarmAtTimeInMillis() will // // return the same hour and minutes which causes this // // Activity to show up continuously. // final int minutes = intent.getIntExtra(Alarms.AlarmColumns.MINUTES, -1) - 1; // final int repeatOnDaysCode = intent.getIntExtra(Alarms.AlarmColumns.REPEAT_DAYS, -1); // final long atTimeInMillis = // Alarms.calculateAlarmAtTimeInMillis(hourOfDay, minutes, repeatOnDaysCode); // final String label = intent.getStringExtra(Alarms.AlarmColumns.LABEL); // final String extraData = intent.getStringExtra(Alarms.AlarmColumns.EXTRA); // Alarms.enableAlarm(this, alarmId, label, atTimeInMillis, repeatOnDaysCode, handlerClassName, extraData); // // Update the new time into database. // ContentValues newValues = new ContentValues(); // newValues.put(Alarms.AlarmColumns.AT_TIME_IN_MILLIS, atTimeInMillis); // Alarms.updateAlarm(this, alarmUri, newValues); Intent rescheduleIntent = new Intent(getIntent()); rescheduleIntent.setAction(Alarms.ACTION_SCHEDULE_ALARM); sendBroadcast(rescheduleIntent); // Notify the system that this alarm is changed. Alarms.setNotification(this, true); stopVibration(); } private void startVibration() { Intent intent = getIntent(); if (intent.getBooleanExtra("vibrate", false)) { if (mVibrator == null) { mVibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); } mVibrator.vibrate(new long[]{500, 500}, 0); } } private void stopVibration() { if (mVibrator != null) { mVibrator.cancel(); } } private void acquireWakeLock() { if (mWakeLock == null) { mWakeLock = mPowerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP| PowerManager.FULL_WAKE_LOCK, TAG); } mWakeLock.acquire(); } private void releaseWakeLock() { if (mWakeLock != null && mWakeLock.isHeld()) { mWakeLock.release(); } } private void enableKeyguard() { if (mKeyguardLock == null) { mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG); } mKeyguardLock.reenableKeyguard(); } private void disableKeyguard() { if (mKeyguardLock == null) { mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG); } mKeyguardLock.disableKeyguard(); } private boolean prepareMediaPlayer() { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } else { mMediaPlayer.stop(); mMediaPlayer.reset(); } Intent intent = getIntent(); if (intent.hasExtra(EXTRA_KEY_RINGTONE)) { String uriString = intent.getStringExtra(EXTRA_KEY_RINGTONE); if (TextUtils.isEmpty(uriString)) { - return; + return false; } Log.d(TAG, "===> Play ringtone: " + uriString); try { // Detects if we are in a call when this alarm goes off. if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) { mMediaPlayer.setDataSource(this, Uri.parse(uriString)); } else { Log.d(TAG, "===> We're in a call. Lower volume and use fallback ringtone!"); // This raw media must be supported by Android // and no errors thrown from it. AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.in_call_ringtone); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME); } } catch (java.io.IOException e) { return false; } mMediaPlayer.setLooping(true); // Prepare MediaPlayer into Prepared state and // MediaPlayer is ready to play. try { mMediaPlayer.prepare(); } catch (java.io.IOException e) { return false; } // Setup a one-shot message to stop playing of // ringtone after TIMEOUT minutes. If it is // established successfully, start playing // ringtone and vibrate if necessary. mHandler.removeMessages(MESSAGE_ID_STOP_PLAYBACK, this); Message message = mHandler.obtainMessage(MESSAGE_ID_STOP_PLAYBACK, this); return mHandler.sendMessageDelayed(message, PLAYBACK_TIMEOUT); } return false; } }
true
true
private boolean prepareMediaPlayer() { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } else { mMediaPlayer.stop(); mMediaPlayer.reset(); } Intent intent = getIntent(); if (intent.hasExtra(EXTRA_KEY_RINGTONE)) { String uriString = intent.getStringExtra(EXTRA_KEY_RINGTONE); if (TextUtils.isEmpty(uriString)) { return; } Log.d(TAG, "===> Play ringtone: " + uriString); try { // Detects if we are in a call when this alarm goes off. if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) { mMediaPlayer.setDataSource(this, Uri.parse(uriString)); } else { Log.d(TAG, "===> We're in a call. Lower volume and use fallback ringtone!"); // This raw media must be supported by Android // and no errors thrown from it. AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.in_call_ringtone); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME); } } catch (java.io.IOException e) { return false; } mMediaPlayer.setLooping(true); // Prepare MediaPlayer into Prepared state and // MediaPlayer is ready to play. try { mMediaPlayer.prepare(); } catch (java.io.IOException e) { return false; } // Setup a one-shot message to stop playing of // ringtone after TIMEOUT minutes. If it is // established successfully, start playing // ringtone and vibrate if necessary. mHandler.removeMessages(MESSAGE_ID_STOP_PLAYBACK, this); Message message = mHandler.obtainMessage(MESSAGE_ID_STOP_PLAYBACK, this); return mHandler.sendMessageDelayed(message, PLAYBACK_TIMEOUT); } return false; }
private boolean prepareMediaPlayer() { if (mMediaPlayer == null) { mMediaPlayer = new MediaPlayer(); } else { mMediaPlayer.stop(); mMediaPlayer.reset(); } Intent intent = getIntent(); if (intent.hasExtra(EXTRA_KEY_RINGTONE)) { String uriString = intent.getStringExtra(EXTRA_KEY_RINGTONE); if (TextUtils.isEmpty(uriString)) { return false; } Log.d(TAG, "===> Play ringtone: " + uriString); try { // Detects if we are in a call when this alarm goes off. if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE) { mMediaPlayer.setDataSource(this, Uri.parse(uriString)); } else { Log.d(TAG, "===> We're in a call. Lower volume and use fallback ringtone!"); // This raw media must be supported by Android // and no errors thrown from it. AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.in_call_ringtone); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.setVolume(IN_CALL_VOLUME, IN_CALL_VOLUME); } } catch (java.io.IOException e) { return false; } mMediaPlayer.setLooping(true); // Prepare MediaPlayer into Prepared state and // MediaPlayer is ready to play. try { mMediaPlayer.prepare(); } catch (java.io.IOException e) { return false; } // Setup a one-shot message to stop playing of // ringtone after TIMEOUT minutes. If it is // established successfully, start playing // ringtone and vibrate if necessary. mHandler.removeMessages(MESSAGE_ID_STOP_PLAYBACK, this); Message message = mHandler.obtainMessage(MESSAGE_ID_STOP_PLAYBACK, this); return mHandler.sendMessageDelayed(message, PLAYBACK_TIMEOUT); } return false; }
diff --git a/src/controller/overview/switches/json/MatchJSON.java b/src/controller/overview/switches/json/MatchJSON.java index b731cf1..b5b2b34 100644 --- a/src/controller/overview/switches/json/MatchJSON.java +++ b/src/controller/overview/switches/json/MatchJSON.java @@ -1,68 +1,68 @@ package controller.overview.switches.json; import java.io.IOException; import model.tools.flowmanager.Match; import controller.util.JSONArray; import controller.util.JSONException; import controller.util.JSONObject; public class MatchJSON { String dataLayerDestination, dataLayerSource, dataLayerType, dataLayerVLAN, dataLayerPCP, inputPort, networkDestination, networkDestinationMaskLength, networkProtocol, networkSource, networkSourceMaskLength, networkTypeOfService, transportDestination, transportSource, wildcards; static JSONObject obj; static JSONArray json; // This parses JSON from the restAPI to get all the match of a flow for the controller overview public static Match getMatch(JSONObject obj) throws JSONException, IOException { Match match = new Match(); // Here we check the values, if they are default we set them emptry strings. // This way they don't confuse the user into thinking they set something // they didn't if (!obj.getString("dataLayerDestination").equals("00:00:00:00:00:00")) match.setDataLayerDestination(obj.getString("dataLayerDestination")); if (!obj.getString("dataLayerSource").equals("00:00:00:00:00:00")) match.setDataLayerSource(obj.getString("dataLayerSource")); if (!obj.getString("dataLayerType").equals("0x0000")) match.setDataLayerType(obj.getString("dataLayerType")); if (obj.getInt("dataLayerVirtualLan") > 0) match.setDataLayerVLAN(String.valueOf(obj .getInt("dataLayerVirtualLan"))); if (obj.getInt("dataLayerVirtualLanPriorityCodePoint") != 0) match.setDataLayerPCP(String.valueOf(obj .getInt("dataLayerVirtualLanPriorityCodePoint"))); - if (obj.getInt("inputPort") != 0) + if (obj.getInt("inputPort") != 0 || obj.getInt("inputPort") != 1) match.setInputPort(String.valueOf(obj.getInt("inputPort"))); if (!obj.getString("networkDestination").equals("0.0.0.0")) match.setNetworkDestination(obj.getString("networkDestination")); // match.setNetworkDestinationMaskLength(String.valueOf(obj.getInt("networkDestinationMaskLen"))); if (obj.getInt("networkProtocol") != 0) match.setNetworkProtocol(String.valueOf(obj .getInt("networkProtocol"))); if (!obj.getString("networkSource").equals("0.0.0.0")) match.setNetworkSource(obj.getString("networkSource")); // match.setNetworkSourceMaskLength(String.valueOf(obj.getInt("networkSourceMaskLen"))); if (obj.getInt("networkTypeOfService") != 0) match.setNetworkTypeOfService(String.valueOf(obj .getInt("networkTypeOfService"))); if (obj.getInt("transportDestination") != 0) match.setTransportDestination(String.valueOf(obj .getInt("transportDestination"))); if (obj.getInt("transportSource") != 0) match.setTransportSource(String.valueOf(obj .getInt("transportSource"))); if(obj.getLong("wildcards") != 4194302) match.setWildcards(String.valueOf(obj.getLong("wildcards"))); return match; } }
true
true
public static Match getMatch(JSONObject obj) throws JSONException, IOException { Match match = new Match(); // Here we check the values, if they are default we set them emptry strings. // This way they don't confuse the user into thinking they set something // they didn't if (!obj.getString("dataLayerDestination").equals("00:00:00:00:00:00")) match.setDataLayerDestination(obj.getString("dataLayerDestination")); if (!obj.getString("dataLayerSource").equals("00:00:00:00:00:00")) match.setDataLayerSource(obj.getString("dataLayerSource")); if (!obj.getString("dataLayerType").equals("0x0000")) match.setDataLayerType(obj.getString("dataLayerType")); if (obj.getInt("dataLayerVirtualLan") > 0) match.setDataLayerVLAN(String.valueOf(obj .getInt("dataLayerVirtualLan"))); if (obj.getInt("dataLayerVirtualLanPriorityCodePoint") != 0) match.setDataLayerPCP(String.valueOf(obj .getInt("dataLayerVirtualLanPriorityCodePoint"))); if (obj.getInt("inputPort") != 0) match.setInputPort(String.valueOf(obj.getInt("inputPort"))); if (!obj.getString("networkDestination").equals("0.0.0.0")) match.setNetworkDestination(obj.getString("networkDestination")); // match.setNetworkDestinationMaskLength(String.valueOf(obj.getInt("networkDestinationMaskLen"))); if (obj.getInt("networkProtocol") != 0) match.setNetworkProtocol(String.valueOf(obj .getInt("networkProtocol"))); if (!obj.getString("networkSource").equals("0.0.0.0")) match.setNetworkSource(obj.getString("networkSource")); // match.setNetworkSourceMaskLength(String.valueOf(obj.getInt("networkSourceMaskLen"))); if (obj.getInt("networkTypeOfService") != 0) match.setNetworkTypeOfService(String.valueOf(obj .getInt("networkTypeOfService"))); if (obj.getInt("transportDestination") != 0) match.setTransportDestination(String.valueOf(obj .getInt("transportDestination"))); if (obj.getInt("transportSource") != 0) match.setTransportSource(String.valueOf(obj .getInt("transportSource"))); if(obj.getLong("wildcards") != 4194302) match.setWildcards(String.valueOf(obj.getLong("wildcards"))); return match; }
public static Match getMatch(JSONObject obj) throws JSONException, IOException { Match match = new Match(); // Here we check the values, if they are default we set them emptry strings. // This way they don't confuse the user into thinking they set something // they didn't if (!obj.getString("dataLayerDestination").equals("00:00:00:00:00:00")) match.setDataLayerDestination(obj.getString("dataLayerDestination")); if (!obj.getString("dataLayerSource").equals("00:00:00:00:00:00")) match.setDataLayerSource(obj.getString("dataLayerSource")); if (!obj.getString("dataLayerType").equals("0x0000")) match.setDataLayerType(obj.getString("dataLayerType")); if (obj.getInt("dataLayerVirtualLan") > 0) match.setDataLayerVLAN(String.valueOf(obj .getInt("dataLayerVirtualLan"))); if (obj.getInt("dataLayerVirtualLanPriorityCodePoint") != 0) match.setDataLayerPCP(String.valueOf(obj .getInt("dataLayerVirtualLanPriorityCodePoint"))); if (obj.getInt("inputPort") != 0 || obj.getInt("inputPort") != 1) match.setInputPort(String.valueOf(obj.getInt("inputPort"))); if (!obj.getString("networkDestination").equals("0.0.0.0")) match.setNetworkDestination(obj.getString("networkDestination")); // match.setNetworkDestinationMaskLength(String.valueOf(obj.getInt("networkDestinationMaskLen"))); if (obj.getInt("networkProtocol") != 0) match.setNetworkProtocol(String.valueOf(obj .getInt("networkProtocol"))); if (!obj.getString("networkSource").equals("0.0.0.0")) match.setNetworkSource(obj.getString("networkSource")); // match.setNetworkSourceMaskLength(String.valueOf(obj.getInt("networkSourceMaskLen"))); if (obj.getInt("networkTypeOfService") != 0) match.setNetworkTypeOfService(String.valueOf(obj .getInt("networkTypeOfService"))); if (obj.getInt("transportDestination") != 0) match.setTransportDestination(String.valueOf(obj .getInt("transportDestination"))); if (obj.getInt("transportSource") != 0) match.setTransportSource(String.valueOf(obj .getInt("transportSource"))); if(obj.getLong("wildcards") != 4194302) match.setWildcards(String.valueOf(obj.getLong("wildcards"))); return match; }
diff --git a/src/com/android/settings/bluetooth/BluetoothDevicePreference.java b/src/com/android/settings/bluetooth/BluetoothDevicePreference.java index c659f705..a443f5ab 100644 --- a/src/com/android/settings/bluetooth/BluetoothDevicePreference.java +++ b/src/com/android/settings/bluetooth/BluetoothDevicePreference.java @@ -1,307 +1,307 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.bluetooth; import android.app.AlertDialog; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.preference.Preference; import android.text.Html; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import com.android.settings.R; import java.util.List; /** * BluetoothDevicePreference is the preference type used to display each remote * Bluetooth device in the Bluetooth Settings screen. */ public final class BluetoothDevicePreference extends Preference implements CachedBluetoothDevice.Callback, OnClickListener { private static final String TAG = "BluetoothDevicePreference"; private static int sDimAlpha = Integer.MIN_VALUE; private final CachedBluetoothDevice mCachedDevice; private OnClickListener mOnSettingsClickListener; private AlertDialog mDisconnectDialog; public BluetoothDevicePreference(Context context, CachedBluetoothDevice cachedDevice) { super(context); if (sDimAlpha == Integer.MIN_VALUE) { TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.disabledAlpha, outValue, true); sDimAlpha = (int) (outValue.getFloat() * 255); } mCachedDevice = cachedDevice; if (cachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) { setWidgetLayoutResource(R.layout.preference_bluetooth); } mCachedDevice.registerCallback(this); onDeviceAttributesChanged(); } CachedBluetoothDevice getCachedDevice() { return mCachedDevice; } public void setOnSettingsClickListener(OnClickListener listener) { mOnSettingsClickListener = listener; } @Override protected void onPrepareForRemoval() { super.onPrepareForRemoval(); mCachedDevice.unregisterCallback(this); if (mDisconnectDialog != null) { mDisconnectDialog.dismiss(); mDisconnectDialog = null; } } public void onDeviceAttributesChanged() { /* * The preference framework takes care of making sure the value has * changed before proceeding. It will also call notifyChanged() if * any preference info has changed from the previous value. */ setTitle(mCachedDevice.getName()); int summaryResId = getConnectionSummary(); if (summaryResId != 0) { setSummary(summaryResId); } else { setSummary(null); // empty summary for unpaired devices } int iconResId = getBtClassDrawable(); if (iconResId != 0) { setIcon(iconResId); } // Used to gray out the item setEnabled(!mCachedDevice.isBusy()); // This could affect ordering, so notify that notifyHierarchyChanged(); } @Override protected void onBindView(View view) { // Disable this view if the bluetooth enable/disable preference view is off if (null != findPreferenceInHierarchy("bt_checkbox")) { setDependency("bt_checkbox"); } if (mCachedDevice.getBondState() == BluetoothDevice.BOND_BONDED) { ImageView deviceDetails = (ImageView) view.findViewById(R.id.deviceDetails); if (deviceDetails != null) { deviceDetails.setOnClickListener(this); deviceDetails.setTag(mCachedDevice); deviceDetails.setAlpha(isEnabled() ? 255 : sDimAlpha); } } super.onBindView(view); } public void onClick(View v) { // Should never be null by construction if (mOnSettingsClickListener != null) { mOnSettingsClickListener.onClick(v); } } @Override public boolean equals(Object o) { if ((o == null) || !(o instanceof BluetoothDevicePreference)) { return false; } return mCachedDevice.equals( ((BluetoothDevicePreference) o).mCachedDevice); } @Override public int hashCode() { return mCachedDevice.hashCode(); } @Override public int compareTo(Preference another) { if (!(another instanceof BluetoothDevicePreference)) { // Rely on default sort return super.compareTo(another); } return mCachedDevice .compareTo(((BluetoothDevicePreference) another).mCachedDevice); } void onClicked() { int bondState = mCachedDevice.getBondState(); if (mCachedDevice.isConnected()) { askDisconnect(); } else if (bondState == BluetoothDevice.BOND_BONDED) { mCachedDevice.connect(true); } else if (bondState == BluetoothDevice.BOND_NONE) { pair(); } } // Show disconnect confirmation dialog for a device. private void askDisconnect() { Context context = getContext(); String name = mCachedDevice.getName(); if (TextUtils.isEmpty(name)) { name = context.getString(R.string.bluetooth_device); } String message = context.getString(R.string.bluetooth_disconnect_all_profiles, name); String title = context.getString(R.string.bluetooth_disconnect_title); DialogInterface.OnClickListener disconnectListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mCachedDevice.disconnect(); } }; mDisconnectDialog = Utils.showDisconnectDialog(context, mDisconnectDialog, disconnectListener, title, Html.fromHtml(message)); } private void pair() { if (!mCachedDevice.startPairing()) { Utils.showError(getContext(), mCachedDevice.getName(), R.string.bluetooth_pairing_error_message); } } private int getConnectionSummary() { final CachedBluetoothDevice cachedDevice = mCachedDevice; boolean profileConnected = false; // at least one profile is connected boolean a2dpNotConnected = false; // A2DP is preferred but not connected boolean headsetNotConnected = false; // Headset is preferred but not connected for (LocalBluetoothProfile profile : cachedDevice.getProfiles()) { int connectionStatus = cachedDevice.getProfileConnectionState(profile); switch (connectionStatus) { case BluetoothProfile.STATE_CONNECTING: case BluetoothProfile.STATE_DISCONNECTING: return Utils.getConnectionStateSummary(connectionStatus); case BluetoothProfile.STATE_CONNECTED: profileConnected = true; break; case BluetoothProfile.STATE_DISCONNECTED: - if (profile.isProfileReady() && profile.isPreferred(cachedDevice.getDevice())) { + if (profile.isProfileReady()) { if (profile instanceof A2dpProfile) { a2dpNotConnected = true; } else if (profile instanceof HeadsetProfile) { headsetNotConnected = true; } } break; } } if (profileConnected) { if (a2dpNotConnected && headsetNotConnected) { return R.string.bluetooth_connected_no_headset_no_a2dp; } else if (a2dpNotConnected) { return R.string.bluetooth_connected_no_a2dp; } else if (headsetNotConnected) { return R.string.bluetooth_connected_no_headset; } else { return R.string.bluetooth_connected; } } switch (cachedDevice.getBondState()) { case BluetoothDevice.BOND_BONDING: return R.string.bluetooth_pairing; case BluetoothDevice.BOND_BONDED: case BluetoothDevice.BOND_NONE: default: return 0; } } private int getBtClassDrawable() { BluetoothClass btClass = mCachedDevice.getBtClass(); if (btClass != null) { switch (btClass.getMajorDeviceClass()) { case BluetoothClass.Device.Major.COMPUTER: return R.drawable.ic_bt_laptop; case BluetoothClass.Device.Major.PHONE: return R.drawable.ic_bt_cellphone; case BluetoothClass.Device.Major.PERIPHERAL: return HidProfile.getHidClassDrawable(btClass); case BluetoothClass.Device.Major.IMAGING: return R.drawable.ic_bt_imaging; default: // unrecognized device class; continue } } else { Log.w(TAG, "mBtClass is null"); } List<LocalBluetoothProfile> profiles = mCachedDevice.getProfiles(); for (LocalBluetoothProfile profile : profiles) { int resId = profile.getDrawableResource(btClass); if (resId != 0) { return resId; } } if (btClass != null) { if (btClass.doesClassMatch(BluetoothClass.PROFILE_A2DP)) { return R.drawable.ic_bt_headphones_a2dp; } if (btClass.doesClassMatch(BluetoothClass.PROFILE_HEADSET)) { return R.drawable.ic_bt_headset_hfp; } } return 0; } }
true
true
private int getConnectionSummary() { final CachedBluetoothDevice cachedDevice = mCachedDevice; boolean profileConnected = false; // at least one profile is connected boolean a2dpNotConnected = false; // A2DP is preferred but not connected boolean headsetNotConnected = false; // Headset is preferred but not connected for (LocalBluetoothProfile profile : cachedDevice.getProfiles()) { int connectionStatus = cachedDevice.getProfileConnectionState(profile); switch (connectionStatus) { case BluetoothProfile.STATE_CONNECTING: case BluetoothProfile.STATE_DISCONNECTING: return Utils.getConnectionStateSummary(connectionStatus); case BluetoothProfile.STATE_CONNECTED: profileConnected = true; break; case BluetoothProfile.STATE_DISCONNECTED: if (profile.isProfileReady() && profile.isPreferred(cachedDevice.getDevice())) { if (profile instanceof A2dpProfile) { a2dpNotConnected = true; } else if (profile instanceof HeadsetProfile) { headsetNotConnected = true; } } break; } } if (profileConnected) { if (a2dpNotConnected && headsetNotConnected) { return R.string.bluetooth_connected_no_headset_no_a2dp; } else if (a2dpNotConnected) { return R.string.bluetooth_connected_no_a2dp; } else if (headsetNotConnected) { return R.string.bluetooth_connected_no_headset; } else { return R.string.bluetooth_connected; } } switch (cachedDevice.getBondState()) { case BluetoothDevice.BOND_BONDING: return R.string.bluetooth_pairing; case BluetoothDevice.BOND_BONDED: case BluetoothDevice.BOND_NONE: default: return 0; } }
private int getConnectionSummary() { final CachedBluetoothDevice cachedDevice = mCachedDevice; boolean profileConnected = false; // at least one profile is connected boolean a2dpNotConnected = false; // A2DP is preferred but not connected boolean headsetNotConnected = false; // Headset is preferred but not connected for (LocalBluetoothProfile profile : cachedDevice.getProfiles()) { int connectionStatus = cachedDevice.getProfileConnectionState(profile); switch (connectionStatus) { case BluetoothProfile.STATE_CONNECTING: case BluetoothProfile.STATE_DISCONNECTING: return Utils.getConnectionStateSummary(connectionStatus); case BluetoothProfile.STATE_CONNECTED: profileConnected = true; break; case BluetoothProfile.STATE_DISCONNECTED: if (profile.isProfileReady()) { if (profile instanceof A2dpProfile) { a2dpNotConnected = true; } else if (profile instanceof HeadsetProfile) { headsetNotConnected = true; } } break; } } if (profileConnected) { if (a2dpNotConnected && headsetNotConnected) { return R.string.bluetooth_connected_no_headset_no_a2dp; } else if (a2dpNotConnected) { return R.string.bluetooth_connected_no_a2dp; } else if (headsetNotConnected) { return R.string.bluetooth_connected_no_headset; } else { return R.string.bluetooth_connected; } } switch (cachedDevice.getBondState()) { case BluetoothDevice.BOND_BONDING: return R.string.bluetooth_pairing; case BluetoothDevice.BOND_BONDED: case BluetoothDevice.BOND_NONE: default: return 0; } }
diff --git a/src/java/com/sapienter/jbilling/server/util/PreferenceBL.java b/src/java/com/sapienter/jbilling/server/util/PreferenceBL.java index 88eb4681..73231946 100644 --- a/src/java/com/sapienter/jbilling/server/util/PreferenceBL.java +++ b/src/java/com/sapienter/jbilling/server/util/PreferenceBL.java @@ -1,174 +1,175 @@ /* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jbilling is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with jbilling. If not, see <http://www.gnu.org/licenses/>. */ package com.sapienter.jbilling.server.util; import com.sapienter.jbilling.server.util.db.JbillingTableDAS; import com.sapienter.jbilling.server.util.db.PreferenceDAS; import com.sapienter.jbilling.server.util.db.PreferenceDTO; import com.sapienter.jbilling.server.util.db.PreferenceTypeDAS; import com.sapienter.jbilling.server.util.db.PreferenceTypeDTO; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.dao.EmptyResultDataAccessException; import java.math.BigDecimal; public class PreferenceBL { private static Logger LOG = Logger.getLogger(PreferenceBL.class); private PreferenceDAS preferenceDas = null; private PreferenceTypeDAS typeDas = null; private PreferenceDTO preference = null; private PreferenceTypeDTO type = null; private JbillingTableDAS jbDAS = null; public PreferenceBL() { init(); } public PreferenceBL(Integer preferenceId) { init(); preference = preferenceDas.find(preferenceId); } public PreferenceBL(Integer entityId, Integer preferenceTypeId) { init(); set(entityId, preferenceTypeId); } private void init() { preferenceDas = new PreferenceDAS(); typeDas = new PreferenceTypeDAS(); jbDAS = (JbillingTableDAS) Context.getBean(Context.Name.JBILLING_TABLE_DAS); } public void set(Integer entityId, Integer typeId) throws EmptyResultDataAccessException { LOG.debug("Looking for preference " + typeId + ", for entity " + entityId + " and table '" + Constants.TABLE_ENTITY + "'"); preference = preferenceDas.findByType_Row( typeId, entityId, Constants.TABLE_ENTITY); type = typeDas.find(typeId); // throw exception if there is no preference, or if the type does not have a // default value that can be returned. if (preference == null) { if (type == null || type.getDefaultValue() == null) { throw new EmptyResultDataAccessException("Could not find preference " + typeId, 1); } } } public void createUpdateForEntity(Integer entityId, Integer preferenceId, Integer value) { createUpdateForEntity(entityId, preferenceId, (value != null ? value.toString() : "")); } public void createUpdateForEntity(Integer entityId, Integer preferenceId, BigDecimal value) { createUpdateForEntity(entityId, preferenceId, (value != null ? value.toString() : "")); } public void createUpdateForEntity(Integer entityId, Integer preferenceId, String value) { - set(entityId, preferenceId); + preference = preferenceDas.findByType_Row(preferenceId, entityId, Constants.TABLE_ENTITY); + type = typeDas.find(preferenceId); if (preference != null) { // update preference preference.setValue(value); } else { // create a new preference preference = new PreferenceDTO(); preference.setValue(value); preference.setForeignId(entityId); preference.setJbillingTable(jbDAS.findByName(Constants.TABLE_ENTITY)); preference.setPreferenceType(new PreferenceTypeDAS().find(preferenceId)); preference = preferenceDas.save(preference); } } /** * Returns the preference value if set. If the preference is null or has no * set value (is blank), the preference type default value will be returned. * * @return preference value as a string */ public String getString() { if (preference != null && StringUtils.isNotBlank(preference.getValue())) { return preference.getValue(); } else { return type != null ? type.getDefaultValue() : null; } } public Integer getInt() { String value = getString(); return value != null ? Integer.valueOf(value) : null; } public Float getFloat() { String value = getString(); return value != null ? Float.valueOf(value) : null; } public BigDecimal getDecimal() { String value = getString(); return value != null ? new BigDecimal(value) : null; } /** * Returns the preference value as a string. * * @see #getString() * @return string value of preference */ public String getValueAsString() { return getString(); } /** * Returns the default value for the given preference type. * * @param preferenceTypeId preference type id * @return default preference value */ public String getDefaultValue(Integer preferenceTypeId) { type = typeDas.find(preferenceTypeId); return type != null ? type.getDefaultValue() : null; } /** * Returns true if the preference value is null, false if value is set. * * This method ignores the preference type default value, unlike {@link #getString()} * and {@link #getValueAsString()} which will return the type default value if the * preference itself is unset. * * @return true if preference value is null, false if value is set. */ public boolean isNull() { return preference == null || preference.getValue() == null; } public PreferenceDTO getEntity() { return preference; } }
true
true
public void createUpdateForEntity(Integer entityId, Integer preferenceId, String value) { set(entityId, preferenceId); if (preference != null) { // update preference preference.setValue(value); } else { // create a new preference preference = new PreferenceDTO(); preference.setValue(value); preference.setForeignId(entityId); preference.setJbillingTable(jbDAS.findByName(Constants.TABLE_ENTITY)); preference.setPreferenceType(new PreferenceTypeDAS().find(preferenceId)); preference = preferenceDas.save(preference); } }
public void createUpdateForEntity(Integer entityId, Integer preferenceId, String value) { preference = preferenceDas.findByType_Row(preferenceId, entityId, Constants.TABLE_ENTITY); type = typeDas.find(preferenceId); if (preference != null) { // update preference preference.setValue(value); } else { // create a new preference preference = new PreferenceDTO(); preference.setValue(value); preference.setForeignId(entityId); preference.setJbillingTable(jbDAS.findByName(Constants.TABLE_ENTITY)); preference.setPreferenceType(new PreferenceTypeDAS().find(preferenceId)); preference = preferenceDas.save(preference); } }
diff --git a/core/src/main/java/mustache/core/Instruction.java b/core/src/main/java/mustache/core/Instruction.java index a2600c3..e25d709 100644 --- a/core/src/main/java/mustache/core/Instruction.java +++ b/core/src/main/java/mustache/core/Instruction.java @@ -1,23 +1,23 @@ package mustache.core; import java.io.Serializable; /** * TODO doc * @author Dri */ public abstract class Instruction implements Serializable { private static final long serialVersionUID = 4440679549428243560L; Instruction() {} public static boolean isIndentation(String indentation) { - for (int i = indentation.length(); --i > 0;) { + for (int i = indentation.length(); --i >= 0;) { char c = indentation.charAt(i); - if (c != ' ' && c != '\t') { + if (c != ' ' & c != '\t') { return false; } } return true; } }
false
true
public static boolean isIndentation(String indentation) { for (int i = indentation.length(); --i > 0;) { char c = indentation.charAt(i); if (c != ' ' && c != '\t') { return false; } } return true; }
public static boolean isIndentation(String indentation) { for (int i = indentation.length(); --i >= 0;) { char c = indentation.charAt(i); if (c != ' ' & c != '\t') { return false; } } return true; }
diff --git a/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/TestResultView.java b/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/TestResultView.java index 4e9d8d7b..2ea92027 100644 --- a/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/TestResultView.java +++ b/com.piece_framework.makegood.ui/src/com/piece_framework/makegood/ui/views/TestResultView.java @@ -1,276 +1,279 @@ package com.piece_framework.makegood.ui.views; import java.io.File; import java.io.FileNotFoundException; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.php.internal.debug.core.model.IPHPDebugTarget; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Tree; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.progress.UIJob; import com.piece_framework.makegood.launch.phpunit.ProblemType; import com.piece_framework.makegood.launch.phpunit.TestCase; import com.piece_framework.makegood.launch.phpunit.TestResultConverter; import com.piece_framework.makegood.launch.phpunit.TestSuite; import com.piece_framework.makegood.ui.Activator; public class TestResultView extends ViewPart { private static final RGB GREEN = new RGB(95, 191, 95); private static final RGB RED = new RGB(159, 63, 63); private static final RGB NONE = new RGB(255, 255, 255); private IDebugEventSetListener listener; private Label progressBar; private ResultLabel tests; private ResultLabel assertions; private ResultLabel passes; private ResultLabel failures; private ResultLabel errors; private TreeViewer resultTreeViewer; private List resultList; public TestResultView() { // TODO Auto-generated constructor stub } @Override public void createPartControl(Composite parent) { parent.setLayout(new GridLayout(1, false)); progressBar = new Label(parent, SWT.BORDER); progressBar.setBackground(new Color(parent.getDisplay(), NONE)); progressBar.setLayoutData(createHorizontalFillGridData()); Composite summary = new Composite(parent, SWT.NULL); summary.setLayoutData(createHorizontalFillGridData()); summary.setLayout(new FillLayout(SWT.HORIZONTAL)); tests = new ResultLabel(summary, "Tests:", null); assertions = new ResultLabel(summary, "Assertions:", null); passes = new ResultLabel(summary, "Passes:", Activator.getImageDescriptor("icons/pass.gif").createImage() ); failures = new ResultLabel(summary, "Failures:", Activator.getImageDescriptor("icons/failure.gif").createImage() ); errors = new ResultLabel(summary, "Errors:", Activator.getImageDescriptor("icons/error.gif").createImage() ); SashForm form = new SashForm(parent, SWT.HORIZONTAL); form.setLayoutData(createBothFillGridData()); form.setLayout(new GridLayout(2, false)); Tree resultTree = new Tree(form, SWT.BORDER); resultTree.setLayoutData(createBothFillGridData()); resultTreeViewer = new TreeViewer(resultTree); resultTreeViewer.setContentProvider(new TestResultContentProvider()); resultTreeViewer.setLabelProvider(new TestResultLabelProvider()); resultTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (!(event.getSelection() instanceof IStructuredSelection)) { return; } IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (!(selection.getFirstElement() instanceof TestCase)) { return; } resultList.removeAll(); TestCase testCase = (TestCase) selection.getFirstElement(); if (testCase.getProblem().getType() == ProblemType.Pass) { return; } String[] contents = testCase.getProblem().getContent().split("\n"); for (String content: contents) { resultList.add(content); } } }); resultList = new List(form, SWT.BORDER + SWT.V_SCROLL + SWT.H_SCROLL); resultList.setLayoutData(createBothFillGridData()); listener = new IDebugEventSetListener() { @Override public void handleDebugEvents(DebugEvent[] events) { for (DebugEvent event: events) { if (event.getKind() != DebugEvent.TERMINATE || !(event.getSource() instanceof IPHPDebugTarget) ) { continue; } final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); Job job = new UIJob("MakeGood result parse") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); try { String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); if (logFile == null) { // TODO return null; } java.util.List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); TestSuite suite = suites.get(0); tests.setCount(suite.getTestCount()); assertions.setCount(suite.getAssertionCount()); passes.setCount(suite.getTestCount() - suite.getFailureCount() - suite.getErrorCount() ); failures.setCount(suite.getFailureCount()); errors.setCount(suite.getErrorCount()); if (!suite.hasErrorChild()) { progressBar.setBackground(new Color(progressBar.getDisplay(), GREEN)); } else { progressBar.setBackground(new Color(progressBar.getDisplay(), RED)); } resultTreeViewer.setInput(suites); + if (suite.hasErrorChild()) { + resultTreeViewer.expandToLevel(2); + } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Status.OK_STATUS; } }; job.schedule(); } } }; DebugPlugin.getDefault().addDebugEventListener(listener); // listener = new IDebugEventSetListener() { // @Override // public void handleDebugEvents(DebugEvent[] events) { // for (DebugEvent event: events) { // if (event.getKind() == DebugEvent.TERMINATE // && event.getSource() instanceof IPHPDebugTarget // ) { // final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); // // Job job = new UIJob("MakeGood result parse") { // public IStatus runInUIThread(IProgressMonitor monitor) { // ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); // // try { // String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); // List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); // block.setInput(suites); // } catch (CoreException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } // // String[] results = debugTarget.getOutputBuffer().toString().split("\n"); // int lastLine = results.length - 1; // String result = results[lastLine]; // // root.setText(result); // if (result.startsWith("OK")) { // root.setBackground(new Color(null, 0, 255, 0)); // } else { // root.setBackground(new Color(null, 255, 0, 0)); // } // // return Status.OK_STATUS; // } // }; // job.schedule(); // } // } // } // }; // DebugPlugin.getDefault().addDebugEventListener(listener); } @Override public void setFocus() { // TODO Auto-generated method stub } @Override public void dispose() { super.dispose(); DebugPlugin.getDefault().removeDebugEventListener(listener); } private GridData createHorizontalFillGridData() { GridData horizontalFillGrid = new GridData(); horizontalFillGrid.horizontalAlignment = GridData.FILL; horizontalFillGrid.grabExcessHorizontalSpace = true; return horizontalFillGrid; } private GridData createBothFillGridData() { GridData bothFillGrid = new GridData(); bothFillGrid.horizontalAlignment = GridData.FILL; bothFillGrid.verticalAlignment = GridData.FILL; bothFillGrid.grabExcessHorizontalSpace = true; bothFillGrid.grabExcessVerticalSpace = true; return bothFillGrid; } private class ResultLabel { private CLabel label; private String text; private ResultLabel(Composite parent, String text, Image icon) { label = new CLabel(parent, SWT.LEFT); label.setText(text); if (icon != null) { label.setImage(icon); } this.text = text; } private void setCount(int count) { label.setText(text + " " + count); } } }
true
true
public void createPartControl(Composite parent) { parent.setLayout(new GridLayout(1, false)); progressBar = new Label(parent, SWT.BORDER); progressBar.setBackground(new Color(parent.getDisplay(), NONE)); progressBar.setLayoutData(createHorizontalFillGridData()); Composite summary = new Composite(parent, SWT.NULL); summary.setLayoutData(createHorizontalFillGridData()); summary.setLayout(new FillLayout(SWT.HORIZONTAL)); tests = new ResultLabel(summary, "Tests:", null); assertions = new ResultLabel(summary, "Assertions:", null); passes = new ResultLabel(summary, "Passes:", Activator.getImageDescriptor("icons/pass.gif").createImage() ); failures = new ResultLabel(summary, "Failures:", Activator.getImageDescriptor("icons/failure.gif").createImage() ); errors = new ResultLabel(summary, "Errors:", Activator.getImageDescriptor("icons/error.gif").createImage() ); SashForm form = new SashForm(parent, SWT.HORIZONTAL); form.setLayoutData(createBothFillGridData()); form.setLayout(new GridLayout(2, false)); Tree resultTree = new Tree(form, SWT.BORDER); resultTree.setLayoutData(createBothFillGridData()); resultTreeViewer = new TreeViewer(resultTree); resultTreeViewer.setContentProvider(new TestResultContentProvider()); resultTreeViewer.setLabelProvider(new TestResultLabelProvider()); resultTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (!(event.getSelection() instanceof IStructuredSelection)) { return; } IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (!(selection.getFirstElement() instanceof TestCase)) { return; } resultList.removeAll(); TestCase testCase = (TestCase) selection.getFirstElement(); if (testCase.getProblem().getType() == ProblemType.Pass) { return; } String[] contents = testCase.getProblem().getContent().split("\n"); for (String content: contents) { resultList.add(content); } } }); resultList = new List(form, SWT.BORDER + SWT.V_SCROLL + SWT.H_SCROLL); resultList.setLayoutData(createBothFillGridData()); listener = new IDebugEventSetListener() { @Override public void handleDebugEvents(DebugEvent[] events) { for (DebugEvent event: events) { if (event.getKind() != DebugEvent.TERMINATE || !(event.getSource() instanceof IPHPDebugTarget) ) { continue; } final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); Job job = new UIJob("MakeGood result parse") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); try { String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); if (logFile == null) { // TODO return null; } java.util.List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); TestSuite suite = suites.get(0); tests.setCount(suite.getTestCount()); assertions.setCount(suite.getAssertionCount()); passes.setCount(suite.getTestCount() - suite.getFailureCount() - suite.getErrorCount() ); failures.setCount(suite.getFailureCount()); errors.setCount(suite.getErrorCount()); if (!suite.hasErrorChild()) { progressBar.setBackground(new Color(progressBar.getDisplay(), GREEN)); } else { progressBar.setBackground(new Color(progressBar.getDisplay(), RED)); } resultTreeViewer.setInput(suites); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Status.OK_STATUS; } }; job.schedule(); } } }; DebugPlugin.getDefault().addDebugEventListener(listener); // listener = new IDebugEventSetListener() { // @Override // public void handleDebugEvents(DebugEvent[] events) { // for (DebugEvent event: events) { // if (event.getKind() == DebugEvent.TERMINATE // && event.getSource() instanceof IPHPDebugTarget // ) { // final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); // // Job job = new UIJob("MakeGood result parse") { // public IStatus runInUIThread(IProgressMonitor monitor) { // ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); // // try { // String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); // List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); // block.setInput(suites); // } catch (CoreException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } // // String[] results = debugTarget.getOutputBuffer().toString().split("\n"); // int lastLine = results.length - 1; // String result = results[lastLine]; // // root.setText(result); // if (result.startsWith("OK")) { // root.setBackground(new Color(null, 0, 255, 0)); // } else { // root.setBackground(new Color(null, 255, 0, 0)); // } // // return Status.OK_STATUS; // } // }; // job.schedule(); // } // } // } // }; // DebugPlugin.getDefault().addDebugEventListener(listener); }
public void createPartControl(Composite parent) { parent.setLayout(new GridLayout(1, false)); progressBar = new Label(parent, SWT.BORDER); progressBar.setBackground(new Color(parent.getDisplay(), NONE)); progressBar.setLayoutData(createHorizontalFillGridData()); Composite summary = new Composite(parent, SWT.NULL); summary.setLayoutData(createHorizontalFillGridData()); summary.setLayout(new FillLayout(SWT.HORIZONTAL)); tests = new ResultLabel(summary, "Tests:", null); assertions = new ResultLabel(summary, "Assertions:", null); passes = new ResultLabel(summary, "Passes:", Activator.getImageDescriptor("icons/pass.gif").createImage() ); failures = new ResultLabel(summary, "Failures:", Activator.getImageDescriptor("icons/failure.gif").createImage() ); errors = new ResultLabel(summary, "Errors:", Activator.getImageDescriptor("icons/error.gif").createImage() ); SashForm form = new SashForm(parent, SWT.HORIZONTAL); form.setLayoutData(createBothFillGridData()); form.setLayout(new GridLayout(2, false)); Tree resultTree = new Tree(form, SWT.BORDER); resultTree.setLayoutData(createBothFillGridData()); resultTreeViewer = new TreeViewer(resultTree); resultTreeViewer.setContentProvider(new TestResultContentProvider()); resultTreeViewer.setLabelProvider(new TestResultLabelProvider()); resultTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (!(event.getSelection() instanceof IStructuredSelection)) { return; } IStructuredSelection selection = (IStructuredSelection) event.getSelection(); if (!(selection.getFirstElement() instanceof TestCase)) { return; } resultList.removeAll(); TestCase testCase = (TestCase) selection.getFirstElement(); if (testCase.getProblem().getType() == ProblemType.Pass) { return; } String[] contents = testCase.getProblem().getContent().split("\n"); for (String content: contents) { resultList.add(content); } } }); resultList = new List(form, SWT.BORDER + SWT.V_SCROLL + SWT.H_SCROLL); resultList.setLayoutData(createBothFillGridData()); listener = new IDebugEventSetListener() { @Override public void handleDebugEvents(DebugEvent[] events) { for (DebugEvent event: events) { if (event.getKind() != DebugEvent.TERMINATE || !(event.getSource() instanceof IPHPDebugTarget) ) { continue; } final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); Job job = new UIJob("MakeGood result parse") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); try { String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); if (logFile == null) { // TODO return null; } java.util.List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); TestSuite suite = suites.get(0); tests.setCount(suite.getTestCount()); assertions.setCount(suite.getAssertionCount()); passes.setCount(suite.getTestCount() - suite.getFailureCount() - suite.getErrorCount() ); failures.setCount(suite.getFailureCount()); errors.setCount(suite.getErrorCount()); if (!suite.hasErrorChild()) { progressBar.setBackground(new Color(progressBar.getDisplay(), GREEN)); } else { progressBar.setBackground(new Color(progressBar.getDisplay(), RED)); } resultTreeViewer.setInput(suites); if (suite.hasErrorChild()) { resultTreeViewer.expandToLevel(2); } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Status.OK_STATUS; } }; job.schedule(); } } }; DebugPlugin.getDefault().addDebugEventListener(listener); // listener = new IDebugEventSetListener() { // @Override // public void handleDebugEvents(DebugEvent[] events) { // for (DebugEvent event: events) { // if (event.getKind() == DebugEvent.TERMINATE // && event.getSource() instanceof IPHPDebugTarget // ) { // final IPHPDebugTarget debugTarget = (IPHPDebugTarget) event.getSource(); // // Job job = new UIJob("MakeGood result parse") { // public IStatus runInUIThread(IProgressMonitor monitor) { // ILaunchConfiguration configuration = debugTarget.getLaunch().getLaunchConfiguration(); // // try { // String logFile = configuration.getAttribute("LOG_JUNIT", (String) null); // List<TestSuite> suites = TestResultConverter.convert(new File(logFile)); // block.setInput(suites); // } catch (CoreException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (Exception e) { // e.printStackTrace(); // } // // String[] results = debugTarget.getOutputBuffer().toString().split("\n"); // int lastLine = results.length - 1; // String result = results[lastLine]; // // root.setText(result); // if (result.startsWith("OK")) { // root.setBackground(new Color(null, 0, 255, 0)); // } else { // root.setBackground(new Color(null, 255, 0, 0)); // } // // return Status.OK_STATUS; // } // }; // job.schedule(); // } // } // } // }; // DebugPlugin.getDefault().addDebugEventListener(listener); }
diff --git a/src/dungeonCrawler/GameElements/Player.java b/src/dungeonCrawler/GameElements/Player.java index a3f9c46..6ddacaf 100644 --- a/src/dungeonCrawler/GameElements/Player.java +++ b/src/dungeonCrawler/GameElements/Player.java @@ -1,139 +1,142 @@ package dungeonCrawler.GameElements; import java.awt.Color; import java.awt.Graphics; import java.util.EnumSet; import java.util.LinkedList; import dungeonCrawler.ElementType; import dungeonCrawler.GameElement; import dungeonCrawler.GameEvent; import dungeonCrawler.GameLogic; import dungeonCrawler.GameObject; import dungeonCrawler.Vector2d; /** * @author Tissen * */ public class Player extends GameElement { public final int maxHealth = 1000; public final int maxMana = 100; private int Health=maxHealth; private int mana = maxMana; public final int maxArmor = 1000; private int armor = 0; private int lives=3; private int money; private LinkedList<GameObject> inventar = new LinkedList<GameObject>(); /** * @param position * @param size */ public Player(Vector2d position, Vector2d size) { super(position, size, "PLAYER", EnumSet.of(ElementType.MOVABLE)); } @Override public void draw(Graphics g) { // TODO Auto-generated method stub g.setColor(Color.BLUE); g.fillRect(0, 0, size.getX(), size.getY()); } public void add(GameObject object){ inventar.add(object); } @Override public void GameEventPerformed(GameEvent e) { // TODO Auto-generated method stub } public void setHealth(int Health) { this.Health = Health; } public void increaseHealth(int Health) { this.Health += Health; if(this.Health > this.maxHealth) this.Health = this.maxHealth; } public void reduceHealth(int Health, GameLogic logic) { this.armor -= Health; System.out.print("R�stung absorbiert "); if (this.armor<0) { System.out.println((Health+this.armor) + " Schaden"); Health = this.armor*(-1); this.armor = 0; } - else System.out.println(Health + " Schaden"); + else { + System.out.println(Health + " Schaden"); + Health = 0; + } if (this.Health-Health > 0){ this.Health = this.Health-Health; System.out.println("Health verloren! Health: " + this.Health); } else { lives--; if(lives<0){ this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); } else { this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); this.Health = 1000; logic.teleportElement(this, logic.getCheckPoint()); } } } public boolean reduceMana(int mana, GameLogic logic) { if (this.mana-mana >= 0){ this.mana = this.mana-mana; return true; } return false; } public void increaseMana(int mana) { this.mana += mana; if(this.mana > this.maxMana) this.mana = this.maxMana; } public int getHealth() { return this.Health; } public int getMana() { return mana; } public void setMana(int m) { this.mana = m; } public LinkedList<GameObject> getInventar() { return inventar; } public int getMoney() { return this.money; } public void setMoney(int money) { this.money = money; } public void addItem(GameObject item) { this.inventar.add(item); } public void increaseArmor(int arm) { this.armor += arm; if(this.armor > this.maxArmor) this.armor = this.maxArmor; } }
true
true
public void reduceHealth(int Health, GameLogic logic) { this.armor -= Health; System.out.print("R�stung absorbiert "); if (this.armor<0) { System.out.println((Health+this.armor) + " Schaden"); Health = this.armor*(-1); this.armor = 0; } else System.out.println(Health + " Schaden"); if (this.Health-Health > 0){ this.Health = this.Health-Health; System.out.println("Health verloren! Health: " + this.Health); } else { lives--; if(lives<0){ this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); } else { this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); this.Health = 1000; logic.teleportElement(this, logic.getCheckPoint()); } } }
public void reduceHealth(int Health, GameLogic logic) { this.armor -= Health; System.out.print("R�stung absorbiert "); if (this.armor<0) { System.out.println((Health+this.armor) + " Schaden"); Health = this.armor*(-1); this.armor = 0; } else { System.out.println(Health + " Schaden"); Health = 0; } if (this.Health-Health > 0){ this.Health = this.Health-Health; System.out.println("Health verloren! Health: " + this.Health); } else { lives--; if(lives<0){ this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); } else { this.Health -= Health; System.out.println("!TOT! (x.x) Health: " + this.Health); this.Health = 1000; logic.teleportElement(this, logic.getCheckPoint()); } } }