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/game/things/Door.java b/game/things/Door.java index 43208f9..930dd6b 100644 --- a/game/things/Door.java +++ b/game/things/Door.java @@ -1,95 +1,95 @@ package game.things; import java.util.ArrayList; import java.util.List; import util.Direction; import serialization.*; import game.*; public class Door extends AbstractGameThing { public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){ union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){ public String type(GameThing g){ return g instanceof Door? "door" : null; } }); union.addSerializer("door", new Serializer<GameThing>(){ public Tree write(GameThing o){ Door in = (Door)o; Tree out = new Tree(); out.add(new Tree.Entry("open", new Tree(in.openRenderer))); out.add(new Tree.Entry("close", new Tree(in.closedRenderer))); out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open))); return out; } public GameThing read(Tree in){ - return new Door(world, in.find("open").value(), in.find("close").value(), Serializers.Serializer_Boolean.read(in.find("state"))); + return new Door(world, in.find("close").value(), in.find("open").value(), Serializers.Serializer_Boolean.read(in.find("state"))); } }); } private final String openRenderer; private final String closedRenderer; private boolean open; public Door(GameWorld world, String closedRenderer, String openRenderer, boolean open){ super(world); this.openRenderer = openRenderer; this.closedRenderer = closedRenderer; this.open = open; update(); } @Override public String renderer(){ return open?openRenderer:closedRenderer; } @Override public List<String> interactions(){ return new ArrayList<String>(){private static final long serialVersionUID = 1L;{this.add(defaultInteraction());}}; } @Override public String defaultInteraction() { if(open) { return "close"; } else { return "open"; } } public void walkAndSet(final boolean s, Player p){ Location l = location(); if(l instanceof Level.Location) p.moveTo((Level.Location)l, 1, new Runnable(){ public void run(){ open = s; update(); } }); } @Override public void interact(String inter, Player who) { if(inter.equals("close")) walkAndSet(false, who); else if(inter.equals("open")) walkAndSet(true, who); } @Override public String name(){ return "Door"; } @Override public boolean canWalkInto(Direction d, game.things.Player who){ return open; } }
true
true
public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){ union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){ public String type(GameThing g){ return g instanceof Door? "door" : null; } }); union.addSerializer("door", new Serializer<GameThing>(){ public Tree write(GameThing o){ Door in = (Door)o; Tree out = new Tree(); out.add(new Tree.Entry("open", new Tree(in.openRenderer))); out.add(new Tree.Entry("close", new Tree(in.closedRenderer))); out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open))); return out; } public GameThing read(Tree in){ return new Door(world, in.find("open").value(), in.find("close").value(), Serializers.Serializer_Boolean.read(in.find("state"))); } }); }
public static void makeSerializer(SerializerUnion<GameThing> union, final GameWorld world){ union.addIdentifier(new SerializerUnion.Identifier<GameThing>(){ public String type(GameThing g){ return g instanceof Door? "door" : null; } }); union.addSerializer("door", new Serializer<GameThing>(){ public Tree write(GameThing o){ Door in = (Door)o; Tree out = new Tree(); out.add(new Tree.Entry("open", new Tree(in.openRenderer))); out.add(new Tree.Entry("close", new Tree(in.closedRenderer))); out.add(new Tree.Entry("state", Serializers.Serializer_Boolean.write(in.open))); return out; } public GameThing read(Tree in){ return new Door(world, in.find("close").value(), in.find("open").value(), Serializers.Serializer_Boolean.read(in.find("state"))); } }); }
diff --git a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/DataLatch.java b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/DataLatch.java index 2f0e01f..c671c82 100644 --- a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/DataLatch.java +++ b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/DataLatch.java @@ -1,156 +1,161 @@ /* * Copyright 2010 the original author or authors. * Copyright 2009 Paxxis Technology LLC * * 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.paxxis.cornerstone.common; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; /** * Used to wait for an object to be supplied * by another thread. It's used to synchronize a producer and * consumer thread and deliver the data to exactly one consumer. * * @author Robert Englander */ public class DataLatch { private static final Logger logger = Logger.getLogger(DataLatch.class); // the object that is being waited for private Object obj; private CountDownLatch latch = new CountDownLatch(1); private boolean interrupted = false; private boolean timedout = false; private Thread waiting; /** * Block until the object is available. This is called * by the consumer side of the interaction. It is illegal to * call this method from multiple threads. It is also illegal to * call this method more than once. * * @return the object */ public Object waitForObject(long timeout) { synchronized (this) { if (!isWaitable()) { IllegalStateException e = new IllegalStateException("Illegal state for consumption"); logger.error(e); throw e; } this.waiting = Thread.currentThread(); } try { + if (timeout < 1) { + //this effectively waits forever - normally zero or less means + //wait forever but in CountDownLatch it means don't wait... + timeout = Long.MAX_VALUE; + } this.timedout = !this.latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { // no-op is correct behavior this.interrupted = true; } synchronized (this) { // grab the object for return to the caller Object result = obj; // set internals to null so data latch cannot be reused obj = null; this.latch = null; this.waiting = null; return result; } } /** * Block until the object is available. This is called * by the consumer side of the interaction. * * @return the object */ public Object waitForObject() { return waitForObject(0); } /** * Set the object that the threads are synchronizing on. This * is called by the producer side of the interaction. Calling this * method more than once or after the consumer has already attempted to * retrieve the data has no effect. * * @param obj the object */ public synchronized void setObject(Object obj) { if (!isSettable()) { //no point to setting the object, the waiting thread is long gone... logger.warn("Trying to set data on latch that is not settable"); return; } this.obj = obj; this.latch.countDown(); } /** * Pool if the data has been set (no waiting). To get the data call * waitForObject. */ public synchronized boolean hasObject() { return this.obj != null; } /** * Will return true if the waiting thread was interrupted. */ public synchronized boolean isInterrupted() { return this.interrupted; } /** * Will return true if the waiting thread timed-out. */ public synchronized boolean hasTimedout() { return this.timedout; } /** * Will return true if this data latch is in a valid state for consumers */ public synchronized boolean isWaitable() { return this.waiting == null && isSettable(); } /** * Will return true if this data latch is in a valid state for producers */ public synchronized boolean isSettable() { return this.latch != null; } /** * Convenience method to determine if data latch was successfully used * without time-out or interruption of consumer. This is in the case that * waitForObject returns null and you need to know if that is because * the a timeout or interrupt occurred. */ public synchronized boolean isSuccessful() { return this.latch == null && !this.timedout && !this.interrupted; } }
true
true
public Object waitForObject(long timeout) { synchronized (this) { if (!isWaitable()) { IllegalStateException e = new IllegalStateException("Illegal state for consumption"); logger.error(e); throw e; } this.waiting = Thread.currentThread(); } try { this.timedout = !this.latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { // no-op is correct behavior this.interrupted = true; } synchronized (this) { // grab the object for return to the caller Object result = obj; // set internals to null so data latch cannot be reused obj = null; this.latch = null; this.waiting = null; return result; } }
public Object waitForObject(long timeout) { synchronized (this) { if (!isWaitable()) { IllegalStateException e = new IllegalStateException("Illegal state for consumption"); logger.error(e); throw e; } this.waiting = Thread.currentThread(); } try { if (timeout < 1) { //this effectively waits forever - normally zero or less means //wait forever but in CountDownLatch it means don't wait... timeout = Long.MAX_VALUE; } this.timedout = !this.latch.await(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { // no-op is correct behavior this.interrupted = true; } synchronized (this) { // grab the object for return to the caller Object result = obj; // set internals to null so data latch cannot be reused obj = null; this.latch = null; this.waiting = null; return result; } }
diff --git a/src/main/java/org/elasticsearch/shell/json/RhinoStringToJson.java b/src/main/java/org/elasticsearch/shell/json/RhinoStringToJson.java index dc3ebf1..f3a54aa 100644 --- a/src/main/java/org/elasticsearch/shell/json/RhinoStringToJson.java +++ b/src/main/java/org/elasticsearch/shell/json/RhinoStringToJson.java @@ -1,46 +1,46 @@ /* * Licensed to Luca Cavanna (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search 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.elasticsearch.shell.json; import org.mozilla.javascript.Context; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.json.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Luca Cavanna * * Handles the conversion from string to native json depending on the rhino engine * A generic <code>Object</code> is produced from a String */ public class RhinoStringToJson implements StringToJson<Object> { private static final Logger logger = LoggerFactory.getLogger(RhinoStringToJson.class); @Override public Object stringToJson(String json) { Context context = Context.getCurrentContext(); try { return new JsonParser(context, ScriptRuntime.getGlobal(context)).parseValue(json); } catch (JsonParser.ParseException e) { logger.error("Unable to create a json object from string {}", json, e); - return null; + throw new IllegalArgumentException(e.getMessage(), e); } } }
true
true
public Object stringToJson(String json) { Context context = Context.getCurrentContext(); try { return new JsonParser(context, ScriptRuntime.getGlobal(context)).parseValue(json); } catch (JsonParser.ParseException e) { logger.error("Unable to create a json object from string {}", json, e); return null; } }
public Object stringToJson(String json) { Context context = Context.getCurrentContext(); try { return new JsonParser(context, ScriptRuntime.getGlobal(context)).parseValue(json); } catch (JsonParser.ParseException e) { logger.error("Unable to create a json object from string {}", json, e); throw new IllegalArgumentException(e.getMessage(), e); } }
diff --git a/src/cx/mccormick/pddroidparty/Slider.java b/src/cx/mccormick/pddroidparty/Slider.java index f066d25..781144f 100644 --- a/src/cx/mccormick/pddroidparty/Slider.java +++ b/src/cx/mccormick/pddroidparty/Slider.java @@ -1,100 +1,100 @@ package cx.mccormick.pddroidparty; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.graphics.Canvas; import android.graphics.RectF; import android.graphics.Paint; import android.view.MotionEvent; import android.util.Log; public class Slider extends Widget { private static final String TAG = "Slider"; float min, max; int log; RectF dRect; boolean orientation_horizontal = true; boolean down = false; public Slider(PdDroidPatchView app, String[] atomline, boolean horizontal) { super(app); orientation_horizontal = horizontal; x = Float.parseFloat(atomline[2]) / parent.patchwidth * screenwidth; y = Float.parseFloat(atomline[3]) / parent.patchheight * screenheight; w = Float.parseFloat(atomline[5]) / parent.patchwidth * screenwidth; h = Float.parseFloat(atomline[6]) / parent.patchheight * screenheight; min = Float.parseFloat(atomline[7]); max = Float.parseFloat(atomline[8]); log = Integer.parseInt(atomline[9]); init = Integer.parseInt(atomline[10]); sendname = atomline[11]; receivename = atomline[12]; label = setLabel(atomline[13]); labelpos[0] = Float.parseFloat(atomline[14]) / parent.patchwidth * screenwidth; labelpos[1] = Float.parseFloat(atomline[15]) / parent.patchheight * screenheight; - setval((Float.parseFloat(atomline[21]) / 100) / w, min); + setval((float)(Float.parseFloat(atomline[21]) * 0.01 * (max - min) / (Float.parseFloat(atomline[5]) - 1) + min), min); // listen out for floats from Pd setupreceive(); // send initial value if we have one initval(); // graphics setup dRect = new RectF(Math.round(x), Math.round(y), Math.round(x + w), Math.round(y + h)); } public void draw(Canvas canvas) { canvas.drawLine(dRect.left + 1, dRect.top, dRect.right, dRect.top, paint); canvas.drawLine(dRect.left + 1, dRect.bottom, dRect.right, dRect.bottom, paint); canvas.drawLine(dRect.left, dRect.top + 1, dRect.left, dRect.bottom, paint); canvas.drawLine(dRect.right, dRect.top + 1, dRect.right, dRect.bottom, paint); if (orientation_horizontal) { canvas.drawLine(Math.round(x + ((val - min) / (max - min)) * w), Math.round(y + 2), Math.round(x + ((val - min) / (max - min)) * w), Math.round(y + h - 2), paint); } else { canvas.drawLine(Math.round(x + 2), Math.round((y + h) - ((val - min) / (max - min)) * h), Math.round(x + w - 2), Math.round((y + h) - ((val - min) / (max - min)) * h), paint); } drawLabel(canvas); } public void touch(MotionEvent event) { float ex = event.getX(); float ey = event.getY(); if (event.getAction() == event.ACTION_DOWN && inside(ex, ey)) { down = true; } if (down) { //Log.e(TAG, "touch:" + val); if (event.getAction() == event.ACTION_DOWN || event.getAction() == event.ACTION_MOVE) { // calculate the new value based on touch if (orientation_horizontal) { val = (((ex - x) / w) * (max - min) + min); } else { val = (((h - (ey - y)) / h) * (max - min) + min); } // clamp the value val = Math.min(max, Math.max(min, val)); // send the result to Pd send("" + val); } else if (event.getAction() == event.ACTION_UP) { down = false; } } } public void receiveFloat(float v) { val = Math.min(max, Math.max(v, min)); } }
true
true
public Slider(PdDroidPatchView app, String[] atomline, boolean horizontal) { super(app); orientation_horizontal = horizontal; x = Float.parseFloat(atomline[2]) / parent.patchwidth * screenwidth; y = Float.parseFloat(atomline[3]) / parent.patchheight * screenheight; w = Float.parseFloat(atomline[5]) / parent.patchwidth * screenwidth; h = Float.parseFloat(atomline[6]) / parent.patchheight * screenheight; min = Float.parseFloat(atomline[7]); max = Float.parseFloat(atomline[8]); log = Integer.parseInt(atomline[9]); init = Integer.parseInt(atomline[10]); sendname = atomline[11]; receivename = atomline[12]; label = setLabel(atomline[13]); labelpos[0] = Float.parseFloat(atomline[14]) / parent.patchwidth * screenwidth; labelpos[1] = Float.parseFloat(atomline[15]) / parent.patchheight * screenheight; setval((Float.parseFloat(atomline[21]) / 100) / w, min); // listen out for floats from Pd setupreceive(); // send initial value if we have one initval(); // graphics setup dRect = new RectF(Math.round(x), Math.round(y), Math.round(x + w), Math.round(y + h)); }
public Slider(PdDroidPatchView app, String[] atomline, boolean horizontal) { super(app); orientation_horizontal = horizontal; x = Float.parseFloat(atomline[2]) / parent.patchwidth * screenwidth; y = Float.parseFloat(atomline[3]) / parent.patchheight * screenheight; w = Float.parseFloat(atomline[5]) / parent.patchwidth * screenwidth; h = Float.parseFloat(atomline[6]) / parent.patchheight * screenheight; min = Float.parseFloat(atomline[7]); max = Float.parseFloat(atomline[8]); log = Integer.parseInt(atomline[9]); init = Integer.parseInt(atomline[10]); sendname = atomline[11]; receivename = atomline[12]; label = setLabel(atomline[13]); labelpos[0] = Float.parseFloat(atomline[14]) / parent.patchwidth * screenwidth; labelpos[1] = Float.parseFloat(atomline[15]) / parent.patchheight * screenheight; setval((float)(Float.parseFloat(atomline[21]) * 0.01 * (max - min) / (Float.parseFloat(atomline[5]) - 1) + min), min); // listen out for floats from Pd setupreceive(); // send initial value if we have one initval(); // graphics setup dRect = new RectF(Math.round(x), Math.round(y), Math.round(x + w), Math.round(y + h)); }
diff --git a/src/paulscode/android/mupen64plusae/input/map/AxisMap.java b/src/paulscode/android/mupen64plusae/input/map/AxisMap.java index aeea5bb1..d57dbaf4 100644 --- a/src/paulscode/android/mupen64plusae/input/map/AxisMap.java +++ b/src/paulscode/android/mupen64plusae/input/map/AxisMap.java @@ -1,195 +1,197 @@ package paulscode.android.mupen64plusae.input.map; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.annotation.TargetApi; import android.text.TextUtils; import android.util.SparseArray; import android.view.InputDevice; import android.view.InputDevice.MotionRange; import android.view.MotionEvent; @TargetApi( 9 ) public class AxisMap extends SerializableMap { public static final int AXIS_CLASS_UNKNOWN = 0; public static final int AXIS_CLASS_IGNORED = 1; public static final int AXIS_CLASS_STICK = 2; public static final int AXIS_CLASS_TRIGGER = 3; public static final int AXIS_CLASS_N64_USB_STICK = 102; private static final int SIGNATURE_HASH_XBOX360 = 449832952; private static final int SIGNATURE_HASH_XBOX360_WIRELESS = -412618953; private static final int SIGNATURE_HASH_PS3 = -528816963; private static final int SIGNATURE_HASH_NYKO_PLAYPAD = 1245841466; private static final int SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD = 1247256123; private static final int SIGNATURE_HASH_MOGA_PRO = -1933523749; private static final int SIGNATURE_HASH_OUYA = 699487739; private static final SparseArray<AxisMap> sAllMaps = new SparseArray<AxisMap>(); private final String mSignature; private final String mSignatureName; public static AxisMap getMap( InputDevice device ) { if( device == null ) return null; int id = device.hashCode(); AxisMap map = sAllMaps.get( id ); if( map == null ) { // Add an entry to the map if not found map = new AxisMap( device ); sAllMaps.put( id, map ); } return map; } @TargetApi( 12 ) public AxisMap( InputDevice device ) { // Auto-classify the axes List<MotionRange> motionRanges = device.getMotionRanges(); List<Integer> axisCodes = new ArrayList<Integer>(); for( MotionRange motionRange : motionRanges ) { if( motionRange.getSource() == InputDevice.SOURCE_JOYSTICK ) { int axisCode = motionRange.getAxis(); int axisClass = detectClass( motionRange ); setClass( axisCode, axisClass ); axisCodes.add( axisCode ); } } // Construct the signature based on the available axes Collections.sort( axisCodes ); mSignature = TextUtils.join( ",", axisCodes ); String signatureName = "Default"; String deviceName = device.getName(); // Use the signature to override faulty auto-classifications switch( mSignature.hashCode() ) { case SIGNATURE_HASH_XBOX360: case SIGNATURE_HASH_XBOX360_WIRELESS: // Resting value is -1 on the analog triggers; fix that setClass( MotionEvent.AXIS_Z, AXIS_CLASS_TRIGGER ); setClass( MotionEvent.AXIS_RZ, AXIS_CLASS_TRIGGER ); signatureName = mSignature.hashCode() == SIGNATURE_HASH_XBOX360_WIRELESS ? "Xbox 360 wireless" : "Xbox 360 compatible"; break; case SIGNATURE_HASH_PS3: // Ignore pressure sensitive buttons (buggy on Android) setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_5, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_6, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_7, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_8, AXIS_CLASS_IGNORED ); signatureName = "PS3 compatible"; break; case SIGNATURE_HASH_NYKO_PLAYPAD: if( !deviceName.contains( "NYKO PLAYPAD" ) && - !deviceName.contains( "Mad Catz" ) ) + !deviceName.contains( "Mad Catz" ) && + !deviceName.contains( "ipega" ) ) { // The first batch of Nyko Playpad controllers have a quirk in the firmware // where AXIS_HAT_X/Y are sent with (and overpower) AXIS_X/Y, and do not // provide a recognizable name for the controller. Newer batches of this // controller fix the quirk, making it a vanilla controller. However the // AXIS_HAT_X/Y channels are now used for the d-pad, so we can't apply a // universal solution for all versions of this controller. Fortunately, the // new version also returns a good name that we can use to differentiate // controller firmware versions. // - // The Mad Catz C.T.R.L.R. controller has the same axis signature as the Nyko - // Playpad, but without the Nyko defect, so we have to check that as well. + // The Mad Catz C.T.R.L.R. and IPEGA PG-9025 controller have the same axis + // signature as the Nyko Playpad, but without the Nyko defect, so we have to + // check that as well. // // For original firmware, ignore AXIS_HAT_X/Y because they are sent with (and // overpower) AXIS_X/Y setClass( MotionEvent.AXIS_HAT_X, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_HAT_Y, AXIS_CLASS_IGNORED ); signatureName = "Nyko PlayPad series (original firmware)"; } break; case SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD: // Bug in controller firmware cross-wires throttle and right stick up/down setClass( MotionEvent.AXIS_THROTTLE, AXIS_CLASS_STICK ); signatureName = "Logitech Wingman Rumblepad"; break; case SIGNATURE_HASH_MOGA_PRO: // Ignore two spurious axes for MOGA Pro in HID (B) mode (as of MOGA Pivot v1.15) // http://www.paulscode.com/forum/index.php?topic=581.msg10094#msg10094 setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); signatureName = "Moga Pro (HID mode)"; break; case SIGNATURE_HASH_OUYA: // Ignore phantom triggers setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); signatureName = "OUYA controller"; break; } // Check if the controller is an N64/USB adapter, to compensate for range of motion if( deviceName.contains( "raphnet.net GC/N64_USB" ) || deviceName.contains( "raphnet.net GC/N64 to USB, v2" ) || deviceName.contains( "HuiJia USB GamePad" ) ) // double space is not a typo { setClass( MotionEvent.AXIS_X, AXIS_CLASS_N64_USB_STICK ); setClass( MotionEvent.AXIS_Y, AXIS_CLASS_N64_USB_STICK ); signatureName = "N64 USB adapter"; } mSignatureName = signatureName; } public void setClass( int axisCode, int axisClass ) { if( axisClass == AXIS_CLASS_UNKNOWN ) mMap.delete( axisCode ); else mMap.put( axisCode, axisClass ); } public int getClass( int axisCode ) { return mMap.get( axisCode ); } public String getSignature() { return mSignature; } public String getSignatureName() { return mSignatureName; } @TargetApi( 12 ) private static int detectClass( MotionRange motionRange ) { if( motionRange != null ) { if( motionRange.getMin() == -1 ) return AXIS_CLASS_STICK; else if( motionRange.getMin() == 0 ) return AXIS_CLASS_TRIGGER; } return AXIS_CLASS_UNKNOWN; } }
false
true
public AxisMap( InputDevice device ) { // Auto-classify the axes List<MotionRange> motionRanges = device.getMotionRanges(); List<Integer> axisCodes = new ArrayList<Integer>(); for( MotionRange motionRange : motionRanges ) { if( motionRange.getSource() == InputDevice.SOURCE_JOYSTICK ) { int axisCode = motionRange.getAxis(); int axisClass = detectClass( motionRange ); setClass( axisCode, axisClass ); axisCodes.add( axisCode ); } } // Construct the signature based on the available axes Collections.sort( axisCodes ); mSignature = TextUtils.join( ",", axisCodes ); String signatureName = "Default"; String deviceName = device.getName(); // Use the signature to override faulty auto-classifications switch( mSignature.hashCode() ) { case SIGNATURE_HASH_XBOX360: case SIGNATURE_HASH_XBOX360_WIRELESS: // Resting value is -1 on the analog triggers; fix that setClass( MotionEvent.AXIS_Z, AXIS_CLASS_TRIGGER ); setClass( MotionEvent.AXIS_RZ, AXIS_CLASS_TRIGGER ); signatureName = mSignature.hashCode() == SIGNATURE_HASH_XBOX360_WIRELESS ? "Xbox 360 wireless" : "Xbox 360 compatible"; break; case SIGNATURE_HASH_PS3: // Ignore pressure sensitive buttons (buggy on Android) setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_5, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_6, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_7, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_8, AXIS_CLASS_IGNORED ); signatureName = "PS3 compatible"; break; case SIGNATURE_HASH_NYKO_PLAYPAD: if( !deviceName.contains( "NYKO PLAYPAD" ) && !deviceName.contains( "Mad Catz" ) ) { // The first batch of Nyko Playpad controllers have a quirk in the firmware // where AXIS_HAT_X/Y are sent with (and overpower) AXIS_X/Y, and do not // provide a recognizable name for the controller. Newer batches of this // controller fix the quirk, making it a vanilla controller. However the // AXIS_HAT_X/Y channels are now used for the d-pad, so we can't apply a // universal solution for all versions of this controller. Fortunately, the // new version also returns a good name that we can use to differentiate // controller firmware versions. // // The Mad Catz C.T.R.L.R. controller has the same axis signature as the Nyko // Playpad, but without the Nyko defect, so we have to check that as well. // // For original firmware, ignore AXIS_HAT_X/Y because they are sent with (and // overpower) AXIS_X/Y setClass( MotionEvent.AXIS_HAT_X, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_HAT_Y, AXIS_CLASS_IGNORED ); signatureName = "Nyko PlayPad series (original firmware)"; } break; case SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD: // Bug in controller firmware cross-wires throttle and right stick up/down setClass( MotionEvent.AXIS_THROTTLE, AXIS_CLASS_STICK ); signatureName = "Logitech Wingman Rumblepad"; break; case SIGNATURE_HASH_MOGA_PRO: // Ignore two spurious axes for MOGA Pro in HID (B) mode (as of MOGA Pivot v1.15) // http://www.paulscode.com/forum/index.php?topic=581.msg10094#msg10094 setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); signatureName = "Moga Pro (HID mode)"; break; case SIGNATURE_HASH_OUYA: // Ignore phantom triggers setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); signatureName = "OUYA controller"; break; } // Check if the controller is an N64/USB adapter, to compensate for range of motion if( deviceName.contains( "raphnet.net GC/N64_USB" ) || deviceName.contains( "raphnet.net GC/N64 to USB, v2" ) || deviceName.contains( "HuiJia USB GamePad" ) ) // double space is not a typo { setClass( MotionEvent.AXIS_X, AXIS_CLASS_N64_USB_STICK ); setClass( MotionEvent.AXIS_Y, AXIS_CLASS_N64_USB_STICK ); signatureName = "N64 USB adapter"; } mSignatureName = signatureName; }
public AxisMap( InputDevice device ) { // Auto-classify the axes List<MotionRange> motionRanges = device.getMotionRanges(); List<Integer> axisCodes = new ArrayList<Integer>(); for( MotionRange motionRange : motionRanges ) { if( motionRange.getSource() == InputDevice.SOURCE_JOYSTICK ) { int axisCode = motionRange.getAxis(); int axisClass = detectClass( motionRange ); setClass( axisCode, axisClass ); axisCodes.add( axisCode ); } } // Construct the signature based on the available axes Collections.sort( axisCodes ); mSignature = TextUtils.join( ",", axisCodes ); String signatureName = "Default"; String deviceName = device.getName(); // Use the signature to override faulty auto-classifications switch( mSignature.hashCode() ) { case SIGNATURE_HASH_XBOX360: case SIGNATURE_HASH_XBOX360_WIRELESS: // Resting value is -1 on the analog triggers; fix that setClass( MotionEvent.AXIS_Z, AXIS_CLASS_TRIGGER ); setClass( MotionEvent.AXIS_RZ, AXIS_CLASS_TRIGGER ); signatureName = mSignature.hashCode() == SIGNATURE_HASH_XBOX360_WIRELESS ? "Xbox 360 wireless" : "Xbox 360 compatible"; break; case SIGNATURE_HASH_PS3: // Ignore pressure sensitive buttons (buggy on Android) setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_5, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_6, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_7, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_8, AXIS_CLASS_IGNORED ); signatureName = "PS3 compatible"; break; case SIGNATURE_HASH_NYKO_PLAYPAD: if( !deviceName.contains( "NYKO PLAYPAD" ) && !deviceName.contains( "Mad Catz" ) && !deviceName.contains( "ipega" ) ) { // The first batch of Nyko Playpad controllers have a quirk in the firmware // where AXIS_HAT_X/Y are sent with (and overpower) AXIS_X/Y, and do not // provide a recognizable name for the controller. Newer batches of this // controller fix the quirk, making it a vanilla controller. However the // AXIS_HAT_X/Y channels are now used for the d-pad, so we can't apply a // universal solution for all versions of this controller. Fortunately, the // new version also returns a good name that we can use to differentiate // controller firmware versions. // // The Mad Catz C.T.R.L.R. and IPEGA PG-9025 controller have the same axis // signature as the Nyko Playpad, but without the Nyko defect, so we have to // check that as well. // // For original firmware, ignore AXIS_HAT_X/Y because they are sent with (and // overpower) AXIS_X/Y setClass( MotionEvent.AXIS_HAT_X, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_HAT_Y, AXIS_CLASS_IGNORED ); signatureName = "Nyko PlayPad series (original firmware)"; } break; case SIGNATURE_HASH_LOGITECH_WINGMAN_RUMBLEPAD: // Bug in controller firmware cross-wires throttle and right stick up/down setClass( MotionEvent.AXIS_THROTTLE, AXIS_CLASS_STICK ); signatureName = "Logitech Wingman Rumblepad"; break; case SIGNATURE_HASH_MOGA_PRO: // Ignore two spurious axes for MOGA Pro in HID (B) mode (as of MOGA Pivot v1.15) // http://www.paulscode.com/forum/index.php?topic=581.msg10094#msg10094 setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); signatureName = "Moga Pro (HID mode)"; break; case SIGNATURE_HASH_OUYA: // Ignore phantom triggers setClass( MotionEvent.AXIS_GENERIC_1, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_2, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_3, AXIS_CLASS_IGNORED ); setClass( MotionEvent.AXIS_GENERIC_4, AXIS_CLASS_IGNORED ); signatureName = "OUYA controller"; break; } // Check if the controller is an N64/USB adapter, to compensate for range of motion if( deviceName.contains( "raphnet.net GC/N64_USB" ) || deviceName.contains( "raphnet.net GC/N64 to USB, v2" ) || deviceName.contains( "HuiJia USB GamePad" ) ) // double space is not a typo { setClass( MotionEvent.AXIS_X, AXIS_CLASS_N64_USB_STICK ); setClass( MotionEvent.AXIS_Y, AXIS_CLASS_N64_USB_STICK ); signatureName = "N64 USB adapter"; } mSignatureName = signatureName; }
diff --git a/bii/lexergenerator/src/main/java/regextodfaconverter/MinimalDfa.java b/bii/lexergenerator/src/main/java/regextodfaconverter/MinimalDfa.java index 8587142c..864c2513 100644 --- a/bii/lexergenerator/src/main/java/regextodfaconverter/MinimalDfa.java +++ b/bii/lexergenerator/src/main/java/regextodfaconverter/MinimalDfa.java @@ -1,150 +1,150 @@ /* * * Copyright 2012 lexergen. * This file is part of lexergen. * * lexergen 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. * * lexergen 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 lexergen. If not, see <http://www.gnu.org/licenses/>. * * lexergen: * A tool to chunk source code into tokens for further processing in a compiler chain. * * Projectgroup: bi, bii * * Authors: Johannes Dahlke * * Module: Softwareprojekt Übersetzerbau 2012 * * Created: Apr. 2012 * Version: 1.0 * */ package regextodfaconverter; import java.util.Collection; import regextodfaconverter.fsm.FiniteStateMachine; import tokenmatcher.DeterministicFiniteAutomata; import tokenmatcher.State; /** * Adapter zur Anpassung an das DFA Interface des TokenMatchers. Garantiert, * dass der gekapselte FSA auch sicher ein DFA ist. * * @author Johannes Dahlke * @author Daniel Rotar * * @param <ConditionType> * Der Typ der Bedingung für einen Zustandsübergang beim verwendeten * endlichen Automaten. * @param <PayloadType> * Der Typ des Inhalts der Zustände beim verwendeten endlichen * Automaten. */ public class MinimalDfa<ConditionType extends Comparable<ConditionType>, PayloadType> implements DeterministicFiniteAutomata<ConditionType, PayloadType> { /** * Der endliche Automat auf dem gearbeitet wird. */ private FiniteStateMachine<ConditionType, PayloadType> finiteStateMachine; /** * Erstellt ein neues MinimalDfa Objekt und garantiert dabei, dass der * endliche Automat ein DFA ist und minimal ist. * * @param finiteStateMachine * Der endliche Automat, aus dem der minimale DFA erstellt werden * soll. * @throws ConvertExecption * Wenn bei der konvertierung in ein DFA oder bei der * minimierung des DFAs ein Fehler auftritt. */ public MinimalDfa( FiniteStateMachine<ConditionType, PayloadType> finiteStateMachine) throws ConvertExecption { super(); this.finiteStateMachine = finiteStateMachine; try { - if (!finiteStateMachine.isDeterministic()) { + if (!this.finiteStateMachine.isDeterministic()) { NfaToDfaConverter<ConditionType, PayloadType> converter = new NfaToDfaConverter<ConditionType, PayloadType>(); - finiteStateMachine = converter.convertToDfa(finiteStateMachine); + this.finiteStateMachine = converter.convertToDfa(this.finiteStateMachine); } DfaMinimizer<ConditionType, PayloadType> minimizer = new DfaMinimizer<ConditionType, PayloadType>(); - finiteStateMachine = minimizer - .convertToMimimumDfa(finiteStateMachine); + this.finiteStateMachine = minimizer + .convertToMimimumDfa(this.finiteStateMachine); } catch (Exception e) { throw new ConvertExecption( "Cannot convert given fsa to minimal dfa."); } } /** * Wechselt in einen anderen Zustand, sofern es einen Übergang in der * Übergangstabelle ausgehend vom aktuellen Zustand in den angegebenen * Element gibt. * * @param element * Das Element, welches den Übergang definiert. * @return Den neuen Zustand oder null, falls es keinen Übergang in der * Übergangstabelle gibt. */ public State<ConditionType, PayloadType> changeStateByElement( ConditionType element) { return finiteStateMachine.changeState(element); } /** * Prüft, ob ein Übergang für das Lesen des spezifizierten Elementes * definiert ist. * * @param element * Das Element, für das geprüft werden soll, ob ein Übergang aus * dem aktuellen Zustand durch Lesen des Elementes definiert ist. * @return true, wenn es einen Übergang gibt, anderenfalls false. */ public boolean canChangeStateByElement(ConditionType element) { return finiteStateMachine.canChangeState(element); } /** * Gibt den aktuellen Zustand zurück. * * @return Der aktuelle Zustand. */ public State<ConditionType, PayloadType> getCurrentState() { return finiteStateMachine.getCurrentState(); } /** * Setzt den DFA wieder in den Startzustand zurück. */ public void resetToInitialState() { finiteStateMachine.resetToInitialState(); } /** * Liefert eine Liste mit allen Elementen, die den vom Zustand state * ausgehenden Übergängen zugeordnet sind. * * @param state * Der Zustand, von dem die Übergange ausgehen. * @return Alle ausgehenden Elemente zu dem angegebenen Zustand. */ public Collection<ConditionType> getElementsOfOutgoingTransitionsFromState( State<ConditionType, PayloadType> state) { return state.getElementsOfOutgoingTransitions(); } }
false
true
public MinimalDfa( FiniteStateMachine<ConditionType, PayloadType> finiteStateMachine) throws ConvertExecption { super(); this.finiteStateMachine = finiteStateMachine; try { if (!finiteStateMachine.isDeterministic()) { NfaToDfaConverter<ConditionType, PayloadType> converter = new NfaToDfaConverter<ConditionType, PayloadType>(); finiteStateMachine = converter.convertToDfa(finiteStateMachine); } DfaMinimizer<ConditionType, PayloadType> minimizer = new DfaMinimizer<ConditionType, PayloadType>(); finiteStateMachine = minimizer .convertToMimimumDfa(finiteStateMachine); } catch (Exception e) { throw new ConvertExecption( "Cannot convert given fsa to minimal dfa."); } }
public MinimalDfa( FiniteStateMachine<ConditionType, PayloadType> finiteStateMachine) throws ConvertExecption { super(); this.finiteStateMachine = finiteStateMachine; try { if (!this.finiteStateMachine.isDeterministic()) { NfaToDfaConverter<ConditionType, PayloadType> converter = new NfaToDfaConverter<ConditionType, PayloadType>(); this.finiteStateMachine = converter.convertToDfa(this.finiteStateMachine); } DfaMinimizer<ConditionType, PayloadType> minimizer = new DfaMinimizer<ConditionType, PayloadType>(); this.finiteStateMachine = minimizer .convertToMimimumDfa(this.finiteStateMachine); } catch (Exception e) { throw new ConvertExecption( "Cannot convert given fsa to minimal dfa."); } }
diff --git a/plugins/org.eclipse.wst.web/static_web_project/org/eclipse/wst/web/internal/deployables/ComponentDeployable.java b/plugins/org.eclipse.wst.web/static_web_project/org/eclipse/wst/web/internal/deployables/ComponentDeployable.java index 3149b99af..35a287b9f 100644 --- a/plugins/org.eclipse.wst.web/static_web_project/org/eclipse/wst/web/internal/deployables/ComponentDeployable.java +++ b/plugins/org.eclipse.wst.web/static_web_project/org/eclipse/wst/web/internal/deployables/ComponentDeployable.java @@ -1,249 +1,252 @@ /******************************************************************************* * Copyright (c) 2003, 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.wst.web.internal.deployables; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.wst.common.componentcore.ComponentCore; import org.eclipse.wst.common.componentcore.resources.IVirtualComponent; import org.eclipse.wst.common.componentcore.resources.IVirtualContainer; import org.eclipse.wst.common.componentcore.resources.IVirtualFolder; import org.eclipse.wst.common.componentcore.resources.IVirtualReference; import org.eclipse.wst.common.componentcore.resources.IVirtualResource; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.ServerUtil; import org.eclipse.wst.server.core.internal.ModuleFile; import org.eclipse.wst.server.core.internal.ModuleFolder; import org.eclipse.wst.server.core.model.IModuleFolder; import org.eclipse.wst.server.core.model.IModuleResource; import org.eclipse.wst.server.core.util.ProjectModule; public abstract class ComponentDeployable extends ProjectModule { protected IVirtualComponent component = null; protected List members = new ArrayList(); public ComponentDeployable(IProject project) { super(project); this.component = ComponentCore.createComponent(project); } /** * @see org.eclipse.jst.server.core.IJ2EEModule#isBinary() */ public boolean isBinary() { return false; } private void addMembersToModuleFolder(ModuleFolder mf, IModuleResource[] mr) { IModuleResource[] existingMembers = null; if (mf == null || mf.members() == null) existingMembers = new IModuleResource[0]; else existingMembers = mf.members(); if (existingMembers==null) existingMembers = new IModuleResource[0]; List membersJoin = new ArrayList(); membersJoin.addAll(Arrays.asList(existingMembers)); List newMembers = Arrays.asList(mr); for (int i=0; i<newMembers.size(); i++) { boolean found = false; IModuleResource newMember = (IModuleResource) newMembers.get(i); for (int k=0; k<membersJoin.size(); k++) { IModuleResource existingResource = (IModuleResource) membersJoin.get(k); if (existingResource.equals(newMember)) { found = true; break; } } if (!found) membersJoin.add(newMember); } if (mf !=null) mf.setMembers((IModuleResource[]) membersJoin.toArray(new IModuleResource[membersJoin.size()])); } /** * Returns the child modules of this module. * * @return org.eclipse.wst.server.core.model.IModule[] */ public IModule[] getChildModules() { return getModules(); } public IModule[] getModules() { List modules = new ArrayList(); if (component != null) { IVirtualReference[] components = component.getReferences(); for (int i = 0; i < components.length; i++) { IVirtualReference reference = components[i]; IVirtualComponent virtualComp = reference.getReferencedComponent(); if (virtualComp != null && virtualComp.getProject()!=component.getProject()) { Object module = ServerUtil.getModule(virtualComp.getProject()); if (module != null && !modules.contains(module)) modules.add(module); } } } return (IModule[]) modules.toArray(new IModule[modules.size()]); } /** * Find the module resources for a given container and path. Inserts in the java containers * at a given path if not null. * * @param cont a container * @param path the current module relative path * @param javaPath the path where Java resources fit in the root * @param javaCont * @return a possibly-empty array of module resources * @throws CoreException */ protected IModuleResource[] getMembers(IContainer cont, IPath path, IPath javaPath, IContainer[] javaCont) throws CoreException { IResource[] res = cont.members(); int size2 = res.length; List list = new ArrayList(size2); for (int j = 0; j < size2; j++) { if (res[j] instanceof IContainer) { IContainer cc = (IContainer) res[j]; IPath newPath = path.append(cc.getName()); // Retrieve already existing module folder if applicable ModuleFolder mf = (ModuleFolder) getExistingModuleResource(members,newPath); if (mf == null) { mf = new ModuleFolder(cc, cc.getName(), path); list.add(mf); } IModuleResource[] mr = getMembers(cc, newPath, javaPath, javaCont); if (javaPath != null && newPath.isPrefixOf(javaPath)) mr = handleJavaPath(path, javaPath, newPath, javaCont, mr, cc); addMembersToModuleFolder(mf, mr); } else { IFile f = (IFile) res[j]; // Handle the default package case if (path.equals(javaPath)) { ModuleFolder mFolder = (ModuleFolder) getExistingModuleResource(members,javaPath); ModuleFile mFile = new ModuleFile(f, f.getName(), javaPath, f.getModificationStamp() + f.getLocalTimeStamp()); - addMembersToModuleFolder(mFolder,new IModuleResource[]{mFile}); + if (mFolder != null) + addMembersToModuleFolder(mFolder,new IModuleResource[]{mFile}); + else + list.add(mFile); } else { ModuleFile mf = new ModuleFile(f, f.getName(), path, f.getModificationStamp() + f.getLocalTimeStamp()); list.add(mf); } } } IModuleResource[] mr = new IModuleResource[list.size()]; list.toArray(mr); return mr; } protected IModuleResource[] getMembers(IVirtualContainer cont, IPath path) throws CoreException { IVirtualResource[] res = cont.members(); int size2 = res.length; List list = new ArrayList(size2); for (int j = 0; j < size2; j++) { if (res[j] instanceof IVirtualContainer) { IVirtualContainer cc = (IVirtualContainer) res[j]; // Retrieve already existing module folder if applicable ModuleFolder mf = (ModuleFolder) getExistingModuleResource(members,new Path(cc.getName())); if (mf == null) { mf = new ModuleFolder((IContainer)cc.getUnderlyingResource(), cc.getName(), path); list.add(mf); } IModuleResource[] mr = getMembers(cc, path.append(cc.getName())); addMembersToModuleFolder(mf, mr); } else { IFile f = (IFile) res[j].getUnderlyingResource(); if (!isFileInSourceContainer(f)) { ModuleFile mf = new ModuleFile(f, f.getName(), path, f.getModificationStamp() + f.getLocalTimeStamp()); list.add(mf); } } } IModuleResource[] mr = new IModuleResource[list.size()]; list.toArray(mr); return mr; } protected boolean isFileInSourceContainer(IFile file) { return false; } private IModuleResource getExistingModuleResource(List aList, IPath path) { IModuleResource result = null; // If the list is empty, return null if (aList==null || aList.isEmpty()) return null; // Otherwise recursively check to see if given resource matches current resource or if it is a child int i=0; do { IModuleResource moduleResource = (IModuleResource) aList.get(i); if (moduleResource.getModuleRelativePath().append(moduleResource.getName()).equals(path)) result = moduleResource; // if it is a folder, check its children for the resource path else if (moduleResource instanceof IModuleFolder) { result = getExistingModuleResource(Arrays.asList(((IModuleFolder)moduleResource).members()),path); } i++; } while (result == null && i<aList.size() ); return result; } protected IModuleResource[] handleJavaPath(IPath path, IPath javaPath, IPath curPath, IContainer[] javaCont, IModuleResource[] mr, IContainer cc) throws CoreException { //subclasses may override return new IModuleResource[]{}; } public IModuleResource[] members() throws CoreException { members.clear(); IVirtualComponent vc = ComponentCore.createComponent(getProject()); if (vc != null) { IVirtualFolder vFolder = vc.getRootFolder(); IModuleResource[] mr = getMembers(vFolder, Path.EMPTY); int size = mr.length; for (int j = 0; j < size; j++) { if (!members.contains(mr[j])) members.add(mr[j]); } } IModuleResource[] mr = new IModuleResource[members.size()]; members.toArray(mr); return mr; } /** * Returns the root folders for the resources in this module. * * @return a possibly-empty array of resource folders */ public IContainer[] getResourceFolders() { IVirtualComponent vc = ComponentCore.createComponent(getProject()); if (vc != null) { IVirtualFolder vFolder = vc.getRootFolder(); if (vFolder != null) return vFolder.getUnderlyingFolders(); } return new IContainer[]{}; } }
true
true
protected IModuleResource[] getMembers(IContainer cont, IPath path, IPath javaPath, IContainer[] javaCont) throws CoreException { IResource[] res = cont.members(); int size2 = res.length; List list = new ArrayList(size2); for (int j = 0; j < size2; j++) { if (res[j] instanceof IContainer) { IContainer cc = (IContainer) res[j]; IPath newPath = path.append(cc.getName()); // Retrieve already existing module folder if applicable ModuleFolder mf = (ModuleFolder) getExistingModuleResource(members,newPath); if (mf == null) { mf = new ModuleFolder(cc, cc.getName(), path); list.add(mf); } IModuleResource[] mr = getMembers(cc, newPath, javaPath, javaCont); if (javaPath != null && newPath.isPrefixOf(javaPath)) mr = handleJavaPath(path, javaPath, newPath, javaCont, mr, cc); addMembersToModuleFolder(mf, mr); } else { IFile f = (IFile) res[j]; // Handle the default package case if (path.equals(javaPath)) { ModuleFolder mFolder = (ModuleFolder) getExistingModuleResource(members,javaPath); ModuleFile mFile = new ModuleFile(f, f.getName(), javaPath, f.getModificationStamp() + f.getLocalTimeStamp()); addMembersToModuleFolder(mFolder,new IModuleResource[]{mFile}); } else { ModuleFile mf = new ModuleFile(f, f.getName(), path, f.getModificationStamp() + f.getLocalTimeStamp()); list.add(mf); } } } IModuleResource[] mr = new IModuleResource[list.size()]; list.toArray(mr); return mr; }
protected IModuleResource[] getMembers(IContainer cont, IPath path, IPath javaPath, IContainer[] javaCont) throws CoreException { IResource[] res = cont.members(); int size2 = res.length; List list = new ArrayList(size2); for (int j = 0; j < size2; j++) { if (res[j] instanceof IContainer) { IContainer cc = (IContainer) res[j]; IPath newPath = path.append(cc.getName()); // Retrieve already existing module folder if applicable ModuleFolder mf = (ModuleFolder) getExistingModuleResource(members,newPath); if (mf == null) { mf = new ModuleFolder(cc, cc.getName(), path); list.add(mf); } IModuleResource[] mr = getMembers(cc, newPath, javaPath, javaCont); if (javaPath != null && newPath.isPrefixOf(javaPath)) mr = handleJavaPath(path, javaPath, newPath, javaCont, mr, cc); addMembersToModuleFolder(mf, mr); } else { IFile f = (IFile) res[j]; // Handle the default package case if (path.equals(javaPath)) { ModuleFolder mFolder = (ModuleFolder) getExistingModuleResource(members,javaPath); ModuleFile mFile = new ModuleFile(f, f.getName(), javaPath, f.getModificationStamp() + f.getLocalTimeStamp()); if (mFolder != null) addMembersToModuleFolder(mFolder,new IModuleResource[]{mFile}); else list.add(mFile); } else { ModuleFile mf = new ModuleFile(f, f.getName(), path, f.getModificationStamp() + f.getLocalTimeStamp()); list.add(mf); } } } IModuleResource[] mr = new IModuleResource[list.size()]; list.toArray(mr); return mr; }
diff --git a/src/main/java/com/ryanmichela/giantcaves/GCWaterHandler.java b/src/main/java/com/ryanmichela/giantcaves/GCWaterHandler.java index d1d8a4c..f9d5557 100644 --- a/src/main/java/com/ryanmichela/giantcaves/GCWaterHandler.java +++ b/src/main/java/com/ryanmichela/giantcaves/GCWaterHandler.java @@ -1,51 +1,51 @@ package com.ryanmichela.giantcaves; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.craftbukkit.v1_6_R3.CraftChunk; import org.bukkit.craftbukkit.v1_6_R3.CraftWorld; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockFromToEvent; import java.util.WeakHashMap; /** * Copyright 2013 Ryan Michela */ public class GCWaterHandler implements Listener { // Keep a map of previous random generators, one per chunk. // WeakHashMap is used to ensure that chunk unloading is not inhibited. This map won't // prevent a chunk from being unloaded and garbage collected. private final WeakHashMap<Chunk, GCRandom> randoms = new WeakHashMap<>(); private final Config config; public GCWaterHandler(Config config) { this.config = config; } @EventHandler public void FromToHandler(BlockFromToEvent event) { // During chunk generation, nms.World.d is set to true. While true, liquids // flow continuously instead tick-by-tick. See nms.WorldGenLiquids line 59. Block b = event.getBlock(); - if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.STATIONARY_WATER) { + if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.STATIONARY_LAVA) { boolean continuousFlowMode = ((CraftWorld)event.getBlock().getWorld()).getHandle().d; if (continuousFlowMode) { CraftChunk c = (CraftChunk)b.getChunk(); if (!randoms.containsKey(c)) { randoms.put(c, new GCRandom(c, config)); } GCRandom r = randoms.get(c); if (r.isInGiantCave(b.getX(), b.getY(), b.getZ())) { if (b.getData() == 0) { // data value of 0 means source block event.setCancelled(true); } } } } } }
true
true
public void FromToHandler(BlockFromToEvent event) { // During chunk generation, nms.World.d is set to true. While true, liquids // flow continuously instead tick-by-tick. See nms.WorldGenLiquids line 59. Block b = event.getBlock(); if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.STATIONARY_WATER) { boolean continuousFlowMode = ((CraftWorld)event.getBlock().getWorld()).getHandle().d; if (continuousFlowMode) { CraftChunk c = (CraftChunk)b.getChunk(); if (!randoms.containsKey(c)) { randoms.put(c, new GCRandom(c, config)); } GCRandom r = randoms.get(c); if (r.isInGiantCave(b.getX(), b.getY(), b.getZ())) { if (b.getData() == 0) { // data value of 0 means source block event.setCancelled(true); } } } } }
public void FromToHandler(BlockFromToEvent event) { // During chunk generation, nms.World.d is set to true. While true, liquids // flow continuously instead tick-by-tick. See nms.WorldGenLiquids line 59. Block b = event.getBlock(); if (b.getType() == Material.STATIONARY_WATER || b.getType() == Material.STATIONARY_LAVA) { boolean continuousFlowMode = ((CraftWorld)event.getBlock().getWorld()).getHandle().d; if (continuousFlowMode) { CraftChunk c = (CraftChunk)b.getChunk(); if (!randoms.containsKey(c)) { randoms.put(c, new GCRandom(c, config)); } GCRandom r = randoms.get(c); if (r.isInGiantCave(b.getX(), b.getY(), b.getZ())) { if (b.getData() == 0) { // data value of 0 means source block event.setCancelled(true); } } } } }
diff --git a/tools/sorcer-launcher/src/main/java/sorcer/launcher/SorcerOutputConsumer.java b/tools/sorcer-launcher/src/main/java/sorcer/launcher/SorcerOutputConsumer.java index 85cd76b5..f7ae6165 100644 --- a/tools/sorcer-launcher/src/main/java/sorcer/launcher/SorcerOutputConsumer.java +++ b/tools/sorcer-launcher/src/main/java/sorcer/launcher/SorcerOutputConsumer.java @@ -1,46 +1,46 @@ /* * Copyright 2014 Sorcersoft.com S.A. * * 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 sorcer.launcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Rafał Krupiński */ public class SorcerOutputConsumer implements OutputConsumer { private static final Logger log = LoggerFactory.getLogger(SorcerOutputConsumer.class); private Pattern pattern = Pattern.compile("Started (\\d+)/(\\d+) services; (\\d+) errors"); @Override public boolean consume(String line) { Matcher m = pattern.matcher(line); if (!m.find()) { return true; } String started = m.group(1); String all = m.group(2); String errors = m.group(3); - log.debug("Stared {} of {} with {} errors", started, all, errors); + log.debug("Started {} of {} with {} errors", started, all, errors); if (!"0".equals(errors)) throw new IllegalArgumentException("Errors while starting services"); return !started.equals(all); } }
true
true
public boolean consume(String line) { Matcher m = pattern.matcher(line); if (!m.find()) { return true; } String started = m.group(1); String all = m.group(2); String errors = m.group(3); log.debug("Stared {} of {} with {} errors", started, all, errors); if (!"0".equals(errors)) throw new IllegalArgumentException("Errors while starting services"); return !started.equals(all); }
public boolean consume(String line) { Matcher m = pattern.matcher(line); if (!m.find()) { return true; } String started = m.group(1); String all = m.group(2); String errors = m.group(3); log.debug("Started {} of {} with {} errors", started, all, errors); if (!"0".equals(errors)) throw new IllegalArgumentException("Errors while starting services"); return !started.equals(all); }
diff --git a/lucene/src/test/org/apache/lucene/index/TestDocsAndPositions.java b/lucene/src/test/org/apache/lucene/index/TestDocsAndPositions.java index 654e33dfb..a63e63db5 100644 --- a/lucene/src/test/org/apache/lucene/index/TestDocsAndPositions.java +++ b/lucene/src/test/org/apache/lucene/index/TestDocsAndPositions.java @@ -1,327 +1,327 @@ package org.apache.lucene.index; /** * 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.IOException; import java.util.ArrayList; import java.util.Arrays; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader.AtomicReaderContext; import org.apache.lucene.index.IndexReader.ReaderContext; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.ReaderUtil; public class TestDocsAndPositions extends LuceneTestCase { private String fieldName; private boolean usePayload; public void setUp() throws Exception { super.setUp(); fieldName = "field" + random.nextInt(); usePayload = random.nextBoolean(); } /** * Simple testcase for {@link DocsAndPositionsEnum} */ public void testPositionsSimple() throws IOException { Directory directory = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); for (int i = 0; i < 39; i++) { Document doc = new Document(); doc.add(newField(fieldName, "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10", Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("1"); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext atomicReaderContext : leaves) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader, bytes, null); assertNotNull(docsAndPosEnum); if (atomicReaderContext.reader.maxDoc() == 0) { continue; } final int advance = docsAndPosEnum.advance(random.nextInt(atomicReaderContext.reader.maxDoc())); do { String msg = "Advanced to: " + advance + " current doc: " + docsAndPosEnum.docID() + " usePayloads: " + usePayload; assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 0, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 10, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 20, docsAndPosEnum.nextPosition()); assertEquals(msg, 4, docsAndPosEnum.freq()); assertEquals(msg, 30, docsAndPosEnum.nextPosition()); } while (docsAndPosEnum.nextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS); } } reader.close(); directory.close(); } public DocsAndPositionsEnum getDocsAndPositions(IndexReader reader, BytesRef bytes, Bits skipDocs) throws IOException { return reader.termPositionsEnum(null, fieldName, bytes); } public DocsEnum getDocsEnum(IndexReader reader, BytesRef bytes, boolean freqs, Bits skipDocs) throws IOException { int randInt = random.nextInt(10); if (randInt == 0) { // once in a while throw in a positions enum return getDocsAndPositions(reader, bytes, skipDocs); } else { return reader.termDocsEnum(skipDocs, fieldName, bytes); } } /** * this test indexes random numbers within a range into a field and checks * their occurrences by searching for a number from that range selected at * random. All positions for that number are saved up front and compared to * the enums positions. */ - public void testRandomPositons() throws IOException { + public void testRandomPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); int numDocs = 131; int max = 1051; int term = random.nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < 3049; j++) { int nextInt = random.nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } doc.add(newField(fieldName, builder.toString(), Field.Store.YES, Field.Index.ANALYZED)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("" + term); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext atomicReaderContext : leaves) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader, bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader.maxDoc(); // initially advance or do next doc if (random.nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random.nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocsAndPositionsEnum.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random.nextInt(20) == 0 ? pos.length - random.nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) + " usePayloads: " + usePayload, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random.nextInt(10) == 0) { // once is a while advance docsAndPosEnum .advance(docID + 1 + random.nextInt((maxDoc - docID))); } } while (docsAndPosEnum.nextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS); } } reader.close(); dir.close(); } public void testRandomDocs() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); int numDocs = 499; int max = 15678; int term = random.nextInt(max); int[] freqInDoc = new int[numDocs]; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < 199; j++) { int nextInt = random.nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { freqInDoc[i]++; } } doc.add(newField(fieldName, builder.toString(), Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("" + term); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext context : leaves) { int maxDoc = context.reader.maxDoc(); DocsEnum docsAndPosEnum = getDocsEnum(context.reader, bytes, true, null); if (findNext(freqInDoc, context.docBase, context.docBase + maxDoc) == Integer.MAX_VALUE) { assertNull(docsAndPosEnum); continue; } assertNotNull(docsAndPosEnum); docsAndPosEnum.nextDoc(); for (int j = 0; j < maxDoc; j++) { if (freqInDoc[context.docBase + j] != 0) { assertEquals(j, docsAndPosEnum.docID()); assertEquals(docsAndPosEnum.freq(), freqInDoc[context.docBase +j]); if (i % 2 == 0 && random.nextInt(10) == 0) { int next = findNext(freqInDoc, context.docBase+j+1, context.docBase + maxDoc) - context.docBase; int advancedTo = docsAndPosEnum.advance(next); if (next >= maxDoc) { assertEquals(DocsEnum.NO_MORE_DOCS, advancedTo); } else { assertTrue("advanced to: " +advancedTo + " but should be <= " + next, next >= advancedTo); } } else { docsAndPosEnum.nextDoc(); } } } assertEquals("docBase: " + context.docBase + " maxDoc: " + maxDoc + " " + docsAndPosEnum.getClass(), DocsEnum.NO_MORE_DOCS, docsAndPosEnum.docID()); } } reader.close(); dir.close(); } private static int findNext(int[] docs, int pos, int max) { for (int i = pos; i < max; i++) { if( docs[i] != 0) { return i; } } return Integer.MAX_VALUE; } /** * tests retrieval of positions for terms that have a large number of * occurrences to force test of buffer refill during positions iteration. */ public void testLargeNumberOfPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); int howMany = 1000; for (int i = 0; i < 39; i++) { Document doc = new Document(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < howMany; j++) { if (j % 2 == 0) { builder.append("even "); } else { builder.append("odd "); } } doc.add(newField(fieldName, builder.toString(), Field.Store.YES, Field.Index.ANALYZED)); writer.addDocument(doc); } // now do seaches IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("even"); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext atomicReaderContext : leaves) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader, bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader.maxDoc(); // initially advance or do next doc if (random.nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random.nextInt(maxDoc)); } String msg = "Iteration: " + i + " initDoc: " + initDoc + " payloads: " + usePayload; assertEquals(howMany / 2, docsAndPosEnum.freq()); for (int j = 0; j < howMany; j += 2) { assertEquals("position missmatch index: " + j + " with freq: " + docsAndPosEnum.freq() + " -- " + msg, j, docsAndPosEnum.nextPosition()); } } } reader.close(); dir.close(); } }
true
true
public void testRandomPositons() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); int numDocs = 131; int max = 1051; int term = random.nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < 3049; j++) { int nextInt = random.nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } doc.add(newField(fieldName, builder.toString(), Field.Store.YES, Field.Index.ANALYZED)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("" + term); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext atomicReaderContext : leaves) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader, bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader.maxDoc(); // initially advance or do next doc if (random.nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random.nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocsAndPositionsEnum.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random.nextInt(20) == 0 ? pos.length - random.nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) + " usePayloads: " + usePayload, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random.nextInt(10) == 0) { // once is a while advance docsAndPosEnum .advance(docID + 1 + random.nextInt((maxDoc - docID))); } } while (docsAndPosEnum.nextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS); } } reader.close(); dir.close(); }
public void testRandomPositions() throws IOException { Directory dir = newDirectory(); RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer( MockTokenizer.WHITESPACE, true, usePayload))); int numDocs = 131; int max = 1051; int term = random.nextInt(max); Integer[][] positionsInDoc = new Integer[numDocs][]; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); ArrayList<Integer> positions = new ArrayList<Integer>(); StringBuilder builder = new StringBuilder(); for (int j = 0; j < 3049; j++) { int nextInt = random.nextInt(max); builder.append(nextInt).append(" "); if (nextInt == term) { positions.add(Integer.valueOf(j)); } } doc.add(newField(fieldName, builder.toString(), Field.Store.YES, Field.Index.ANALYZED)); positionsInDoc[i] = positions.toArray(new Integer[0]); writer.addDocument(doc); } IndexReader reader = writer.getReader(); writer.close(); for (int i = 0; i < 39 * RANDOM_MULTIPLIER; i++) { BytesRef bytes = new BytesRef("" + term); ReaderContext topReaderContext = reader.getTopReaderContext(); AtomicReaderContext[] leaves = ReaderUtil.leaves(topReaderContext); for (AtomicReaderContext atomicReaderContext : leaves) { DocsAndPositionsEnum docsAndPosEnum = getDocsAndPositions( atomicReaderContext.reader, bytes, null); assertNotNull(docsAndPosEnum); int initDoc = 0; int maxDoc = atomicReaderContext.reader.maxDoc(); // initially advance or do next doc if (random.nextBoolean()) { initDoc = docsAndPosEnum.nextDoc(); } else { initDoc = docsAndPosEnum.advance(random.nextInt(maxDoc)); } // now run through the scorer and check if all positions are there... do { int docID = docsAndPosEnum.docID(); if (docID == DocsAndPositionsEnum.NO_MORE_DOCS) { break; } Integer[] pos = positionsInDoc[atomicReaderContext.docBase + docID]; assertEquals(pos.length, docsAndPosEnum.freq()); // number of positions read should be random - don't read all of them // allways final int howMany = random.nextInt(20) == 0 ? pos.length - random.nextInt(pos.length) : pos.length; for (int j = 0; j < howMany; j++) { assertEquals("iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.docBase + " positions: " + Arrays.toString(pos) + " usePayloads: " + usePayload, pos[j].intValue(), docsAndPosEnum.nextPosition()); } if (random.nextInt(10) == 0) { // once is a while advance docsAndPosEnum .advance(docID + 1 + random.nextInt((maxDoc - docID))); } } while (docsAndPosEnum.nextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS); } } reader.close(); dir.close(); }
diff --git a/src/main/java/de/beimax/spacealert/render/XmlRenderer.java b/src/main/java/de/beimax/spacealert/render/XmlRenderer.java index be5b965..08255b4 100644 --- a/src/main/java/de/beimax/spacealert/render/XmlRenderer.java +++ b/src/main/java/de/beimax/spacealert/render/XmlRenderer.java @@ -1,154 +1,155 @@ /** * This file is part of the JSpaceAlertMissionGenerator software. * Copyright (C) 2011 Maximilian Kalus * See http://www.beimax.de/ and https://github.com/mkalus/JSpaceAlertMissionGenerator * * 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 de.beimax.spacealert.render; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import de.beimax.spacealert.mission.Event; import de.beimax.spacealert.mission.Mission; import de.beimax.spacealert.util.Options; /** * @author mkalus * */ public class XmlRenderer implements Renderer { /* (non-Javadoc) * @see de.beimax.spacealert.render.Renderer#print(de.beimax.spacealert.mission.Mission) */ public boolean print(Mission mission) { System.out.println(getMissionXML(mission)); return true; } /* (non-Javadoc) * @see de.beimax.spacealert.render.Renderer#output(de.beimax.spacealert.mission.Mission) */ public boolean output(Mission mission) { // get options Options options = Options.getOptions(); // check file name/size if (options.outPutfilePrefix == null || options.outPutfilePrefix.isEmpty()) { System.out.println("Error writing XML file: file prefix is empty."); } // write file try { FileWriter outFile = new FileWriter(options.outPutfilePrefix + ".xml"); outFile.write(getMissionXML(mission)); outFile.close(); } catch (IOException e) { System.out.println("Error writing XML file: " + e.getMessage()); } return true; } private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases - if (++phase >= 2) { + if (phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } + phase++; } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); } /* <Mission> <Phase duration="203000"> <Element start="0" type="Announcement" message="AnnounceBeginFirstPhase" /> <Element start="17848" type="Threat" confidence="Confirmed" threatLevel="NormalThreat" threatType="ExternalThreat" time="0" zone="Blue" /> <Element start="40943" type="DataTransfer" /> <Element start="68085" type="Threat" confidence="Unconfirmed" threatLevel="NormalThreat" threatType="InternalThreat" time="1" /> <Element start="140452" type="Announcement" message="AnnounceFirstPhaseEndsInOneMinute" /> <Element start="145638" type="CommFailure" duration="17000" /> <Element start="165712" type="Threat" confidence="Confirmed" threatLevel="SeriousThreat" threatType="InternalThreat" time="3" /> <Element start="177436" type="Announcement" message="AnnounceFirstPhaseEndsInTwentySeconds" /> <Element start="193198" type="Announcement" message="AnnounceFirstPhaseEnds" /> </Phase> <Phase duration="173000"> <Element start="0" type="Announcement" message="AnnounceSecondPhaseBegins" /> <Element start="10621" type="DataTransfer" /> <Element start="34353" type="IncomingData" /> <Element start="58479" type="Threat" confidence="Confirmed" threatLevel="NormalThreat" threatType="ExternalThreat" time="5" zone="White" /> <Element start="77687" type="CommFailure" duration="17000" /> <Element start="110634" type="Announcement" message="AnnounceSecondPhaseEndsInOneMinute" /> <Element start="119504" type="IncomingData" /> <Element start="127399" type="DataTransfer" /> <Element start="142821" type="IncomingData" /> <Element start="150114" type="Announcement" message="AnnounceSecondPhaseEndsInTwentySeconds" /> <Element start="163276" type="Announcement" message="AnnounceSecondPhaseEnds" /> </Phase> <Phase duration="125000"> <Element start="0" type="Announcement" message="AnnounceThirdPhaseBegins" /> <Element start="10190" type="DataTransfer" /> <Element start="31021" type="CommFailure" duration="14000" /> <Element start="62530" type="Announcement" message="AnnounceThirdPhaseEndsInOneMinute" /> <Element start="102218" type="Announcement" message="AnnounceThirdPhaseEndsInTwentySeconds" /> <Element start="118000" type="Announcement" message="AnnounceThirdPhaseEnds" /> </Phase> </Mission> */ @Override public String toString() { return "XML"; } }
false
true
private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases if (++phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); }
private String getMissionXML(Mission mission) { StringBuilder sb = new StringBuilder(); // some render statistics stuff int phaseLength = 0; int lastPhaseLength = 0; int phase = 1; // create XML beginning sb.append("<Mission>\n"); // get values for(Map.Entry<Integer,Event> entry : mission.getMissionEvents().getEntrySet()) { int time = entry.getKey(); // new phase? if (time >= phaseLength) { // calculate new phase length lastPhaseLength = phaseLength; phaseLength += mission.getMissionPhaseLength(phase); // output info sb.append("\t<Phase duration=\"" + mission.getMissionPhaseLength(phase) + "000\">\n"); // phase anouncements for secons and third phases if (phase >= 2) { sb.append("\t\t<Element start=\"0\" type=\"Announcement\" message=\"Announce").append(phase==2?"Second":"Third").append("PhaseBegins\" />\n"); } phase++; } sb.append("\t\t<Element start=\"").append((long)(time - lastPhaseLength) * 1000).append("\" ").append(entry.getValue().getXMLAttributes(time)).append(" />\n"); } // create XML end sb.append("\t</Phase>\n</Mission>"); return sb.toString(); }
diff --git a/errai-common/src/main/java/org/jboss/errai/common/client/json/JSONEncoderCli.java b/errai-common/src/main/java/org/jboss/errai/common/client/json/JSONEncoderCli.java index 390325897..d1c5b9313 100644 --- a/errai-common/src/main/java/org/jboss/errai/common/client/json/JSONEncoderCli.java +++ b/errai-common/src/main/java/org/jboss/errai/common/client/json/JSONEncoderCli.java @@ -1,224 +1,224 @@ /* * Copyright 2010 JBoss, a divison Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.errai.common.client.json; import org.jboss.errai.common.client.types.EncodingContext; import org.jboss.errai.common.client.types.Marshaller; import java.util.Collection; import java.util.Iterator; import java.util.Map; import static org.jboss.errai.common.client.types.TypeMarshallers.getMarshaller; import static org.jboss.errai.common.client.types.TypeMarshallers.hasMarshaller; public class JSONEncoderCli { boolean defer; String marshall; private Map<String, String> marshalledTypes; public String encode(Object v, EncodingContext ctx) { return _encode(v, ctx); } @SuppressWarnings({"unchecked"}) public String _encode(Object v, EncodingContext ctx) { if (v == null) { return "null"; } else if (v instanceof String) { return "\"" + ((String) v) .replaceAll("\\\\\"", "\\\\\\\\\"") .replaceAll("\"", "\\\\\"") .replaceAll("\\\\", "\\\\\\\\\\\\\\\\") + "\""; } else if (v instanceof Number || v instanceof Boolean) { return String.valueOf(v); } else if (v instanceof Collection) { return encodeCollection((Collection) v, ctx); } else if (v instanceof Map) { return encodeMap((Map<Object, Object>) v, ctx); } else if (v instanceof Object[]) { return encodeArray((Object[]) v, ctx); } else if (v.getClass().isArray()) { if (v instanceof char[]) { return encodeArray((char[]) v, ctx); } else if (v instanceof int[]) { return encodeArray((int[]) v, ctx); } else if (v instanceof double[]) { return encodeArray((double[]) v, ctx); } else if (v instanceof long[]) { return encodeArray((long[]) v, ctx); } else if (v instanceof boolean[]) { return encodeArray((boolean[]) v, ctx); } else if (v instanceof byte[]) { return encodeArray((byte[]) v, ctx); } else if (v instanceof short[]) { return encodeArray((short[]) v, ctx); } else if (v instanceof float[]) { return encodeArray((float[]) v, ctx); } return null; } else if (hasMarshaller(v.getClass().getName())) { Marshaller<Object> m = getMarshaller(marshall = v.getClass().getName()); String enc = m.marshall(v, ctx); return enc; } else if (v instanceof Enum) { - return "\"" + v.toString() + "\""; + return _encode(v.toString(), ctx); } else { defer = true; return null; } } public String encodeMap(Map<Object, Object> map, EncodingContext ctx) { StringBuilder mapBuild = new StringBuilder("{"); boolean first = true; for (Map.Entry<Object, Object> entry : map.entrySet()) { String val = _encode(entry.getValue(), ctx); if (!defer) { if (!first) { mapBuild.append(","); } mapBuild.append(_encode(entry.getKey(), ctx)) .append(":").append(val); first = false; } else { defer = false; } } return mapBuild.append("}").toString(); } private String encodeCollection(Collection col, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); Iterator iter = col.iterator(); while (iter.hasNext()) { buildCol.append(_encode(iter.next(), ctx)); if (iter.hasNext()) buildCol.append(','); } return buildCol.append("]").toString(); } private String encodeArray(Object[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(char[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(int[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(long[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(short[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(double[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(float[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(boolean[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } private String encodeArray(byte[] array, EncodingContext ctx) { StringBuilder buildCol = new StringBuilder("["); for (int i = 0; i < array.length; i++) { buildCol.append(_encode(array[i], ctx)); if ((i + 1) < array.length) buildCol.append(","); } return buildCol.append("]").toString(); } public Map<String, String> getMarshalledTypes() { return marshalledTypes; } }
true
true
public String _encode(Object v, EncodingContext ctx) { if (v == null) { return "null"; } else if (v instanceof String) { return "\"" + ((String) v) .replaceAll("\\\\\"", "\\\\\\\\\"") .replaceAll("\"", "\\\\\"") .replaceAll("\\\\", "\\\\\\\\\\\\\\\\") + "\""; } else if (v instanceof Number || v instanceof Boolean) { return String.valueOf(v); } else if (v instanceof Collection) { return encodeCollection((Collection) v, ctx); } else if (v instanceof Map) { return encodeMap((Map<Object, Object>) v, ctx); } else if (v instanceof Object[]) { return encodeArray((Object[]) v, ctx); } else if (v.getClass().isArray()) { if (v instanceof char[]) { return encodeArray((char[]) v, ctx); } else if (v instanceof int[]) { return encodeArray((int[]) v, ctx); } else if (v instanceof double[]) { return encodeArray((double[]) v, ctx); } else if (v instanceof long[]) { return encodeArray((long[]) v, ctx); } else if (v instanceof boolean[]) { return encodeArray((boolean[]) v, ctx); } else if (v instanceof byte[]) { return encodeArray((byte[]) v, ctx); } else if (v instanceof short[]) { return encodeArray((short[]) v, ctx); } else if (v instanceof float[]) { return encodeArray((float[]) v, ctx); } return null; } else if (hasMarshaller(v.getClass().getName())) { Marshaller<Object> m = getMarshaller(marshall = v.getClass().getName()); String enc = m.marshall(v, ctx); return enc; } else if (v instanceof Enum) { return "\"" + v.toString() + "\""; } else { defer = true; return null; } }
public String _encode(Object v, EncodingContext ctx) { if (v == null) { return "null"; } else if (v instanceof String) { return "\"" + ((String) v) .replaceAll("\\\\\"", "\\\\\\\\\"") .replaceAll("\"", "\\\\\"") .replaceAll("\\\\", "\\\\\\\\\\\\\\\\") + "\""; } else if (v instanceof Number || v instanceof Boolean) { return String.valueOf(v); } else if (v instanceof Collection) { return encodeCollection((Collection) v, ctx); } else if (v instanceof Map) { return encodeMap((Map<Object, Object>) v, ctx); } else if (v instanceof Object[]) { return encodeArray((Object[]) v, ctx); } else if (v.getClass().isArray()) { if (v instanceof char[]) { return encodeArray((char[]) v, ctx); } else if (v instanceof int[]) { return encodeArray((int[]) v, ctx); } else if (v instanceof double[]) { return encodeArray((double[]) v, ctx); } else if (v instanceof long[]) { return encodeArray((long[]) v, ctx); } else if (v instanceof boolean[]) { return encodeArray((boolean[]) v, ctx); } else if (v instanceof byte[]) { return encodeArray((byte[]) v, ctx); } else if (v instanceof short[]) { return encodeArray((short[]) v, ctx); } else if (v instanceof float[]) { return encodeArray((float[]) v, ctx); } return null; } else if (hasMarshaller(v.getClass().getName())) { Marshaller<Object> m = getMarshaller(marshall = v.getClass().getName()); String enc = m.marshall(v, ctx); return enc; } else if (v instanceof Enum) { return _encode(v.toString(), ctx); } else { defer = true; return null; } }
diff --git a/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java b/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java index 2f6374c..1c0f517 100644 --- a/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java +++ b/src/main/java/com/redhat/automationportal/scripts/RegenSplash.java @@ -1,229 +1,230 @@ package com.redhat.automationportal.scripts; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import com.redhat.automationportal.base.AutomationBase; import com.redhat.automationportal.rest.StringPair; import com.redhat.ecs.commonutils.InetUtilities; import com.redhat.ecs.commonutils.XMLUtilities; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * Requires: * * /opt/automation-interface/cvs/dummyeditor.sh to avoid editor prompts and errors. * The script just needs to change the time stamp and add something to the file. * * #!/bin/sh * echo "Automation Interface TOC Update" > $1 * sleep 1 * touch $1 * exit 0 * * EDITOR environment variable needs to point to /opt/automation-interface/cvs/dummyeditor.sh * * Set "StrictHostKeyChecking no" in /etc/ssh/ssh_config to avoid key issues with cvs in a script * * empty http://empty.sourceforge.net/">http://empty.sourceforge.net/ * brewkoji http://download.devel.redhat.com/rel-eng/brew/rhel/6/ * publican &gt;= 2.6 http://porkchop.redhat.com/rel-eng/repos/eng-rhel-6/x86_64/ * regensplash.rb https://engineering.redhat.com/trac/ContentServices/wiki/RegenSplash * publican_build https://svn.devel.redhat.com/repos/ecs/toolkit/publican_build/publican_build */ public class RegenSplash extends AutomationBase { private static String BUILD = "20120105-0812"; //private static final String PRODUCT_RE = "<span id=\".*?\" class=\"product\">(?<product>.*?)</span>"; private static final String PASSWORD_ENV_VARIABLE_NAME = "PASSWORD"; private static final String SCRIPT_NAME = "regensplash.rb"; private static final String SCRIPT_PATH = "/opt/automation-interface/regensplash/" + SCRIPT_NAME; private static final String DOCS_STAGE_DUMP_XML = "http://documentation-stage.bne.redhat.com/DUMP.xml"; private static final String DOCS_REDHAT_DUMP_XML = "http://docs.redhat.com/DUMP.xml"; private static final String DOCS_STAGE_TOC_URL = "http://documentation-stage.bne.redhat.com/docs/toc.html"; private static final String DOCS_REDHAT_TOC_URL = "http://docs.redhat.com/docs/toc.html"; private String product; private String selectedSite; private final List<StringPair> sites; public RegenSplash() { this.sites = new ArrayList<StringPair>(); this.sites.add(new StringPair(DOCS_REDHAT_DUMP_XML, "Redhat Docs (Can take a few seconds to get the products)")); this.sites.add(new StringPair(DOCS_STAGE_DUMP_XML, "Docs Stage")); } public List<StringPair> getSites() { return sites; } public String getBuild() { return BUILD; } public void setProduct(final String product) { this.product = product; } public String getProduct() { return product; } public void setSelectedSite(String selectedSite) { this.selectedSite = selectedSite; } public String getSelectedSite() { return selectedSite; } public List<String> getProducts(final String tocURL) { final List<String> products = new ArrayList<String>(); // add an empty string to represent a null selection products.add(""); final String toc = new String(InetUtilities.getURLData(tocURL)); final Document doc = XMLUtilities.convertStringToDocument(toc); if (doc != null) { final List<Node> productNodes = XMLUtilities.getNodes(doc.getDocumentElement(), "product"); for (final Node node : productNodes) { final String productName = node.getTextContent().replaceAll("_", " ").replaceAll("&#x200B;", "").trim(); if (!products.contains(productName)) { products.add(productName); } } } Collections.sort(products); return products; } public boolean run() { final Integer randomInt = this.generateRandomInt(); if (!validateInput()) return false; String tocURL = ""; if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML)) tocURL = DOCS_STAGE_TOC_URL; else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML)) tocURL = DOCS_REDHAT_TOC_URL; final String script = /* * Publican requires a Kerberos ticket to interact with the CVS repo. * The Map we supply to the runScript function below contains the * challenge / response data needed to supply the password. */ "kinit \\\"" + this.getUsername() + "\\\" " + /* copy the script to the temporary directory */ "&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* create a temporary directory to hold the downloaded files */ "&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* run the regenplash.rb script */ - "&& ./" + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") + + "&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") + /* dump the contents of the version_packages.txt and product_packages.txt files */ "&& echo -------------------" + "&& echo version_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " + "&& echo -------------------" + "&& echo product_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\""; /* * Define some environment variables. The password is placed in a * variable to prevent it from showing up in a ps listing. The CVSEDITOR * variable is used to set the "editor" used by cvs to generate log * messages. In this case the editor is just a script that changes the * contents of the supplied file, and updates the time stamp: */ // #!/bin/sh // # add a generic message echo // "Automation Interface TOC Update" > $1 // # update the time stamp (has to be different by at least a second) // sleep 1 // touch $1 // exit 0 final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" }; /* * The kinit command will expect to be fed a password for the current * user. Here we define a challenge of REDHAT.COM to be responded with * the users password. * * Use an environment variable to hold sensitive strings, like the * password. This prevents the strings from showing up in a ps listing. */ final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>(); - responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}"); + //responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}"); + responses.put("REDHAT.COM", this.getPassword()); runScript(script, randomInt, true, true, true, responses, environment); cleanup(randomInt); return true; } protected boolean validateInput() { if (super.validateInput()) { if (selectedSite == null || selectedSite.length() == 0) { this.message = "You need to specify a site."; return false; } boolean foundSite = false; for (final StringPair item : this.sites) { if (item.getFirstString().equals(this.selectedSite)) { foundSite = true; break; } } if (!foundSite) { this.message = "The site is not valid."; return false; } return true; } return false; } }
false
true
public boolean run() { final Integer randomInt = this.generateRandomInt(); if (!validateInput()) return false; String tocURL = ""; if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML)) tocURL = DOCS_STAGE_TOC_URL; else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML)) tocURL = DOCS_REDHAT_TOC_URL; final String script = /* * Publican requires a Kerberos ticket to interact with the CVS repo. * The Map we supply to the runScript function below contains the * challenge / response data needed to supply the password. */ "kinit \\\"" + this.getUsername() + "\\\" " + /* copy the script to the temporary directory */ "&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* create a temporary directory to hold the downloaded files */ "&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* run the regenplash.rb script */ "&& ./" + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") + /* dump the contents of the version_packages.txt and product_packages.txt files */ "&& echo -------------------" + "&& echo version_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " + "&& echo -------------------" + "&& echo product_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\""; /* * Define some environment variables. The password is placed in a * variable to prevent it from showing up in a ps listing. The CVSEDITOR * variable is used to set the "editor" used by cvs to generate log * messages. In this case the editor is just a script that changes the * contents of the supplied file, and updates the time stamp: */ // #!/bin/sh // # add a generic message echo // "Automation Interface TOC Update" > $1 // # update the time stamp (has to be different by at least a second) // sleep 1 // touch $1 // exit 0 final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" }; /* * The kinit command will expect to be fed a password for the current * user. Here we define a challenge of REDHAT.COM to be responded with * the users password. * * Use an environment variable to hold sensitive strings, like the * password. This prevents the strings from showing up in a ps listing. */ final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>(); responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}"); runScript(script, randomInt, true, true, true, responses, environment); cleanup(randomInt); return true; }
public boolean run() { final Integer randomInt = this.generateRandomInt(); if (!validateInput()) return false; String tocURL = ""; if (this.selectedSite.equals(DOCS_STAGE_DUMP_XML)) tocURL = DOCS_STAGE_TOC_URL; else if (this.selectedSite.equals(DOCS_REDHAT_DUMP_XML)) tocURL = DOCS_REDHAT_TOC_URL; final String script = /* * Publican requires a Kerberos ticket to interact with the CVS repo. * The Map we supply to the runScript function below contains the * challenge / response data needed to supply the password. */ "kinit \\\"" + this.getUsername() + "\\\" " + /* copy the script to the temporary directory */ "&& cp \\\"" + SCRIPT_PATH + "\\\" \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* create a temporary directory to hold the downloaded files */ "&& cd \\\"" + getTmpDirectory(randomInt) + "\\\" " + /* run the regenplash.rb script */ "&& ruby " + SCRIPT_NAME + " \\\"" + tocURL + "\\\"" + (this.product != null && this.product.length() == 0 ? " \\\"" + this.product + "\\\" " : " ") + /* dump the contents of the version_packages.txt and product_packages.txt files */ "&& echo -------------------" + "&& echo version_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/version_packages.txt\\\" " + "&& echo -------------------" + "&& echo product_packages.txt " + "&& echo -------------------" + "&& cat \\\"" + getTmpDirectory(randomInt) + "/product_packages.txt\\\""; /* * Define some environment variables. The password is placed in a * variable to prevent it from showing up in a ps listing. The CVSEDITOR * variable is used to set the "editor" used by cvs to generate log * messages. In this case the editor is just a script that changes the * contents of the supplied file, and updates the time stamp: */ // #!/bin/sh // # add a generic message echo // "Automation Interface TOC Update" > $1 // # update the time stamp (has to be different by at least a second) // sleep 1 // touch $1 // exit 0 final String[] environment = new String[] { PASSWORD_ENV_VARIABLE_NAME + "=" + this.getPassword(), "CVSEDITOR=/opt/automation-interface/cvs/dummyeditor.sh" }; /* * The kinit command will expect to be fed a password for the current * user. Here we define a challenge of REDHAT.COM to be responded with * the users password. * * Use an environment variable to hold sensitive strings, like the * password. This prevents the strings from showing up in a ps listing. */ final LinkedHashMap<String, String> responses = new LinkedHashMap<String, String>(); //responses.put("REDHAT.COM", "${" + PASSWORD_ENV_VARIABLE_NAME + "}"); responses.put("REDHAT.COM", this.getPassword()); runScript(script, randomInt, true, true, true, responses, environment); cleanup(randomInt); return true; }
diff --git a/src/jar/resolver/java/org/mulgara/resolver/ExportOperation.java b/src/jar/resolver/java/org/mulgara/resolver/ExportOperation.java index 483ae9d1..766ebd59 100644 --- a/src/jar/resolver/java/org/mulgara/resolver/ExportOperation.java +++ b/src/jar/resolver/java/org/mulgara/resolver/ExportOperation.java @@ -1,134 +1,134 @@ /* * The contents of this file are subject to the Open Software License * Version 3.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.opensource.org/licenses/osl-3.0.txt * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. */ package org.mulgara.resolver; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URI; import java.util.Map; import org.mulgara.content.rdfxml.writer.RDFXMLWriter; import org.mulgara.content.n3.N3Writer; import org.mulgara.query.Constraint; import org.mulgara.query.ConstraintImpl; import org.mulgara.query.LocalNode; import org.mulgara.query.QueryException; import org.mulgara.query.Variable; import org.mulgara.query.rdf.URIReferenceImpl; import org.mulgara.resolver.spi.DatabaseMetadata; import org.mulgara.resolver.spi.ResolverFactory; import org.mulgara.resolver.spi.Statements; import org.mulgara.resolver.spi.SystemResolver; import org.mulgara.resolver.spi.TuplesWrapperStatements; import org.mulgara.store.statement.StatementStore; import org.mulgara.store.tuples.Tuples; /** * An {@link Operation} that serializes the contents of an RDF graph to either * an output stream or a destination file. * * @created Jun 25, 2008 * @author Alex Hall * @copyright &copy; 2008 <a href="http://www.revelytix.com">Revelytix, Inc.</a> * @licence <a href="{@docRoot}/../../LICENCE.txt">Open Software License v3.0</a> */ class ExportOperation extends OutputOperation { private final URI graphURI; private final Map<String,URI> prefixes; /** * Create an {@link Operation} which exports the contents of the specified RDF graph * to a URI or to an output stream. * * The database is not changed by this method. * If an {@link OutputStream} is supplied then the destinationURI is ignored. * * @param outputStream An output stream to receive the contents, may be * <code>null</code> if a <var>destinationURI</var> is specified * @param graphURI The URI of the graph to export, never <code>null</code>. * @param destinationURI The URI of the file to export into, may be * <code>null</code> if an <var>outputStream</var> is specified * @param initialPrefixes An optional set of user-supplied namespace prefix mappings; * may be <code>null</code> to use the generated namespace prefixes. */ public ExportOperation(OutputStream outputStream, URI graphURI, URI destinationURI, Map<String,URI> initialPrefixes) { super(outputStream, destinationURI); if (graphURI == null) { throw new IllegalArgumentException("Graph URI may not be null."); } this.graphURI = graphURI; this.prefixes = initialPrefixes; } /* (non-Javadoc) * @see org.mulgara.resolver.OutputOperation#execute(org.mulgara.resolver.OperationContext, org.mulgara.resolver.spi.SystemResolver, org.mulgara.resolver.spi.DatabaseMetadata) */ @Override public void execute(OperationContext operationContext, SystemResolver systemResolver, DatabaseMetadata metadata) throws Exception { // Verify that the graph is of a type that supports exports. long graph = systemResolver.localize(new URIReferenceImpl(graphURI)); ResolverFactory resolverFactory = operationContext.findModelResolverFactory(graph); if (resolverFactory.supportsExport()) { OutputStream os = getOutputStream(); assert os != null; OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(os, "UTF-8"); // create a constraint to get all statements Variable[] vars = new Variable[] { StatementStore.VARIABLES[0], StatementStore.VARIABLES[1], StatementStore.VARIABLES[2] }; Constraint constraint = new ConstraintImpl(vars[0], vars[1], vars[2], new LocalNode(graph)); // Get all statements from the graph. Delegate to the operation context to do the security check. Tuples resolution = operationContext.resolve(constraint); Statements graphStatements = new TuplesWrapperStatements(resolution, vars[0], vars[1], vars[2]); // Do the writing. try { - String path = destinationURI.getPath(); - if (path.endsWith(".n3") || path.endsWith(".nt") || path.endsWith(".ttl")) { + String path = (destinationURI != null) ? destinationURI.getPath() : null; + if (path != null && (path.endsWith(".n3") || path.endsWith(".nt") || path.endsWith(".ttl"))) { N3Writer n3Writer = new N3Writer(); n3Writer.write(graphStatements, systemResolver, writer); } else { RDFXMLWriter rdfWriter = new RDFXMLWriter(); rdfWriter.write(graphStatements, systemResolver, writer, prefixes); } } finally { // This will close the wrapped resolution as well. graphStatements.close(); } } finally { // Clean up. if (writer != null) { // Close the writer if it exists. This will also close the wrapped // OutputStream. writer.close(); } else if (os != null) { // Close the os if it exists. os.close(); } } } else { throw new QueryException("Graph " + graphURI + " does not support export."); } } }
true
true
public void execute(OperationContext operationContext, SystemResolver systemResolver, DatabaseMetadata metadata) throws Exception { // Verify that the graph is of a type that supports exports. long graph = systemResolver.localize(new URIReferenceImpl(graphURI)); ResolverFactory resolverFactory = operationContext.findModelResolverFactory(graph); if (resolverFactory.supportsExport()) { OutputStream os = getOutputStream(); assert os != null; OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(os, "UTF-8"); // create a constraint to get all statements Variable[] vars = new Variable[] { StatementStore.VARIABLES[0], StatementStore.VARIABLES[1], StatementStore.VARIABLES[2] }; Constraint constraint = new ConstraintImpl(vars[0], vars[1], vars[2], new LocalNode(graph)); // Get all statements from the graph. Delegate to the operation context to do the security check. Tuples resolution = operationContext.resolve(constraint); Statements graphStatements = new TuplesWrapperStatements(resolution, vars[0], vars[1], vars[2]); // Do the writing. try { String path = destinationURI.getPath(); if (path.endsWith(".n3") || path.endsWith(".nt") || path.endsWith(".ttl")) { N3Writer n3Writer = new N3Writer(); n3Writer.write(graphStatements, systemResolver, writer); } else { RDFXMLWriter rdfWriter = new RDFXMLWriter(); rdfWriter.write(graphStatements, systemResolver, writer, prefixes); } } finally { // This will close the wrapped resolution as well. graphStatements.close(); } } finally { // Clean up. if (writer != null) { // Close the writer if it exists. This will also close the wrapped // OutputStream. writer.close(); } else if (os != null) { // Close the os if it exists. os.close(); } } } else { throw new QueryException("Graph " + graphURI + " does not support export."); } }
public void execute(OperationContext operationContext, SystemResolver systemResolver, DatabaseMetadata metadata) throws Exception { // Verify that the graph is of a type that supports exports. long graph = systemResolver.localize(new URIReferenceImpl(graphURI)); ResolverFactory resolverFactory = operationContext.findModelResolverFactory(graph); if (resolverFactory.supportsExport()) { OutputStream os = getOutputStream(); assert os != null; OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(os, "UTF-8"); // create a constraint to get all statements Variable[] vars = new Variable[] { StatementStore.VARIABLES[0], StatementStore.VARIABLES[1], StatementStore.VARIABLES[2] }; Constraint constraint = new ConstraintImpl(vars[0], vars[1], vars[2], new LocalNode(graph)); // Get all statements from the graph. Delegate to the operation context to do the security check. Tuples resolution = operationContext.resolve(constraint); Statements graphStatements = new TuplesWrapperStatements(resolution, vars[0], vars[1], vars[2]); // Do the writing. try { String path = (destinationURI != null) ? destinationURI.getPath() : null; if (path != null && (path.endsWith(".n3") || path.endsWith(".nt") || path.endsWith(".ttl"))) { N3Writer n3Writer = new N3Writer(); n3Writer.write(graphStatements, systemResolver, writer); } else { RDFXMLWriter rdfWriter = new RDFXMLWriter(); rdfWriter.write(graphStatements, systemResolver, writer, prefixes); } } finally { // This will close the wrapped resolution as well. graphStatements.close(); } } finally { // Clean up. if (writer != null) { // Close the writer if it exists. This will also close the wrapped // OutputStream. writer.close(); } else if (os != null) { // Close the os if it exists. os.close(); } } } else { throw new QueryException("Graph " + graphURI + " does not support export."); } }
diff --git a/test/smartpool/functional/BaseTest.java b/test/smartpool/functional/BaseTest.java index 8174f4f..dba2ba9 100644 --- a/test/smartpool/functional/BaseTest.java +++ b/test/smartpool/functional/BaseTest.java @@ -1,23 +1,24 @@ package smartpool.functional; import org.junit.After; import org.junit.Before; import org.openqa.selenium.firefox.FirefoxDriver; import smartpool.util.EnvironmentLoader; public abstract class BaseTest { protected FirefoxDriver webDriver; @Before public void setUp() { webDriver = new FirefoxDriver(); + webDriver.manage().window().maximize(); webDriver.get(new EnvironmentLoader().getPropertyList(EnvironmentLoader.APPLICATION_PATH, EnvironmentLoader.APPLICATION_URL)); } @After public void tearDown() { webDriver.manage().deleteAllCookies(); webDriver.quit(); } }
true
true
public void setUp() { webDriver = new FirefoxDriver(); webDriver.get(new EnvironmentLoader().getPropertyList(EnvironmentLoader.APPLICATION_PATH, EnvironmentLoader.APPLICATION_URL)); }
public void setUp() { webDriver = new FirefoxDriver(); webDriver.manage().window().maximize(); webDriver.get(new EnvironmentLoader().getPropertyList(EnvironmentLoader.APPLICATION_PATH, EnvironmentLoader.APPLICATION_URL)); }
diff --git a/src/CountandraServer.java b/src/CountandraServer.java old mode 100644 new mode 100755 index 5fc0924..43bfabc --- a/src/CountandraServer.java +++ b/src/CountandraServer.java @@ -1,150 +1,157 @@ import java.io.*; import org.apache.cassandra.thrift.CassandraServer; import org.apache.cassandra.thrift.CfDef; import org.apache.cassandra.thrift.Column; import org.apache.cassandra.thrift.ColumnOrSuperColumn; import org.apache.cassandra.thrift.ColumnParent; import org.apache.cassandra.thrift.ColumnPath; import org.apache.cassandra.thrift.ConsistencyLevel; import org.apache.cassandra.thrift.KsDef; import org.apache.cassandra.thrift.Mutation; import org.apache.cassandra.thrift.SlicePredicate; import org.apache.cassandra.thrift.SliceRange; import org.apache.cassandra.utils.ByteBufferUtil; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.countandra.netty.*; import org.countandra.cassandra.*; import org.countandra.utils.*; // CassandraServer is local (with CassandraYaml specify the data store and distributed servers) // -local-cassandra -local-cassandra-thrift-port -local-cassandra-thrift-ip // Therefore start the CassandraServer and // Initialize the data structures associated with Countandra including some default values // on localhost and specified port 9160? // CassandraServer is remote // Assume that the initialization is done seperately and the CassandraServer is started seperately // just need a pointer there to the host and port (could be localhost and default port) // -remote-cassandra -remote-cassandra-thrift-port -remote-cassandra-thrift-ip // HttpServer is always assumed to be local and should be started // --http-server -http-server-port public class CountandraServer { public static Options options = new Options(); static { options.addOption("s", "server-mode", false, " Cassandra Server Mode"); options.addOption("i", "init", false, " Initialize Cassandra with basic structures"); options.addOption("h", "httpserver", false, " Whether to include httserver"); options.addOption("httpserverport", "httpserverport", true, " httpserver port in case the default of 8080 does not work"); options.addOption("cassandrahostip", "cassandrahostip", true, " cassandra host ip for httpserverto communicate to"); options.addOption("consistencylevel", "consistencylevel", true, " consistency levels of writes/reads"); options.addOption("replicationfactor", "replicationfactor", true, " replicas of data"); options.addOption("locatorstrategy", "locatorstrategy", true, "how the rows should be located"); } private static int httpPort = 8080; private static String cassandraServerForClient = new String("localhost:9160"); public static void main (String args[]) { try { System.out.println(args[0]); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse( options, args ); if (line.hasOption("cassandrahostip")) { if (line.hasOption("consistencylevel")) { if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } else { // no consistency level -- assumed to be ONE if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } } if (line.hasOption("s")) { System.out.println("Starting Cassandra"); // cassandra server CassandraUtils.startupCassandraServer(); } if (line.hasOption("i")) { + if (line.hasOption("cassandrahostip") ) { + System.out.println("Initializing Basic structures"); + CountandraUtils.initBasicDataStructures(line.getOptionValue("cassandrahostIp")); + System.out.println("Initialized Basic structures"); + } + else{ System.out.println("Initializing Basic structures"); CountandraUtils.initBasicDataStructures(); System.out.println("Initialized Basic structures"); + } } if (line.hasOption("h")) { if (line.hasOption("httpserverport") ) { httpPort = Integer.parseInt(line.getOptionValue("httpserverport")); } if (line.hasOption("cassandrahostip") ) { CountandraUtils.setCassandraHostIp(line.getOptionValue("cassandrahostIp")); } else { CountandraUtils.setCassandraHostIp("localhost:9160"); } NettyUtils.startupNettyServer(httpPort); } // http server } catch (IOException ioe) { System.out.println(ioe); } catch (Exception e) { System.out.println(e); } } }
false
true
public static void main (String args[]) { try { System.out.println(args[0]); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse( options, args ); if (line.hasOption("cassandrahostip")) { if (line.hasOption("consistencylevel")) { if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } else { // no consistency level -- assumed to be ONE if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } } if (line.hasOption("s")) { System.out.println("Starting Cassandra"); // cassandra server CassandraUtils.startupCassandraServer(); } if (line.hasOption("i")) { System.out.println("Initializing Basic structures"); CountandraUtils.initBasicDataStructures(); System.out.println("Initialized Basic structures"); } if (line.hasOption("h")) { if (line.hasOption("httpserverport") ) { httpPort = Integer.parseInt(line.getOptionValue("httpserverport")); } if (line.hasOption("cassandrahostip") ) { CountandraUtils.setCassandraHostIp(line.getOptionValue("cassandrahostIp")); } else { CountandraUtils.setCassandraHostIp("localhost:9160"); } NettyUtils.startupNettyServer(httpPort); } // http server } catch (IOException ioe) { System.out.println(ioe); } catch (Exception e) { System.out.println(e); } }
public static void main (String args[]) { try { System.out.println(args[0]); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse( options, args ); if (line.hasOption("cassandrahostip")) { if (line.hasOption("consistencylevel")) { if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("consistencylevel")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } else { // no consistency level -- assumed to be ONE if (line.hasOption("replicationfactor")) { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip"), line.getOptionValue("replicationfactor")); } else { CassandraStorage.setGlobalParams(line.getOptionValue("cassandrahostip")); CassandraDB.setGlobalParams(line.getOptionValue("cassandrahostip")); } } } if (line.hasOption("s")) { System.out.println("Starting Cassandra"); // cassandra server CassandraUtils.startupCassandraServer(); } if (line.hasOption("i")) { if (line.hasOption("cassandrahostip") ) { System.out.println("Initializing Basic structures"); CountandraUtils.initBasicDataStructures(line.getOptionValue("cassandrahostIp")); System.out.println("Initialized Basic structures"); } else{ System.out.println("Initializing Basic structures"); CountandraUtils.initBasicDataStructures(); System.out.println("Initialized Basic structures"); } } if (line.hasOption("h")) { if (line.hasOption("httpserverport") ) { httpPort = Integer.parseInt(line.getOptionValue("httpserverport")); } if (line.hasOption("cassandrahostip") ) { CountandraUtils.setCassandraHostIp(line.getOptionValue("cassandrahostIp")); } else { CountandraUtils.setCassandraHostIp("localhost:9160"); } NettyUtils.startupNettyServer(httpPort); } // http server } catch (IOException ioe) { System.out.println(ioe); } catch (Exception e) { System.out.println(e); } }
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java index de02d09a3..8a996e81f 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/listeners/UpdateListener.java @@ -1,280 +1,284 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * 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://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.core.client.listeners; import java.util.Map; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.team.internal.ccvs.core.CVSException; import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin; import org.eclipse.team.internal.ccvs.core.CVSStatus; import org.eclipse.team.internal.ccvs.core.ICVSFile; import org.eclipse.team.internal.ccvs.core.ICVSFolder; import org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation; import org.eclipse.team.internal.ccvs.core.Policy; import org.eclipse.team.internal.ccvs.core.client.CommandOutputListener; import org.eclipse.team.internal.ccvs.core.client.Update; import org.eclipse.team.internal.ccvs.core.util.Util; public class UpdateListener extends CommandOutputListener { // Pattern matchers private static ServerMessageLineMatcher MERGED_BINARY_FILE_LINE_1; private static ServerMessageLineMatcher MERGED_BINARY_FILE_LINE_2; // Pattern Variables private static final String REVISION_VARIABLE_NAME = "revision"; //$NON-NLS-1$ private static final String LOCAL_FILE_PATH_VARIABLE_NAME = "localFilePath"; //$NON-NLS-1$ private static final String BACKUP_FILE_VARIABLE_NAME = "backupFile"; //$NON-NLS-1$ static { try { String line1 = "revision " //$NON-NLS-1$ + Util.getVariablePattern(IMessagePatterns.REVISION_PATTERN, REVISION_VARIABLE_NAME) + " from repository is now in " //$NON-NLS-1$ + Util.getVariablePattern(IMessagePatterns.FILE_PATH_PATTERN, LOCAL_FILE_PATH_VARIABLE_NAME); MERGED_BINARY_FILE_LINE_1 = new ServerMessageLineMatcher( line1, new String[] {REVISION_VARIABLE_NAME, LOCAL_FILE_PATH_VARIABLE_NAME}); String line2 = "file from working directory is now in " //$NON-NLS-1$ + Util.getVariablePattern(IMessagePatterns.REVISION_PATTERN, BACKUP_FILE_VARIABLE_NAME); MERGED_BINARY_FILE_LINE_2 = new ServerMessageLineMatcher( line2, new String[] {BACKUP_FILE_VARIABLE_NAME}); } catch (CVSException e) { // Shouldn't happen CVSProviderPlugin.log(e); } } IUpdateMessageListener updateMessageListener; boolean merging = false; boolean mergingBinary = false; String mergedBinaryFileRevision, mergedBinaryFilePath; public UpdateListener(IUpdateMessageListener updateMessageListener) { this.updateMessageListener = updateMessageListener; } public IStatus messageLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { mergingBinary = false; if (updateMessageListener == null) return OK; if(line.startsWith("Merging differences")) { //$NON-NLS-1$ merging = true; } else if(line.indexOf(' ')==1) { // We have a message that indicates the type of update. The possible messages are // defined by the prefix constants MLP_*. String path = line.substring(2); char changeType = line.charAt(0); // calculate change type int type = 0; switch(changeType) { case 'A': type = Update.STATE_ADDED_LOCAL; break; // new file locally that was added but not comitted to server yet case '?': type = Update.STATE_UNKOWN; break; // new file locally but not added to server case 'U': type = Update.STATE_REMOTE_CHANGES; break; // remote changes to an unmodified local file case 'R': type = Update.STATE_DELETED; break; // removed locally but still exists on the server case 'M': type = Update.STATE_MODIFIED; break; // modified locally case 'C': type = Update.STATE_CONFLICT; break; // modified locally and on the server but cannot be auto-merged case 'D': type = Update.STATE_DELETED; break; // deleted locally but still exists on server default: type = Update.STATE_NONE; } if (merging) { // If we are merging the modified prefix is used both to show merges and // local changes. We have to detect this case and use a more specific change // type. if (type == Update.STATE_MODIFIED) type = Update.STATE_MERGEABLE_CONFLICT; merging = false; } updateMessageListener.fileInformation(type, commandRoot, path); } return OK; } /** * This handler is used by the RemoteResource hierarchy to retrieve E messages * from the CVS server in order to determine the folders contained in a parent folder. * * WARNING: This class parses the message output to determine the state of files in the * repository. Unfortunately, these messages seem to be customizable on a server by server basis. * * Here's a list of responses we expect in various situations: * * Directory exists remotely: * cvs server: Updating folder1/folder2 * Directory doesn't exist remotely: * cvs server: skipping directory folder1/folder2 * New (or unknown) remote directory * cvs server: New Directory folder1/folder2 * File removed remotely * cvs server: folder1/file.ext is no longer in the repository * cvs server: warning: folder1/file.ext is not (any longer) pertinent * Locally added file was added remotely as well * cvs server: conflict: folder/file.ext created independently by second party * File removed locally and modified remotely * cvs server: conflict: removed file.txt was modified by second party * File modified locally but removed remotely * cvs server: conflict: file.txt is modified but no longer in the repository * Ignored Messages * cvs server: cannot open directory ... * cvs server: nothing known about ... * Tag error that really means there are no files in a directory * cvs [server aborted]: no such tag * Merge contained conflicts * rcsmerge: warning: conflicts during merge * Binary file conflict * cvs server: nonmergeable file needs merge * cvs server: revision 1.4 from repository is now in a1/a2/test * cvs server: file from working directory is now in .#test.1.3 */ public IStatus errorLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { try { // Reset flag globally here because we have to many exit points boolean wasMergingBinary = mergingBinary; mergingBinary = false; String serverMessage = getServerMessage(line, location); if (serverMessage != null) { // Strip the prefix from the line String message = serverMessage; if (message.startsWith("Updating")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(9); updateMessageListener.directoryInformation(commandRoot, path, false); } return OK; } else if (message.startsWith("skipping directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(18).trim(); updateMessageListener.directoryDoesNotExist(commandRoot, path); } return OK; } else if (message.startsWith("New directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(15, message.lastIndexOf('\'')); updateMessageListener.directoryInformation(commandRoot, path, true); } return OK; } else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$ if (updateMessageListener != null) { String filename = message.substring(0, message.length() - 31); + // CVS version 12 fix - filenames are returned inside quotes + // Fixes bug 49056 + if (filename.startsWith("`") && filename.endsWith("'")) //$NON-NLS-1$ //$NON-NLS-2$ + filename = filename.substring(1,filename.length()-1); updateMessageListener.fileDoesNotExist(commandRoot, filename); } return OK; } else if (message.startsWith("conflict:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: conflict: folder/file.ext created independently by second party * cvs server: conflict: removed file.txt was modified by second party * cvs server: conflict: file.txt is modified but no longer in the repository * If we get the above line, we have conflicting additions or deletions and we can expect a server error. * We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case) */ if (updateMessageListener != null) { if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$ // The "C foler/file.ext" will come after this so if whould be ignored! String filename = message.substring(10, message.length() - 44); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("warning:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: warning: folder1/file.ext is not (any longer) pertinent * If we get the above line, we have local changes to a remotely deleted file. */ if (updateMessageListener != null) { if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$ String filename = message.substring(9, message.length() - 30); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("conflicts")) { //$NON-NLS-1$ // This line is info only. The server doesn't report an error. return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("nonmergeable file needs merge")) { //$NON-NLS-1$ mergingBinary = true; mergedBinaryFileRevision = null; mergedBinaryFilePath = null; return OK; } else if (wasMergingBinary) { Map variables = MERGED_BINARY_FILE_LINE_1.processServerMessage(message); if (variables != null) { mergedBinaryFileRevision = (String)variables.get(REVISION_VARIABLE_NAME); mergedBinaryFilePath = (String)variables.get(LOCAL_FILE_PATH_VARIABLE_NAME); mergingBinary = true; return OK; } variables = MERGED_BINARY_FILE_LINE_2.processServerMessage(message); if (variables != null) { String backupFile = (String)variables.get(BACKUP_FILE_VARIABLE_NAME); try { if (mergedBinaryFileRevision != null && mergedBinaryFilePath != null) { ICVSFile file = commandRoot.getFile(mergedBinaryFilePath); IResource resource = file.getIResource(); if (resource != null) { return new CVSStatus(IStatus.ERROR, CVSStatus.UNMEGERED_BINARY_CONFLICT, Policy.bind("UpdateListener.0", new Object[] { //$NON-NLS-1$ resource.getFullPath().toString(), mergedBinaryFileRevision, resource.getFullPath().removeLastSegments(1).append(backupFile).toString()})); } } } catch (CVSException e1) { CVSProviderPlugin.log(e1); } return OK; } } // Fallthrough case for "cvs server" messages if (!message.startsWith("cannot open directory") //$NON-NLS-1$ && !message.startsWith("nothing known about")) { //$NON-NLS-1$ return super.errorLine(line, location, commandRoot, monitor); } } else { String serverAbortedMessage = getServerAbortedMessage(line, location); if (serverAbortedMessage != null) { // Strip the prefix from the line String message = serverAbortedMessage; if (message.startsWith("no such tag")) { //$NON-NLS-1$ // This is reported from CVS when a tag is used on the update there are no files in the directory // To get the folders, the update request should be re-issued for HEAD return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, commandRoot, line); } else { return super.errorLine(line, location, commandRoot, monitor); } } else if (line.equals("rcsmerge: warning: conflicts during merge")) { //$NON-NLS-1$ // There were conflicts in the merge return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } } } catch (StringIndexOutOfBoundsException e) { // Something went wrong in the parsing of the message. // Return a status indicating the problem if (CVSProviderPlugin.getPlugin().isDebugging()) { System.out.println("Error parsing E line: " + line); //$NON-NLS-1$ } return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE_PARSE_FAILURE, commandRoot, line); } return super.errorLine(line, location, commandRoot, monitor); } }
true
true
public IStatus errorLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { try { // Reset flag globally here because we have to many exit points boolean wasMergingBinary = mergingBinary; mergingBinary = false; String serverMessage = getServerMessage(line, location); if (serverMessage != null) { // Strip the prefix from the line String message = serverMessage; if (message.startsWith("Updating")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(9); updateMessageListener.directoryInformation(commandRoot, path, false); } return OK; } else if (message.startsWith("skipping directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(18).trim(); updateMessageListener.directoryDoesNotExist(commandRoot, path); } return OK; } else if (message.startsWith("New directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(15, message.lastIndexOf('\'')); updateMessageListener.directoryInformation(commandRoot, path, true); } return OK; } else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$ if (updateMessageListener != null) { String filename = message.substring(0, message.length() - 31); updateMessageListener.fileDoesNotExist(commandRoot, filename); } return OK; } else if (message.startsWith("conflict:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: conflict: folder/file.ext created independently by second party * cvs server: conflict: removed file.txt was modified by second party * cvs server: conflict: file.txt is modified but no longer in the repository * If we get the above line, we have conflicting additions or deletions and we can expect a server error. * We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case) */ if (updateMessageListener != null) { if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$ // The "C foler/file.ext" will come after this so if whould be ignored! String filename = message.substring(10, message.length() - 44); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("warning:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: warning: folder1/file.ext is not (any longer) pertinent * If we get the above line, we have local changes to a remotely deleted file. */ if (updateMessageListener != null) { if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$ String filename = message.substring(9, message.length() - 30); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("conflicts")) { //$NON-NLS-1$ // This line is info only. The server doesn't report an error. return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("nonmergeable file needs merge")) { //$NON-NLS-1$ mergingBinary = true; mergedBinaryFileRevision = null; mergedBinaryFilePath = null; return OK; } else if (wasMergingBinary) { Map variables = MERGED_BINARY_FILE_LINE_1.processServerMessage(message); if (variables != null) { mergedBinaryFileRevision = (String)variables.get(REVISION_VARIABLE_NAME); mergedBinaryFilePath = (String)variables.get(LOCAL_FILE_PATH_VARIABLE_NAME); mergingBinary = true; return OK; } variables = MERGED_BINARY_FILE_LINE_2.processServerMessage(message); if (variables != null) { String backupFile = (String)variables.get(BACKUP_FILE_VARIABLE_NAME); try { if (mergedBinaryFileRevision != null && mergedBinaryFilePath != null) { ICVSFile file = commandRoot.getFile(mergedBinaryFilePath); IResource resource = file.getIResource(); if (resource != null) { return new CVSStatus(IStatus.ERROR, CVSStatus.UNMEGERED_BINARY_CONFLICT, Policy.bind("UpdateListener.0", new Object[] { //$NON-NLS-1$ resource.getFullPath().toString(), mergedBinaryFileRevision, resource.getFullPath().removeLastSegments(1).append(backupFile).toString()})); } } } catch (CVSException e1) { CVSProviderPlugin.log(e1); } return OK; } } // Fallthrough case for "cvs server" messages if (!message.startsWith("cannot open directory") //$NON-NLS-1$ && !message.startsWith("nothing known about")) { //$NON-NLS-1$ return super.errorLine(line, location, commandRoot, monitor); } } else { String serverAbortedMessage = getServerAbortedMessage(line, location); if (serverAbortedMessage != null) { // Strip the prefix from the line String message = serverAbortedMessage; if (message.startsWith("no such tag")) { //$NON-NLS-1$ // This is reported from CVS when a tag is used on the update there are no files in the directory // To get the folders, the update request should be re-issued for HEAD return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, commandRoot, line); } else { return super.errorLine(line, location, commandRoot, monitor); } } else if (line.equals("rcsmerge: warning: conflicts during merge")) { //$NON-NLS-1$ // There were conflicts in the merge return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } } } catch (StringIndexOutOfBoundsException e) { // Something went wrong in the parsing of the message. // Return a status indicating the problem if (CVSProviderPlugin.getPlugin().isDebugging()) { System.out.println("Error parsing E line: " + line); //$NON-NLS-1$ } return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE_PARSE_FAILURE, commandRoot, line); } return super.errorLine(line, location, commandRoot, monitor); }
public IStatus errorLine(String line, ICVSRepositoryLocation location, ICVSFolder commandRoot, IProgressMonitor monitor) { try { // Reset flag globally here because we have to many exit points boolean wasMergingBinary = mergingBinary; mergingBinary = false; String serverMessage = getServerMessage(line, location); if (serverMessage != null) { // Strip the prefix from the line String message = serverMessage; if (message.startsWith("Updating")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(9); updateMessageListener.directoryInformation(commandRoot, path, false); } return OK; } else if (message.startsWith("skipping directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(18).trim(); updateMessageListener.directoryDoesNotExist(commandRoot, path); } return OK; } else if (message.startsWith("New directory")) { //$NON-NLS-1$ if (updateMessageListener != null) { String path = message.substring(15, message.lastIndexOf('\'')); updateMessageListener.directoryInformation(commandRoot, path, true); } return OK; } else if (message.endsWith("is no longer in the repository")) { //$NON-NLS-1$ if (updateMessageListener != null) { String filename = message.substring(0, message.length() - 31); // CVS version 12 fix - filenames are returned inside quotes // Fixes bug 49056 if (filename.startsWith("`") && filename.endsWith("'")) //$NON-NLS-1$ //$NON-NLS-2$ filename = filename.substring(1,filename.length()-1); updateMessageListener.fileDoesNotExist(commandRoot, filename); } return OK; } else if (message.startsWith("conflict:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: conflict: folder/file.ext created independently by second party * cvs server: conflict: removed file.txt was modified by second party * cvs server: conflict: file.txt is modified but no longer in the repository * If we get the above line, we have conflicting additions or deletions and we can expect a server error. * We still get "C foler/file.ext" so we don't need to do anything else (except in the remotely deleted case) */ if (updateMessageListener != null) { if (message.endsWith("is modified but no longer in the repository")) { //$NON-NLS-1$ // The "C foler/file.ext" will come after this so if whould be ignored! String filename = message.substring(10, message.length() - 44); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("warning:")) { //$NON-NLS-1$ /* * We can get the following conflict warnings * cvs server: warning: folder1/file.ext is not (any longer) pertinent * If we get the above line, we have local changes to a remotely deleted file. */ if (updateMessageListener != null) { if (message.endsWith("is not (any longer) pertinent")) { //$NON-NLS-1$ String filename = message.substring(9, message.length() - 30); updateMessageListener.fileDoesNotExist(commandRoot, filename); } } return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("conflicts")) { //$NON-NLS-1$ // This line is info only. The server doesn't report an error. return new CVSStatus(IStatus.INFO, CVSStatus.CONFLICT, commandRoot, line); } else if (message.startsWith("nonmergeable file needs merge")) { //$NON-NLS-1$ mergingBinary = true; mergedBinaryFileRevision = null; mergedBinaryFilePath = null; return OK; } else if (wasMergingBinary) { Map variables = MERGED_BINARY_FILE_LINE_1.processServerMessage(message); if (variables != null) { mergedBinaryFileRevision = (String)variables.get(REVISION_VARIABLE_NAME); mergedBinaryFilePath = (String)variables.get(LOCAL_FILE_PATH_VARIABLE_NAME); mergingBinary = true; return OK; } variables = MERGED_BINARY_FILE_LINE_2.processServerMessage(message); if (variables != null) { String backupFile = (String)variables.get(BACKUP_FILE_VARIABLE_NAME); try { if (mergedBinaryFileRevision != null && mergedBinaryFilePath != null) { ICVSFile file = commandRoot.getFile(mergedBinaryFilePath); IResource resource = file.getIResource(); if (resource != null) { return new CVSStatus(IStatus.ERROR, CVSStatus.UNMEGERED_BINARY_CONFLICT, Policy.bind("UpdateListener.0", new Object[] { //$NON-NLS-1$ resource.getFullPath().toString(), mergedBinaryFileRevision, resource.getFullPath().removeLastSegments(1).append(backupFile).toString()})); } } } catch (CVSException e1) { CVSProviderPlugin.log(e1); } return OK; } } // Fallthrough case for "cvs server" messages if (!message.startsWith("cannot open directory") //$NON-NLS-1$ && !message.startsWith("nothing known about")) { //$NON-NLS-1$ return super.errorLine(line, location, commandRoot, monitor); } } else { String serverAbortedMessage = getServerAbortedMessage(line, location); if (serverAbortedMessage != null) { // Strip the prefix from the line String message = serverAbortedMessage; if (message.startsWith("no such tag")) { //$NON-NLS-1$ // This is reported from CVS when a tag is used on the update there are no files in the directory // To get the folders, the update request should be re-issued for HEAD return new CVSStatus(CVSStatus.WARNING, CVSStatus.NO_SUCH_TAG, commandRoot, line); } else { return super.errorLine(line, location, commandRoot, monitor); } } else if (line.equals("rcsmerge: warning: conflicts during merge")) { //$NON-NLS-1$ // There were conflicts in the merge return new CVSStatus(CVSStatus.WARNING, CVSStatus.CONFLICT, commandRoot, line); } } } catch (StringIndexOutOfBoundsException e) { // Something went wrong in the parsing of the message. // Return a status indicating the problem if (CVSProviderPlugin.getPlugin().isDebugging()) { System.out.println("Error parsing E line: " + line); //$NON-NLS-1$ } return new CVSStatus(CVSStatus.ERROR, CVSStatus.ERROR_LINE_PARSE_FAILURE, commandRoot, line); } return super.errorLine(line, location, commandRoot, monitor); }
diff --git a/src/main/java/org/blitzortung/android/alarm/AlarmManager.java b/src/main/java/org/blitzortung/android/alarm/AlarmManager.java index ba26854..63ca329 100644 --- a/src/main/java/org/blitzortung/android/alarm/AlarmManager.java +++ b/src/main/java/org/blitzortung/android/alarm/AlarmManager.java @@ -1,138 +1,138 @@ package org.blitzortung.android.alarm; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.location.Location; import org.blitzortung.android.app.TimerTask; import org.blitzortung.android.app.controller.LocationHandler; import org.blitzortung.android.app.view.PreferenceKey; import org.blitzortung.android.data.beans.Stroke; import org.blitzortung.android.util.MeasurementSystem; import java.util.Collection; import java.util.HashSet; import java.util.Set; public class AlarmManager implements OnSharedPreferenceChangeListener, LocationHandler.Listener { private Collection<? extends Stroke> strokes; private boolean alarmActive; public interface AlarmListener { void onAlarmResult(AlarmStatus alarmStatus); void onAlarmClear(); } private final long alarmInterval; private final TimerTask timerTask; private final LocationHandler locationHandler; private Location location; private boolean alarmEnabled; private MeasurementSystem measurementSystem; // VisibleForTesting protected final Set<AlarmListener> alarmListeners; private AlarmStatus alarmStatus; public AlarmManager(LocationHandler locationHandler, SharedPreferences preferences, TimerTask timerTask) { this.timerTask = timerTask; alarmListeners = new HashSet<AlarmListener>(); this.locationHandler = locationHandler; preferences.registerOnSharedPreferenceChangeListener(this); onSharedPreferenceChanged(preferences, PreferenceKey.ALARM_ENABLED); onSharedPreferenceChanged(preferences, PreferenceKey.MEASUREMENT_UNIT); alarmInterval = 600000; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String keyString) { onSharedPreferenceChanged(sharedPreferences, PreferenceKey.fromString(keyString)); } private void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) { switch (key) { case ALARM_ENABLED: - alarmEnabled = sharedPreferences.getBoolean(key.toString(), false) && locationHandler.isProviderEnabled(); + alarmEnabled = sharedPreferences.getBoolean(key.toString(), true) && locationHandler.isProviderEnabled(); if (alarmEnabled) { locationHandler.requestUpdates(this); } else { locationHandler.removeUpdates(this); for (AlarmListener alarmListener : alarmListeners) { alarmListener.onAlarmClear(); } } timerTask.setAlarmEnabled(alarmEnabled); break; case MEASUREMENT_UNIT: String measurementSystemName = sharedPreferences.getString(key.toString(), MeasurementSystem.METRIC.toString()); measurementSystem = MeasurementSystem.valueOf(measurementSystemName); break; } } @Override public void onLocationChanged(Location location) { this.location = location; check(strokes, alarmActive); } public boolean isAlarmEnabled() { return alarmEnabled; } public void check(Collection<? extends Stroke> strokes, boolean alarmActive) { this.strokes = strokes; this.alarmActive = alarmActive; if (alarmEnabled && alarmActive && strokes != null && location != null) { long now = System.currentTimeMillis(); long thresholdTime = now - alarmInterval; if (alarmStatus == null) { alarmStatus = new AlarmStatus(thresholdTime, measurementSystem); } else { alarmStatus.update(thresholdTime, measurementSystem); } alarmStatus.check(strokes, location); } else { alarmStatus = null; } for (AlarmListener alarmListener : alarmListeners) { alarmListener.onAlarmResult(alarmStatus); } } public AlarmStatus getAlarmStatus() { return alarmStatus; } public void clearAlarmListeners() { alarmListeners.clear(); } public void addAlarmListener(AlarmListener alarmListener) { alarmListeners.add(alarmListener); } public void removeAlarmListener(AlarmListener alarmView) { alarmListeners.remove(alarmView); } }
true
true
private void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) { switch (key) { case ALARM_ENABLED: alarmEnabled = sharedPreferences.getBoolean(key.toString(), false) && locationHandler.isProviderEnabled(); if (alarmEnabled) { locationHandler.requestUpdates(this); } else { locationHandler.removeUpdates(this); for (AlarmListener alarmListener : alarmListeners) { alarmListener.onAlarmClear(); } } timerTask.setAlarmEnabled(alarmEnabled); break; case MEASUREMENT_UNIT: String measurementSystemName = sharedPreferences.getString(key.toString(), MeasurementSystem.METRIC.toString()); measurementSystem = MeasurementSystem.valueOf(measurementSystemName); break; } }
private void onSharedPreferenceChanged(SharedPreferences sharedPreferences, PreferenceKey key) { switch (key) { case ALARM_ENABLED: alarmEnabled = sharedPreferences.getBoolean(key.toString(), true) && locationHandler.isProviderEnabled(); if (alarmEnabled) { locationHandler.requestUpdates(this); } else { locationHandler.removeUpdates(this); for (AlarmListener alarmListener : alarmListeners) { alarmListener.onAlarmClear(); } } timerTask.setAlarmEnabled(alarmEnabled); break; case MEASUREMENT_UNIT: String measurementSystemName = sharedPreferences.getString(key.toString(), MeasurementSystem.METRIC.toString()); measurementSystem = MeasurementSystem.valueOf(measurementSystemName); break; } }
diff --git a/src/java/fedora/server/storage/DefaultExternalContentManager.java b/src/java/fedora/server/storage/DefaultExternalContentManager.java index 3051cad6c..febda0556 100755 --- a/src/java/fedora/server/storage/DefaultExternalContentManager.java +++ b/src/java/fedora/server/storage/DefaultExternalContentManager.java @@ -1,198 +1,198 @@ /* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://www.fedora.info/license/). */ package fedora.server.storage; import java.util.Hashtable; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.log4j.Logger; import fedora.common.http.HttpInputStream; import fedora.common.http.WebClient; import fedora.server.Context; import fedora.server.Module; import fedora.server.Server; import fedora.server.errors.GeneralException; import fedora.server.errors.HttpServiceNotFoundException; import fedora.server.errors.ModuleInitializationException; import fedora.server.security.BackendPolicies; import fedora.server.security.BackendSecurity; import fedora.server.security.BackendSecuritySpec; import fedora.server.storage.types.MIMETypedStream; import fedora.server.storage.types.Property; import fedora.server.utilities.ServerUtility; /** * * <p><b>Title:</b> DefaultExternalContentManager.java</p> * <p><b>Description:</b> Provides a mechanism to obtain external HTTP-accessible * content.</p> * * @author [email protected] * @version $Id$ */ public class DefaultExternalContentManager extends Module implements ExternalContentManager { /** Logger for this class. */ private static final Logger LOG = Logger.getLogger( DefaultExternalContentManager.class.getName()); private String m_userAgent; private String fedoraServerHost; private String fedoraServerPort; private String fedoraServerRedirectPort; private WebClient m_http; /** * <p> Creates a new DefaultExternalContentManager.</p> * * @param moduleParameters The name/value pair map of module parameters. * @param server The server instance. * @param role The module role name. * @throws ModuleInitializationException If initialization values are * invalid or initialization fails for some other reason. */ public DefaultExternalContentManager(Map moduleParameters, Server server, String role) throws ModuleInitializationException { super(moduleParameters, server, role); } /** * Initializes the Module based on configuration parameters. The * implementation of this method is dependent on the schema used to define * the parameter names for the role of * <code>fedora.server.storage.DefaultExternalContentManager</code>. * * @throws ModuleInitializationException If initialization values are * invalid or initialization fails for some other reason. */ public void initModule() throws ModuleInitializationException { try { Server s_server = this.getServer(); m_userAgent=getParameter("userAgent"); if (m_userAgent==null) { m_userAgent="Fedora"; } fedoraServerPort = s_server.getParameter("fedoraServerPort"); fedoraServerHost = s_server.getParameter("fedoraServerHost"); fedoraServerRedirectPort = s_server.getParameter("fedoraRedirectPort"); m_http = new WebClient(); m_http.USER_AGENT = m_userAgent; } catch (Throwable th) { throw new ModuleInitializationException("[DefaultExternalContentManager] " + "An external content manager " + "could not be instantiated. The underlying error was a " + th.getClass().getName() + "The message was \"" + th.getMessage() + "\".", getRole()); } } /** * Get a MIMETypedStream for the given URL. * * If user or password are <code>null</code>, basic authentication will * not be attempted. */ private MIMETypedStream get(String url, String user, String pass) throws GeneralException { LOG.debug("DefaultExternalContentManager.get(" + url + ")"); try { HttpInputStream response = m_http.get(url, true, user, pass); String mimeType = response.getResponseHeaderValue("Content-Type", "text/plain"); Property[] headerArray = toPropertyArray( response.getResponseHeaders()); return new MIMETypedStream(mimeType, response, headerArray); } catch (Exception e) { throw new GeneralException("Error getting " + url, e); } } /** * Convert the given HTTP <code>Headers</code> to an array of * <code>Property</code> objects. */ private static Property[] toPropertyArray(Header[] headers) { Property[] props = new Property[headers.length]; for (int i = 0; i < headers.length; i++) { props[i] = new Property(); props[i].name = headers[i].getName(); props[i].value = headers[i].getValue(); } return props; } /** * A method that reads the contents of the specified URL and returns the * result as a MIMETypedStream * * @param url The URL of the external content. * @return A MIME-typed stream. * @throws HttpServiceNotFoundException If the URL connection could not * be established. */ public MIMETypedStream getExternalContent(String url, Context context) throws GeneralException, HttpServiceNotFoundException { LOG.debug("in getExternalContent(), url=" + url); try { String backendUsername = ""; String backendPassword = ""; boolean backendSSL = false; String modURL = url; if (ServerUtility.isURLFedoraServer(modURL)) { BackendSecuritySpec m_beSS; BackendSecurity m_beSecurity = (BackendSecurity) getServer().getModule("fedora.server.security.BackendSecurity"); try { m_beSS = m_beSecurity.getBackendSecuritySpec(); } catch (Exception e) { throw new ModuleInitializationException("Can't intitialize BackendSecurity module (in default access) from Server.getModule", getRole()); } Hashtable beHash = m_beSS.getSecuritySpec(BackendPolicies.FEDORA_INTERNAL_CALL); backendUsername = (String) beHash.get("callUsername"); backendPassword = (String) beHash.get("callPassword"); - backendSSL = new Boolean((String) beHash.get("callBasicAuth")).booleanValue(); + backendSSL = new Boolean((String) beHash.get("callSSL")).booleanValue(); if (backendSSL) { if (modURL.startsWith("http:")) { modURL = modURL.replaceFirst("http:", "https:"); } modURL = modURL.replaceFirst(":"+fedoraServerPort+"/", ":"+fedoraServerRedirectPort+"/"); } } if (LOG.isDebugEnabled()) { LOG.debug("************************* backendUsername: "+backendUsername+ " backendPassword: "+backendPassword+" backendSSL: "+backendSSL); LOG.debug("************************* doAuthnGetURL: "+modURL); } return get(modURL, backendUsername, backendPassword); } catch (GeneralException ge) { throw ge; } catch (Throwable th) { // catch anything but generalexception th.printStackTrace(); throw new HttpServiceNotFoundException("[DefaultExternalContentManager] " + "returned an error. The underlying error was a " + th.getClass().getName() + " The message " + "was \"" + th.getMessage() + "\" . "); } } }
true
true
public MIMETypedStream getExternalContent(String url, Context context) throws GeneralException, HttpServiceNotFoundException { LOG.debug("in getExternalContent(), url=" + url); try { String backendUsername = ""; String backendPassword = ""; boolean backendSSL = false; String modURL = url; if (ServerUtility.isURLFedoraServer(modURL)) { BackendSecuritySpec m_beSS; BackendSecurity m_beSecurity = (BackendSecurity) getServer().getModule("fedora.server.security.BackendSecurity"); try { m_beSS = m_beSecurity.getBackendSecuritySpec(); } catch (Exception e) { throw new ModuleInitializationException("Can't intitialize BackendSecurity module (in default access) from Server.getModule", getRole()); } Hashtable beHash = m_beSS.getSecuritySpec(BackendPolicies.FEDORA_INTERNAL_CALL); backendUsername = (String) beHash.get("callUsername"); backendPassword = (String) beHash.get("callPassword"); backendSSL = new Boolean((String) beHash.get("callBasicAuth")).booleanValue(); if (backendSSL) { if (modURL.startsWith("http:")) { modURL = modURL.replaceFirst("http:", "https:"); } modURL = modURL.replaceFirst(":"+fedoraServerPort+"/", ":"+fedoraServerRedirectPort+"/"); } } if (LOG.isDebugEnabled()) { LOG.debug("************************* backendUsername: "+backendUsername+ " backendPassword: "+backendPassword+" backendSSL: "+backendSSL); LOG.debug("************************* doAuthnGetURL: "+modURL); } return get(modURL, backendUsername, backendPassword); } catch (GeneralException ge) { throw ge; } catch (Throwable th) { // catch anything but generalexception th.printStackTrace(); throw new HttpServiceNotFoundException("[DefaultExternalContentManager] " + "returned an error. The underlying error was a " + th.getClass().getName() + " The message " + "was \"" + th.getMessage() + "\" . "); } }
public MIMETypedStream getExternalContent(String url, Context context) throws GeneralException, HttpServiceNotFoundException { LOG.debug("in getExternalContent(), url=" + url); try { String backendUsername = ""; String backendPassword = ""; boolean backendSSL = false; String modURL = url; if (ServerUtility.isURLFedoraServer(modURL)) { BackendSecuritySpec m_beSS; BackendSecurity m_beSecurity = (BackendSecurity) getServer().getModule("fedora.server.security.BackendSecurity"); try { m_beSS = m_beSecurity.getBackendSecuritySpec(); } catch (Exception e) { throw new ModuleInitializationException("Can't intitialize BackendSecurity module (in default access) from Server.getModule", getRole()); } Hashtable beHash = m_beSS.getSecuritySpec(BackendPolicies.FEDORA_INTERNAL_CALL); backendUsername = (String) beHash.get("callUsername"); backendPassword = (String) beHash.get("callPassword"); backendSSL = new Boolean((String) beHash.get("callSSL")).booleanValue(); if (backendSSL) { if (modURL.startsWith("http:")) { modURL = modURL.replaceFirst("http:", "https:"); } modURL = modURL.replaceFirst(":"+fedoraServerPort+"/", ":"+fedoraServerRedirectPort+"/"); } } if (LOG.isDebugEnabled()) { LOG.debug("************************* backendUsername: "+backendUsername+ " backendPassword: "+backendPassword+" backendSSL: "+backendSSL); LOG.debug("************************* doAuthnGetURL: "+modURL); } return get(modURL, backendUsername, backendPassword); } catch (GeneralException ge) { throw ge; } catch (Throwable th) { // catch anything but generalexception th.printStackTrace(); throw new HttpServiceNotFoundException("[DefaultExternalContentManager] " + "returned an error. The underlying error was a " + th.getClass().getName() + " The message " + "was \"" + th.getMessage() + "\" . "); } }
diff --git a/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java b/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java index 7d64bd34d..477e8bc30 100644 --- a/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java +++ b/rdt/org.eclipse.ptp.rdt.sync.core/src/org/eclipse/ptp/rdt/sync/core/remotemake/SyncCommandLauncher.java @@ -1,428 +1,433 @@ /******************************************************************************* * Copyright (c) 2009, 2010 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.ptp.rdt.sync.core.remotemake; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.ICommandLauncher; import org.eclipse.cdt.managedbuilder.core.IBuilder; import org.eclipse.cdt.managedbuilder.core.IConfiguration; import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.ptp.internal.rdt.core.index.IndexBuildSequenceController; import org.eclipse.ptp.internal.rdt.core.remotemake.RemoteProcessClosure; import org.eclipse.ptp.rdt.core.serviceproviders.IRemoteExecutionServiceProvider; import org.eclipse.ptp.rdt.core.services.IRDTServiceConstants; import org.eclipse.ptp.rdt.sync.core.BuildConfigurationManager; import org.eclipse.ptp.rdt.sync.core.SyncFlag; import org.eclipse.ptp.rdt.sync.core.serviceproviders.ISyncServiceProvider; import org.eclipse.ptp.rdt.sync.core.services.IRemoteSyncServiceConstants; import org.eclipse.ptp.remote.core.IRemoteConnection; import org.eclipse.ptp.remote.core.IRemoteFileManager; import org.eclipse.ptp.remote.core.IRemoteProcess; import org.eclipse.ptp.remote.core.IRemoteProcessBuilder; import org.eclipse.ptp.remote.core.IRemoteServices; import org.eclipse.ptp.remote.core.RemoteProcessAdapter; import org.eclipse.ptp.remote.core.exception.RemoteConnectionException; import org.eclipse.ptp.services.core.IService; import org.eclipse.ptp.services.core.IServiceConfiguration; import org.eclipse.ptp.services.core.IServiceProvider; import org.eclipse.ptp.services.core.ServiceModelManager; /** * <strong>EXPERIMENTAL</strong>. This class or interface has been added as * part of a work in progress. There is no guarantee that this API will work or * that it will remain the same. Please do not use this API without consulting * with the RDT team. * * @author crecoskie * */ public class SyncCommandLauncher implements ICommandLauncher { protected IProject fProject; protected Process fProcess; protected IRemoteProcess fRemoteProcess; protected boolean fShowCommand; protected String[] fCommandArgs; protected String lineSeparator = "\r\n"; //$NON-NLS-1$ protected String fErrorMessage; protected Map<String, String> remoteEnvMap; private boolean isCleanBuild; /** * The number of milliseconds to pause between polling. */ protected static final long DELAY = 50L; /** * */ public SyncCommandLauncher() { } private boolean isCleanBuild(String[] args){ for(int i=0; i< args.length; i++){ if(IBuilder.DEFAULT_TARGET_CLEAN.equals(args[i])){ return true; } } return false; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#execute(org.eclipse.core.runtime.IPath, java.lang.String[], java.lang.String[], org.eclipse.core.runtime.IPath) */ public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild= isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if(getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot().getLocation().toPortableString() + getProject().getFullPath().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration). getLocation(); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectWorkspaceRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Determine the service model for this configuration, and use the provider of the build // service to execute the build command. Also get the sync provider to sync before and // after building. ServiceModelManager smm = ServiceModelManager.getInstance(); IServiceConfiguration serviceConfig = BuildConfigurationManager.getInstance(). getConfigurationForBuildConfiguration(configuration); if (serviceConfig == null) { throw new RuntimeException("Cannot find service configuration for build configuration"); //$NON-NLS-1$ } IService syncService = smm.getService(IRemoteSyncServiceConstants.SERVICE_SYNC); ISyncServiceProvider syncProvider = null; if (!(serviceConfig.isDisabled(syncService))) { syncProvider = (ISyncServiceProvider) serviceConfig.getServiceProvider(syncService); } IService buildService = smm.getService(IRDTServiceConstants.SERVICE_BUILD); IServiceProvider provider = serviceConfig.getServiceProvider(buildService); IRemoteExecutionServiceProvider executionProvider = null; if(provider instanceof IRemoteExecutionServiceProvider) { executionProvider = (IRemoteExecutionServiceProvider) provider; } if (executionProvider != null) { IRemoteServices remoteServices = executionProvider.getRemoteServices(); if(!remoteServices.isInitialized()) { remoteServices.initialize(); } if (remoteServices == null) return null; IRemoteConnection connection = executionProvider.getConnection(); if(!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } List<String> command = new LinkedList<String>(); command.add(commandPath.toString()); for(int k = 0; k < args.length; k++) command.add(args[k]); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for(String envVar : env) { String[] splitStr = envVar.split("="); //$NON-NLS-1$ - remoteEnvMap.put(splitStr[0], splitStr[1]); + if (splitStr.length > 1) { + remoteEnvMap.put(splitStr[0], splitStr[1]); + } else if (splitStr.length == 1){ + // Empty environment variable + remoteEnvMap.put(splitStr[0], ""); //$NON-NLS-1$ + } } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if(changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // combine stdout and stderr processBuilder.redirectErrorStream(true); // Synchronize before building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if(projectStatus!=null){ if(!isCleanBuild){ projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); // wait for the process to finish while (!p.isCompleted()) { try { p.waitFor(); } catch (InterruptedException e) { // just keep waiting until the process is done } } // Synchronize after building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } return fProcess; } return null; } private String getCommandLine(String[] commandArgs) { if(fProject == null) return null; StringBuffer buf = new StringBuffer(); if (fCommandArgs != null) { for (String commandArg : commandArgs) { buf.append(commandArg); buf.append(' '); } buf.append(lineSeparator); } return buf.toString(); } /** * Constructs a command array that will be passed to the process */ protected String[] constructCommandArray(String command, String[] commandArgs) { String[] args = new String[1 + commandArgs.length]; args[0] = command; System.arraycopy(commandArgs, 0, args, 1, commandArgs.length); return args; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#getCommandLine() */ public String getCommandLine() { return getCommandLine(getCommandArgs()); } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#getCommandArgs() */ public String[] getCommandArgs() { return fCommandArgs; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#getEnvironment() */ public Properties getEnvironment() { return convertEnvMapToProperties(); } private Properties convertEnvMapToProperties() { Properties properties = new Properties(); for(String key : remoteEnvMap.keySet()) { properties.put(key, remoteEnvMap.get(key)); } return properties; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#getErrorMessage() */ public String getErrorMessage() { return fErrorMessage; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#setErrorMessage(java.lang.String) */ public void setErrorMessage(String error) { fErrorMessage = error; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#showCommand(boolean) */ public void showCommand(boolean show) { fShowCommand = show; } protected void printCommandLine(OutputStream os) { if (os != null) { String cmd = getCommandLine(getCommandArgs()); try { os.write(cmd.getBytes()); os.flush(); } catch (IOException e) { // ignore; } } } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#waitAndRead(java.io.OutputStream, java.io.OutputStream) */ public int waitAndRead(OutputStream out, OutputStream err) { if (fShowCommand) { printCommandLine(out); } if (fProcess == null) { return ILLEGAL_COMMAND; } RemoteProcessClosure closure = new RemoteProcessClosure(fRemoteProcess, out, err); closure.runBlocking(); // a blocking call return OK; } /* (non-Javadoc) * @see org.eclipse.cdt.core.ICommandLauncher#waitAndRead(java.io.OutputStream, java.io.OutputStream, org.eclipse.core.runtime.IProgressMonitor) */ public int waitAndRead(OutputStream output, OutputStream err, IProgressMonitor monitor) { if (fShowCommand) { printCommandLine(output); } if (fProcess == null) { return ILLEGAL_COMMAND; } RemoteProcessClosure closure = new RemoteProcessClosure(fRemoteProcess, output, err); closure.runNonBlocking(); while (!monitor.isCanceled() && closure.isAlive()) { try { Thread.sleep(DELAY); } catch (InterruptedException ie) { // ignore } } int state = OK; final IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); // Operation canceled by the user, terminate abnormally. if (monitor.isCanceled()) { closure.terminate(); state = COMMAND_CANCELED; setErrorMessage(CCorePlugin.getResourceString("CommandLauncher.error.commandCanceled")); //$NON-NLS-1$ if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } } try { fProcess.waitFor(); } catch (InterruptedException e) { // ignore } try { // Do not allow the cancel of the refresh, since the // builder is external // to Eclipse, files may have been created/modified // and we will be out-of-sync. // The caveat is that for huge projects, it may take a while getProject().refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { // this should never happen because we should never be building from a // state where ressource changes are disallowed } if(projectStatus!=null){ if(isCleanBuild){ projectStatus.setBuildInCompletedForCleanBuild(); }else{ if(projectStatus.isIndexAfterBuildSet()){ projectStatus.invokeIndex(); }else{ projectStatus.setFinalBuildStatus(); } } } return state; } public IProject getProject() { return fProject; } public void setProject(IProject project) { fProject = project; } }
true
true
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild= isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if(getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot().getLocation().toPortableString() + getProject().getFullPath().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration). getLocation(); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectWorkspaceRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Determine the service model for this configuration, and use the provider of the build // service to execute the build command. Also get the sync provider to sync before and // after building. ServiceModelManager smm = ServiceModelManager.getInstance(); IServiceConfiguration serviceConfig = BuildConfigurationManager.getInstance(). getConfigurationForBuildConfiguration(configuration); if (serviceConfig == null) { throw new RuntimeException("Cannot find service configuration for build configuration"); //$NON-NLS-1$ } IService syncService = smm.getService(IRemoteSyncServiceConstants.SERVICE_SYNC); ISyncServiceProvider syncProvider = null; if (!(serviceConfig.isDisabled(syncService))) { syncProvider = (ISyncServiceProvider) serviceConfig.getServiceProvider(syncService); } IService buildService = smm.getService(IRDTServiceConstants.SERVICE_BUILD); IServiceProvider provider = serviceConfig.getServiceProvider(buildService); IRemoteExecutionServiceProvider executionProvider = null; if(provider instanceof IRemoteExecutionServiceProvider) { executionProvider = (IRemoteExecutionServiceProvider) provider; } if (executionProvider != null) { IRemoteServices remoteServices = executionProvider.getRemoteServices(); if(!remoteServices.isInitialized()) { remoteServices.initialize(); } if (remoteServices == null) return null; IRemoteConnection connection = executionProvider.getConnection(); if(!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } List<String> command = new LinkedList<String>(); command.add(commandPath.toString()); for(int k = 0; k < args.length; k++) command.add(args[k]); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for(String envVar : env) { String[] splitStr = envVar.split("="); //$NON-NLS-1$ remoteEnvMap.put(splitStr[0], splitStr[1]); } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if(changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // combine stdout and stderr processBuilder.redirectErrorStream(true); // Synchronize before building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if(projectStatus!=null){ if(!isCleanBuild){ projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); // wait for the process to finish while (!p.isCompleted()) { try { p.waitFor(); } catch (InterruptedException e) { // just keep waiting until the process is done } } // Synchronize after building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } return fProcess; } return null; }
public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory, final IProgressMonitor monitor) throws CoreException { isCleanBuild= isCleanBuild(args); IndexBuildSequenceController projectStatus = IndexBuildSequenceController.getIndexBuildSequenceController(getProject()); if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(null); } // if there is no project associated to us then we cannot function... throw an exception if(getProject() == null) { throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "RemoteCommandLauncher has not been associated with a project.")); //$NON-NLS-1$ //$NON-NLS-2$ } // Set correct directory // For managed projects and configurations other than workspace, the directory is incorrect and needs to be fixed. IConfiguration configuration = ManagedBuildManager.getBuildInfo(getProject()).getDefaultConfiguration(); String projectWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot().getLocation().toPortableString() + getProject().getFullPath().toPortableString(); String projectActualRoot = BuildConfigurationManager.getInstance().getBuildScenarioForBuildConfiguration(configuration). getLocation(); changeToDirectory = new Path(changeToDirectory.toString().replaceFirst(projectWorkspaceRoot, projectActualRoot)); fCommandArgs = constructCommandArray(commandPath.toPortableString(), args); // Determine the service model for this configuration, and use the provider of the build // service to execute the build command. Also get the sync provider to sync before and // after building. ServiceModelManager smm = ServiceModelManager.getInstance(); IServiceConfiguration serviceConfig = BuildConfigurationManager.getInstance(). getConfigurationForBuildConfiguration(configuration); if (serviceConfig == null) { throw new RuntimeException("Cannot find service configuration for build configuration"); //$NON-NLS-1$ } IService syncService = smm.getService(IRemoteSyncServiceConstants.SERVICE_SYNC); ISyncServiceProvider syncProvider = null; if (!(serviceConfig.isDisabled(syncService))) { syncProvider = (ISyncServiceProvider) serviceConfig.getServiceProvider(syncService); } IService buildService = smm.getService(IRDTServiceConstants.SERVICE_BUILD); IServiceProvider provider = serviceConfig.getServiceProvider(buildService); IRemoteExecutionServiceProvider executionProvider = null; if(provider instanceof IRemoteExecutionServiceProvider) { executionProvider = (IRemoteExecutionServiceProvider) provider; } if (executionProvider != null) { IRemoteServices remoteServices = executionProvider.getRemoteServices(); if(!remoteServices.isInitialized()) { remoteServices.initialize(); } if (remoteServices == null) return null; IRemoteConnection connection = executionProvider.getConnection(); if(!connection.isOpen()) { try { connection.open(monitor); } catch (RemoteConnectionException e1) { // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.core", "Error opening connection.", e1)); //$NON-NLS-1$ //$NON-NLS-2$ } } List<String> command = new LinkedList<String>(); command.add(commandPath.toString()); for(int k = 0; k < args.length; k++) command.add(args[k]); IRemoteProcessBuilder processBuilder = remoteServices.getProcessBuilder(connection, command); remoteEnvMap = processBuilder.environment(); for(String envVar : env) { String[] splitStr = envVar.split("="); //$NON-NLS-1$ if (splitStr.length > 1) { remoteEnvMap.put(splitStr[0], splitStr[1]); } else if (splitStr.length == 1){ // Empty environment variable remoteEnvMap.put(splitStr[0], ""); //$NON-NLS-1$ } } // set the directory in which to run the command IRemoteFileManager fileManager = remoteServices.getFileManager(connection); if(changeToDirectory != null && fileManager != null) { processBuilder.directory(fileManager.getResource(changeToDirectory.toString())); } // combine stdout and stderr processBuilder.redirectErrorStream(true); // Synchronize before building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } IRemoteProcess p = null; try { p = processBuilder.start(); } catch (IOException e) { if(projectStatus!=null){ projectStatus.setRuntimeBuildStatus(IndexBuildSequenceController.STATUS_INCOMPLETE); } // rethrow as CoreException throw new CoreException(new Status(IStatus.ERROR, "org.eclipse.ptp.rdt.sync.core", "Error launching remote process.", e)); //$NON-NLS-1$ //$NON-NLS-2$ } if(projectStatus!=null){ if(!isCleanBuild){ projectStatus.setBuildRunning(); } } fRemoteProcess = p; fProcess = new RemoteProcessAdapter(p); // wait for the process to finish while (!p.isCompleted()) { try { p.waitFor(); } catch (InterruptedException e) { // just keep waiting until the process is done } } // Synchronize after building if (syncProvider != null) { syncProvider.synchronize(null, new SubProgressMonitor(monitor, 10), SyncFlag.FORCE); } return fProcess; } return null; }
diff --git a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/util/ImportActivity.java b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/util/ImportActivity.java index eee66f94..23aea0ad 100755 --- a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/util/ImportActivity.java +++ b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/util/ImportActivity.java @@ -1,163 +1,159 @@ /* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2010 HydroloGIS (www.hydrologis.com) * * 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 eu.hydrologis.geopaparazzi.util; import static eu.hydrologis.geopaparazzi.util.Constants.PREF_KEY_PWD; import static eu.hydrologis.geopaparazzi.util.Constants.PREF_KEY_SERVER; import static eu.hydrologis.geopaparazzi.util.Constants.PREF_KEY_USER; import java.io.File; import java.io.IOException; import java.util.List; import java.util.TreeSet; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import eu.geopaparazzi.library.network.NetworkUtilities; import eu.geopaparazzi.library.util.FileUtilities; import eu.geopaparazzi.library.util.LibraryConstants; import eu.geopaparazzi.library.util.ResourcesManager; import eu.geopaparazzi.library.util.Utilities; import eu.geopaparazzi.library.util.activities.DirectoryBrowserActivity; import eu.geopaparazzi.library.webproject.WebProjectsListActivity; import eu.hydrologis.geopaparazzi.R; import eu.hydrologis.geopaparazzi.database.DaoBookmarks; /** * Activity for export tasks. * * @author Andrea Antonello (www.hydrologis.com) */ public class ImportActivity extends Activity { public void onCreate( Bundle icicle ) { super.onCreate(icicle); setContentView(R.layout.imports); ImageButton gpxExportButton = (ImageButton) findViewById(R.id.gpxImportButton); gpxExportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { importGpx(); } }); ImageButton cloudImportButton = (ImageButton) findViewById(R.id.cloudImportButton); cloudImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; if (!NetworkUtilities.isNetworkAvailable(context)) { Utilities.messageDialog(context, context.getString(R.string.available_only_with_network), null); return; } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ImportActivity.this); final String user = preferences.getString(PREF_KEY_USER, "geopaparazziuser"); //$NON-NLS-1$ final String passwd = preferences.getString(PREF_KEY_PWD, "geopaparazzipwd"); //$NON-NLS-1$ final String server = preferences.getString(PREF_KEY_SERVER, ""); //$NON-NLS-1$ if (server.length() == 0) { Utilities.messageDialog(context, R.string.error_set_cloud_settings, null); return; } Intent webImportIntent = new Intent(ImportActivity.this, WebProjectsListActivity.class); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_URL, server); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_USER, user); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_PWD, passwd); startActivity(webImportIntent); } }); ImageButton bookmarksImportButton = (ImageButton) findViewById(R.id.bookmarksImportButton); bookmarksImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; ResourcesManager resourcesManager = ResourcesManager.getInstance(context); File sdcardDir = resourcesManager.getSdcardDir(); File bookmarksfile = new File(sdcardDir, "bookmarks.csv"); //$NON-NLS-1$ if (bookmarksfile.exists()) { try { // try to load it List<Bookmark> allBookmarks = DaoBookmarks.getAllBookmarks(context); TreeSet<String> bookmarksNames = new TreeSet<String>(); for( Bookmark bookmark : allBookmarks ) { String tmpName = bookmark.getName(); bookmarksNames.add(tmpName.trim()); } List<String> bookmarksList = FileUtilities.readfileToList(bookmarksfile); int imported = 0; for( String bookmarkLine : bookmarksList ) { String[] split = bookmarkLine.split(","); //$NON-NLS-1$ // bookmarks are of type: Agritur BeB In Valle, 45.46564, 11.58969, 12 if (split.length < 3) { continue; } String name = split[0].trim(); if (bookmarksNames.contains(name)) { continue; } try { double zoom = 16.0; if (split.length == 4) { zoom = Double.parseDouble(split[3]); } double lat = Double.parseDouble(split[1]); double lon = Double.parseDouble(split[2]); DaoBookmarks.addBookmark(context, lon, lat, name, zoom, -1, -1, -1, -1); imported++; } catch (Exception e) { e.printStackTrace(); } } - Utilities.messageDialog(context, R.string.successfully_imported_bookmarks + imported, null); + Utilities.messageDialog(context, getString(R.string.successfully_imported_bookmarks) + imported, null); } catch (IOException e) { e.printStackTrace(); Utilities.messageDialog(context, R.string.error_bookmarks_import, null); } } else { - Utilities - .messageDialog( - context, - R.string.no_bookmarks_csv, - null); + Utilities.messageDialog(context, R.string.no_bookmarks_csv, null); } } }); } private void importGpx() { Intent browseIntent = new Intent(ImportActivity.this, DirectoryBrowserActivity.class); browseIntent.putExtra(DirectoryBrowserActivity.STARTFOLDERPATH, ResourcesManager.getInstance(ImportActivity.this) .getApplicationDir().getAbsolutePath()); browseIntent.putExtra(DirectoryBrowserActivity.INTENT_ID, Constants.GPXIMPORT); browseIntent.putExtra(DirectoryBrowserActivity.EXTENTION, ".gpx"); //$NON-NLS-1$ startActivity(browseIntent); finish(); } }
false
true
public void onCreate( Bundle icicle ) { super.onCreate(icicle); setContentView(R.layout.imports); ImageButton gpxExportButton = (ImageButton) findViewById(R.id.gpxImportButton); gpxExportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { importGpx(); } }); ImageButton cloudImportButton = (ImageButton) findViewById(R.id.cloudImportButton); cloudImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; if (!NetworkUtilities.isNetworkAvailable(context)) { Utilities.messageDialog(context, context.getString(R.string.available_only_with_network), null); return; } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ImportActivity.this); final String user = preferences.getString(PREF_KEY_USER, "geopaparazziuser"); //$NON-NLS-1$ final String passwd = preferences.getString(PREF_KEY_PWD, "geopaparazzipwd"); //$NON-NLS-1$ final String server = preferences.getString(PREF_KEY_SERVER, ""); //$NON-NLS-1$ if (server.length() == 0) { Utilities.messageDialog(context, R.string.error_set_cloud_settings, null); return; } Intent webImportIntent = new Intent(ImportActivity.this, WebProjectsListActivity.class); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_URL, server); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_USER, user); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_PWD, passwd); startActivity(webImportIntent); } }); ImageButton bookmarksImportButton = (ImageButton) findViewById(R.id.bookmarksImportButton); bookmarksImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; ResourcesManager resourcesManager = ResourcesManager.getInstance(context); File sdcardDir = resourcesManager.getSdcardDir(); File bookmarksfile = new File(sdcardDir, "bookmarks.csv"); //$NON-NLS-1$ if (bookmarksfile.exists()) { try { // try to load it List<Bookmark> allBookmarks = DaoBookmarks.getAllBookmarks(context); TreeSet<String> bookmarksNames = new TreeSet<String>(); for( Bookmark bookmark : allBookmarks ) { String tmpName = bookmark.getName(); bookmarksNames.add(tmpName.trim()); } List<String> bookmarksList = FileUtilities.readfileToList(bookmarksfile); int imported = 0; for( String bookmarkLine : bookmarksList ) { String[] split = bookmarkLine.split(","); //$NON-NLS-1$ // bookmarks are of type: Agritur BeB In Valle, 45.46564, 11.58969, 12 if (split.length < 3) { continue; } String name = split[0].trim(); if (bookmarksNames.contains(name)) { continue; } try { double zoom = 16.0; if (split.length == 4) { zoom = Double.parseDouble(split[3]); } double lat = Double.parseDouble(split[1]); double lon = Double.parseDouble(split[2]); DaoBookmarks.addBookmark(context, lon, lat, name, zoom, -1, -1, -1, -1); imported++; } catch (Exception e) { e.printStackTrace(); } } Utilities.messageDialog(context, R.string.successfully_imported_bookmarks + imported, null); } catch (IOException e) { e.printStackTrace(); Utilities.messageDialog(context, R.string.error_bookmarks_import, null); } } else { Utilities .messageDialog( context, R.string.no_bookmarks_csv, null); } } }); }
public void onCreate( Bundle icicle ) { super.onCreate(icicle); setContentView(R.layout.imports); ImageButton gpxExportButton = (ImageButton) findViewById(R.id.gpxImportButton); gpxExportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { importGpx(); } }); ImageButton cloudImportButton = (ImageButton) findViewById(R.id.cloudImportButton); cloudImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; if (!NetworkUtilities.isNetworkAvailable(context)) { Utilities.messageDialog(context, context.getString(R.string.available_only_with_network), null); return; } SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ImportActivity.this); final String user = preferences.getString(PREF_KEY_USER, "geopaparazziuser"); //$NON-NLS-1$ final String passwd = preferences.getString(PREF_KEY_PWD, "geopaparazzipwd"); //$NON-NLS-1$ final String server = preferences.getString(PREF_KEY_SERVER, ""); //$NON-NLS-1$ if (server.length() == 0) { Utilities.messageDialog(context, R.string.error_set_cloud_settings, null); return; } Intent webImportIntent = new Intent(ImportActivity.this, WebProjectsListActivity.class); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_URL, server); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_USER, user); webImportIntent.putExtra(LibraryConstants.PREFS_KEY_PWD, passwd); startActivity(webImportIntent); } }); ImageButton bookmarksImportButton = (ImageButton) findViewById(R.id.bookmarksImportButton); bookmarksImportButton.setOnClickListener(new Button.OnClickListener(){ public void onClick( View v ) { final ImportActivity context = ImportActivity.this; ResourcesManager resourcesManager = ResourcesManager.getInstance(context); File sdcardDir = resourcesManager.getSdcardDir(); File bookmarksfile = new File(sdcardDir, "bookmarks.csv"); //$NON-NLS-1$ if (bookmarksfile.exists()) { try { // try to load it List<Bookmark> allBookmarks = DaoBookmarks.getAllBookmarks(context); TreeSet<String> bookmarksNames = new TreeSet<String>(); for( Bookmark bookmark : allBookmarks ) { String tmpName = bookmark.getName(); bookmarksNames.add(tmpName.trim()); } List<String> bookmarksList = FileUtilities.readfileToList(bookmarksfile); int imported = 0; for( String bookmarkLine : bookmarksList ) { String[] split = bookmarkLine.split(","); //$NON-NLS-1$ // bookmarks are of type: Agritur BeB In Valle, 45.46564, 11.58969, 12 if (split.length < 3) { continue; } String name = split[0].trim(); if (bookmarksNames.contains(name)) { continue; } try { double zoom = 16.0; if (split.length == 4) { zoom = Double.parseDouble(split[3]); } double lat = Double.parseDouble(split[1]); double lon = Double.parseDouble(split[2]); DaoBookmarks.addBookmark(context, lon, lat, name, zoom, -1, -1, -1, -1); imported++; } catch (Exception e) { e.printStackTrace(); } } Utilities.messageDialog(context, getString(R.string.successfully_imported_bookmarks) + imported, null); } catch (IOException e) { e.printStackTrace(); Utilities.messageDialog(context, R.string.error_bookmarks_import, null); } } else { Utilities.messageDialog(context, R.string.no_bookmarks_csv, null); } } }); }
diff --git a/src/org/apache/xml/utils/URI.java b/src/org/apache/xml/utils/URI.java index 4ca91720..a88bbd9c 100644 --- a/src/org/apache/xml/utils/URI.java +++ b/src/org/apache/xml/utils/URI.java @@ -1,1687 +1,1687 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xml.utils; import java.io.IOException; import java.io.Serializable; /** * A class to represent a Uniform Resource Identifier (URI). This class * is designed to handle the parsing of URIs and provide access to * the various components (scheme, host, port, userinfo, path, query * string and fragment) that may constitute a URI. * <p> * Parsing of a URI specification is done according to the URI * syntax described in RFC 2396 * <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI consists * of a scheme, followed by a colon (':'), followed by a scheme-specific * part. For URIs that follow the "generic URI" syntax, the scheme- * specific part begins with two slashes ("//") and may be followed * by an authority segment (comprised of user information, host, and * port), path segment, query segment and fragment. Note that RFC 2396 * no longer specifies the use of the parameters segment and excludes * the "user:password" syntax as part of the authority segment. If * "user:password" appears in a URI, the entire user/password string * is stored as userinfo. * <p> * For URIs that do not follow the "generic URI" syntax (e.g. mailto), * the entire scheme-specific part is treated as the "path" portion * of the URI. * <p> * Note that, unlike the java.net.URL class, this class does not provide * any built-in network access functionality nor does it provide any * scheme-specific functionality (for example, it does not know a * default port for a specific scheme). Rather, it only knows the * grammar and basic set of operations that can be applied to a URI. * * @version $Id$ * */ public class URI implements Serializable { /** * MalformedURIExceptions are thrown in the process of building a URI * or setting fields on a URI when an operation would result in an * invalid URI specification. * */ public static class MalformedURIException extends IOException { /** * Constructs a <code>MalformedURIException</code> with no specified * detail message. */ public MalformedURIException() { super(); } /** * Constructs a <code>MalformedURIException</code> with the * specified detail message. * * @param p_msg the detail message. */ public MalformedURIException(String p_msg) { super(p_msg); } } /** reserved characters */ private static final String RESERVED_CHARACTERS = ";/?:@&=+$,"; /** * URI punctuation mark characters - these, combined with * alphanumerics, constitute the "unreserved" characters */ private static final String MARK_CHARACTERS = "-_.!~*'() "; /** scheme can be composed of alphanumerics and these characters */ private static final String SCHEME_CHARACTERS = "+-."; /** * userinfo can be composed of unreserved, escaped and these * characters */ private static final String USERINFO_CHARACTERS = ";:&=+$,"; /** Stores the scheme (usually the protocol) for this URI. * @serial */ private String m_scheme = null; /** If specified, stores the userinfo for this URI; otherwise null. * @serial */ private String m_userinfo = null; /** If specified, stores the host for this URI; otherwise null. * @serial */ private String m_host = null; /** If specified, stores the port for this URI; otherwise -1. * @serial */ private int m_port = -1; /** If specified, stores the path for this URI; otherwise null. * @serial */ private String m_path = null; /** * If specified, stores the query string for this URI; otherwise * null. * @serial */ private String m_queryString = null; /** If specified, stores the fragment for this URI; otherwise null. * @serial */ private String m_fragment = null; /** Indicate whether in DEBUG mode */ private static boolean DEBUG = false; /** * Construct a new and uninitialized URI. */ public URI(){} /** * Construct a new URI from another URI. All fields for this URI are * set equal to the fields of the URI passed in. * * @param p_other the URI to copy (cannot be null) */ public URI(URI p_other) { initialize(p_other); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * * @throws MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(String p_uriSpec) throws MalformedURIException { this((URI) null, p_uriSpec); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * * @throws MalformedURIException if p_uriSpec violates any syntax * rules */ public URI(URI p_base, String p_uriSpec) throws MalformedURIException { initialize(p_base, p_uriSpec); } /** * Construct a new URI that does not follow the generic URI syntax. * Only the scheme and scheme-specific part (stored as the path) are * initialized. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_schemeSpecificPart the scheme-specific part (cannot be * null or empty) * * @throws MalformedURIException if p_scheme violates any * syntax rules */ public URI(String p_scheme, String p_schemeSpecificPart) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme!"); } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme-specific part!"); } setScheme(p_scheme); setPath(p_schemeSpecificPart); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_host the hostname or IPv4 address for the URI * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @throws MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_host, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_userinfo the URI userinfo (cannot be specified if host * is null) * @param p_host the hostname or IPv4 address for the URI * @param p_port the URI port (may be -1 for "unspecified"; cannot * be specified if host is null) * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @throws MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public URI(String p_scheme, String p_userinfo, String p_host, int p_port, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException("Scheme is required!"); } if (p_host == null) { if (p_userinfo != null) { throw new MalformedURIException( "Userinfo may not be specified if host is not specified!"); } if (p_port != -1) { throw new MalformedURIException( "Port may not be specified if host is not specified!"); } } if (p_path != null) { if (p_path.indexOf('?') != -1 && p_queryString != null) { throw new MalformedURIException( "Query string cannot be specified in path and query string!"); } if (p_path.indexOf('#') != -1 && p_fragment != null) { throw new MalformedURIException( "Fragment cannot be specified in both the path and fragment!"); } } setScheme(p_scheme); setHost(p_host); setPort(p_port); setUserinfo(p_userinfo); setPath(p_path); setQueryString(p_queryString); setFragment(p_fragment); } /** * Initialize all fields of this URI from another URI. * * @param p_other the URI to copy (cannot be null) */ private void initialize(URI p_other) { m_scheme = p_other.getScheme(); m_userinfo = p_other.getUserinfo(); m_host = p_other.getHost(); m_port = p_other.getPort(); m_path = p_other.getPath(); m_queryString = p_other.getQueryString(); m_fragment = p_other.getFragment(); } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * * @throws MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { if (p_base == null && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (p_uriSpec == null || p_uriSpec.trim().length() == 0) { initialize(p_base); return; } String uriSpec = p_uriSpec.trim(); int uriSpecLen = uriSpec.length(); int index = 0; // check for scheme if (uriSpec.indexOf(':') == -1) { if (p_base == null) { - throw new MalformedURIException("No scheme found in URI."); + throw new MalformedURIException("No scheme found in URI: "+uriSpec); } } else { initializeScheme(uriSpec); index = m_scheme.length() + 1; } // two slashes means generic URI syntax, so we get the authority if (((index + 1) < uriSpecLen) && (uriSpec.substring(index).startsWith("//"))) { index += 2; int startPos = index; // get authority - everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // if we found authority, parse it out, otherwise we set the // host to empty string if (index > startPos) { initializeAuthority(uriSpec.substring(startPos, index)); } else { m_host = ""; } } initializePath(uriSpec.substring(index)); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = new String(); String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash + 1); } } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index + 1).concat(path.substring(index + 3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length() - 1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = -1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../")) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex++).equals("..")) { path = path.substring(0, segIndex).concat(path.substring(index + 4)); } } } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length() - 3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex + 1); } } m_path = path; } } /** * Initialize the scheme for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @throws MalformedURIException if URI does not have a conformant * scheme */ private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException("No scheme found in URI."); } else { setScheme(scheme); } } /** * Initialize the authority (userinfo, host and port) for this * URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @throws MalformedURIException if p_uriSpec violates syntax rules */ private void initializeAuthority(String p_uriSpec) throws MalformedURIException { int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; String userinfo = null; // userinfo is everything up @ if (p_uriSpec.indexOf('@', start) != -1) { while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '@') { break; } index++; } userinfo = p_uriSpec.substring(start, index); index++; } // host is everything up to ':' String host = null; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == ':') { break; } index++; } host = p_uriSpec.substring(start, index); int port = -1; if (host.length() > 0) { // port if (testChar == ':') { index++; start = index; while (index < end) { index++; } String portStr = p_uriSpec.substring(start, index); if (portStr.length() > 0) { for (int i = 0; i < portStr.length(); i++) { if (!isDigit(portStr.charAt(i))) { throw new MalformedURIException( portStr + " is invalid. Port should only contain digits!"); } } try { port = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { // can't happen } } } } setHost(host); setPort(port); setUserinfo(userinfo); } /** * Initialize the path for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @throws MalformedURIException if p_uriSpec violates syntax rules */ private void initializePath(String p_uriSpec) throws MalformedURIException { if (p_uriSpec == null) { throw new MalformedURIException( "Cannot initialize path from null string!"); } int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; // path - everything up to query string or fragment while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '?' || testChar == '#') { break; } // check for valid escape sequence if (testChar == '%') { if (index + 2 >= end ||!isHex(p_uriSpec.charAt(index + 1)) ||!isHex(p_uriSpec.charAt(index + 2))) { throw new MalformedURIException( "Path contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) &&!isUnreservedCharacter(testChar)) { if ('\\' != testChar) throw new MalformedURIException("Path contains invalid character: " + testChar); } index++; } m_path = p_uriSpec.substring(start, index); // query - starts with ? and up to fragment or end if (testChar == '?') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '#') { break; } if (testChar == '%') { if (index + 2 >= end ||!isHex(p_uriSpec.charAt(index + 1)) ||!isHex(p_uriSpec.charAt(index + 2))) { throw new MalformedURIException( "Query string contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) &&!isUnreservedCharacter(testChar)) { throw new MalformedURIException( "Query string contains invalid character:" + testChar); } index++; } m_queryString = p_uriSpec.substring(start, index); } // fragment - starts with # if (testChar == '#') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '%') { if (index + 2 >= end ||!isHex(p_uriSpec.charAt(index + 1)) ||!isHex(p_uriSpec.charAt(index + 2))) { throw new MalformedURIException( "Fragment contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) &&!isUnreservedCharacter(testChar)) { throw new MalformedURIException( "Fragment contains invalid character:" + testChar); } index++; } m_fragment = p_uriSpec.substring(start, index); } } /** * Get the scheme for this URI. * * @return the scheme for this URI */ public String getScheme() { return m_scheme; } /** * Get the scheme-specific part for this URI (everything following the * scheme and the first colon). See RFC 2396 Section 5.2 for spec. * * @return the scheme-specific part for this URI */ public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_userinfo != null || m_host != null || m_port != -1) { schemespec.append("//"); } if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } if (m_host != null) { schemespec.append(m_host); } if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } if (m_path != null) { schemespec.append((m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); } /** * Get the userinfo for this URI. * * @return the userinfo for this URI (null if not specified). */ public String getUserinfo() { return m_userinfo; } /** * Get the host for this URI. * * @return the host for this URI (null if not specified). */ public String getHost() { return m_host; } /** * Get the port for this URI. * * @return the port for this URI (-1 if not specified). */ public int getPort() { return m_port; } /** * Get the path for this URI (optionally with the query string and * fragment). * * @param p_includeQueryString if true (and query string is not null), * then a "?" followed by the query string * will be appended * @param p_includeFragment if true (and fragment is not null), * then a "#" followed by the fragment * will be appended * * @return the path for this URI possibly including the query string * and fragment */ public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_includeFragment && m_fragment != null) { pathString.append('#'); pathString.append(m_fragment); } return pathString.toString(); } /** * Get the path for this URI. Note that the value returned is the path * only and does not include the query string or fragment. * * @return the path for this URI. */ public String getPath() { return m_path; } /** * Get the query string for this URI. * * @return the query string for this URI. Null is returned if there * was no "?" in the URI spec, empty string if there was a * "?" but no query string following it. */ public String getQueryString() { return m_queryString; } /** * Get the fragment for this URI. * * @return the fragment for this URI. Null is returned if there * was no "#" in the URI spec, empty string if there was a * "#" but no fragment following it. */ public String getFragment() { return m_fragment; } /** * Set the scheme for this URI. The scheme is converted to lowercase * before it is set. * * @param p_scheme the scheme for this URI (cannot be null) * * @throws MalformedURIException if p_scheme is not a conformant * scheme name */ public void setScheme(String p_scheme) throws MalformedURIException { if (p_scheme == null) { throw new MalformedURIException("Cannot set scheme from null string!"); } if (!isConformantSchemeName(p_scheme)) { throw new MalformedURIException("The scheme is not conformant."); } m_scheme = p_scheme.toLowerCase(); } /** * Set the userinfo for this URI. If a non-null value is passed in and * the host value is null, then an exception is thrown. * * @param p_userinfo the userinfo for this URI * * @throws MalformedURIException if p_userinfo contains invalid * characters */ public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; } else { if (m_host == null) { throw new MalformedURIException( "Userinfo cannot be set when host is null!"); } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index + 2 >= end ||!isHex(p_userinfo.charAt(index + 1)) ||!isHex(p_userinfo.charAt(index + 2))) { throw new MalformedURIException( "Userinfo contains invalid escape sequence!"); } } else if (!isUnreservedCharacter(testChar) && USERINFO_CHARACTERS.indexOf(testChar) == -1) { throw new MalformedURIException( "Userinfo contains invalid character:" + testChar); } index++; } } m_userinfo = p_userinfo; } /** * Set the host for this URI. If null is passed in, the userinfo * field is also set to null and the port is set to -1. * * @param p_host the host for this URI * * @throws MalformedURIException if p_host is not a valid IP * address or DNS hostname. */ public void setHost(String p_host) throws MalformedURIException { if (p_host == null || p_host.trim().length() == 0) { m_host = p_host; m_userinfo = null; m_port = -1; } else if (!isWellFormedAddress(p_host)) { throw new MalformedURIException("Host is not a well formed address!"); } m_host = p_host; } /** * Set the port for this URI. -1 is used to indicate that the port is * not specified, otherwise valid port numbers are between 0 and 65535. * If a valid port number is passed in and the host field is null, * an exception is thrown. * * @param p_port the port number for this URI * * @throws MalformedURIException if p_port is not -1 and not a * valid port number */ public void setPort(int p_port) throws MalformedURIException { if (p_port >= 0 && p_port <= 65535) { if (m_host == null) { throw new MalformedURIException( "Port cannot be set when host is null!"); } } else if (p_port != -1) { throw new MalformedURIException("Invalid port number!"); } m_port = p_port; } /** * Set the path for this URI. If the supplied path is null, then the * query string and fragment are set to null as well. If the supplied * path includes a query string and/or fragment, these fields will be * parsed and set as well. Note that, for URIs following the "generic * URI" syntax, the path specified should start with a slash. * For URIs that do not follow the generic URI syntax, this method * sets the scheme-specific part. * * @param p_path the path for this URI (may be null) * * @throws MalformedURIException if p_path contains invalid * characters */ public void setPath(String p_path) throws MalformedURIException { if (p_path == null) { m_path = null; m_queryString = null; m_fragment = null; } else { initializePath(p_path); } } /** * Append to the end of the path of this URI. If the current path does * not end in a slash and the path to be appended does not begin with * a slash, a slash will be appended to the current path before the * new segment is added. Also, if the current path ends in a slash * and the new segment begins with a slash, the extra slash will be * removed before the new segment is appended. * * @param p_addToPath the new segment to be added to the current path * * @throws MalformedURIException if p_addToPath contains syntax * errors */ public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException("Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } } /** * Set the query string for this URI. A non-null value is valid only * if this is an URI conforming to the generic URI syntax and * the path value is not null. * * @param p_queryString the query string for this URI * * @throws MalformedURIException if p_queryString is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setQueryString(String p_queryString) throws MalformedURIException { if (p_queryString == null) { m_queryString = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Query string can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Query string cannot be set when path is null!"); } else if (!isURIString(p_queryString)) { throw new MalformedURIException( "Query string contains invalid character!"); } else { m_queryString = p_queryString; } } /** * Set the fragment for this URI. A non-null value is valid only * if this is a URI conforming to the generic URI syntax and * the path value is not null. * * @param p_fragment the fragment for this URI * * @throws MalformedURIException if p_fragment is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setFragment(String p_fragment) throws MalformedURIException { if (p_fragment == null) { m_fragment = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Fragment can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Fragment cannot be set when path is null!"); } else if (!isURIString(p_fragment)) { throw new MalformedURIException("Fragment contains invalid character!"); } else { m_fragment = p_fragment; } } /** * Determines if the passed-in Object is equivalent to this URI. * * @param p_test the Object to test for equality. * * @return true if p_test is a URI with all values equal to this * URI, false otherwise */ public boolean equals(Object p_test) { if (p_test instanceof URI) { URI testURI = (URI) p_test; if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme.equals( testURI.m_scheme))) && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null && testURI.m_userinfo != null && m_userinfo.equals( testURI.m_userinfo))) && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host.equals( testURI.m_host))) && m_port == testURI.m_port && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path.equals( testURI.m_path))) && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null && testURI.m_queryString != null && m_queryString.equals( testURI.m_queryString))) && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null && testURI.m_fragment != null && m_fragment.equals( testURI.m_fragment)))) { return true; } } return false; } /** * Get the URI as a string specification. See RFC 2396 Section 5.2. * * @return the URI string specification */ public String toString() { StringBuffer uriSpecString = new StringBuffer(); if (m_scheme != null) { uriSpecString.append(m_scheme); uriSpecString.append(':'); } uriSpecString.append(getSchemeSpecificPart()); return uriSpecString.toString(); } /** * Get the indicator as to whether this URI uses the "generic URI" * syntax. * * @return true if this URI uses the "generic URI" syntax, false * otherwise */ public boolean isGenericURI() { // presence of the host (whether valid or empty) means // double-slashes which means generic uri return (m_host != null); } /** * Determine whether a scheme conforms to the rules for a scheme name. * A scheme is conformant if it starts with an alphanumeric, and * contains only alphanumerics, '+','-' and '.'. * * * @param p_scheme The sheme name to check * @return true if the scheme is conformant, false otherwise */ public static boolean isConformantSchemeName(String p_scheme) { if (p_scheme == null || p_scheme.trim().length() == 0) { return false; } if (!isAlpha(p_scheme.charAt(0))) { return false; } char testChar; for (int i = 1; i < p_scheme.length(); i++) { testChar = p_scheme.charAt(i); if (!isAlphanum(testChar) && SCHEME_CHARACTERS.indexOf(testChar) == -1) { return false; } } return true; } /** * Determine whether a string is syntactically capable of representing * a valid IPv4 address or the domain name of a network host. A valid * IPv4 address consists of four decimal digit groups separated by a * '.'. A hostname consists of domain labels (each of which must * begin and end with an alphanumeric but may contain '-') separated * & by a '.'. See RFC 2396 Section 3.2.2. * * * @param p_address The address string to check * @return true if the string is a syntactically valid IPv4 address * or hostname */ public static boolean isWellFormedAddress(String p_address) { if (p_address == null) { return false; } String address = p_address.trim(); int addrLength = address.length(); if (addrLength == 0 || addrLength > 255) { return false; } if (address.startsWith(".") || address.startsWith("-")) { return false; } // rightmost domain label starting with digit indicates IP address // since top level domain label can only start with an alpha // see RFC 2396 Section 3.2.2 int index = address.lastIndexOf('.'); if (address.endsWith(".")) { index = address.substring(0, index).lastIndexOf('.'); } if (index + 1 < addrLength && isDigit(p_address.charAt(index + 1))) { char testChar; int numDots = 0; // make sure that 1) we see only digits and dot separators, 2) that // any dot separator is preceded and followed by a digit and // 3) that we find 3 dots for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isDigit(address.charAt(i - 1)) || (i + 1 < addrLength &&!isDigit(address.charAt(i + 1)))) { return false; } numDots++; } else if (!isDigit(testChar)) { return false; } } if (numDots != 3) { return false; } } else { // domain labels can contain alphanumerics and '-" // but must start and end with an alphanumeric char testChar; for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isAlphanum(address.charAt(i - 1))) { return false; } if (i + 1 < addrLength &&!isAlphanum(address.charAt(i + 1))) { return false; } } else if (!isAlphanum(testChar) && testChar != '-') { return false; } } } return true; } /** * Determine whether a char is a digit. * * * @param p_char the character to check * @return true if the char is betweeen '0' and '9', false otherwise */ private static boolean isDigit(char p_char) { return p_char >= '0' && p_char <= '9'; } /** * Determine whether a character is a hexadecimal character. * * * @param p_char the character to check * @return true if the char is betweeen '0' and '9', 'a' and 'f' * or 'A' and 'F', false otherwise */ private static boolean isHex(char p_char) { return (isDigit(p_char) || (p_char >= 'a' && p_char <= 'f') || (p_char >= 'A' && p_char <= 'F')); } /** * Determine whether a char is an alphabetic character: a-z or A-Z * * * @param p_char the character to check * @return true if the char is alphabetic, false otherwise */ private static boolean isAlpha(char p_char) { return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z')); } /** * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z * * * @param p_char the character to check * @return true if the char is alphanumeric, false otherwise */ private static boolean isAlphanum(char p_char) { return (isAlpha(p_char) || isDigit(p_char)); } /** * Determine whether a character is a reserved character: * ';', '/', '?', ':', '@', '&', '=', '+', '$' or ',' * * * @param p_char the character to check * @return true if the string contains any reserved characters */ private static boolean isReservedCharacter(char p_char) { return RESERVED_CHARACTERS.indexOf(p_char) != -1; } /** * Determine whether a char is an unreserved character. * * * @param p_char the character to check * @return true if the char is unreserved, false otherwise */ private static boolean isUnreservedCharacter(char p_char) { return (isAlphanum(p_char) || MARK_CHARACTERS.indexOf(p_char) != -1); } /** * Determine whether a given string contains only URI characters (also * called "uric" in RFC 2396). uric consist of all reserved * characters, unreserved characters and escaped characters. * * * @param p_uric URI string * @return true if the string is comprised of uric, false otherwise */ private static boolean isURIString(String p_uric) { if (p_uric == null) { return false; } int end = p_uric.length(); char testChar = '\0'; for (int i = 0; i < end; i++) { testChar = p_uric.charAt(i); if (testChar == '%') { if (i + 2 >= end ||!isHex(p_uric.charAt(i + 1)) ||!isHex(p_uric.charAt(i + 2))) { return false; } else { i += 2; continue; } } if (isReservedCharacter(testChar) || isUnreservedCharacter(testChar)) { continue; } else { return false; } } return true; } }
true
true
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { if (p_base == null && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (p_uriSpec == null || p_uriSpec.trim().length() == 0) { initialize(p_base); return; } String uriSpec = p_uriSpec.trim(); int uriSpecLen = uriSpec.length(); int index = 0; // check for scheme if (uriSpec.indexOf(':') == -1) { if (p_base == null) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length() + 1; } // two slashes means generic URI syntax, so we get the authority if (((index + 1) < uriSpecLen) && (uriSpec.substring(index).startsWith("//"))) { index += 2; int startPos = index; // get authority - everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // if we found authority, parse it out, otherwise we set the // host to empty string if (index > startPos) { initializeAuthority(uriSpec.substring(startPos, index)); } else { m_host = ""; } } initializePath(uriSpec.substring(index)); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = new String(); String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash + 1); } } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index + 1).concat(path.substring(index + 3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length() - 1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = -1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../")) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex++).equals("..")) { path = path.substring(0, segIndex).concat(path.substring(index + 4)); } } } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length() - 3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex + 1); } } m_path = path; } }
private void initialize(URI p_base, String p_uriSpec) throws MalformedURIException { if (p_base == null && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (p_uriSpec == null || p_uriSpec.trim().length() == 0) { initialize(p_base); return; } String uriSpec = p_uriSpec.trim(); int uriSpecLen = uriSpec.length(); int index = 0; // check for scheme if (uriSpec.indexOf(':') == -1) { if (p_base == null) { throw new MalformedURIException("No scheme found in URI: "+uriSpec); } } else { initializeScheme(uriSpec); index = m_scheme.length() + 1; } // two slashes means generic URI syntax, so we get the authority if (((index + 1) < uriSpecLen) && (uriSpec.substring(index).startsWith("//"))) { index += 2; int startPos = index; // get authority - everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // if we found authority, parse it out, otherwise we set the // host to empty string if (index > startPos) { initializeAuthority(uriSpec.substring(startPos, index)); } else { m_host = ""; } } initializePath(uriSpec.substring(index)); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = new String(); String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash + 1); } } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index + 1).concat(path.substring(index + 3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length() - 1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = -1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../")) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex++).equals("..")) { path = path.substring(0, segIndex).concat(path.substring(index + 4)); } } } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length() - 3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex + 1); } } m_path = path; } }
diff --git a/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/facade/internal/P2ApplicationLauncher.java b/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/facade/internal/P2ApplicationLauncher.java index 4cddde7..4f829a4 100644 --- a/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/facade/internal/P2ApplicationLauncher.java +++ b/tycho-p2/tycho-p2-facade/src/main/java/org/eclipse/tycho/p2/facade/internal/P2ApplicationLauncher.java @@ -1,144 +1,149 @@ /******************************************************************************* * Copyright (c) 2008, 2011 Sonatype Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sonatype Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.tycho.p2.facade.internal; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.logging.Logger; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.cli.Commandline; import org.eclipse.tycho.ArtifactKey; import org.eclipse.tycho.core.TychoProject; import org.eclipse.tycho.core.osgitools.OsgiBundleProject; import org.eclipse.tycho.equinox.EquinoxRuntimeLocator; import org.eclipse.tycho.equinox.launching.DefaultEquinoxInstallationDescription; import org.eclipse.tycho.equinox.launching.EquinoxInstallation; import org.eclipse.tycho.equinox.launching.EquinoxInstallationDescription; import org.eclipse.tycho.equinox.launching.EquinoxInstallationFactory; import org.eclipse.tycho.equinox.launching.EquinoxLauncher; import org.eclipse.tycho.equinox.launching.internal.EquinoxLaunchConfiguration; /** * Convenience wrapper around {@link Commandline} to run Eclipse applications from tycho-p2-runtime * * @author igor */ @Component(role = P2ApplicationLauncher.class, instantiationStrategy = "per-lookup") public class P2ApplicationLauncher { @Requirement private Logger logger; @Requirement private EquinoxInstallationFactory installationFactory; @Requirement private EquinoxLauncher launcher; @Requirement private EquinoxRuntimeLocator runtimeLocator; @Requirement(role = TychoProject.class, hint = ArtifactKey.TYPE_ECLIPSE_PLUGIN) private OsgiBundleProject osgiBundle; private File workingDirectory; private String applicationName; private final List<String> vmargs = new ArrayList<String>(); private final List<String> args = new ArrayList<String>(); public void setWorkingDirectory(File workingDirectory) { this.workingDirectory = workingDirectory; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public void addArguments(String... args) { for (String arg : args) { this.args.add(arg); } } public void addVMArguments(String... vmargs) { for (String vmarg : vmargs) { this.vmargs.add(vmarg); } } public int execute(int forkedProcessTimeoutInSeconds) { try { File installationFolder = newTemporaryFolder(); try { EquinoxInstallationDescription description = new DefaultEquinoxInstallationDescription(); List<File> locations = runtimeLocator.getRuntimeLocations(); for (File location : locations) { if (location.isDirectory()) { for (File file : new File(location, "plugins").listFiles()) { addBundle(description, file); } } else { addBundle(description, location); } } EquinoxInstallation installation = installationFactory.createInstallation(description, installationFolder); EquinoxLaunchConfiguration launchConfiguration = new EquinoxLaunchConfiguration(installation); launchConfiguration.setWorkingDirectory(workingDirectory); // logging if (logger.isDebugEnabled()) { launchConfiguration.addProgramArguments("-debug", "-consoleLog"); } // application and application arguments launchConfiguration.addProgramArguments("-nosplash", "-application", applicationName); launchConfiguration.addProgramArguments(true, args.toArray(new String[args.size()])); return launcher.execute(launchConfiguration, forkedProcessTimeoutInSeconds); } finally { - FileUtils.deleteDirectory(installationFolder); + try { + FileUtils.deleteDirectory(installationFolder); + } catch (IOException e) { + // this may happen if child process did not close all file handles + logger.warn("Failed to delete temp folder " + installationFolder); + } } } catch (Exception e) { // TODO better exception? throw new RuntimeException(e); } } private void addBundle(EquinoxInstallationDescription description, File file) { ArtifactKey key = osgiBundle.readArtifactKey(file); if (key != null) { description.addBundle(key, file); } } private File newTemporaryFolder() throws IOException { File tmp = File.createTempFile("tycho-p2-runtime", ".tmp"); tmp.delete(); tmp.mkdir(); // anyone got any better idea? return tmp; } }
true
true
public int execute(int forkedProcessTimeoutInSeconds) { try { File installationFolder = newTemporaryFolder(); try { EquinoxInstallationDescription description = new DefaultEquinoxInstallationDescription(); List<File> locations = runtimeLocator.getRuntimeLocations(); for (File location : locations) { if (location.isDirectory()) { for (File file : new File(location, "plugins").listFiles()) { addBundle(description, file); } } else { addBundle(description, location); } } EquinoxInstallation installation = installationFactory.createInstallation(description, installationFolder); EquinoxLaunchConfiguration launchConfiguration = new EquinoxLaunchConfiguration(installation); launchConfiguration.setWorkingDirectory(workingDirectory); // logging if (logger.isDebugEnabled()) { launchConfiguration.addProgramArguments("-debug", "-consoleLog"); } // application and application arguments launchConfiguration.addProgramArguments("-nosplash", "-application", applicationName); launchConfiguration.addProgramArguments(true, args.toArray(new String[args.size()])); return launcher.execute(launchConfiguration, forkedProcessTimeoutInSeconds); } finally { FileUtils.deleteDirectory(installationFolder); } } catch (Exception e) { // TODO better exception? throw new RuntimeException(e); } }
public int execute(int forkedProcessTimeoutInSeconds) { try { File installationFolder = newTemporaryFolder(); try { EquinoxInstallationDescription description = new DefaultEquinoxInstallationDescription(); List<File> locations = runtimeLocator.getRuntimeLocations(); for (File location : locations) { if (location.isDirectory()) { for (File file : new File(location, "plugins").listFiles()) { addBundle(description, file); } } else { addBundle(description, location); } } EquinoxInstallation installation = installationFactory.createInstallation(description, installationFolder); EquinoxLaunchConfiguration launchConfiguration = new EquinoxLaunchConfiguration(installation); launchConfiguration.setWorkingDirectory(workingDirectory); // logging if (logger.isDebugEnabled()) { launchConfiguration.addProgramArguments("-debug", "-consoleLog"); } // application and application arguments launchConfiguration.addProgramArguments("-nosplash", "-application", applicationName); launchConfiguration.addProgramArguments(true, args.toArray(new String[args.size()])); return launcher.execute(launchConfiguration, forkedProcessTimeoutInSeconds); } finally { try { FileUtils.deleteDirectory(installationFolder); } catch (IOException e) { // this may happen if child process did not close all file handles logger.warn("Failed to delete temp folder " + installationFolder); } } } catch (Exception e) { // TODO better exception? throw new RuntimeException(e); } }
diff --git a/src/android/TTS.java b/src/android/TTS.java index 16c9671..cdbd1f3 100644 --- a/src/android/TTS.java +++ b/src/android/TTS.java @@ -1,248 +1,250 @@ /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2011, IBM Corporation * * Modified by Murray Macdonald ([email protected]) on 2012/05/30 to add support for stop(), pitch(), speed() and interrupt(); * */ package org.apache.cordova.plugin; import java.util.HashMap; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; public class TTS extends CordovaPlugin implements OnInitListener, OnUtteranceCompletedListener { private static final String LOG_TAG = "TTS"; private static final int STOPPED = 0; private static final int INITIALIZING = 1; private static final int STARTED = 2; private TextToSpeech mTts = null; private int state = STOPPED; private CallbackContext startupCallbackContext; private CallbackContext callbackContext; //private String startupCallbackId = ""; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try { if (action.equals("speak")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.speak(text, TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("interrupt")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); //map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackId); mTts.speak(text, TextToSpeech.QUEUE_FLUSH, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("stop")) { if (isReady()) { mTts.stop(); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("silence")) { if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("speed")) { if (isReady()) { float speed= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setSpeechRate(speed); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("pitch")) { if (isReady()) { float pitch= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setPitch(pitch); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("startup")) { this.startupCallbackContext = callbackContext; if (mTts == null) { state = TTS.INITIALIZING; mTts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this); } PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING); pluginResult.setKeepCallback(true); - startupCallbackContext.sendPluginResult(pluginResult); + // this line is not needed as the same is repeated in the onInit() + // domaemon + // startupCallbackContext.sendPluginResult(pluginResult); } else if (action.equals("shutdown")) { if (mTts != null) { mTts.shutdown(); } callbackContext.sendPluginResult(new PluginResult(status, result)); } else if (action.equals("getLanguage")) { if (mTts != null) { result = mTts.getLanguage().toString(); callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("isLanguageAvailable")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.isLanguageAvailable(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("setLanguage")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.setLanguage(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } return true; } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; } /** * Is the TTS service ready to play yet? * * @return */ private boolean isReady() { return (state == TTS.STARTED) ? true : false; } /** * Called when the TTS service is initialized. * * @param status */ public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { state = TTS.STARTED; PluginResult result = new PluginResult(PluginResult.Status.OK, TTS.STARTED); result.setKeepCallback(false); //this.success(result, this.startupCallbackId); this.startupCallbackContext.sendPluginResult(result); mTts.setOnUtteranceCompletedListener(this); // Putting this code in hear as a place holder. When everything moves to API level 15 or greater // we'll switch over to this way of trackign progress. // mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() { // // @Override // public void onDone(String utteranceId) { // Log.d(LOG_TAG, "got completed utterance"); // PluginResult result = new PluginResult(PluginResult.Status.OK); // result.setKeepCallback(false); // callbackContext.sendPluginResult(result); // } // // @Override // public void onError(String utteranceId) { // Log.d(LOG_TAG, "got utterance error"); // PluginResult result = new PluginResult(PluginResult.Status.ERROR); // result.setKeepCallback(false); // callbackContext.sendPluginResult(result); // } // // @Override // public void onStart(String utteranceId) { // Log.d(LOG_TAG, "started talking"); // } // // }); } else if (status == TextToSpeech.ERROR) { state = TTS.STOPPED; PluginResult result = new PluginResult(PluginResult.Status.ERROR, TTS.STOPPED); result.setKeepCallback(false); this.startupCallbackContext.sendPluginResult(result); } } /** * Clean up the TTS resources */ public void onDestroy() { if (mTts != null) { mTts.shutdown(); } } /** * Once the utterance has completely been played call the speak's success callback */ public void onUtteranceCompleted(String utteranceId) { PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(false); this.callbackContext.sendPluginResult(result); } }
true
true
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try { if (action.equals("speak")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.speak(text, TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("interrupt")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); //map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackId); mTts.speak(text, TextToSpeech.QUEUE_FLUSH, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("stop")) { if (isReady()) { mTts.stop(); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("silence")) { if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("speed")) { if (isReady()) { float speed= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setSpeechRate(speed); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("pitch")) { if (isReady()) { float pitch= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setPitch(pitch); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("startup")) { this.startupCallbackContext = callbackContext; if (mTts == null) { state = TTS.INITIALIZING; mTts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this); } PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING); pluginResult.setKeepCallback(true); startupCallbackContext.sendPluginResult(pluginResult); } else if (action.equals("shutdown")) { if (mTts != null) { mTts.shutdown(); } callbackContext.sendPluginResult(new PluginResult(status, result)); } else if (action.equals("getLanguage")) { if (mTts != null) { result = mTts.getLanguage().toString(); callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("isLanguageAvailable")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.isLanguageAvailable(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("setLanguage")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.setLanguage(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } return true; } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; this.callbackContext = callbackContext; try { if (action.equals("speak")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.speak(text, TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("interrupt")) { String text = args.getString(0); if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); //map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackId); mTts.speak(text, TextToSpeech.QUEUE_FLUSH, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("stop")) { if (isReady()) { mTts.stop(); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("silence")) { if (isReady()) { HashMap<String, String> map = null; map = new HashMap<String, String>(); map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, callbackContext.getCallbackId()); mTts.playSilence(args.getLong(0), TextToSpeech.QUEUE_ADD, map); PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT); pr.setKeepCallback(true); callbackContext.sendPluginResult(pr); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("speed")) { if (isReady()) { float speed= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setSpeechRate(speed); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("pitch")) { if (isReady()) { float pitch= (float) (args.optLong(0, 100)) /(float) 100.0; mTts.setPitch(pitch); callbackContext.sendPluginResult(new PluginResult(status, result)); } else { JSONObject error = new JSONObject(); error.put("message","TTS service is still initialzing."); error.put("code", TTS.INITIALIZING); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error)); } } else if (action.equals("startup")) { this.startupCallbackContext = callbackContext; if (mTts == null) { state = TTS.INITIALIZING; mTts = new TextToSpeech(cordova.getActivity().getApplicationContext(), this); } PluginResult pluginResult = new PluginResult(status, TTS.INITIALIZING); pluginResult.setKeepCallback(true); // this line is not needed as the same is repeated in the onInit() // domaemon // startupCallbackContext.sendPluginResult(pluginResult); } else if (action.equals("shutdown")) { if (mTts != null) { mTts.shutdown(); } callbackContext.sendPluginResult(new PluginResult(status, result)); } else if (action.equals("getLanguage")) { if (mTts != null) { result = mTts.getLanguage().toString(); callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("isLanguageAvailable")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.isLanguageAvailable(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } else if (action.equals("setLanguage")) { if (mTts != null) { Locale loc = new Locale(args.getString(0)); int available = mTts.setLanguage(loc); result = (available < 0) ? "false" : "true"; callbackContext.sendPluginResult(new PluginResult(status, result)); } } return true; } catch (JSONException e) { e.printStackTrace(); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } return false; }
diff --git a/src/net/slipcor/pvparena/commands/PAG_Join.java b/src/net/slipcor/pvparena/commands/PAG_Join.java index 26edb194..c522218d 100644 --- a/src/net/slipcor/pvparena/commands/PAG_Join.java +++ b/src/net/slipcor/pvparena/commands/PAG_Join.java @@ -1,92 +1,92 @@ package net.slipcor.pvparena.commands; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.classes.PACheck; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Help; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Help.HELP; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.loadables.ArenaRegionShape; import net.slipcor.pvparena.managers.ConfigurationManager; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * <pre>PVP Arena JOIN Command class</pre> * * A command to join an arena * * @author slipcor * * @version v0.10.2 */ public class PAG_Join extends AbstractArenaCommand { private final Debug debug = new Debug(200); public PAG_Join() { super(new String[] {"pvparena.user"}); } @Override public void commit(final Arena arena, final CommandSender sender, final String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } if (!PVPArena.hasPerms(sender, arena)) { arena.msg(sender, Language.parse(MSG.ERROR_NOPERM_JOIN)); return; } final String error = ConfigurationManager.isSetup(arena); if (error != null) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } if (ArenaRegionShape.tooFarAway(arena, (Player) sender)) { - arena.msg(sender, Language.parse(MSG.ERROR_JOIN_RANGE, error)); + arena.msg(sender, Language.parse(MSG.ERROR_JOIN_RANGE)); return; } final ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(sender.getName()); if (aPlayer.getArena() == null) { if (arena.hasAlreadyPlayed(aPlayer.getName())) { debug.i("Join_2", sender); arena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, arena.getName())); } else { PACheck.handleJoin(arena, sender, args); } } else { final Arena pArena = aPlayer.getArena(); debug.i("Join_1", sender); pArena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, pArena.getName())); } } @Override public String getName() { return this.getClass().getName(); } @Override public void displayHelp(final CommandSender sender) { Arena.pmsg(sender, Help.parse(HELP.JOIN)); } }
true
true
public void commit(final Arena arena, final CommandSender sender, final String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } if (!PVPArena.hasPerms(sender, arena)) { arena.msg(sender, Language.parse(MSG.ERROR_NOPERM_JOIN)); return; } final String error = ConfigurationManager.isSetup(arena); if (error != null) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } if (ArenaRegionShape.tooFarAway(arena, (Player) sender)) { arena.msg(sender, Language.parse(MSG.ERROR_JOIN_RANGE, error)); return; } final ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(sender.getName()); if (aPlayer.getArena() == null) { if (arena.hasAlreadyPlayed(aPlayer.getName())) { debug.i("Join_2", sender); arena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, arena.getName())); } else { PACheck.handleJoin(arena, sender, args); } } else { final Arena pArena = aPlayer.getArena(); debug.i("Join_1", sender); pArena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, pArena.getName())); } }
public void commit(final Arena arena, final CommandSender sender, final String[] args) { if (!this.hasPerms(sender, arena)) { return; } if (!argCountValid(sender, arena, args, new Integer[]{0,1})) { return; } if (!(sender instanceof Player)) { Arena.pmsg(sender, Language.parse(MSG.ERROR_ONLY_PLAYERS)); return; } if (!PVPArena.hasPerms(sender, arena)) { arena.msg(sender, Language.parse(MSG.ERROR_NOPERM_JOIN)); return; } final String error = ConfigurationManager.isSetup(arena); if (error != null) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, error)); return; } if (ArenaRegionShape.tooFarAway(arena, (Player) sender)) { arena.msg(sender, Language.parse(MSG.ERROR_JOIN_RANGE)); return; } final ArenaPlayer aPlayer = ArenaPlayer.parsePlayer(sender.getName()); if (aPlayer.getArena() == null) { if (arena.hasAlreadyPlayed(aPlayer.getName())) { debug.i("Join_2", sender); arena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, arena.getName())); } else { PACheck.handleJoin(arena, sender, args); } } else { final Arena pArena = aPlayer.getArena(); debug.i("Join_1", sender); pArena.msg(sender, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, pArena.getName())); } }
diff --git a/Paintroid/src/org/catrobat/paintroid/ToolsDialogActivity.java b/Paintroid/src/org/catrobat/paintroid/ToolsDialogActivity.java index 4510b550..6b3101f0 100644 --- a/Paintroid/src/org/catrobat/paintroid/ToolsDialogActivity.java +++ b/Paintroid/src/org/catrobat/paintroid/ToolsDialogActivity.java @@ -1,87 +1,88 @@ /** * Catroid: An on-device visual programming system for Android devices * Copyright (C) 2010-2012 The Catrobat Team * (<http://developer.catrobat.org/credits>) * * 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. * * An additional term exception under section 7 of the GNU Affero * General Public License, version 3, is available at * http://www.catroid.org/catroid/licenseadditionalterm * * 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 org.catrobat.paintroid; import org.catrobat.paintroid.dialog.DialogTools; import org.catrobat.paintroid.dialog.InfoDialog; import org.catrobat.paintroid.dialog.InfoDialog.DialogType; import org.catrobat.paintroid.tools.ToolType; import org.catrobat.paintroid.ui.button.ToolsAdapter; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import com.actionbarsherlock.app.SherlockFragmentActivity; public class ToolsDialogActivity extends SherlockFragmentActivity implements OnItemClickListener, OnItemLongClickListener { public static final String EXTRA_SELECTED_TOOL = "EXTRA_SELECTED_TOOL"; protected ToolsAdapter mToolButtonAdapter; private DialogTools mDialogTools; @Override protected void onCreate(Bundle savedInstanceState) { + setTheme(R.style.Theme_Transparent); super.onCreate(savedInstanceState); boolean openedFromCatrobat; Intent intent = getIntent(); openedFromCatrobat = intent.getExtras().getBoolean( MainActivity.EXTRA_INSTANCE_FROM_CATROBAT); mToolButtonAdapter = new ToolsAdapter(this, openedFromCatrobat); int actionBarHeight = intent.getExtras().getInt( MainActivity.EXTRA_ACTION_BAR_HEIGHT); mDialogTools = new DialogTools(this, this, mToolButtonAdapter, actionBarHeight); mDialogTools.show(); } @Override public void onItemClick(AdapterView<?> adapterView, View button, int position, long id) { ToolType toolType = mToolButtonAdapter.getToolType(position); Intent resultIntent = new Intent(); resultIntent.putExtra(EXTRA_SELECTED_TOOL, toolType.ordinal()); setResult(Activity.RESULT_OK, resultIntent); mDialogTools.cancel(); if (isFinishing() == false) { finish(); } } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View button, int position, long id) { ToolType toolType = mToolButtonAdapter.getToolType(position); new InfoDialog(DialogType.INFO, toolType.getHelpTextResource(), toolType.getNameResource()).show(getSupportFragmentManager(), "helpdialog"); return true; } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean openedFromCatrobat; Intent intent = getIntent(); openedFromCatrobat = intent.getExtras().getBoolean( MainActivity.EXTRA_INSTANCE_FROM_CATROBAT); mToolButtonAdapter = new ToolsAdapter(this, openedFromCatrobat); int actionBarHeight = intent.getExtras().getInt( MainActivity.EXTRA_ACTION_BAR_HEIGHT); mDialogTools = new DialogTools(this, this, mToolButtonAdapter, actionBarHeight); mDialogTools.show(); }
protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.Theme_Transparent); super.onCreate(savedInstanceState); boolean openedFromCatrobat; Intent intent = getIntent(); openedFromCatrobat = intent.getExtras().getBoolean( MainActivity.EXTRA_INSTANCE_FROM_CATROBAT); mToolButtonAdapter = new ToolsAdapter(this, openedFromCatrobat); int actionBarHeight = intent.getExtras().getInt( MainActivity.EXTRA_ACTION_BAR_HEIGHT); mDialogTools = new DialogTools(this, this, mToolButtonAdapter, actionBarHeight); mDialogTools.show(); }
diff --git a/src/main/java/com/solidstategroup/radar/web/panels/DiagnosisPanel.java b/src/main/java/com/solidstategroup/radar/web/panels/DiagnosisPanel.java index e788a8e4..9340fdf7 100644 --- a/src/main/java/com/solidstategroup/radar/web/panels/DiagnosisPanel.java +++ b/src/main/java/com/solidstategroup/radar/web/panels/DiagnosisPanel.java @@ -1,584 +1,587 @@ package com.solidstategroup.radar.web.panels; import com.solidstategroup.radar.model.ClinicalPresentation; import com.solidstategroup.radar.model.Demographics; import com.solidstategroup.radar.model.Diagnosis; import com.solidstategroup.radar.model.DiagnosisCode; import com.solidstategroup.radar.model.Karotype; import com.solidstategroup.radar.model.sequenced.ClinicalData; import com.solidstategroup.radar.service.ClinicalDataManager; import com.solidstategroup.radar.service.DemographicsManager; import com.solidstategroup.radar.service.DiagnosisManager; import com.solidstategroup.radar.web.RadarApplication; import com.solidstategroup.radar.web.components.ClinicalPresentationDropDownChoice; import com.solidstategroup.radar.web.components.ComponentHelper; import com.solidstategroup.radar.web.components.RadarComponentFactory; import com.solidstategroup.radar.web.components.RadarDateTextField; import com.solidstategroup.radar.web.components.RadarTextFieldWithValidation; import com.solidstategroup.radar.web.models.RadarModelFactory; import com.solidstategroup.radar.web.pages.PatientPage; import org.apache.commons.lang.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink; import org.apache.wicket.extensions.markup.html.form.DateTextField; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.markup.html.form.Radio; import org.apache.wicket.markup.html.form.RadioGroup; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.ComponentFeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.validation.validator.RangeValidator; import org.joda.time.DateTime; import org.joda.time.Years; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; public class DiagnosisPanel extends Panel { public static final Long SRNS_ID = new Long(1); public static final String OTHER_CONTAINER_ID = "otherContainer"; public static final Long KAROTYPE_OTHER_ID = new Long(8); @SpringBean private DiagnosisManager diagnosisManager; @SpringBean private DemographicsManager demographicsManager; @SpringBean private ClinicalDataManager clinicalDataManager; public DiagnosisPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model // Set up loadable detachable, working for null radar numbers (new patients) and existing final CompoundPropertyModel<Diagnosis> model = new CompoundPropertyModel<Diagnosis>(new LoadableDetachableModel<Diagnosis>() { @Override protected Diagnosis load() { if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(radarNumber); if (diagnosis != null) { return diagnosis; } else { return new Diagnosis(); } } else { return new Diagnosis(); } } }); // Clinical presentation A - goes here in the file as referenced in form submit final DropDownChoice<ClinicalPresentation> clinicalPresentationA = new ClinicalPresentationDropDownChoice("clinicalPresentationA"); clinicalPresentationA.setOutputMarkupId(true); clinicalPresentationA.setOutputMarkupPlaceholderTag(true); final Form<Diagnosis> form = new Form<Diagnosis>("form", model) { @Override protected void onValidateModelObjects() { super.onValidateModelObjects(); Diagnosis diagnosis = getModelObject(); ClinicalPresentation presentationA = diagnosis.getClinicalPresentationA(); ClinicalPresentation presentationB = diagnosis.getClinicalPresentationB(); // Validate that the two aren't the same if (presentationA != null && presentationB != null && presentationA.equals(presentationB)) { clinicalPresentationA.error("A and B cannot be the same"); } } @Override protected void onSubmit() { Diagnosis diagnosis = getModelObject(); Date dateOfDiagnosis = diagnosis.getBiopsyDate(); Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Demographics demographics = demographicsManager.getDemographicsByRadarNumber(radarNumber); Date dob = demographics.getDateOfBirth(); if (dateOfDiagnosis != null && dob != null) { int age = Years.yearsBetween(new DateTime(dob), new DateTime(dateOfDiagnosis)).getYears(); diagnosis.setAgeAtDiagnosis(age); } diagnosisManager.saveDiagnosis(diagnosis); // additional significant diagnosis needs to carry through to clinical data List<ClinicalData> clinicalDataList = clinicalDataManager.getClinicalDataByRadarNumber( diagnosis.getRadarNumber()); if (clinicalDataList.isEmpty()) { ClinicalData clinicalData = new ClinicalData(); clinicalData.setSequenceNumber(1); clinicalData.setRadarNumber(diagnosis.getRadarNumber()); clinicalDataList.add(clinicalData); } for (ClinicalData clinicalData : clinicalDataList) { clinicalData.setSignificantDiagnosis1(diagnosis.getSignificantDiagnosis1()); clinicalData.setSignificantDiagnosis2(diagnosis.getSignificantDiagnosis2()); clinicalDataManager.saveClinicalDate(clinicalData); } } }; add(form); final List<Component> componentsToUpdate = new ArrayList<Component>(); Label successLabel = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); Label successLabelDown = RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); Label errorLabel = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); Label errorLabelDown = RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); TextField<Long> radarNumber = new TextField<Long>("radarNumber"); radarNumber.setEnabled(false); form.add(radarNumber); TextField hospitalNumber = new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel( radarNumberModel, demographicsManager)); form.add(hospitalNumber); TextField firstName = new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager)); form.add(firstName); TextField surname = new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager)); form.add(surname); TextField dob = new DateTextField("dateOfBirth", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager), RadarApplication.DATE_PATTERN); form.add(dob); DropDownChoice<DiagnosisCode> diagnosisCodeDropDownChoice = new DropDownChoice<DiagnosisCode>("diagnosisCode", diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer<DiagnosisCode>("abbreviation", "id")); diagnosisCodeDropDownChoice.setEnabled(false); form.add(diagnosisCodeDropDownChoice); form.add(new TextArea("text")); form.add(new Label("diagnosisOrBiopsy", new LoadableDetachableModel<Object>() { @Override protected Object load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID) ? "diagnosis" : "original biopsy"; } return ""; } })); // this field is also used for date of diagnosis RadarDateTextField biopsyDate = new RadarDateTextField("biopsyDate", form, componentsToUpdate); form.add(biopsyDate); RadarDateTextField esrfDate = new RadarDateTextField("esrfDate", form, componentsToUpdate); form.add(esrfDate); TextField ageAtDiagnosis = new TextField("ageAtDiagnosis"); ageAtDiagnosis.setOutputMarkupId(true); ageAtDiagnosis.setOutputMarkupPlaceholderTag(true); form.add(ageAtDiagnosis); componentsToUpdate.add(ageAtDiagnosis); form.add(new CheckBox("prepubertalAtDiagnosis")); final RadarTextFieldWithValidation heightAtDiagnosis = new RadarTextFieldWithValidation("heightAtDiagnosis", new RangeValidator<Double>( RadarApplication.MIN_HEIGHT, RadarApplication.MAX_HEIGHT), form, componentsToUpdate); form.add(heightAtDiagnosis); // Clinical presentation B - A is further up the file final DropDownChoice<ClinicalPresentation> clinicalPresentationB = new ClinicalPresentationDropDownChoice("clinicalPresentationB"); clinicalPresentationB.setOutputMarkupId(true); clinicalPresentationB.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationA, clinicalPresentationB); form.add(new RadarDateTextField("onsetSymptomsDate", form, componentsToUpdate)); ComponentFeedbackPanel clinicalPresentationFeedback = new ComponentFeedbackPanel("clinicalPresentationFeedback", clinicalPresentationA); clinicalPresentationFeedback.setOutputMarkupId(true); clinicalPresentationFeedback.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationFeedback); // Steroid resistance radio groups RadioGroup steroidRadioGroup = new RadioGroup("steroidResistance") { @Override public boolean isVisible() { DiagnosisCode diagnosisCode = model.getObject().getDiagnosisCode(); if (diagnosisCode != null) { return diagnosisCode.getId().equals(SRNS_ID); } else { return false; } } }; steroidRadioGroup.setRequired(true); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("primarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRIMARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("secondarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.SECONDARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("presumedSteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRESUMED))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("biopsyProven", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.BPS))); form.add(steroidRadioGroup); // Construct feedback panel final ComponentFeedbackPanel steroidFeedbackPanel = new ComponentFeedbackPanel("steroidResistanceFeedback", steroidRadioGroup); steroidFeedbackPanel.setOutputMarkupPlaceholderTag(true); form.add(steroidFeedbackPanel); steroidRadioGroup.setOutputMarkupPlaceholderTag(true); steroidRadioGroup.add(steroidFeedbackPanel); componentsToUpdate.add(steroidFeedbackPanel); // Additional significant diagnosis form.add(new TextField("significantDiagnosis1")); form.add(new TextField("significantDiagnosis2")); // Biopsy Diagnosis visibilities IModel<String> biopsyLabelModel = new LoadableDetachableModel<String>() { @Override protected String load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return "Biopsy Diagnosis"; } else { return "Biopsy Proven Diagnosis"; } } else { return ""; } } }; IModel<List> biopsyDiagnosisModel = new LoadableDetachableModel<List>() { @Override protected List load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return Arrays.asList(Diagnosis.BiopsyDiagnosis.MINIMAL_CHANGE, Diagnosis.BiopsyDiagnosis.FSGS, Diagnosis.BiopsyDiagnosis.MESANGIAL_HYPERTROPHY, Diagnosis.BiopsyDiagnosis.OTHER); } else { return Arrays.asList(Diagnosis.BiopsyDiagnosis.YES, Diagnosis.BiopsyDiagnosis.NO); } } return Collections.emptyList(); } }; DropDownChoice biopsyDiagnosis = new DropDownChoice("biopsyProvenDiagnosis", biopsyDiagnosisModel, new ChoiceRenderer("label", "id")); Label biopsyDiagnosisLabel = new Label("biopsyDiagnosisLabel", biopsyLabelModel); form.add(biopsyDiagnosis, biopsyDiagnosisLabel); Diagnosis diagnosis = model.getObject(); boolean showOtherDetailsOnInit; showOtherDetailsOnInit = diagnosis.getMutationYorN9() == Diagnosis.MutationYorN.Y; final IModel<Boolean> otherDetailsVisibilityModel = new Model<Boolean>(showOtherDetailsOnInit); boolean showMoreDetailsOnInit = false; if (diagnosis.getMutationYorN1() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN2() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN3() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN4() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN5() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN6() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN7() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN8() == Diagnosis.MutationYorN.Y) { showMoreDetailsOnInit = true; } final IModel<Boolean> moreDetailsVisibilityModel = new Model<Boolean>(showMoreDetailsOnInit); WebMarkupContainer geneMutationContainer = new WebMarkupContainer("geneMutationContainer") { @Override public boolean isVisible() { - IModel<Boolean> isSrnsModel = RadarModelFactory.getIsSrnsModel(radarNumberModel, diagnosisManager); - return isSrnsModel.getObject(); + Diagnosis diagnosis = model.getObject(); + if (diagnosis.getDiagnosisCode() != null) { + return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID); + } + return false; } }; WebMarkupContainer mutationContainer = new WebMarkupContainer("mutationContainer"); form.add(geneMutationContainer); Label geneMutationLabel = new Label("geneMutationLabel", "Gene Mutation"); geneMutationContainer.add(geneMutationLabel); geneMutationContainer.add(mutationContainer); // Gene mutations mutationContainer.add(new DiagnosisGeneMutationPanel("nphs1Container", 1, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs2Container", 2, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs3Container", 3, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("wt1Container", 4, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("cd2apContainer", 5, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("trpc6Container", 6, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("actn4Container", 7, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("lamb2Container", 8, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel(OTHER_CONTAINER_ID, 9, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); // Other gene mutation container MarkupContainer otherGeneMutationContainer = new WebMarkupContainer("otherGeneMutationContainer") { @Override public boolean isVisible() { return otherDetailsVisibilityModel.getObject(); } }; otherGeneMutationContainer.setOutputMarkupId(true); otherGeneMutationContainer.setOutputMarkupPlaceholderTag(true); otherGeneMutationContainer.add(new TextArea("otherGeneMutation")); geneMutationContainer.add(otherGeneMutationContainer); // more details MarkupContainer moreDetailsContainer = new WebMarkupContainer("moreDetailsContainer") { @Override public boolean isVisible() { return moreDetailsVisibilityModel.getObject(); } }; moreDetailsContainer.setOutputMarkupId(true); moreDetailsContainer.setOutputMarkupPlaceholderTag(true); moreDetailsContainer.add(new TextArea("moreDetails", new Model())); geneMutationContainer.add(moreDetailsContainer); componentsToUpdate.add(moreDetailsContainer); componentsToUpdate.add(otherGeneMutationContainer); boolean showKaroTypeOtherOnInit = false; if (diagnosis.getKarotype() != null) { showKaroTypeOtherOnInit = diagnosis.getKarotype().getId().equals(KAROTYPE_OTHER_ID); } final IModel<Boolean> karoTypeOtherVisibilityModel = new Model<Boolean>(showKaroTypeOtherOnInit); // Add Karotype DropDownChoice<Karotype> karotypeDropDownChoice = new DropDownChoice<Karotype>("karotype", diagnosisManager.getKarotypes(), new ChoiceRenderer<Karotype>("description", "id")); WebMarkupContainer karoTypeContainer = new WebMarkupContainer("karoTypeContainer") { @Override public boolean isVisible() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID); } return false; } }; karoTypeContainer.add(karotypeDropDownChoice); form.add(karoTypeContainer); karotypeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); Karotype karotype = diagnosis.getKarotype(); if (karotype != null) { karoTypeOtherVisibilityModel.setObject(karotype.getId().equals(KAROTYPE_OTHER_ID)); ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } } }); // karotype other MarkupContainer karoTypeOtherContainer = new WebMarkupContainer("karoTypeOtherContainer") { @Override public boolean isVisible() { return karoTypeOtherVisibilityModel.getObject(); } }; karoTypeOtherContainer.setOutputMarkupId(true); karoTypeOtherContainer.setOutputMarkupPlaceholderTag(true); karoTypeOtherContainer.add(new TextArea("karoTypeOtherText")); componentsToUpdate.add(karoTypeOtherContainer); form.add(karoTypeOtherContainer); // Parental consanguinity and family history form.add(new YesNoDropDownChoice("parentalConsanguinity")); YesNoDropDownChoice familyHistory = new YesNoDropDownChoice("familyHistory"); boolean showFamilyOnInit = false; showFamilyOnInit = diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES; final IModel<Boolean> familyVisibilityModel = new Model<Boolean>(showFamilyOnInit); familyHistory.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); if (diagnosis.getFamilyHistory() != null) { familyVisibilityModel.setObject(diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES); } ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } }); form.add(familyHistory); // Family history containers form.add(new DiagnosisRelativePanel("relative1Container", 1, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative2Container", 2, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative3Container", 3, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative4Container", 4, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative5Container", 5, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative6Container", 6, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); componentsToUpdate.add(clinicalPresentationFeedback); Label radarFamilyLabel = new Label("radarFamilyLabel", "RADAR No") { @Override public boolean isVisible() { return familyVisibilityModel.getObject(); } }; radarFamilyLabel.setOutputMarkupId(true); radarFamilyLabel.setOutputMarkupPlaceholderTag(true); componentsToUpdate.add(radarFamilyLabel); form.add(radarFamilyLabel); DiagnosisAjaxSubmitLink save = new DiagnosisAjaxSubmitLink("save") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; DiagnosisAjaxSubmitLink saveDown = new DiagnosisAjaxSubmitLink("saveDown") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; form.add(save, saveDown); } @Override public boolean isVisible() { return ((PatientPage) getPage()).getCurrentTab().equals(PatientPage.CurrentTab.DIAGNOSIS); } private abstract class DiagnosisAjaxSubmitLink extends AjaxSubmitLink { public DiagnosisAjaxSubmitLink(String id) { super(id); } @Override public void onSubmit(AjaxRequestTarget target, Form<?> form) { ComponentHelper.updateComponentsIfParentIsVisible(target, getComponentsToUpdate()); } @Override protected void onError(AjaxRequestTarget target, Form<?> form) { ComponentHelper.updateComponentsIfParentIsVisible(target, getComponentsToUpdate()); } protected abstract List<? extends Component> getComponentsToUpdate(); } private class YesNoDropDownChoice extends DropDownChoice<Diagnosis.YesNo> { public YesNoDropDownChoice(String id) { super(id); setChoices(Arrays.asList(Diagnosis.YesNo.values())); // Capitalise value setChoiceRenderer(new IChoiceRenderer<Diagnosis.YesNo>() { public Object getDisplayValue(Diagnosis.YesNo object) { return StringUtils.capitalize(object.toString().toLowerCase()); } public String getIdValue(Diagnosis.YesNo object, int index) { return String.valueOf(object.getId()); } }); } } }
true
true
public DiagnosisPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model // Set up loadable detachable, working for null radar numbers (new patients) and existing final CompoundPropertyModel<Diagnosis> model = new CompoundPropertyModel<Diagnosis>(new LoadableDetachableModel<Diagnosis>() { @Override protected Diagnosis load() { if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(radarNumber); if (diagnosis != null) { return diagnosis; } else { return new Diagnosis(); } } else { return new Diagnosis(); } } }); // Clinical presentation A - goes here in the file as referenced in form submit final DropDownChoice<ClinicalPresentation> clinicalPresentationA = new ClinicalPresentationDropDownChoice("clinicalPresentationA"); clinicalPresentationA.setOutputMarkupId(true); clinicalPresentationA.setOutputMarkupPlaceholderTag(true); final Form<Diagnosis> form = new Form<Diagnosis>("form", model) { @Override protected void onValidateModelObjects() { super.onValidateModelObjects(); Diagnosis diagnosis = getModelObject(); ClinicalPresentation presentationA = diagnosis.getClinicalPresentationA(); ClinicalPresentation presentationB = diagnosis.getClinicalPresentationB(); // Validate that the two aren't the same if (presentationA != null && presentationB != null && presentationA.equals(presentationB)) { clinicalPresentationA.error("A and B cannot be the same"); } } @Override protected void onSubmit() { Diagnosis diagnosis = getModelObject(); Date dateOfDiagnosis = diagnosis.getBiopsyDate(); Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Demographics demographics = demographicsManager.getDemographicsByRadarNumber(radarNumber); Date dob = demographics.getDateOfBirth(); if (dateOfDiagnosis != null && dob != null) { int age = Years.yearsBetween(new DateTime(dob), new DateTime(dateOfDiagnosis)).getYears(); diagnosis.setAgeAtDiagnosis(age); } diagnosisManager.saveDiagnosis(diagnosis); // additional significant diagnosis needs to carry through to clinical data List<ClinicalData> clinicalDataList = clinicalDataManager.getClinicalDataByRadarNumber( diagnosis.getRadarNumber()); if (clinicalDataList.isEmpty()) { ClinicalData clinicalData = new ClinicalData(); clinicalData.setSequenceNumber(1); clinicalData.setRadarNumber(diagnosis.getRadarNumber()); clinicalDataList.add(clinicalData); } for (ClinicalData clinicalData : clinicalDataList) { clinicalData.setSignificantDiagnosis1(diagnosis.getSignificantDiagnosis1()); clinicalData.setSignificantDiagnosis2(diagnosis.getSignificantDiagnosis2()); clinicalDataManager.saveClinicalDate(clinicalData); } } }; add(form); final List<Component> componentsToUpdate = new ArrayList<Component>(); Label successLabel = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); Label successLabelDown = RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); Label errorLabel = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); Label errorLabelDown = RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); TextField<Long> radarNumber = new TextField<Long>("radarNumber"); radarNumber.setEnabled(false); form.add(radarNumber); TextField hospitalNumber = new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel( radarNumberModel, demographicsManager)); form.add(hospitalNumber); TextField firstName = new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager)); form.add(firstName); TextField surname = new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager)); form.add(surname); TextField dob = new DateTextField("dateOfBirth", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager), RadarApplication.DATE_PATTERN); form.add(dob); DropDownChoice<DiagnosisCode> diagnosisCodeDropDownChoice = new DropDownChoice<DiagnosisCode>("diagnosisCode", diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer<DiagnosisCode>("abbreviation", "id")); diagnosisCodeDropDownChoice.setEnabled(false); form.add(diagnosisCodeDropDownChoice); form.add(new TextArea("text")); form.add(new Label("diagnosisOrBiopsy", new LoadableDetachableModel<Object>() { @Override protected Object load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID) ? "diagnosis" : "original biopsy"; } return ""; } })); // this field is also used for date of diagnosis RadarDateTextField biopsyDate = new RadarDateTextField("biopsyDate", form, componentsToUpdate); form.add(biopsyDate); RadarDateTextField esrfDate = new RadarDateTextField("esrfDate", form, componentsToUpdate); form.add(esrfDate); TextField ageAtDiagnosis = new TextField("ageAtDiagnosis"); ageAtDiagnosis.setOutputMarkupId(true); ageAtDiagnosis.setOutputMarkupPlaceholderTag(true); form.add(ageAtDiagnosis); componentsToUpdate.add(ageAtDiagnosis); form.add(new CheckBox("prepubertalAtDiagnosis")); final RadarTextFieldWithValidation heightAtDiagnosis = new RadarTextFieldWithValidation("heightAtDiagnosis", new RangeValidator<Double>( RadarApplication.MIN_HEIGHT, RadarApplication.MAX_HEIGHT), form, componentsToUpdate); form.add(heightAtDiagnosis); // Clinical presentation B - A is further up the file final DropDownChoice<ClinicalPresentation> clinicalPresentationB = new ClinicalPresentationDropDownChoice("clinicalPresentationB"); clinicalPresentationB.setOutputMarkupId(true); clinicalPresentationB.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationA, clinicalPresentationB); form.add(new RadarDateTextField("onsetSymptomsDate", form, componentsToUpdate)); ComponentFeedbackPanel clinicalPresentationFeedback = new ComponentFeedbackPanel("clinicalPresentationFeedback", clinicalPresentationA); clinicalPresentationFeedback.setOutputMarkupId(true); clinicalPresentationFeedback.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationFeedback); // Steroid resistance radio groups RadioGroup steroidRadioGroup = new RadioGroup("steroidResistance") { @Override public boolean isVisible() { DiagnosisCode diagnosisCode = model.getObject().getDiagnosisCode(); if (diagnosisCode != null) { return diagnosisCode.getId().equals(SRNS_ID); } else { return false; } } }; steroidRadioGroup.setRequired(true); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("primarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRIMARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("secondarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.SECONDARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("presumedSteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRESUMED))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("biopsyProven", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.BPS))); form.add(steroidRadioGroup); // Construct feedback panel final ComponentFeedbackPanel steroidFeedbackPanel = new ComponentFeedbackPanel("steroidResistanceFeedback", steroidRadioGroup); steroidFeedbackPanel.setOutputMarkupPlaceholderTag(true); form.add(steroidFeedbackPanel); steroidRadioGroup.setOutputMarkupPlaceholderTag(true); steroidRadioGroup.add(steroidFeedbackPanel); componentsToUpdate.add(steroidFeedbackPanel); // Additional significant diagnosis form.add(new TextField("significantDiagnosis1")); form.add(new TextField("significantDiagnosis2")); // Biopsy Diagnosis visibilities IModel<String> biopsyLabelModel = new LoadableDetachableModel<String>() { @Override protected String load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return "Biopsy Diagnosis"; } else { return "Biopsy Proven Diagnosis"; } } else { return ""; } } }; IModel<List> biopsyDiagnosisModel = new LoadableDetachableModel<List>() { @Override protected List load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return Arrays.asList(Diagnosis.BiopsyDiagnosis.MINIMAL_CHANGE, Diagnosis.BiopsyDiagnosis.FSGS, Diagnosis.BiopsyDiagnosis.MESANGIAL_HYPERTROPHY, Diagnosis.BiopsyDiagnosis.OTHER); } else { return Arrays.asList(Diagnosis.BiopsyDiagnosis.YES, Diagnosis.BiopsyDiagnosis.NO); } } return Collections.emptyList(); } }; DropDownChoice biopsyDiagnosis = new DropDownChoice("biopsyProvenDiagnosis", biopsyDiagnosisModel, new ChoiceRenderer("label", "id")); Label biopsyDiagnosisLabel = new Label("biopsyDiagnosisLabel", biopsyLabelModel); form.add(biopsyDiagnosis, biopsyDiagnosisLabel); Diagnosis diagnosis = model.getObject(); boolean showOtherDetailsOnInit; showOtherDetailsOnInit = diagnosis.getMutationYorN9() == Diagnosis.MutationYorN.Y; final IModel<Boolean> otherDetailsVisibilityModel = new Model<Boolean>(showOtherDetailsOnInit); boolean showMoreDetailsOnInit = false; if (diagnosis.getMutationYorN1() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN2() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN3() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN4() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN5() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN6() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN7() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN8() == Diagnosis.MutationYorN.Y) { showMoreDetailsOnInit = true; } final IModel<Boolean> moreDetailsVisibilityModel = new Model<Boolean>(showMoreDetailsOnInit); WebMarkupContainer geneMutationContainer = new WebMarkupContainer("geneMutationContainer") { @Override public boolean isVisible() { IModel<Boolean> isSrnsModel = RadarModelFactory.getIsSrnsModel(radarNumberModel, diagnosisManager); return isSrnsModel.getObject(); } }; WebMarkupContainer mutationContainer = new WebMarkupContainer("mutationContainer"); form.add(geneMutationContainer); Label geneMutationLabel = new Label("geneMutationLabel", "Gene Mutation"); geneMutationContainer.add(geneMutationLabel); geneMutationContainer.add(mutationContainer); // Gene mutations mutationContainer.add(new DiagnosisGeneMutationPanel("nphs1Container", 1, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs2Container", 2, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs3Container", 3, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("wt1Container", 4, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("cd2apContainer", 5, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("trpc6Container", 6, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("actn4Container", 7, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("lamb2Container", 8, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel(OTHER_CONTAINER_ID, 9, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); // Other gene mutation container MarkupContainer otherGeneMutationContainer = new WebMarkupContainer("otherGeneMutationContainer") { @Override public boolean isVisible() { return otherDetailsVisibilityModel.getObject(); } }; otherGeneMutationContainer.setOutputMarkupId(true); otherGeneMutationContainer.setOutputMarkupPlaceholderTag(true); otherGeneMutationContainer.add(new TextArea("otherGeneMutation")); geneMutationContainer.add(otherGeneMutationContainer); // more details MarkupContainer moreDetailsContainer = new WebMarkupContainer("moreDetailsContainer") { @Override public boolean isVisible() { return moreDetailsVisibilityModel.getObject(); } }; moreDetailsContainer.setOutputMarkupId(true); moreDetailsContainer.setOutputMarkupPlaceholderTag(true); moreDetailsContainer.add(new TextArea("moreDetails", new Model())); geneMutationContainer.add(moreDetailsContainer); componentsToUpdate.add(moreDetailsContainer); componentsToUpdate.add(otherGeneMutationContainer); boolean showKaroTypeOtherOnInit = false; if (diagnosis.getKarotype() != null) { showKaroTypeOtherOnInit = diagnosis.getKarotype().getId().equals(KAROTYPE_OTHER_ID); } final IModel<Boolean> karoTypeOtherVisibilityModel = new Model<Boolean>(showKaroTypeOtherOnInit); // Add Karotype DropDownChoice<Karotype> karotypeDropDownChoice = new DropDownChoice<Karotype>("karotype", diagnosisManager.getKarotypes(), new ChoiceRenderer<Karotype>("description", "id")); WebMarkupContainer karoTypeContainer = new WebMarkupContainer("karoTypeContainer") { @Override public boolean isVisible() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID); } return false; } }; karoTypeContainer.add(karotypeDropDownChoice); form.add(karoTypeContainer); karotypeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); Karotype karotype = diagnosis.getKarotype(); if (karotype != null) { karoTypeOtherVisibilityModel.setObject(karotype.getId().equals(KAROTYPE_OTHER_ID)); ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } } }); // karotype other MarkupContainer karoTypeOtherContainer = new WebMarkupContainer("karoTypeOtherContainer") { @Override public boolean isVisible() { return karoTypeOtherVisibilityModel.getObject(); } }; karoTypeOtherContainer.setOutputMarkupId(true); karoTypeOtherContainer.setOutputMarkupPlaceholderTag(true); karoTypeOtherContainer.add(new TextArea("karoTypeOtherText")); componentsToUpdate.add(karoTypeOtherContainer); form.add(karoTypeOtherContainer); // Parental consanguinity and family history form.add(new YesNoDropDownChoice("parentalConsanguinity")); YesNoDropDownChoice familyHistory = new YesNoDropDownChoice("familyHistory"); boolean showFamilyOnInit = false; showFamilyOnInit = diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES; final IModel<Boolean> familyVisibilityModel = new Model<Boolean>(showFamilyOnInit); familyHistory.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); if (diagnosis.getFamilyHistory() != null) { familyVisibilityModel.setObject(diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES); } ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } }); form.add(familyHistory); // Family history containers form.add(new DiagnosisRelativePanel("relative1Container", 1, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative2Container", 2, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative3Container", 3, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative4Container", 4, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative5Container", 5, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative6Container", 6, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); componentsToUpdate.add(clinicalPresentationFeedback); Label radarFamilyLabel = new Label("radarFamilyLabel", "RADAR No") { @Override public boolean isVisible() { return familyVisibilityModel.getObject(); } }; radarFamilyLabel.setOutputMarkupId(true); radarFamilyLabel.setOutputMarkupPlaceholderTag(true); componentsToUpdate.add(radarFamilyLabel); form.add(radarFamilyLabel); DiagnosisAjaxSubmitLink save = new DiagnosisAjaxSubmitLink("save") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; DiagnosisAjaxSubmitLink saveDown = new DiagnosisAjaxSubmitLink("saveDown") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; form.add(save, saveDown); }
public DiagnosisPanel(String id, final IModel<Long> radarNumberModel) { super(id); setOutputMarkupId(true); setOutputMarkupPlaceholderTag(true); // Set up model // Set up loadable detachable, working for null radar numbers (new patients) and existing final CompoundPropertyModel<Diagnosis> model = new CompoundPropertyModel<Diagnosis>(new LoadableDetachableModel<Diagnosis>() { @Override protected Diagnosis load() { if (radarNumberModel.getObject() != null) { Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Diagnosis diagnosis = diagnosisManager.getDiagnosisByRadarNumber(radarNumber); if (diagnosis != null) { return diagnosis; } else { return new Diagnosis(); } } else { return new Diagnosis(); } } }); // Clinical presentation A - goes here in the file as referenced in form submit final DropDownChoice<ClinicalPresentation> clinicalPresentationA = new ClinicalPresentationDropDownChoice("clinicalPresentationA"); clinicalPresentationA.setOutputMarkupId(true); clinicalPresentationA.setOutputMarkupPlaceholderTag(true); final Form<Diagnosis> form = new Form<Diagnosis>("form", model) { @Override protected void onValidateModelObjects() { super.onValidateModelObjects(); Diagnosis diagnosis = getModelObject(); ClinicalPresentation presentationA = diagnosis.getClinicalPresentationA(); ClinicalPresentation presentationB = diagnosis.getClinicalPresentationB(); // Validate that the two aren't the same if (presentationA != null && presentationB != null && presentationA.equals(presentationB)) { clinicalPresentationA.error("A and B cannot be the same"); } } @Override protected void onSubmit() { Diagnosis diagnosis = getModelObject(); Date dateOfDiagnosis = diagnosis.getBiopsyDate(); Long radarNumber; try { radarNumber = radarNumberModel.getObject(); } catch (ClassCastException e) { Object obj = radarNumberModel.getObject(); radarNumber = Long.parseLong((String) obj); } Demographics demographics = demographicsManager.getDemographicsByRadarNumber(radarNumber); Date dob = demographics.getDateOfBirth(); if (dateOfDiagnosis != null && dob != null) { int age = Years.yearsBetween(new DateTime(dob), new DateTime(dateOfDiagnosis)).getYears(); diagnosis.setAgeAtDiagnosis(age); } diagnosisManager.saveDiagnosis(diagnosis); // additional significant diagnosis needs to carry through to clinical data List<ClinicalData> clinicalDataList = clinicalDataManager.getClinicalDataByRadarNumber( diagnosis.getRadarNumber()); if (clinicalDataList.isEmpty()) { ClinicalData clinicalData = new ClinicalData(); clinicalData.setSequenceNumber(1); clinicalData.setRadarNumber(diagnosis.getRadarNumber()); clinicalDataList.add(clinicalData); } for (ClinicalData clinicalData : clinicalDataList) { clinicalData.setSignificantDiagnosis1(diagnosis.getSignificantDiagnosis1()); clinicalData.setSignificantDiagnosis2(diagnosis.getSignificantDiagnosis2()); clinicalDataManager.saveClinicalDate(clinicalData); } } }; add(form); final List<Component> componentsToUpdate = new ArrayList<Component>(); Label successLabel = RadarComponentFactory.getSuccessMessageLabel("successMessage", form, componentsToUpdate); Label successLabelDown = RadarComponentFactory.getSuccessMessageLabel("successMessageDown", form, componentsToUpdate); Label errorLabel = RadarComponentFactory.getErrorMessageLabel("errorMessage", form, componentsToUpdate); Label errorLabelDown = RadarComponentFactory.getErrorMessageLabel("errorMessageDown", form, componentsToUpdate); TextField<Long> radarNumber = new TextField<Long>("radarNumber"); radarNumber.setEnabled(false); form.add(radarNumber); TextField hospitalNumber = new TextField("hospitalNumber", RadarModelFactory.getHospitalNumberModel( radarNumberModel, demographicsManager)); form.add(hospitalNumber); TextField firstName = new TextField("firstName", RadarModelFactory.getFirstNameModel(radarNumberModel, demographicsManager)); form.add(firstName); TextField surname = new TextField("surname", RadarModelFactory.getSurnameModel(radarNumberModel, demographicsManager)); form.add(surname); TextField dob = new DateTextField("dateOfBirth", RadarModelFactory.getDobModel(radarNumberModel, demographicsManager), RadarApplication.DATE_PATTERN); form.add(dob); DropDownChoice<DiagnosisCode> diagnosisCodeDropDownChoice = new DropDownChoice<DiagnosisCode>("diagnosisCode", diagnosisManager.getDiagnosisCodes(), new ChoiceRenderer<DiagnosisCode>("abbreviation", "id")); diagnosisCodeDropDownChoice.setEnabled(false); form.add(diagnosisCodeDropDownChoice); form.add(new TextArea("text")); form.add(new Label("diagnosisOrBiopsy", new LoadableDetachableModel<Object>() { @Override protected Object load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID) ? "diagnosis" : "original biopsy"; } return ""; } })); // this field is also used for date of diagnosis RadarDateTextField biopsyDate = new RadarDateTextField("biopsyDate", form, componentsToUpdate); form.add(biopsyDate); RadarDateTextField esrfDate = new RadarDateTextField("esrfDate", form, componentsToUpdate); form.add(esrfDate); TextField ageAtDiagnosis = new TextField("ageAtDiagnosis"); ageAtDiagnosis.setOutputMarkupId(true); ageAtDiagnosis.setOutputMarkupPlaceholderTag(true); form.add(ageAtDiagnosis); componentsToUpdate.add(ageAtDiagnosis); form.add(new CheckBox("prepubertalAtDiagnosis")); final RadarTextFieldWithValidation heightAtDiagnosis = new RadarTextFieldWithValidation("heightAtDiagnosis", new RangeValidator<Double>( RadarApplication.MIN_HEIGHT, RadarApplication.MAX_HEIGHT), form, componentsToUpdate); form.add(heightAtDiagnosis); // Clinical presentation B - A is further up the file final DropDownChoice<ClinicalPresentation> clinicalPresentationB = new ClinicalPresentationDropDownChoice("clinicalPresentationB"); clinicalPresentationB.setOutputMarkupId(true); clinicalPresentationB.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationA, clinicalPresentationB); form.add(new RadarDateTextField("onsetSymptomsDate", form, componentsToUpdate)); ComponentFeedbackPanel clinicalPresentationFeedback = new ComponentFeedbackPanel("clinicalPresentationFeedback", clinicalPresentationA); clinicalPresentationFeedback.setOutputMarkupId(true); clinicalPresentationFeedback.setOutputMarkupPlaceholderTag(true); form.add(clinicalPresentationFeedback); // Steroid resistance radio groups RadioGroup steroidRadioGroup = new RadioGroup("steroidResistance") { @Override public boolean isVisible() { DiagnosisCode diagnosisCode = model.getObject().getDiagnosisCode(); if (diagnosisCode != null) { return diagnosisCode.getId().equals(SRNS_ID); } else { return false; } } }; steroidRadioGroup.setRequired(true); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("primarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRIMARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("secondarySteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.SECONDARY))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("presumedSteroidResistance", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.PRESUMED))); steroidRadioGroup.add(new Radio<Diagnosis.SteroidResistance>("biopsyProven", new Model<Diagnosis.SteroidResistance>(Diagnosis.SteroidResistance.BPS))); form.add(steroidRadioGroup); // Construct feedback panel final ComponentFeedbackPanel steroidFeedbackPanel = new ComponentFeedbackPanel("steroidResistanceFeedback", steroidRadioGroup); steroidFeedbackPanel.setOutputMarkupPlaceholderTag(true); form.add(steroidFeedbackPanel); steroidRadioGroup.setOutputMarkupPlaceholderTag(true); steroidRadioGroup.add(steroidFeedbackPanel); componentsToUpdate.add(steroidFeedbackPanel); // Additional significant diagnosis form.add(new TextField("significantDiagnosis1")); form.add(new TextField("significantDiagnosis2")); // Biopsy Diagnosis visibilities IModel<String> biopsyLabelModel = new LoadableDetachableModel<String>() { @Override protected String load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return "Biopsy Diagnosis"; } else { return "Biopsy Proven Diagnosis"; } } else { return ""; } } }; IModel<List> biopsyDiagnosisModel = new LoadableDetachableModel<List>() { @Override protected List load() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { if (diagnosis.getDiagnosisCode().getId().equals(SRNS_ID)) { return Arrays.asList(Diagnosis.BiopsyDiagnosis.MINIMAL_CHANGE, Diagnosis.BiopsyDiagnosis.FSGS, Diagnosis.BiopsyDiagnosis.MESANGIAL_HYPERTROPHY, Diagnosis.BiopsyDiagnosis.OTHER); } else { return Arrays.asList(Diagnosis.BiopsyDiagnosis.YES, Diagnosis.BiopsyDiagnosis.NO); } } return Collections.emptyList(); } }; DropDownChoice biopsyDiagnosis = new DropDownChoice("biopsyProvenDiagnosis", biopsyDiagnosisModel, new ChoiceRenderer("label", "id")); Label biopsyDiagnosisLabel = new Label("biopsyDiagnosisLabel", biopsyLabelModel); form.add(biopsyDiagnosis, biopsyDiagnosisLabel); Diagnosis diagnosis = model.getObject(); boolean showOtherDetailsOnInit; showOtherDetailsOnInit = diagnosis.getMutationYorN9() == Diagnosis.MutationYorN.Y; final IModel<Boolean> otherDetailsVisibilityModel = new Model<Boolean>(showOtherDetailsOnInit); boolean showMoreDetailsOnInit = false; if (diagnosis.getMutationYorN1() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN2() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN3() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN4() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN5() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN6() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN7() == Diagnosis.MutationYorN.Y || diagnosis.getMutationYorN8() == Diagnosis.MutationYorN.Y) { showMoreDetailsOnInit = true; } final IModel<Boolean> moreDetailsVisibilityModel = new Model<Boolean>(showMoreDetailsOnInit); WebMarkupContainer geneMutationContainer = new WebMarkupContainer("geneMutationContainer") { @Override public boolean isVisible() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID); } return false; } }; WebMarkupContainer mutationContainer = new WebMarkupContainer("mutationContainer"); form.add(geneMutationContainer); Label geneMutationLabel = new Label("geneMutationLabel", "Gene Mutation"); geneMutationContainer.add(geneMutationLabel); geneMutationContainer.add(mutationContainer); // Gene mutations mutationContainer.add(new DiagnosisGeneMutationPanel("nphs1Container", 1, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs2Container", 2, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("nphs3Container", 3, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("wt1Container", 4, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("cd2apContainer", 5, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("trpc6Container", 6, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("actn4Container", 7, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel("lamb2Container", 8, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); mutationContainer.add(new DiagnosisGeneMutationPanel(OTHER_CONTAINER_ID, 9, (CompoundPropertyModel) form.getModel(), otherDetailsVisibilityModel, moreDetailsVisibilityModel, componentsToUpdate)); // Other gene mutation container MarkupContainer otherGeneMutationContainer = new WebMarkupContainer("otherGeneMutationContainer") { @Override public boolean isVisible() { return otherDetailsVisibilityModel.getObject(); } }; otherGeneMutationContainer.setOutputMarkupId(true); otherGeneMutationContainer.setOutputMarkupPlaceholderTag(true); otherGeneMutationContainer.add(new TextArea("otherGeneMutation")); geneMutationContainer.add(otherGeneMutationContainer); // more details MarkupContainer moreDetailsContainer = new WebMarkupContainer("moreDetailsContainer") { @Override public boolean isVisible() { return moreDetailsVisibilityModel.getObject(); } }; moreDetailsContainer.setOutputMarkupId(true); moreDetailsContainer.setOutputMarkupPlaceholderTag(true); moreDetailsContainer.add(new TextArea("moreDetails", new Model())); geneMutationContainer.add(moreDetailsContainer); componentsToUpdate.add(moreDetailsContainer); componentsToUpdate.add(otherGeneMutationContainer); boolean showKaroTypeOtherOnInit = false; if (diagnosis.getKarotype() != null) { showKaroTypeOtherOnInit = diagnosis.getKarotype().getId().equals(KAROTYPE_OTHER_ID); } final IModel<Boolean> karoTypeOtherVisibilityModel = new Model<Boolean>(showKaroTypeOtherOnInit); // Add Karotype DropDownChoice<Karotype> karotypeDropDownChoice = new DropDownChoice<Karotype>("karotype", diagnosisManager.getKarotypes(), new ChoiceRenderer<Karotype>("description", "id")); WebMarkupContainer karoTypeContainer = new WebMarkupContainer("karoTypeContainer") { @Override public boolean isVisible() { Diagnosis diagnosis = model.getObject(); if (diagnosis.getDiagnosisCode() != null) { return diagnosis.getDiagnosisCode().getId().equals(SRNS_ID); } return false; } }; karoTypeContainer.add(karotypeDropDownChoice); form.add(karoTypeContainer); karotypeDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); Karotype karotype = diagnosis.getKarotype(); if (karotype != null) { karoTypeOtherVisibilityModel.setObject(karotype.getId().equals(KAROTYPE_OTHER_ID)); ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } } }); // karotype other MarkupContainer karoTypeOtherContainer = new WebMarkupContainer("karoTypeOtherContainer") { @Override public boolean isVisible() { return karoTypeOtherVisibilityModel.getObject(); } }; karoTypeOtherContainer.setOutputMarkupId(true); karoTypeOtherContainer.setOutputMarkupPlaceholderTag(true); karoTypeOtherContainer.add(new TextArea("karoTypeOtherText")); componentsToUpdate.add(karoTypeOtherContainer); form.add(karoTypeOtherContainer); // Parental consanguinity and family history form.add(new YesNoDropDownChoice("parentalConsanguinity")); YesNoDropDownChoice familyHistory = new YesNoDropDownChoice("familyHistory"); boolean showFamilyOnInit = false; showFamilyOnInit = diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES; final IModel<Boolean> familyVisibilityModel = new Model<Boolean>(showFamilyOnInit); familyHistory.add(new AjaxFormComponentUpdatingBehavior("onChange") { @Override protected void onUpdate(AjaxRequestTarget target) { Diagnosis diagnosis = model.getObject(); if (diagnosis.getFamilyHistory() != null) { familyVisibilityModel.setObject(diagnosis.getFamilyHistory() == Diagnosis.YesNo.YES); } ComponentHelper.updateComponentsIfParentIsVisible(target, componentsToUpdate); } }); form.add(familyHistory); // Family history containers form.add(new DiagnosisRelativePanel("relative1Container", 1, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative2Container", 2, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative3Container", 3, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative4Container", 4, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative5Container", 5, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); form.add(new DiagnosisRelativePanel("relative6Container", 6, (CompoundPropertyModel) form.getModel(), familyVisibilityModel, componentsToUpdate)); componentsToUpdate.add(clinicalPresentationFeedback); Label radarFamilyLabel = new Label("radarFamilyLabel", "RADAR No") { @Override public boolean isVisible() { return familyVisibilityModel.getObject(); } }; radarFamilyLabel.setOutputMarkupId(true); radarFamilyLabel.setOutputMarkupPlaceholderTag(true); componentsToUpdate.add(radarFamilyLabel); form.add(radarFamilyLabel); DiagnosisAjaxSubmitLink save = new DiagnosisAjaxSubmitLink("save") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; DiagnosisAjaxSubmitLink saveDown = new DiagnosisAjaxSubmitLink("saveDown") { @Override protected List<? extends Component> getComponentsToUpdate() { return componentsToUpdate; } }; form.add(save, saveDown); }
diff --git a/src/fm/smart/r1/Main.java b/src/fm/smart/r1/Main.java index 0e77974..dabf800 100644 --- a/src/fm/smart/r1/Main.java +++ b/src/fm/smart/r1/Main.java @@ -1,1060 +1,1054 @@ package fm.smart.r1; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Vector; import oauth.signpost.OAuth; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.speech.RecognizerIntent; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.TextView.OnEditorActionListener; import com.nullwire.trace.ExceptionHandler; import fm.smart.r1.activity.AndroidHttpClient; import fm.smart.r1.activity.CreateListResult; import fm.smart.r1.activity.LoginActivity; import fm.smart.r1.provider.SearchSuggestionSampleProvider; /** * publish apps here http://market.android.com/publish/Home * * Should look at Unit testing for android here: http://p-unit.sourceforge.net/ * http://developer.android.com/guide/index.html is dev guide ... * http://openhandsetmagazine * .com/2008/01/tips-how-to-install-apk-files-on-android-emulator/ * * also layout article here: * http://www.curious-creature.org/2009/03/01/android-layout * -tricks-3-optimize-part-1/ */ public class Main extends Activity implements View.OnClickListener { public static final String SOUND_DIRECTORY = "sounds"; static final String PREF_REF = "SMART_FM_PREFERENCES"; public static ProgressDialog myProgressDialog; public ListDownload list_download = null; private SmartFmMenus menus; public static List<String> languages = null; public static String username(Activity activity) { return activity.getSharedPreferences(PREF_REF, 0).getString("username", null); } public static String password(Activity activity) { return activity.getSharedPreferences(PREF_REF, 0).getString("password", null); } public static boolean isNotLoggedIn(Activity activity) { String username = activity.getSharedPreferences(PREF_REF, 0).getString( "username", ""); Log.d("LOGIN-DEBUG", "pref username is: " + username); return TextUtils.isEmpty(username); } public static void login(Activity activity, String username, String password) { SharedPreferences.Editor editor = activity.getSharedPreferences( PREF_REF, 0).edit(); editor.putString("username", username); editor.putString("password", password); editor.commit(); Log.d("LOGIN-DEBUG", "entered: " + username + "," + password); // Set a default list? // do created list call } public static CreateListResult getDefaultStudyList(Activity activity) { CreateListResult result = null; try { Vector<Node> items = new SmartFmLookup().userLists(Main .username(activity)); // network time outs causing recreate here? if (items == null || items.size() == 0) { // create default list for user result = LoginActivity.createList(Main.username(activity) + "'s first list", "List created for " + Main.username(activity) + "by Google Android Application to store study items", Main.search_lang, Main.result_lang, activity); Main.default_study_list_id = result.getHttpResponse(); } else { Main.default_study_list_id = items.firstElement().atts .get("id").toString(); } } catch (Exception e) { e.printStackTrace(); } return result; } public class LanguagePair extends Object { String search_language_code; String result_language_code; public LanguagePair(String search_language_code, String result_language_code) { this.search_language_code = search_language_code; this.result_language_code = result_language_code; } public String toString() { return search_language_code + " , " + result_language_code; } public boolean equals(Object pair) { Log.d("LP-DEBUG", pair.getClass().getName()); Log.d("LP-DEBUG", pair.toString()); Log.d("LP-DEBUG", this.toString()); if (pair.getClass().getName().equals( "fm.smart.r1.Main$LanguagePair")) { LanguagePair lp = (LanguagePair) pair; if (this.result_language_code.equals(lp.result_language_code) && this.search_language_code .equals(lp.search_language_code)) { return true; } } return false; } } public static String search_lang = "ja"; public static String result_lang = "en"; // not being persisted have to think carefully about that ... public static LinkedList<LanguagePair> recent_lang_pairs_stack = new LinkedList<LanguagePair>(); private void loadRecentLanguagePairs(Vector<String> imes) { Iterator<String> iter = imes.iterator(); boolean chinese = false; boolean japanese = false; String ime = null; while (iter.hasNext()) { ime = iter.next().toLowerCase(); if (ime.contains("pinyin") || ime.contains("chinese")) { chinese = true; } if (ime.contains("simeji") || ime.contains("japan") || ime.contains("iwnn") || ime.contains("NTT") || ime.contains("ntt")) { japanese = true; } } String default_lang = Locale.getDefault().getLanguage(); String EN = "en"; String ES = "es"; String JA = "ja"; String ZH = "zh-Hant"; String[] default_1 = new String[2]; String[] default_2 = new String[2]; String[] default_3 = new String[2]; default_1[0] = (default_lang.equals(EN) ? ES : EN); default_1[1] = default_lang; default_2[0] = default_lang; default_2[1] = (default_lang.equals(EN) ? ES : EN); default_3[0] = default_lang; default_3[1] = default_lang; if (chinese) { default_1[0] = (default_lang.equals(ZH) ? EN : ZH); default_1[1] = default_lang; default_2[0] = default_lang; default_2[1] = (default_lang.equals(ZH) ? EN : ZH); } if (japanese) { default_1[0] = (default_lang.equals(JA) ? EN : JA); default_1[1] = default_lang; default_2[0] = default_lang; default_2[1] = (default_lang.equals(JA) ? EN : JA); } LanguagePair one = new LanguagePair(getSharedPreferences(PREF_REF, 0) .getString("search_lang_1", default_1[0]), getSharedPreferences(PREF_REF, 0).getString("result_lang_1", default_1[1])); LanguagePair two = new LanguagePair(getSharedPreferences(PREF_REF, 0) .getString("search_lang_2", default_2[0]), getSharedPreferences(PREF_REF, 0).getString("result_lang_2", default_2[1])); LanguagePair three = new LanguagePair(getSharedPreferences(PREF_REF, 0) .getString("search_lang_3", default_3[0]), getSharedPreferences(PREF_REF, 0).getString("result_lang_3", default_3[1])); recent_lang_pairs_stack.clear(); recent_lang_pairs_stack.add(one); recent_lang_pairs_stack.add(two); recent_lang_pairs_stack.add(three); } private void persistRecentLanguagePairs() { SharedPreferences.Editor editor = getSharedPreferences(PREF_REF, 0) .edit(); editor.putString("search_lang_1", recent_lang_pairs_stack.get(0).search_language_code); editor.putString("result_lang_1", recent_lang_pairs_stack.get(0).result_language_code); editor.putString("search_lang_2", recent_lang_pairs_stack.get(1).search_language_code); editor.putString("result_lang_2", recent_lang_pairs_stack.get(1).result_language_code); editor.putString("search_lang_3", recent_lang_pairs_stack.get(2).search_language_code); editor.putString("result_lang_3", recent_lang_pairs_stack.get(2).result_language_code); editor.commit(); } public static String default_study_list_id = null;// "57692"; public static CommonsHttpOAuthConsumer consumer = null; public static DefaultOAuthProvider provider = null; public static String ACCESS_TOKEN = null; public static String TOKEN_SECRET = null; private static SaveFileResult save_file_result = null; protected static MediaPlayer mediaPlayer; final private int VOICE_RECOGNITION_REQUEST_CODE = 0; public static final String API_KEY = "7pvmc285fxnexgwhbfddzkjn"; private String query_string = null; @Override public void onResume() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onResume"); } protected void onStart() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onStart"); } protected void onRestart() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onRestart"); } protected void onPause() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onPause"); } protected void onStop() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onStop"); } protected void onDestroy() { super.onResume(); Log.d("ACTIVITY-DEBUG", "onDestroy"); }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("ACTIVITY-DEBUG", "onCreate"); if (!Main.isNotLoggedIn(this)) { Main.getDefaultStudyList(this); } ExceptionHandler.register(this); menus = new SmartFmMenus(this); this.setContentView(R.layout.main); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); Bundle extras = queryIntent.getExtras(); String listType = null; if (extras != null) { listType = (String) extras.get("list_type"); query_string = (String) extras.get("query_string"); if (!TextUtils.isEmpty(query_string)) { query_string = query_string.replaceAll("\\++", " "); } } if (listType == null) { // hansleOauth(queryIntent); } if (Intent.ACTION_SEARCH.equals(queryAction)) { doSearchQuery(queryIntent, "onCreate()"); } else if (listType != null && listType.equals("recent_lists")) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading recent lists...", true, true); if (list_download == null) { list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.recentLists(); } }; } list_download.start(); } else if ((listType != null && listType.equals("my_study_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog .show(Main.this, "Please wait...", "Downloading " + username(this) + "'s lists...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userStudyLists(username(Main.this)); } }; list_download.start(); } else if ((listType != null && listType.equals("my_created_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading lists created by " + username(this) + "...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userLists(username(Main.this)); } }; list_download.start(); } final ImageButton button = (ImageButton) findViewById(R.id.main_submit); button.setOnClickListener(this); // button.setEnabled(false); ImageButton vbutton = (ImageButton) findViewById(R.id.main_voice); final Intent intent = new Intent( "android.speech.action.RECOGNIZE_SPEECH"); ComponentName cname = intent.resolveActivity(getPackageManager()); if (cname != null) { Log.d("SPEECH-DEBUG", cname.toString()); } else { Log.d("SPEECH-DEBUG", "NULL"); vbutton.setEnabled(false); } // TODO some way to test if voice is available and disable // android.content.ActivityNotFoundException: No Activity found to // handle Intent { action=android.speech.action.RECOGNIZE_SPEECH (has // extras) } // test for presence of activities? vbutton.setOnClickListener(new OnClickListener() { public void onClick(View view) { // Create Intent // Settings intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form"); intent.putExtra("android.speech.extra.PROMPT", "Speak now"); button.setEnabled(true);// TODO ensure activate search button // .... or search on first match ... // Start the Recognition Activity startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); } }); InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); List<InputMethodInfo> inputMethodInfoList = inputManager .getEnabledInputMethodList(); Vector<String> imes = new Vector<String>(); for (InputMethodInfo i : inputMethodInfoList) { imes.add(i.getServiceName()); - Log.d("INPUT-DEBUG", i.getServiceName()); - Log.d("INPUT-DEBUG", i.getPackageName()); - Log.d("INPUT-DEBUG", i.getSettingsActivity()); + try { + Log.d("INPUT-DEBUG", i.getServiceName()); + Log.d("INPUT-DEBUG", i.getPackageName()); + Log.d("INPUT-DEBUG", i.getSettingsActivity()); + } catch (Exception e) { + e.printStackTrace(); + } } /* * large number of locales - not apparently related to what user had set * up for languages they care about ... List<Locale> locales = new * ArrayList(Arrays.asList(Locale.getAvailableLocales())); for (Locale l * : locales) { Log.d("LOCALE-DEBUG", l.getCountry()); * Log.d("LOCALE-DEBUG", l.getLanguage()); Log.d("LOCALE-DEBUG", * l.getISO3Language()); } */ final TextView lookup_legend_textView = (TextView) findViewById(R.id.main_lookup); final AutoCompleteTextView lookup_textView = (AutoCompleteTextView) findViewById(R.id.lookup); lookup_textView.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (v.equals(lookup_textView)) { if (!TextUtils .isEmpty(((AutoCompleteTextView) v).getText())) { button.setEnabled(true); } if (event != null) { onClick(v); Log.d("KEY-DEBUG", "enter key pressed"); return true; } } return false; } }); // lookup_textView.setOnKeyListener(new OnKeyListener() { // // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (v.equals(lookup_textView)) { // if (!TextUtils // .isEmpty(((AutoCompleteTextView) v).getText())) { // button.setEnabled(true); // } // switch (keyCode) { // case KeyEvent.KEYCODE_ENTER: // if (event.getAction() == KeyEvent.ACTION_UP) { // onClick(v); // Log.d("KEY-DEBUG", "enter key pressed"); // return true; // } // } // } // return false; // } // }); lookup_textView.setSelectAllOnFocus(true); if (!TextUtils.isEmpty(query_string)) { lookup_textView.setText(query_string); button.setEnabled(true); } Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getCountry()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getLanguage()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getISO3Language()); PackageManager pm = getPackageManager(); -/* - PackageInfo pi; - try { - pi = pm - .getPackageInfo("fm.smart.r1", - PackageManager.GET_ACTIVITIES); - for (ActivityInfo a : pi.activities) { - Log.d("PACKAGE-DEBUG", a.name); - } - pi = pm.getPackageInfo("android.speech", - PackageManager.GET_ACTIVITIES); - for (ActivityInfo a : pi.activities) { - Log.d("PACKAGE-DEBUG", a.name); - } - } catch (NameNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -*/ + /* + * PackageInfo pi; try { pi = pm .getPackageInfo("fm.smart.r1", + * PackageManager.GET_ACTIVITIES); for (ActivityInfo a : pi.activities) + * { Log.d("PACKAGE-DEBUG", a.name); } pi = + * pm.getPackageInfo("android.speech", PackageManager.GET_ACTIVITIES); + * for (ActivityInfo a : pi.activities) { Log.d("PACKAGE-DEBUG", + * a.name); } } catch (NameNotFoundException e) { // TODO Auto-generated + * catch block e.printStackTrace(); } + */ // languages = new Vector<String>(Utils.LANGUAGE_MAP.keySet()); languages = Utils.POPULAR_LANGUAGES; Collections.sort(languages); ArrayAdapter<String> search_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner search_language_spinner = (Spinner) findViewById(R.id.search_language); ArrayAdapter<String> result_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner result_language_spinner = (Spinner) findViewById(R.id.result_language); search_language_spinner.setAdapter(search_language_adapter); result_language_spinner.setAdapter(result_language_adapter); search_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + languages.get(position) + " or " + result_language_spinner.getSelectedItem() + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); result_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + search_language_spinner.getSelectedItem() + " or " + languages.get(position) + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); search_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.search_lang))); result_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.result_lang))); loadRecentLanguagePairs(imes); updateSpinner(); // TODO // switch autocompletes to spinners on main languages we support, // and have a change listener update the lookup text } private void handleOauth(final Intent queryIntent) { try { Log.d("OAUTH-DEBUG", "Token: " + queryIntent.getData() .getQueryParameter(OAuth.OAUTH_TOKEN)); String pinCode = queryIntent.getData().getQueryParameter( OAuth.OAUTH_VERIFIER); Log.d("OAUTH-DEBUG", "Verifier: " + queryIntent.getData().getQueryParameter( OAuth.OAUTH_VERIFIER)); Main.provider.retrieveAccessToken(pinCode); ACCESS_TOKEN = Main.consumer.getToken(); TOKEN_SECRET = Main.consumer.getTokenSecret(); Log.d("LOGIN-DEBUG", Main.consumer.getToken()); Log.d("LOGIN-DEBUG", Main.consumer.getTokenSecret()); } catch (Exception e) { e.printStackTrace(); } } // this forces the menu to be reloaded each time, checking for login status @Override public boolean onPrepareOptionsMenu(Menu menu) { Log.d("DEBUG-MENU", "onPrepareOptionsMenu"); super.onPrepareOptionsMenu(menu); return onCreateOptionsMenu(menu); } public void updateSpinner() { final Spinner search_language_spinner = (Spinner) findViewById(R.id.search_language); final Spinner result_language_spinner = (Spinner) findViewById(R.id.result_language); String search_language = search_language_spinner.getSelectedItem() .toString(); String result_language = result_language_spinner.getSelectedItem() .toString(); String search_language_code = Utils.LANGUAGE_MAP.get(search_language); String result_language_code = Utils.LANGUAGE_MAP.get(result_language); if (!TextUtils.isEmpty(search_language_code)) { Main.search_lang = search_language_code; } if (!TextUtils.isEmpty(result_language_code)) { Main.result_lang = result_language_code; } LanguagePair pair = new LanguagePair(Main.search_lang, Main.result_lang); Log.d("DEBUG_SPINNER", "language pair: " + pair.toString()); Log.d("DEBUG_SPINNER", "language pair: " + recent_lang_pairs_stack.get(0).toString()); Log.d("DEBUG_SPINNER", "language pair: " + recent_lang_pairs_stack.get(1).toString()); Log.d("DEBUG_SPINNER", "language pair: " + recent_lang_pairs_stack.get(2).toString()); int position = recent_lang_pairs_stack.indexOf(pair); Log.d("DEBUG_SPINNER", "position: " + position); if (position == -1) { Log.d("DEBUG_SPINNER", "removing last pair!!!!"); recent_lang_pairs_stack.removeLast(); recent_lang_pairs_stack.addFirst(pair); } else { Log.d("DEBUG_SPINNER", "removing an existing pair!!!!"); recent_lang_pairs_stack.remove(pair); recent_lang_pairs_stack.addFirst(pair); } persistRecentLanguagePairs(); String[] spinner_list = new String[Main.recent_lang_pairs_stack.size()]; for (int i = 0; i < Main.recent_lang_pairs_stack.size(); i++) { spinner_list[i] = Utils.INV_LANGUAGE_MAP .get(recent_lang_pairs_stack.get(i).search_language_code) + ", " + Utils.INV_LANGUAGE_MAP .get(recent_lang_pairs_stack.get(i).result_language_code); Log .d( "SPINNER-DEBUG", recent_lang_pairs_stack.get(i).search_language_code + ": " + recent_lang_pairs_stack.get(i).result_language_code); Log .d("SPINNER-DEBUG", Integer.toString(i) + ": " + spinner_list[i]); } Spinner s1 = (Spinner) findViewById(R.id.recent_lang_pairs_spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_list); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); s1.setAdapter(adapter); s1.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { search_language_spinner .setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP .get(recent_lang_pairs_stack .get(position).search_language_code))); result_language_spinner .setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP .get(recent_lang_pairs_stack .get(position).result_language_code))); } public void onNothingSelected(AdapterView<?> parent) { } }); } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { // Fill the list view with the strings the recognizer thought it // could have heard ArrayList<String> matches = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); if (matches != null && matches.size() > 0) { Log.d("VOICE-DEBUG", matches.toString()); ArrayAdapter<String> lookup_voice_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_dropdown_item_1line, matches); AutoCompleteTextView lookup_textView = (AutoCompleteTextView) findViewById(R.id.lookup); lookup_textView.setAdapter(lookup_voice_adapter); lookup_textView.setText(matches.get(0)); } } super.onActivityResult(requestCode, resultCode, data); } public void onClick(View view) { EditText lookupInput = (EditText) findViewById(R.id.lookup); String lookup = lookupInput.getText().toString(); if (!TextUtils.isEmpty(lookup)) { updateSpinner(); // TODO pop this new language search pair onto the language search // pair // stack // would be good to search stack and move item to top if already // present // in order // to avoid list filling up with multiple instances of same item // persistence could be an issue - simplest might be having 3/4 // spaces // in preferences ... // but conflict there between what user want's to set as preference // and // what // is actually recent // TODO should we move language autocompletes over to spinners? // autocomplete // pros: // a) user can type a letter and get suggestions vs having to // navigate // long list // // cons // a) incorrect entry can lead to failure [i) can catch and ask user // to // select] // b) user can't see list of all possibilities [i) present in other // location ii) don't care?] // c) inconvenient to delete existing item // spinner // pros // a) user can see all possibilities // b) any item selected will necessarily be correct // // cons // a) list may be too long making navigation challenging [i) can put // freq at top of list ii) allow keypress to nav list (not supported // on // android)] // b) // other issue is for user setting a group of pairs they want as // defaults and also about making a list of recent pairs available // ... // TODO could replace this with making an intent and passing it to // SmartFmMenus with appropriate query string extra - would reduce // shared // code and could call own search method ... SearchRecentSuggestions suggestions = new SearchRecentSuggestions( this, SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE); suggestions.saveRecentQuery(lookup, null); SmartFmMenus.loadItems(this, lookup, 1); } } public void openMenu() { this.getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)); } public boolean onOptionsItemSelected(MenuItem item) { menus.onOptionsItemSelected(item, this); return super.onOptionsItemSelected(item); } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return menus.onCreateOptionsMenu(menu); } @Override public void onConfigurationChanged(Configuration config) { Log.d("ORIENTATION-DEBUG", "onConfigurationChanged"); // Do nothing, this is to prevent the activity from being restarted when // the keyboard opens. super.onConfigurationChanged(config); } private final DialogInterface.OnClickListener mAboutListener = new DialogInterface.OnClickListener() { public void onClick(android.content.DialogInterface dialogInterface, int i) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri .parse(getString(R.string.smartfm_url))); startActivity(intent); } }; public static Bitmap getRemoteImage(String url, Bitmap default_bitmap) { Bitmap bm = null; AndroidHttpClient client = null; Log.d("DEBUG", url); try { // Log.d("DEBUG", file); // URLConnection conn = new URL(file).openConnection(); // conn.connect(); // InputStream is = conn.getInputStream(); // BufferedInputStream bis = new BufferedInputStream(is); // bm = BitmapFactory.decodeStream(bis); // bis.close(); // is.close(); if (!url.equals("")) { URI uri = new URI(url); HttpGet get = new HttpGet(uri); client = AndroidHttpClient.newInstance("Main"); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); bm = BitmapFactory.decodeStream(entity.getContent()); } } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bm == null) { bm = default_bitmap; } if (client != null) { client.close(); } } // return bm; } private void doSearchQuery(final Intent queryIntent, final String entryPoint) { menus.doSearchQuery(queryIntent, entryPoint, this); } public static void playSound(final String sound_url, final MediaPlayer mediaPlayer, final Context context) { File dir = context.getDir(SOUND_DIRECTORY, MODE_WORLD_READABLE); final File cache = new File(dir, "Sound" + Integer.toString(sound_url.hashCode()) + ".mp3"); if (cache.exists()) { employMediaPlayer(cache); } else { final ProgressDialog myOtherProgressDialog = new ProgressDialog( context); myOtherProgressDialog.setTitle("Please Wait ..."); myOtherProgressDialog.setMessage("Downloading sound file ..."); myOtherProgressDialog.setIndeterminate(true); myOtherProgressDialog.setCancelable(true); final Thread download = new Thread() { public void run() { Main.save_file_result = saveFile(sound_url, cache, context); // TODO would be nice if failure could give report to the // user // ... if (Main.save_file_result.success()) { employMediaPlayer(cache); myOtherProgressDialog.dismiss(); } else { myOtherProgressDialog.dismiss(); ((Activity) context).runOnUiThread(new Thread() { public void run() { final AlertDialog dialog = new AlertDialog.Builder( context).create(); dialog.setTitle(Main.save_file_result .getTitle()); dialog.setMessage(Main.save_file_result .getMessage()); Main.save_file_result = null; dialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { } }); // TODO suggest to user to upload new sound? dialog.show(); } }); } } }; myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { download.interrupt(); } }); OnCancelListener ocl = new OnCancelListener() { public void onCancel(DialogInterface arg0) { download.interrupt(); } }; myOtherProgressDialog.setOnCancelListener(ocl); myOtherProgressDialog.show(); download.start(); } } private static void employMediaPlayer(final File cache) { if (Main.mediaPlayer != null) { Main.mediaPlayer.release(); Main.mediaPlayer = null; } Main.mediaPlayer = new MediaPlayer(); FileInputStream is = null; try { is = new FileInputStream(cache); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Main.mediaPlayer.setDataSource(is.getFD()); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Main.mediaPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Main.mediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } public static SaveFileResult saveFile(String url, File file, Context context) { String http_response = ""; int status_code = 0; AndroidHttpClient client = null; FileOutputStream fos = null; InputStream is = null; FileDescriptor fd = null; try { URI uri = new URI(url); Log.d("DEBUG", uri.toString()); HttpGet get = new HttpGet(uri); // GET /assets/legacy/halpern/ja_female/16/J0150989.mp3 HTTP/1.1 // Host: assets1.smart.fm // User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; // rv:1.8.1.20) Gecko/20081217 Firefox/2.0.0.20 // Accept: // text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 // Accept-Language: en-us,en;q=0.5 // Accept-Encoding: gzip,deflate // Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 // Keep-Alive: 300 // Connection: keep-alive get.setHeader("Host", uri.getHost()); Header[] array = get.getAllHeaders(); for (Header h : array) { Log.d("DEBUG", h.toString()); } client = AndroidHttpClient.newInstance("Main"); HttpResponse response1 = client.execute(get); status_code = response1.getStatusLine().getStatusCode(); Log.d("DEBUG", response1.getStatusLine().toString()); array = response1.getAllHeaders(); for (Header h : array) { Log.d("DEBUG", h.toString()); } long length = response1.getEntity().getContentLength(); // byte[] response_bytes = new byte[(int) length]; http_response = Long.toString(length); // avoid writing file if not a successful response if (status_code == 200) { HttpEntity entity = response1.getEntity(); // .getContent().read(response_bytes) fos = new FileOutputStream(file); fd = fos.getFD(); is = entity.getContent(); int chomp = is.read(); while (chomp != -1) { fos.write(chomp); chomp = is.read(); } fos.flush(); fos.close(); } else { file.delete(); } } catch (IOException e) { // Reset to Default image on any error. e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (client != null) { client.close(); } try { if (fos != null) { fos.flush(); fos.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (is != null) { is.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return new SaveFileResult(status_code, http_response, fd); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("ACTIVITY-DEBUG", "onCreate"); if (!Main.isNotLoggedIn(this)) { Main.getDefaultStudyList(this); } ExceptionHandler.register(this); menus = new SmartFmMenus(this); this.setContentView(R.layout.main); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); Bundle extras = queryIntent.getExtras(); String listType = null; if (extras != null) { listType = (String) extras.get("list_type"); query_string = (String) extras.get("query_string"); if (!TextUtils.isEmpty(query_string)) { query_string = query_string.replaceAll("\\++", " "); } } if (listType == null) { // hansleOauth(queryIntent); } if (Intent.ACTION_SEARCH.equals(queryAction)) { doSearchQuery(queryIntent, "onCreate()"); } else if (listType != null && listType.equals("recent_lists")) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading recent lists...", true, true); if (list_download == null) { list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.recentLists(); } }; } list_download.start(); } else if ((listType != null && listType.equals("my_study_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog .show(Main.this, "Please wait...", "Downloading " + username(this) + "'s lists...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userStudyLists(username(Main.this)); } }; list_download.start(); } else if ((listType != null && listType.equals("my_created_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading lists created by " + username(this) + "...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userLists(username(Main.this)); } }; list_download.start(); } final ImageButton button = (ImageButton) findViewById(R.id.main_submit); button.setOnClickListener(this); // button.setEnabled(false); ImageButton vbutton = (ImageButton) findViewById(R.id.main_voice); final Intent intent = new Intent( "android.speech.action.RECOGNIZE_SPEECH"); ComponentName cname = intent.resolveActivity(getPackageManager()); if (cname != null) { Log.d("SPEECH-DEBUG", cname.toString()); } else { Log.d("SPEECH-DEBUG", "NULL"); vbutton.setEnabled(false); } // TODO some way to test if voice is available and disable // android.content.ActivityNotFoundException: No Activity found to // handle Intent { action=android.speech.action.RECOGNIZE_SPEECH (has // extras) } // test for presence of activities? vbutton.setOnClickListener(new OnClickListener() { public void onClick(View view) { // Create Intent // Settings intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form"); intent.putExtra("android.speech.extra.PROMPT", "Speak now"); button.setEnabled(true);// TODO ensure activate search button // .... or search on first match ... // Start the Recognition Activity startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); } }); InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); List<InputMethodInfo> inputMethodInfoList = inputManager .getEnabledInputMethodList(); Vector<String> imes = new Vector<String>(); for (InputMethodInfo i : inputMethodInfoList) { imes.add(i.getServiceName()); Log.d("INPUT-DEBUG", i.getServiceName()); Log.d("INPUT-DEBUG", i.getPackageName()); Log.d("INPUT-DEBUG", i.getSettingsActivity()); } /* * large number of locales - not apparently related to what user had set * up for languages they care about ... List<Locale> locales = new * ArrayList(Arrays.asList(Locale.getAvailableLocales())); for (Locale l * : locales) { Log.d("LOCALE-DEBUG", l.getCountry()); * Log.d("LOCALE-DEBUG", l.getLanguage()); Log.d("LOCALE-DEBUG", * l.getISO3Language()); } */ final TextView lookup_legend_textView = (TextView) findViewById(R.id.main_lookup); final AutoCompleteTextView lookup_textView = (AutoCompleteTextView) findViewById(R.id.lookup); lookup_textView.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (v.equals(lookup_textView)) { if (!TextUtils .isEmpty(((AutoCompleteTextView) v).getText())) { button.setEnabled(true); } if (event != null) { onClick(v); Log.d("KEY-DEBUG", "enter key pressed"); return true; } } return false; } }); // lookup_textView.setOnKeyListener(new OnKeyListener() { // // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (v.equals(lookup_textView)) { // if (!TextUtils // .isEmpty(((AutoCompleteTextView) v).getText())) { // button.setEnabled(true); // } // switch (keyCode) { // case KeyEvent.KEYCODE_ENTER: // if (event.getAction() == KeyEvent.ACTION_UP) { // onClick(v); // Log.d("KEY-DEBUG", "enter key pressed"); // return true; // } // } // } // return false; // } // }); lookup_textView.setSelectAllOnFocus(true); if (!TextUtils.isEmpty(query_string)) { lookup_textView.setText(query_string); button.setEnabled(true); } Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getCountry()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getLanguage()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getISO3Language()); PackageManager pm = getPackageManager(); /* PackageInfo pi; try { pi = pm .getPackageInfo("fm.smart.r1", PackageManager.GET_ACTIVITIES); for (ActivityInfo a : pi.activities) { Log.d("PACKAGE-DEBUG", a.name); } pi = pm.getPackageInfo("android.speech", PackageManager.GET_ACTIVITIES); for (ActivityInfo a : pi.activities) { Log.d("PACKAGE-DEBUG", a.name); } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ // languages = new Vector<String>(Utils.LANGUAGE_MAP.keySet()); languages = Utils.POPULAR_LANGUAGES; Collections.sort(languages); ArrayAdapter<String> search_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner search_language_spinner = (Spinner) findViewById(R.id.search_language); ArrayAdapter<String> result_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner result_language_spinner = (Spinner) findViewById(R.id.result_language); search_language_spinner.setAdapter(search_language_adapter); result_language_spinner.setAdapter(result_language_adapter); search_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + languages.get(position) + " or " + result_language_spinner.getSelectedItem() + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); result_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + search_language_spinner.getSelectedItem() + " or " + languages.get(position) + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); search_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.search_lang))); result_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.result_lang))); loadRecentLanguagePairs(imes); updateSpinner(); // TODO // switch autocompletes to spinners on main languages we support, // and have a change listener update the lookup text }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("ACTIVITY-DEBUG", "onCreate"); if (!Main.isNotLoggedIn(this)) { Main.getDefaultStudyList(this); } ExceptionHandler.register(this); menus = new SmartFmMenus(this); this.setContentView(R.layout.main); final Intent queryIntent = getIntent(); final String queryAction = queryIntent.getAction(); Bundle extras = queryIntent.getExtras(); String listType = null; if (extras != null) { listType = (String) extras.get("list_type"); query_string = (String) extras.get("query_string"); if (!TextUtils.isEmpty(query_string)) { query_string = query_string.replaceAll("\\++", " "); } } if (listType == null) { // hansleOauth(queryIntent); } if (Intent.ACTION_SEARCH.equals(queryAction)) { doSearchQuery(queryIntent, "onCreate()"); } else if (listType != null && listType.equals("recent_lists")) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading recent lists...", true, true); if (list_download == null) { list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.recentLists(); } }; } list_download.start(); } else if ((listType != null && listType.equals("my_study_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog .show(Main.this, "Please wait...", "Downloading " + username(this) + "'s lists...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userStudyLists(username(Main.this)); } }; list_download.start(); } else if ((listType != null && listType.equals("my_created_lists"))) { // Display an indeterminate Progress-Dialog myProgressDialog = ProgressDialog.show(Main.this, "Please wait...", "Downloading lists created by " + username(this) + "...", true, true); list_download = new ListDownload(this, myProgressDialog) { public Vector<Node> downloadCall(SmartFmLookup lookup) { return lookup.userLists(username(Main.this)); } }; list_download.start(); } final ImageButton button = (ImageButton) findViewById(R.id.main_submit); button.setOnClickListener(this); // button.setEnabled(false); ImageButton vbutton = (ImageButton) findViewById(R.id.main_voice); final Intent intent = new Intent( "android.speech.action.RECOGNIZE_SPEECH"); ComponentName cname = intent.resolveActivity(getPackageManager()); if (cname != null) { Log.d("SPEECH-DEBUG", cname.toString()); } else { Log.d("SPEECH-DEBUG", "NULL"); vbutton.setEnabled(false); } // TODO some way to test if voice is available and disable // android.content.ActivityNotFoundException: No Activity found to // handle Intent { action=android.speech.action.RECOGNIZE_SPEECH (has // extras) } // test for presence of activities? vbutton.setOnClickListener(new OnClickListener() { public void onClick(View view) { // Create Intent // Settings intent.putExtra("android.speech.extra.LANGUAGE_MODEL", "free_form"); intent.putExtra("android.speech.extra.PROMPT", "Speak now"); button.setEnabled(true);// TODO ensure activate search button // .... or search on first match ... // Start the Recognition Activity startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); } }); InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); List<InputMethodInfo> inputMethodInfoList = inputManager .getEnabledInputMethodList(); Vector<String> imes = new Vector<String>(); for (InputMethodInfo i : inputMethodInfoList) { imes.add(i.getServiceName()); try { Log.d("INPUT-DEBUG", i.getServiceName()); Log.d("INPUT-DEBUG", i.getPackageName()); Log.d("INPUT-DEBUG", i.getSettingsActivity()); } catch (Exception e) { e.printStackTrace(); } } /* * large number of locales - not apparently related to what user had set * up for languages they care about ... List<Locale> locales = new * ArrayList(Arrays.asList(Locale.getAvailableLocales())); for (Locale l * : locales) { Log.d("LOCALE-DEBUG", l.getCountry()); * Log.d("LOCALE-DEBUG", l.getLanguage()); Log.d("LOCALE-DEBUG", * l.getISO3Language()); } */ final TextView lookup_legend_textView = (TextView) findViewById(R.id.main_lookup); final AutoCompleteTextView lookup_textView = (AutoCompleteTextView) findViewById(R.id.lookup); lookup_textView.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (v.equals(lookup_textView)) { if (!TextUtils .isEmpty(((AutoCompleteTextView) v).getText())) { button.setEnabled(true); } if (event != null) { onClick(v); Log.d("KEY-DEBUG", "enter key pressed"); return true; } } return false; } }); // lookup_textView.setOnKeyListener(new OnKeyListener() { // // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (v.equals(lookup_textView)) { // if (!TextUtils // .isEmpty(((AutoCompleteTextView) v).getText())) { // button.setEnabled(true); // } // switch (keyCode) { // case KeyEvent.KEYCODE_ENTER: // if (event.getAction() == KeyEvent.ACTION_UP) { // onClick(v); // Log.d("KEY-DEBUG", "enter key pressed"); // return true; // } // } // } // return false; // } // }); lookup_textView.setSelectAllOnFocus(true); if (!TextUtils.isEmpty(query_string)) { lookup_textView.setText(query_string); button.setEnabled(true); } Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getCountry()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getLanguage()); Log.d("LOCALE-DEFAULT-DEBUG", Locale.getDefault().getISO3Language()); PackageManager pm = getPackageManager(); /* * PackageInfo pi; try { pi = pm .getPackageInfo("fm.smart.r1", * PackageManager.GET_ACTIVITIES); for (ActivityInfo a : pi.activities) * { Log.d("PACKAGE-DEBUG", a.name); } pi = * pm.getPackageInfo("android.speech", PackageManager.GET_ACTIVITIES); * for (ActivityInfo a : pi.activities) { Log.d("PACKAGE-DEBUG", * a.name); } } catch (NameNotFoundException e) { // TODO Auto-generated * catch block e.printStackTrace(); } */ // languages = new Vector<String>(Utils.LANGUAGE_MAP.keySet()); languages = Utils.POPULAR_LANGUAGES; Collections.sort(languages); ArrayAdapter<String> search_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner search_language_spinner = (Spinner) findViewById(R.id.search_language); ArrayAdapter<String> result_language_adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, languages); final Spinner result_language_spinner = (Spinner) findViewById(R.id.result_language); search_language_spinner.setAdapter(search_language_adapter); result_language_spinner.setAdapter(result_language_adapter); search_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + languages.get(position) + " or " + result_language_spinner.getSelectedItem() + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); result_language_spinner .setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lookup_legend_textView.setText("Search " + search_language_spinner.getSelectedItem() + " or " + languages.get(position) + " words"); } public void onNothingSelected(AdapterView<?> parent) { } }); search_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.search_lang))); result_language_spinner.setSelection(languages .indexOf(Utils.INV_LANGUAGE_MAP.get(Main.result_lang))); loadRecentLanguagePairs(imes); updateSpinner(); // TODO // switch autocompletes to spinners on main languages we support, // and have a change listener update the lookup text }
diff --git a/src/community/dxf/src/main/java/org/geoserver/wfs/response/dxf/util/JulianDate.java b/src/community/dxf/src/main/java/org/geoserver/wfs/response/dxf/util/JulianDate.java index cb5bcf2774..f6068e1f62 100644 --- a/src/community/dxf/src/main/java/org/geoserver/wfs/response/dxf/util/JulianDate.java +++ b/src/community/dxf/src/main/java/org/geoserver/wfs/response/dxf/util/JulianDate.java @@ -1,47 +1,47 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.geoserver.wfs.response.dxf.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Julian Date Converter. * Formulas got from http://en.wikipedia.org/wiki/Julian_day * * @author Mauro Bartolomeoli, [email protected] * */ public class JulianDate { /** * Converts a Date to JD format. * @param dt * @return */ public static double toJulian(Date dt) { Calendar calendar = new GregorianCalendar(); calendar.setTime(dt); - int month = calendar.get(Calendar.MONTH + 1); + int month = calendar.get(Calendar.MONTH)+1; int year = calendar.get(Calendar.YEAR); int day = calendar.get(Calendar.DAY_OF_MONTH); // precalc some parameters double a = Math.floor((14 - month) / 12); double y = year + 4800 - a; double m = month + 12 * a - 3; // julian day number double jdn = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045; int hour = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); double jd = jdn + ((hour - 12) / 24) + minutes / 1440 + seconds / 86400; return jd; } }
true
true
public static double toJulian(Date dt) { Calendar calendar = new GregorianCalendar(); calendar.setTime(dt); int month = calendar.get(Calendar.MONTH + 1); int year = calendar.get(Calendar.YEAR); int day = calendar.get(Calendar.DAY_OF_MONTH); // precalc some parameters double a = Math.floor((14 - month) / 12); double y = year + 4800 - a; double m = month + 12 * a - 3; // julian day number double jdn = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045; int hour = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); double jd = jdn + ((hour - 12) / 24) + minutes / 1440 + seconds / 86400; return jd; }
public static double toJulian(Date dt) { Calendar calendar = new GregorianCalendar(); calendar.setTime(dt); int month = calendar.get(Calendar.MONTH)+1; int year = calendar.get(Calendar.YEAR); int day = calendar.get(Calendar.DAY_OF_MONTH); // precalc some parameters double a = Math.floor((14 - month) / 12); double y = year + 4800 - a; double m = month + 12 * a - 3; // julian day number double jdn = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045; int hour = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); int seconds = calendar.get(Calendar.SECOND); double jd = jdn + ((hour - 12) / 24) + minutes / 1440 + seconds / 86400; return jd; }
diff --git a/src/main/java/com/sampullara/cli/Args.java b/src/main/java/com/sampullara/cli/Args.java index 43e33a5..6c8b79a 100644 --- a/src/main/java/com/sampullara/cli/Args.java +++ b/src/main/java/com/sampullara/cli/Args.java @@ -1,343 +1,348 @@ /* * Copyright (c) 2005, Sam Pullara. All Rights Reserved. * You may modify and redistribute as long as this attribution remains. */ package com.sampullara.cli; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.*; import java.util.*; public class Args { /** * Parse a set of arguments and populate the target with the appropriate values. * * @param target Either an instance or a class * @param args The arguments you want to parse and populate * @return The list of arguments that were not consumed */ public static List<String> parse(Object target, String[] args) { List<String> arguments = new ArrayList<String>(); arguments.addAll(Arrays.asList(args)); Class clazz; if (target instanceof Class) { clazz = (Class) target; } else { clazz = target.getClass(); try { BeanInfo info = Introspector.getBeanInfo(clazz); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { processProperty(target, pd, arguments); } } catch (IntrospectionException e) { // If its not a JavaBean we ignore it } } for (Field field : clazz.getDeclaredFields()) { processField(target, field, arguments); } for (String argument : arguments) { if (argument.startsWith("-")) { throw new IllegalArgumentException("Invalid argument: " + argument); } } return arguments; } private static void processField(Object target, Field field, List<String> arguments) { Argument argument = field.getAnnotation(Argument.class); if (argument != null) { boolean set = false; for (Iterator<String> i = arguments.iterator(); i.hasNext();) { String arg = i.next(); String prefix = argument.prefix(); String delimiter = argument.delimiter(); if (arg.startsWith(prefix)) { Object value; String name = getName(argument, field); String alias = getAlias(argument); arg = arg.substring(prefix.length()); if (arg.equals(name) || (alias != null && arg.equals(alias))) { i.remove(); Class type = field.getType(); value = consumeArgumentValue(type, argument, i); setField(type, field, target, value, delimiter); set = true; } if (set) break; } } if (!set && argument.required()) { String name = getName(argument, field); throw new IllegalArgumentException("You must set argument " + name); } } } private static void processProperty(Object target, PropertyDescriptor property, List<String> arguments) { Method writeMethod = property.getWriteMethod(); if (writeMethod != null) { Argument argument = writeMethod.getAnnotation(Argument.class); if (argument != null) { boolean set = false; for (Iterator<String> i = arguments.iterator(); i.hasNext();) { String arg = i.next(); String prefix = argument.prefix(); String delimiter = argument.delimiter(); if (arg.startsWith(prefix)) { Object value; String name = getName(argument, property); String alias = getAlias(argument); arg = arg.substring(prefix.length()); if (arg.equals(name) || (alias != null && arg.equals(alias))) { i.remove(); Class type = property.getPropertyType(); value = consumeArgumentValue(type, argument, i); setProperty(type, property, target, value, delimiter); set = true; } if (set) break; } } if (!set && argument.required()) { String name = getName(argument, property); throw new IllegalArgumentException("You must set argument " + name); } } } } /** * Generate usage information based on the target annotations. * * @param target An instance or class. */ public static void usage(Object target) { Class clazz; if (target instanceof Class) { clazz = (Class) target; } else { clazz = target.getClass(); } System.err.println("Usage: " + clazz.getName()); for (Field field : clazz.getDeclaredFields()) { fieldUsage(target, field); } try { BeanInfo info = Introspector.getBeanInfo(clazz); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { propertyUsage(target, pd); } } catch (IntrospectionException e) { // If its not a JavaBean we ignore it } } private static void fieldUsage(Object target, Field field) { Argument argument = field.getAnnotation(Argument.class); if (argument != null) { String name = getName(argument, field); String alias = getAlias(argument); String prefix = argument.prefix(); String delimiter = argument.delimiter(); String description = argument.description(); makeAccessible(field); try { Object defaultValue = field.get(target); Class type = field.getType(); propertyUsage(prefix, name, alias, type, delimiter, description, defaultValue); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not use thie field " + field + " as an argument field", e); } } } private static void propertyUsage(Object target, PropertyDescriptor field) { Method writeMethod = field.getWriteMethod(); if (writeMethod != null) { Argument argument = writeMethod.getAnnotation(Argument.class); if (argument != null) { String name = getName(argument, field); String alias = getAlias(argument); String prefix = argument.prefix(); String delimiter = argument.delimiter(); String description = argument.description(); try { Method readMethod = field.getReadMethod(); Object defaultValue; if (readMethod == null) { defaultValue = null; } else { defaultValue = readMethod.invoke(target, (Object[]) null); } Class type = field.getPropertyType(); propertyUsage(prefix, name, alias, type, delimiter, description, defaultValue); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not use thie field " + field + " as an argument field", e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Could not get default value for " + field, e); } } } } private static void propertyUsage(String prefix, String name, String alias, Class type, String delimiter, String description, Object defaultValue) { StringBuilder sb = new StringBuilder(" "); sb.append(prefix); sb.append(name); if (alias != null) { sb.append(" ("); sb.append(prefix); sb.append(alias); sb.append(")"); } if (type == Boolean.TYPE || type == Boolean.class) { sb.append(" [flag] "); sb.append(description); } else { sb.append(" ["); if (type.isArray()) { String typeName = getTypeName(type.getComponentType()); sb.append(typeName); sb.append("["); sb.append(delimiter); sb.append("]"); } else { String typeName = getTypeName(type); sb.append(typeName); } sb.append("] "); sb.append(description); if (defaultValue != null) { sb.append(" ("); if (type.isArray()) { - sb.append(Arrays.asList(defaultValue)); + List list = new ArrayList(); + int len = Array.getLength(defaultValue); + for (int i = 0; i < len; i++) { + list.add(Array.get(defaultValue, i)); + } + sb.append(list); } else { sb.append(defaultValue); } sb.append(")"); } } System.err.println(sb); } private static String getTypeName(Class type) { String typeName = type.getName(); int beginIndex = typeName.lastIndexOf("."); typeName = typeName.substring(beginIndex + 1); return typeName; } static String getName(Argument argument, PropertyDescriptor property) { String name = argument.value(); if (name.equals("")) { name = property.getName(); } return name; } private static Object consumeArgumentValue(Class type, Argument argument, Iterator<String> i) { Object value; if (type == Boolean.TYPE || type == Boolean.class) { value = true; } else { if (i.hasNext()) { value = i.next(); i.remove(); } else { throw new IllegalArgumentException("Must have a value for non-boolean argument " + argument.value()); } } return value; } static void setProperty(Class type, PropertyDescriptor property, Object target, Object value, String delimiter) { try { value = getValue(type, value, delimiter); property.getWriteMethod().invoke(target, value); } catch (IllegalAccessException iae) { throw new IllegalArgumentException("Could not set property " + property, iae); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Could not find constructor in class " + type.getName() + " that takes a string", e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Failed to validate argument " + value + " for " + property); } } static String getAlias(Argument argument) { String alias = argument.alias(); if (alias.equals("")) { alias = null; } return alias; } static String getName(Argument argument, Field field) { String name = argument.value(); if (name.equals("")) { name = field.getName(); } return name; } static void setField(Class type, Field field, Object target, Object value, String delimiter) { makeAccessible(field); try { value = getValue(type, value, delimiter); field.set(target, value); } catch (IllegalAccessException iae) { throw new IllegalArgumentException("Could not set field " + field, iae); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Could not find constructor in class " + type.getName() + " that takes a string", e); } } private static Object getValue(Class type, Object value, String delimiter) throws NoSuchMethodException { if (type != String.class && type != Boolean.class && type != Boolean.TYPE) { if (type.isArray()) { String string = (String) value; String[] strings = string.split(delimiter); type = type.getComponentType(); if (type == String.class) { value = strings; } else { Object[] array = (Object[]) Array.newInstance(type, strings.length); for (int i = 0; i < array.length; i++) { array[i] = createValue(type, strings[i]); } value = array; } } else { value = createValue(type, value); } } return value; } private static Object createValue(Class type, Object value) throws NoSuchMethodException { Constructor init = type.getDeclaredConstructor(String.class); try { value = init.newInstance(value); } catch (Exception e) { throw new IllegalArgumentException("Failed to convert " + value + " to type " + type.getName(), e); } return value; } private static void makeAccessible(AccessibleObject ao) { if (ao instanceof Member) { Member member = (Member) ao; if (!Modifier.isPublic(member.getModifiers())) { ao.setAccessible(true); } } } }
true
true
private static void propertyUsage(String prefix, String name, String alias, Class type, String delimiter, String description, Object defaultValue) { StringBuilder sb = new StringBuilder(" "); sb.append(prefix); sb.append(name); if (alias != null) { sb.append(" ("); sb.append(prefix); sb.append(alias); sb.append(")"); } if (type == Boolean.TYPE || type == Boolean.class) { sb.append(" [flag] "); sb.append(description); } else { sb.append(" ["); if (type.isArray()) { String typeName = getTypeName(type.getComponentType()); sb.append(typeName); sb.append("["); sb.append(delimiter); sb.append("]"); } else { String typeName = getTypeName(type); sb.append(typeName); } sb.append("] "); sb.append(description); if (defaultValue != null) { sb.append(" ("); if (type.isArray()) { sb.append(Arrays.asList(defaultValue)); } else { sb.append(defaultValue); } sb.append(")"); } } System.err.println(sb); }
private static void propertyUsage(String prefix, String name, String alias, Class type, String delimiter, String description, Object defaultValue) { StringBuilder sb = new StringBuilder(" "); sb.append(prefix); sb.append(name); if (alias != null) { sb.append(" ("); sb.append(prefix); sb.append(alias); sb.append(")"); } if (type == Boolean.TYPE || type == Boolean.class) { sb.append(" [flag] "); sb.append(description); } else { sb.append(" ["); if (type.isArray()) { String typeName = getTypeName(type.getComponentType()); sb.append(typeName); sb.append("["); sb.append(delimiter); sb.append("]"); } else { String typeName = getTypeName(type); sb.append(typeName); } sb.append("] "); sb.append(description); if (defaultValue != null) { sb.append(" ("); if (type.isArray()) { List list = new ArrayList(); int len = Array.getLength(defaultValue); for (int i = 0; i < len; i++) { list.add(Array.get(defaultValue, i)); } sb.append(list); } else { sb.append(defaultValue); } sb.append(")"); } } System.err.println(sb); }
diff --git a/android/src/com/google/android/apps/iosched/io/SessionsHandler.java b/android/src/com/google/android/apps/iosched/io/SessionsHandler.java index c6bcd5c..e432254 100644 --- a/android/src/com/google/android/apps/iosched/io/SessionsHandler.java +++ b/android/src/com/google/android/apps/iosched/io/SessionsHandler.java @@ -1,382 +1,382 @@ /* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import android.content.ContentProviderOperation; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import android.text.format.Time; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.gson.Gson; import no.java.schedule.R; import no.java.schedule.io.model.JZLabel; import no.java.schedule.io.model.JZSessionsResponse; import no.java.schedule.io.model.JZSessionsResult; import no.java.schedule.io.model.JZSpeaker; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; /** * Handler that parses session JSON data into a list of content provider operations. */ public class SessionsHandler extends JSONHandler { private static final String TAG = makeLogTag(SessionsHandler.class); private static final String BASE_SESSION_URL = "https://developers.google.com/events/io/sessions/"; private static final String EVENT_TYPE_KEYNOTE = "keynote"; private static final String EVENT_TYPE_CODELAB = "codelab"; private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1; private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2; private static final Time sTime = new Time(); private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//"); private boolean mLocal; private boolean mThrowIfNoAuthToken; public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) { super(context); mLocal = local; mThrowIfNoAuthToken = throwIfNoAuthToken; } public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); JZSessionsResponse response = new Gson().fromJson(json, JZSessionsResponse.class); LOGI(TAG, "Updating sessions data"); // by default retain locally starred if local sync boolean retainLocallyStarredSessions = true; //mLocal; if (response.error != null && response.error.isJsonPrimitive()) { String errorMessageLower = response.error.getAsString().toLowerCase(); if (!mLocal && (errorMessageLower.contains("no profile") || errorMessageLower.contains("no auth token"))) { // There was some authentication issue; retain locally starred sessions. retainLocallyStarredSessions = true; LOGW(TAG, "The user has no developers.google.com profile or this call is " + "not authenticated. Retaining locally starred sessions."); } if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) { throw new HandlerException.UnauthorizedException("No auth token but we tried " + "authenticating. Need to invalidate the auth token."); } } Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { // Collect the list of current starred sessions Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created block IDs Set<String> blockIds = new HashSet<String>(); for (JZSessionsResult event : response.sessions) { int flags = 0; if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(event.id) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } String sessionId = event.id; if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title - fix special titles String sessionTitle = event.title; //if (EVENT_TYPE_CODELAB.equals(event.event_type)) { // sessionTitle = mContext.getString( // R.string.codelab_title_template, sessionTitle); //} // Whether or not it's in the schedule boolean inSchedule = "Y".equals(event.attending); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } // Special handing of sessiosn that should always be in schedule //if (EVENT_TYPE_KEYNOTE.equals(event.event_type)) { // // Keynotes are always in your schedule. // inSchedule = true; //} // Special sorting of sessions based on tracks etc // Re-order session tracks so that Code Lab is last //if (event.labels != null) { // Arrays.sort(event.track, sTracksComparator); //} // Hashtags String hashtags = ""; //if (event.labels != null) { // StringBuilder hashtagsBuilder = new StringBuilder(); // for (JZLabel trackName : event.labels) { // // hashtagsBuilder.append(" #"); // hashtagsBuilder.append( // ScheduleContract.Tracks.generateTrackId(trackName)); // } // hashtags = hashtagsBuilder.toString().trim(); //} // Pre-reqs String prereqs = ""; //if (event.prereq != null && event.prereq.length > 0) { // StringBuilder sb = new StringBuilder(); // for (String prereq : event.prereq) { // sb.append(prereq); // sb.append(" "); // } // prereqs = sb.toString(); // if (prereqs.startsWith("<br>")) { // prereqs = prereqs.substring(4); // } //} String youtubeUrl = null; //if (event.youtube_url != null && event.youtube_url.length > 0) { // youtubeUrl = event.youtube_url[0]; //} long sessionStartTime=0; long sessionEndTime=0; //TODO handle sessions without timeslot long originalSessionEndTime=1; long originalSessionStartTime=1; if (event.start!=null && event.end!=null){ originalSessionStartTime = event.start.millis(); originalSessionEndTime = event.end.millis(); sessionStartTime = event.start.millis();//parseTime(event.start_date, event.start_time); sessionEndTime = event.end.millis();//event.end_date, event.end_time); } if ("Quickie".equals(event.format)){ sessionStartTime=snapStartTime(sessionStartTime); sessionEndTime=snapEndTime(sessionEndTime); } // Insert session info final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, event.format) - .withValue(Sessions.SESSION_LEVEL, event.level.displayName)//TODO + .withValue(Sessions.SESSION_LEVEL, event.level!=null ? event.level.displayName : "")//TODO .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, event.bodyHtml) .withValue(Sessions.SESSION_TAGS, event.labelstrings()) .withValue(Sessions.SESSION_URL,event.sessionHtmlUrl.toString()) .withValue(Sessions.SESSION_LIVESTREAM_URL, "") .withValue(Sessions.SESSION_REQUIREMENTS, prereqs) .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_HASHTAGS, hashtags) .withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, "") .withValue(Sessions.SESSION_NOTES_URL, "") .withValue(Sessions.ROOM_ID, sanitizeId(event.room)) .withValue(Sessions.START, originalSessionStartTime) .withValue(Sessions.END, originalSessionEndTime); String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId)) { String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_CODE_LAB; blockTitle = mContext .getString(R.string.schedule_block_title_code_labs); } else { blockType = ParserUtils.BLOCK_TYPE_SESSION; blockTitle = mContext.getString(R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } builder.withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); if (event.speakers != null) { for (JZSpeaker speaker : event.speakers) { //speaker = sRemoveSpeakerIdPrefixPattern.matcher(speaker).replaceAll(""); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speaker.name).build());//TODO ID for speakers } } // Replace all session tracks final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); if (event.labels != null) { for (JZLabel trackName : event.labels) { //if (trackName.contains("Code Lab")) { // trackName = "Code Labs"; //} String trackId = ScheduleContract.Tracks.generateTrackId(trackName.id); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } } return batch; } private static long snapStartTime(final long pSessionStartTime) { Date date = new Date(pSessionStartTime); int minutes = (date.getHours()-9)*60+(date.getMinutes()-0); int offset = minutes % (60+20); date.setMinutes(date.getMinutes()-offset); return date.getTime(); } private static long snapEndTime(final long pSessionEndTime) { Date date = new Date(pSessionEndTime); int minutes = (date.getHours()-9)*60+(date.getMinutes()+0); int offset = minutes % (60+20); date.setMinutes(date.getMinutes()+60-offset); return date.getTime(); } private Comparator<String> sTracksComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { // TODO: improve performance of this comparator return (s1.contains("Code Lab") ? "z" : s1).compareTo( (s2.contains("Code Lab") ? "z" : s2)); } }; private String makeSessionUrl(String sessionId) { if (TextUtils.isEmpty(sessionId)) { return null; } return BASE_SESSION_URL + sessionId; } private static long parseTime(String date, String time) { //change to this format : 2011-05-10T07:00:00.000-07:00 int index = time.indexOf(":"); if (index == 1) { time = "0" + time; } final String composed = String.format("%sT%s:00.000-07:00", date, time); //return sTimeFormat.parse(composed).getTime(); sTime.parse3339(composed); return sTime.toMillis(false); } }
true
true
public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); JZSessionsResponse response = new Gson().fromJson(json, JZSessionsResponse.class); LOGI(TAG, "Updating sessions data"); // by default retain locally starred if local sync boolean retainLocallyStarredSessions = true; //mLocal; if (response.error != null && response.error.isJsonPrimitive()) { String errorMessageLower = response.error.getAsString().toLowerCase(); if (!mLocal && (errorMessageLower.contains("no profile") || errorMessageLower.contains("no auth token"))) { // There was some authentication issue; retain locally starred sessions. retainLocallyStarredSessions = true; LOGW(TAG, "The user has no developers.google.com profile or this call is " + "not authenticated. Retaining locally starred sessions."); } if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) { throw new HandlerException.UnauthorizedException("No auth token but we tried " + "authenticating. Need to invalidate the auth token."); } } Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { // Collect the list of current starred sessions Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created block IDs Set<String> blockIds = new HashSet<String>(); for (JZSessionsResult event : response.sessions) { int flags = 0; if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(event.id) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } String sessionId = event.id; if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title - fix special titles String sessionTitle = event.title; //if (EVENT_TYPE_CODELAB.equals(event.event_type)) { // sessionTitle = mContext.getString( // R.string.codelab_title_template, sessionTitle); //} // Whether or not it's in the schedule boolean inSchedule = "Y".equals(event.attending); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } // Special handing of sessiosn that should always be in schedule //if (EVENT_TYPE_KEYNOTE.equals(event.event_type)) { // // Keynotes are always in your schedule. // inSchedule = true; //} // Special sorting of sessions based on tracks etc // Re-order session tracks so that Code Lab is last //if (event.labels != null) { // Arrays.sort(event.track, sTracksComparator); //} // Hashtags String hashtags = ""; //if (event.labels != null) { // StringBuilder hashtagsBuilder = new StringBuilder(); // for (JZLabel trackName : event.labels) { // // hashtagsBuilder.append(" #"); // hashtagsBuilder.append( // ScheduleContract.Tracks.generateTrackId(trackName)); // } // hashtags = hashtagsBuilder.toString().trim(); //} // Pre-reqs String prereqs = ""; //if (event.prereq != null && event.prereq.length > 0) { // StringBuilder sb = new StringBuilder(); // for (String prereq : event.prereq) { // sb.append(prereq); // sb.append(" "); // } // prereqs = sb.toString(); // if (prereqs.startsWith("<br>")) { // prereqs = prereqs.substring(4); // } //} String youtubeUrl = null; //if (event.youtube_url != null && event.youtube_url.length > 0) { // youtubeUrl = event.youtube_url[0]; //} long sessionStartTime=0; long sessionEndTime=0; //TODO handle sessions without timeslot long originalSessionEndTime=1; long originalSessionStartTime=1; if (event.start!=null && event.end!=null){ originalSessionStartTime = event.start.millis(); originalSessionEndTime = event.end.millis(); sessionStartTime = event.start.millis();//parseTime(event.start_date, event.start_time); sessionEndTime = event.end.millis();//event.end_date, event.end_time); } if ("Quickie".equals(event.format)){ sessionStartTime=snapStartTime(sessionStartTime); sessionEndTime=snapEndTime(sessionEndTime); } // Insert session info final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, event.format) .withValue(Sessions.SESSION_LEVEL, event.level.displayName)//TODO .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, event.bodyHtml) .withValue(Sessions.SESSION_TAGS, event.labelstrings()) .withValue(Sessions.SESSION_URL,event.sessionHtmlUrl.toString()) .withValue(Sessions.SESSION_LIVESTREAM_URL, "") .withValue(Sessions.SESSION_REQUIREMENTS, prereqs) .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_HASHTAGS, hashtags) .withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, "") .withValue(Sessions.SESSION_NOTES_URL, "") .withValue(Sessions.ROOM_ID, sanitizeId(event.room)) .withValue(Sessions.START, originalSessionStartTime) .withValue(Sessions.END, originalSessionEndTime); String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId)) { String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_CODE_LAB; blockTitle = mContext .getString(R.string.schedule_block_title_code_labs); } else { blockType = ParserUtils.BLOCK_TYPE_SESSION; blockTitle = mContext.getString(R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } builder.withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); if (event.speakers != null) { for (JZSpeaker speaker : event.speakers) { //speaker = sRemoveSpeakerIdPrefixPattern.matcher(speaker).replaceAll(""); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speaker.name).build());//TODO ID for speakers } } // Replace all session tracks final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); if (event.labels != null) { for (JZLabel trackName : event.labels) { //if (trackName.contains("Code Lab")) { // trackName = "Code Labs"; //} String trackId = ScheduleContract.Tracks.generateTrackId(trackName.id); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } } return batch; }
public ArrayList<ContentProviderOperation> parse(String json) throws IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); JZSessionsResponse response = new Gson().fromJson(json, JZSessionsResponse.class); LOGI(TAG, "Updating sessions data"); // by default retain locally starred if local sync boolean retainLocallyStarredSessions = true; //mLocal; if (response.error != null && response.error.isJsonPrimitive()) { String errorMessageLower = response.error.getAsString().toLowerCase(); if (!mLocal && (errorMessageLower.contains("no profile") || errorMessageLower.contains("no auth token"))) { // There was some authentication issue; retain locally starred sessions. retainLocallyStarredSessions = true; LOGW(TAG, "The user has no developers.google.com profile or this call is " + "not authenticated. Retaining locally starred sessions."); } if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) { throw new HandlerException.UnauthorizedException("No auth token but we tried " + "authenticating. Need to invalidate the auth token."); } } Set<String> starredSessionIds = new HashSet<String>(); if (retainLocallyStarredSessions) { // Collect the list of current starred sessions Cursor starredSessionsCursor = mContext.getContentResolver().query( Sessions.CONTENT_STARRED_URI, new String[]{ScheduleContract.Sessions.SESSION_ID}, null, null, null); while (starredSessionsCursor.moveToNext()) { starredSessionIds.add(starredSessionsCursor.getString(0)); } starredSessionsCursor.close(); } // Clear out existing sessions batch.add(ContentProviderOperation .newDelete(ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.CONTENT_URI)) .build()); // Maintain a list of created block IDs Set<String> blockIds = new HashSet<String>(); for (JZSessionsResult event : response.sessions) { int flags = 0; if (retainLocallyStarredSessions) { flags = (starredSessionIds.contains(event.id) ? PARSE_FLAG_FORCE_SCHEDULE_ADD : PARSE_FLAG_FORCE_SCHEDULE_REMOVE); } String sessionId = event.id; if (TextUtils.isEmpty(sessionId)) { LOGW(TAG, "Found session with empty ID in API response."); continue; } // Session title - fix special titles String sessionTitle = event.title; //if (EVENT_TYPE_CODELAB.equals(event.event_type)) { // sessionTitle = mContext.getString( // R.string.codelab_title_template, sessionTitle); //} // Whether or not it's in the schedule boolean inSchedule = "Y".equals(event.attending); if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0 || (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) { inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0; } // Special handing of sessiosn that should always be in schedule //if (EVENT_TYPE_KEYNOTE.equals(event.event_type)) { // // Keynotes are always in your schedule. // inSchedule = true; //} // Special sorting of sessions based on tracks etc // Re-order session tracks so that Code Lab is last //if (event.labels != null) { // Arrays.sort(event.track, sTracksComparator); //} // Hashtags String hashtags = ""; //if (event.labels != null) { // StringBuilder hashtagsBuilder = new StringBuilder(); // for (JZLabel trackName : event.labels) { // // hashtagsBuilder.append(" #"); // hashtagsBuilder.append( // ScheduleContract.Tracks.generateTrackId(trackName)); // } // hashtags = hashtagsBuilder.toString().trim(); //} // Pre-reqs String prereqs = ""; //if (event.prereq != null && event.prereq.length > 0) { // StringBuilder sb = new StringBuilder(); // for (String prereq : event.prereq) { // sb.append(prereq); // sb.append(" "); // } // prereqs = sb.toString(); // if (prereqs.startsWith("<br>")) { // prereqs = prereqs.substring(4); // } //} String youtubeUrl = null; //if (event.youtube_url != null && event.youtube_url.length > 0) { // youtubeUrl = event.youtube_url[0]; //} long sessionStartTime=0; long sessionEndTime=0; //TODO handle sessions without timeslot long originalSessionEndTime=1; long originalSessionStartTime=1; if (event.start!=null && event.end!=null){ originalSessionStartTime = event.start.millis(); originalSessionEndTime = event.end.millis(); sessionStartTime = event.start.millis();//parseTime(event.start_date, event.start_time); sessionEndTime = event.end.millis();//event.end_date, event.end_time); } if ("Quickie".equals(event.format)){ sessionStartTime=snapStartTime(sessionStartTime); sessionEndTime=snapEndTime(sessionEndTime); } // Insert session info final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(ScheduleContract .addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI)) .withValue(SyncColumns.UPDATED, System.currentTimeMillis()) .withValue(Sessions.SESSION_ID, sessionId) .withValue(Sessions.SESSION_TYPE, event.format) .withValue(Sessions.SESSION_LEVEL, event.level!=null ? event.level.displayName : "")//TODO .withValue(Sessions.SESSION_TITLE, sessionTitle) .withValue(Sessions.SESSION_ABSTRACT, event.bodyHtml) .withValue(Sessions.SESSION_TAGS, event.labelstrings()) .withValue(Sessions.SESSION_URL,event.sessionHtmlUrl.toString()) .withValue(Sessions.SESSION_LIVESTREAM_URL, "") .withValue(Sessions.SESSION_REQUIREMENTS, prereqs) .withValue(Sessions.SESSION_STARRED, inSchedule) .withValue(Sessions.SESSION_HASHTAGS, hashtags) .withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl) .withValue(Sessions.SESSION_PDF_URL, "") .withValue(Sessions.SESSION_NOTES_URL, "") .withValue(Sessions.ROOM_ID, sanitizeId(event.room)) .withValue(Sessions.START, originalSessionStartTime) .withValue(Sessions.END, originalSessionEndTime); String blockId = ScheduleContract.Blocks.generateBlockId( sessionStartTime, sessionEndTime); if (!blockIds.contains(blockId)) { String blockType; String blockTitle; if (EVENT_TYPE_KEYNOTE.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_KEYNOTE; blockTitle = mContext.getString(R.string.schedule_block_title_keynote); } else if (EVENT_TYPE_CODELAB.equals(event.format)) { blockType = ParserUtils.BLOCK_TYPE_CODE_LAB; blockTitle = mContext .getString(R.string.schedule_block_title_code_labs); } else { blockType = ParserUtils.BLOCK_TYPE_SESSION; blockTitle = mContext.getString(R.string.schedule_block_title_sessions); } batch.add(ContentProviderOperation .newInsert(ScheduleContract.Blocks.CONTENT_URI) .withValue(ScheduleContract.Blocks.BLOCK_ID, blockId) .withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType) .withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle) .withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime) .withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime) .build()); blockIds.add(blockId); } builder.withValue(Sessions.BLOCK_ID, blockId); batch.add(builder.build()); // Replace all session speakers final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); batch.add(ContentProviderOperation .newDelete(ScheduleContract .addCallerIsSyncAdapterParameter(sessionSpeakersUri)) .build()); if (event.speakers != null) { for (JZSpeaker speaker : event.speakers) { //speaker = sRemoveSpeakerIdPrefixPattern.matcher(speaker).replaceAll(""); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speaker.name).build());//TODO ID for speakers } } // Replace all session tracks final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter( Sessions.buildTracksDirUri(sessionId)); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); if (event.labels != null) { for (JZLabel trackName : event.labels) { //if (trackName.contains("Code Lab")) { // trackName = "Code Labs"; //} String trackId = ScheduleContract.Tracks.generateTrackId(trackName.id); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } } return batch; }
diff --git a/geopaparazzilibrary/src/eu/geopaparazzi/library/util/ResourcesManager.java b/geopaparazzilibrary/src/eu/geopaparazzi/library/util/ResourcesManager.java index b11ef7ea..f243190d 100755 --- a/geopaparazzilibrary/src/eu/geopaparazzi/library/util/ResourcesManager.java +++ b/geopaparazzilibrary/src/eu/geopaparazzi/library/util/ResourcesManager.java @@ -1,372 +1,373 @@ /* * Geopaparazzi - Digital field mapping on Android based devices * Copyright (C) 2010 HydroloGIS (www.hydrologis.com) * * 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 eu.geopaparazzi.library.util; import static eu.geopaparazzi.library.util.LibraryConstants.PREFS_KEY_BASEFOLDER; import static eu.geopaparazzi.library.util.LibraryConstants.PREFS_KEY_CUSTOM_EXTERNALSTORAGE; import static eu.geopaparazzi.library.util.Utilities.messageDialog; import java.io.File; import java.io.IOException; import java.io.Serializable; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import eu.geopaparazzi.library.R; import eu.geopaparazzi.library.database.GPLog; /** * Singleton that takes care of resources management. * * <p>It creates a folder structure with possible database and log file names.</p> * * @author Andrea Antonello (www.hydrologis.com) */ public class ResourcesManager implements Serializable { private static final long serialVersionUID = 1L; private static final String PATH_MAPS = "maps"; //$NON-NLS-1$ private static final String PATH_MEDIA = "media"; //$NON-NLS-1$ private File applicationDir; private File databaseFile; private File mediaDir; private File mapsDir; private File exportDir; private static ResourcesManager resourcesManager; private String applicationLabel; private static boolean useInternalMemory = true; private File sdcardDir; private boolean createdApplicationDirOnInit = false; public static void setUseInternalMemory( boolean useInternalMemory ) { ResourcesManager.useInternalMemory = useInternalMemory; } /** * The getter for the {@link ResourcesManager} singleton. * * <p>This is a singletone but might require to be recreated * in every moment of the application. This is due to the fact * that when the application looses focus (for example because of * an incoming call, and therefore at a random moment, if the memory * is too low, the parent activity could have been killed by * the system in background. In which case we need to recreate it.) * * @param context the context to refer to. * @return the {@link ResourcesManager} instance. * @throws Exception */ public synchronized static ResourcesManager getInstance( Context context ) throws Exception { if (resourcesManager == null) { resourcesManager = new ResourcesManager(context); } return resourcesManager; } public static void resetManager() { resourcesManager = null; } public String getApplicationName() { return applicationLabel; } private ResourcesManager( Context context ) throws Exception { Context appContext = context.getApplicationContext(); ApplicationInfo appInfo = appContext.getApplicationInfo(); String packageName = appInfo.packageName; int lastDot = packageName.lastIndexOf('.'); applicationLabel = packageName.replace('.', '_'); if (lastDot != -1) { applicationLabel = packageName.substring(lastDot + 1, packageName.length()); } applicationLabel = applicationLabel.toLowerCase(); String databaseName = applicationLabel + ".db"; //$NON-NLS-1$ /* * take care to create all the folders needed * * The default structure is: * * sdcard * | * |-- applicationname * | | * | |--- applicationname.db * | |--- media (folder) * | |--- export (folder) * | `--- debug.log * `-- mapsdir */ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext); String baseFolder = preferences.getString(PREFS_KEY_BASEFOLDER, ""); //$NON-NLS-1$ applicationDir = new File(baseFolder); File parentFile = applicationDir.getParentFile(); boolean parentExists = false; boolean parentCanWrite = false; if (parentFile != null) { parentExists = parentFile.exists(); parentCanWrite = parentFile.canWrite(); } // the folder doesn't exist for some reason, fallback on default String state = Environment.getExternalStorageState(); if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", state); } boolean mExternalStorageAvailable; boolean mExternalStorageWriteable; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { mExternalStorageAvailable = mExternalStorageWriteable = false; } String cantCreateSdcardmsg = appContext.getResources().getString(R.string.cantcreate_sdcard); File possibleApplicationDir; if (mExternalStorageAvailable && mExternalStorageWriteable) { // and external storage exists and is usable String customFolderPath = preferences.getString(PREFS_KEY_CUSTOM_EXTERNALSTORAGE, "asdasdpoipoi"); + customFolderPath = customFolderPath.trim(); File customFolderFile = new File(customFolderPath); if (customFolderFile.exists() && customFolderFile.isDirectory() && customFolderFile.canWrite()) { /* * the user wants a different storage path: * - use that as sdcard * - create an app folder inside it */ sdcardDir = customFolderFile; possibleApplicationDir = new File(sdcardDir, applicationLabel); } else { if (customFolderPath.equals("internal")) { /* * the user folder doesn't exist, but is "internal": * - use internal app memory * - set sdcard anyways to the external folder for maps use */ useInternalMemory = true; possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = Environment.getExternalStorageDirectory(); } else { sdcardDir = Environment.getExternalStorageDirectory(); possibleApplicationDir = new File(sdcardDir, applicationLabel); } } } else if (useInternalMemory) { /* * no external storage available: * - use internal memory * - set sdcard for maps inside the space */ possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = possibleApplicationDir; } else { String msgFormat = Utilities.format(cantCreateSdcardmsg, "sdcard/" + applicationLabel); throw new IOException(msgFormat); } if (baseFolder.length() == 0 || !parentExists || !parentCanWrite) { applicationDir = possibleApplicationDir; } // if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "Possible app dir: " + applicationDir); // } String applicationDirPath = applicationDir.getAbsolutePath(); if (!applicationDir.exists()) { createdApplicationDirOnInit = true; // RandomAccessFile file = null; // try { // file = new RandomAccessFile(applicationDir, "rw"); // final FileLock fileLock = file.getChannel().tryLock(); // Log.i("RESOURCESMANAGER", "Got the lock? " + (null != fileLock)); // if (null != fileLock) { // Log.i("RESOURCESMANAGER", "Is a valid lock? " + fileLock.isValid()); // } // } finally { // file.close(); // } // Process proc = Runtime.getRuntime().exec(new String[]{"lsof", // applicationDir.getAbsolutePath()}); // StringBuilder sb = new StringBuilder("LOSF RESULT: "); // BufferedReader stdInput = new BufferedReader(new // InputStreamReader(proc.getInputStream())); // BufferedReader stdError = new BufferedReader(new // InputStreamReader(proc.getErrorStream())); // String s; // while( (s = stdInput.readLine()) != null ) { // sb.append(s).append("\n"); // } // while( (s = stdError.readLine()) != null ) { // sb.append(s).append("\n"); // } // Log.i("RESOURCESMANAGER", sb.toString()); if (!applicationDir.mkdirs()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, applicationDirPath); throw new IOException(msgFormat); } } if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "App dir exists: " + applicationDir.exists()); } databaseFile = new File(applicationDirPath, databaseName); mediaDir = new File(applicationDir, PATH_MEDIA); if (!mediaDir.exists()) if (!mediaDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mediaDir.getAbsolutePath()); throw new IOException(msgFormat); } exportDir = applicationDir.getParentFile(); mapsDir = new File(sdcardDir, PATH_MAPS); if (!mapsDir.exists()) if (!mapsDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mapsDir.getAbsolutePath()); messageDialog(appContext, msgFormat, null); mapsDir = sdcardDir; } } /** * Get the file to the main application folder. * * @return the {@link File} to the app folder. */ public File getApplicationDir() { return applicationDir; } /** * Get info about the application folder's pre-existence. * * @return <code>true</code> if on initialisation an * application folder had to be created, <code>false</code> * if the application folder already existed. */ public boolean hadToCreateApplicationDirOnInit() { return createdApplicationDirOnInit; } /** * Get the file to the main application's parent folder. * * @return the {@link File} to the app's parent folder. */ public File getApplicationParentDir() { return applicationDir.getParentFile(); } /** * Get the sdcard dir or <code>null</code>. * * @return the sdcard folder file. */ public File getSdcardDir() { return sdcardDir; } /** * Sets a new application folder. * * <p>Note that this will reset all the folders and resources that are bound * to it. For example there might be the need to recreate the database file.</p> * * @param context the context to use. * @param path the path to the new application. */ public void setApplicationDir( Context context, String path ) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = preferences.edit(); editor.putString(LibraryConstants.PREFS_KEY_BASEFOLDER, path); editor.commit(); resetManager(); } /** * Get the file to a default database location for the app. * * <p>This path is generated with default values and can be * exploited. It doesn't assure that in the location there really is a db. * * @return the {@link File} to the database. */ public File getDatabaseFile() { return databaseFile; } /** * Get the default media folder. * * @return the default media folder. */ public File getMediaDir() { return mediaDir; } /** * Get the default export folder. * * @return the default export folder. */ public File getExportDir() { return exportDir; } /** * Get the default maps folder. * * @return the default maps folder. */ public File getMapsDir() { return mapsDir; } /** * Update the description file of the project. * * @param description a new description for the project. * @throws IOException */ public void addProjectDescription( String description ) throws IOException { File applicationDir = getApplicationDir(); File descriptionFile = new File(applicationDir, "description"); //$NON-NLS-1$ FileUtilities.writefile(description, descriptionFile); } }
true
true
private ResourcesManager( Context context ) throws Exception { Context appContext = context.getApplicationContext(); ApplicationInfo appInfo = appContext.getApplicationInfo(); String packageName = appInfo.packageName; int lastDot = packageName.lastIndexOf('.'); applicationLabel = packageName.replace('.', '_'); if (lastDot != -1) { applicationLabel = packageName.substring(lastDot + 1, packageName.length()); } applicationLabel = applicationLabel.toLowerCase(); String databaseName = applicationLabel + ".db"; //$NON-NLS-1$ /* * take care to create all the folders needed * * The default structure is: * * sdcard * | * |-- applicationname * | | * | |--- applicationname.db * | |--- media (folder) * | |--- export (folder) * | `--- debug.log * `-- mapsdir */ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext); String baseFolder = preferences.getString(PREFS_KEY_BASEFOLDER, ""); //$NON-NLS-1$ applicationDir = new File(baseFolder); File parentFile = applicationDir.getParentFile(); boolean parentExists = false; boolean parentCanWrite = false; if (parentFile != null) { parentExists = parentFile.exists(); parentCanWrite = parentFile.canWrite(); } // the folder doesn't exist for some reason, fallback on default String state = Environment.getExternalStorageState(); if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", state); } boolean mExternalStorageAvailable; boolean mExternalStorageWriteable; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { mExternalStorageAvailable = mExternalStorageWriteable = false; } String cantCreateSdcardmsg = appContext.getResources().getString(R.string.cantcreate_sdcard); File possibleApplicationDir; if (mExternalStorageAvailable && mExternalStorageWriteable) { // and external storage exists and is usable String customFolderPath = preferences.getString(PREFS_KEY_CUSTOM_EXTERNALSTORAGE, "asdasdpoipoi"); File customFolderFile = new File(customFolderPath); if (customFolderFile.exists() && customFolderFile.isDirectory() && customFolderFile.canWrite()) { /* * the user wants a different storage path: * - use that as sdcard * - create an app folder inside it */ sdcardDir = customFolderFile; possibleApplicationDir = new File(sdcardDir, applicationLabel); } else { if (customFolderPath.equals("internal")) { /* * the user folder doesn't exist, but is "internal": * - use internal app memory * - set sdcard anyways to the external folder for maps use */ useInternalMemory = true; possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = Environment.getExternalStorageDirectory(); } else { sdcardDir = Environment.getExternalStorageDirectory(); possibleApplicationDir = new File(sdcardDir, applicationLabel); } } } else if (useInternalMemory) { /* * no external storage available: * - use internal memory * - set sdcard for maps inside the space */ possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = possibleApplicationDir; } else { String msgFormat = Utilities.format(cantCreateSdcardmsg, "sdcard/" + applicationLabel); throw new IOException(msgFormat); } if (baseFolder.length() == 0 || !parentExists || !parentCanWrite) { applicationDir = possibleApplicationDir; } // if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "Possible app dir: " + applicationDir); // } String applicationDirPath = applicationDir.getAbsolutePath(); if (!applicationDir.exists()) { createdApplicationDirOnInit = true; // RandomAccessFile file = null; // try { // file = new RandomAccessFile(applicationDir, "rw"); // final FileLock fileLock = file.getChannel().tryLock(); // Log.i("RESOURCESMANAGER", "Got the lock? " + (null != fileLock)); // if (null != fileLock) { // Log.i("RESOURCESMANAGER", "Is a valid lock? " + fileLock.isValid()); // } // } finally { // file.close(); // } // Process proc = Runtime.getRuntime().exec(new String[]{"lsof", // applicationDir.getAbsolutePath()}); // StringBuilder sb = new StringBuilder("LOSF RESULT: "); // BufferedReader stdInput = new BufferedReader(new // InputStreamReader(proc.getInputStream())); // BufferedReader stdError = new BufferedReader(new // InputStreamReader(proc.getErrorStream())); // String s; // while( (s = stdInput.readLine()) != null ) { // sb.append(s).append("\n"); // } // while( (s = stdError.readLine()) != null ) { // sb.append(s).append("\n"); // } // Log.i("RESOURCESMANAGER", sb.toString()); if (!applicationDir.mkdirs()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, applicationDirPath); throw new IOException(msgFormat); } } if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "App dir exists: " + applicationDir.exists()); } databaseFile = new File(applicationDirPath, databaseName); mediaDir = new File(applicationDir, PATH_MEDIA); if (!mediaDir.exists()) if (!mediaDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mediaDir.getAbsolutePath()); throw new IOException(msgFormat); } exportDir = applicationDir.getParentFile(); mapsDir = new File(sdcardDir, PATH_MAPS); if (!mapsDir.exists()) if (!mapsDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mapsDir.getAbsolutePath()); messageDialog(appContext, msgFormat, null); mapsDir = sdcardDir; } }
private ResourcesManager( Context context ) throws Exception { Context appContext = context.getApplicationContext(); ApplicationInfo appInfo = appContext.getApplicationInfo(); String packageName = appInfo.packageName; int lastDot = packageName.lastIndexOf('.'); applicationLabel = packageName.replace('.', '_'); if (lastDot != -1) { applicationLabel = packageName.substring(lastDot + 1, packageName.length()); } applicationLabel = applicationLabel.toLowerCase(); String databaseName = applicationLabel + ".db"; //$NON-NLS-1$ /* * take care to create all the folders needed * * The default structure is: * * sdcard * | * |-- applicationname * | | * | |--- applicationname.db * | |--- media (folder) * | |--- export (folder) * | `--- debug.log * `-- mapsdir */ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext); String baseFolder = preferences.getString(PREFS_KEY_BASEFOLDER, ""); //$NON-NLS-1$ applicationDir = new File(baseFolder); File parentFile = applicationDir.getParentFile(); boolean parentExists = false; boolean parentCanWrite = false; if (parentFile != null) { parentExists = parentFile.exists(); parentCanWrite = parentFile.canWrite(); } // the folder doesn't exist for some reason, fallback on default String state = Environment.getExternalStorageState(); if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", state); } boolean mExternalStorageAvailable; boolean mExternalStorageWriteable; if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { mExternalStorageAvailable = mExternalStorageWriteable = false; } String cantCreateSdcardmsg = appContext.getResources().getString(R.string.cantcreate_sdcard); File possibleApplicationDir; if (mExternalStorageAvailable && mExternalStorageWriteable) { // and external storage exists and is usable String customFolderPath = preferences.getString(PREFS_KEY_CUSTOM_EXTERNALSTORAGE, "asdasdpoipoi"); customFolderPath = customFolderPath.trim(); File customFolderFile = new File(customFolderPath); if (customFolderFile.exists() && customFolderFile.isDirectory() && customFolderFile.canWrite()) { /* * the user wants a different storage path: * - use that as sdcard * - create an app folder inside it */ sdcardDir = customFolderFile; possibleApplicationDir = new File(sdcardDir, applicationLabel); } else { if (customFolderPath.equals("internal")) { /* * the user folder doesn't exist, but is "internal": * - use internal app memory * - set sdcard anyways to the external folder for maps use */ useInternalMemory = true; possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = Environment.getExternalStorageDirectory(); } else { sdcardDir = Environment.getExternalStorageDirectory(); possibleApplicationDir = new File(sdcardDir, applicationLabel); } } } else if (useInternalMemory) { /* * no external storage available: * - use internal memory * - set sdcard for maps inside the space */ possibleApplicationDir = appContext.getDir(applicationLabel, Context.MODE_PRIVATE); sdcardDir = possibleApplicationDir; } else { String msgFormat = Utilities.format(cantCreateSdcardmsg, "sdcard/" + applicationLabel); throw new IOException(msgFormat); } if (baseFolder.length() == 0 || !parentExists || !parentCanWrite) { applicationDir = possibleApplicationDir; } // if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "Possible app dir: " + applicationDir); // } String applicationDirPath = applicationDir.getAbsolutePath(); if (!applicationDir.exists()) { createdApplicationDirOnInit = true; // RandomAccessFile file = null; // try { // file = new RandomAccessFile(applicationDir, "rw"); // final FileLock fileLock = file.getChannel().tryLock(); // Log.i("RESOURCESMANAGER", "Got the lock? " + (null != fileLock)); // if (null != fileLock) { // Log.i("RESOURCESMANAGER", "Is a valid lock? " + fileLock.isValid()); // } // } finally { // file.close(); // } // Process proc = Runtime.getRuntime().exec(new String[]{"lsof", // applicationDir.getAbsolutePath()}); // StringBuilder sb = new StringBuilder("LOSF RESULT: "); // BufferedReader stdInput = new BufferedReader(new // InputStreamReader(proc.getInputStream())); // BufferedReader stdError = new BufferedReader(new // InputStreamReader(proc.getErrorStream())); // String s; // while( (s = stdInput.readLine()) != null ) { // sb.append(s).append("\n"); // } // while( (s = stdError.readLine()) != null ) { // sb.append(s).append("\n"); // } // Log.i("RESOURCESMANAGER", sb.toString()); if (!applicationDir.mkdirs()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, applicationDirPath); throw new IOException(msgFormat); } } if (GPLog.LOG_HEAVY) { Log.i("RESOURCESMANAGER", "App dir exists: " + applicationDir.exists()); } databaseFile = new File(applicationDirPath, databaseName); mediaDir = new File(applicationDir, PATH_MEDIA); if (!mediaDir.exists()) if (!mediaDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mediaDir.getAbsolutePath()); throw new IOException(msgFormat); } exportDir = applicationDir.getParentFile(); mapsDir = new File(sdcardDir, PATH_MAPS); if (!mapsDir.exists()) if (!mapsDir.mkdir()) { String msgFormat = Utilities.format(cantCreateSdcardmsg, mapsDir.getAbsolutePath()); messageDialog(appContext, msgFormat, null); mapsDir = sdcardDir; } }
diff --git a/src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java b/src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java index 66fd4c99..1181c274 100644 --- a/src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java +++ b/src/share/classes/com/sun/tools/javac/nio/JavacPathFileManager.java @@ -1,543 +1,543 @@ /* * Copyright (c) 2009, 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. */ package com.sun.tools.javac.nio; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.Attributes; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.lang.model.SourceVersion; import javax.tools.FileObject; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardLocation; import static java.nio.file.FileVisitOption.*; import static javax.tools.StandardLocation.*; import com.sun.tools.javac.file.Paths; import com.sun.tools.javac.util.BaseFileManager; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import static com.sun.tools.javac.main.OptionName.*; // NOTE the imports carefully for this compilation unit. // // Path: java.nio.file.Path -- the new NIO type for which this file manager exists // // Paths: com.sun.tools.javac.file.Paths -- legacy javac type for handling path options // The other Paths (java.nio.file.Paths) is not used // NOTE this and related classes depend on new API in JDK 7. // This requires special handling while bootstrapping the JDK build, // when these classes might not yet have been compiled. To workaround // this, the build arranges to make stubs of these classes available // when compiling this and related classes. The set of stub files // is specified in make/build.properties. /** * Implementation of PathFileManager: a JavaFileManager based on the use * of java.nio.file.Path. * * <p>Just as a Path is somewhat analagous to a File, so too is this * JavacPathFileManager analogous to JavacFileManager, as it relates to the * support of FileObjects based on File objects (i.e. just RegularFileObject, * not ZipFileObject and its variants.) * * <p>The default values for the standard locations supported by this file * manager are the same as the default values provided by JavacFileManager -- * i.e. as determined by the javac.file.Paths class. To override these values, * call {@link #setLocation}. * * <p>To reduce confusion with Path objects, the locations such as "class path", * "source path", etc, are generically referred to here as "search paths". * * <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 JavacPathFileManager extends BaseFileManager implements PathFileManager { protected FileSystem defaultFileSystem; /** * Create a JavacPathFileManager using a given context, optionally registering * it as the JavaFileManager for that context. */ public JavacPathFileManager(Context context, boolean register, Charset charset) { super(charset); if (register) context.put(JavaFileManager.class, this); pathsForLocation = new HashMap<Location, PathsForLocation>(); fileSystems = new HashMap<Path,FileSystem>(); setContext(context); } /** * Set the context for JavacPathFileManager. */ @Override protected void setContext(Context context) { super.setContext(context); searchPaths = Paths.instance(context); } @Override public FileSystem getDefaultFileSystem() { if (defaultFileSystem == null) defaultFileSystem = FileSystems.getDefault(); return defaultFileSystem; } @Override public void setDefaultFileSystem(FileSystem fs) { defaultFileSystem = fs; } @Override public void flush() throws IOException { contentCache.clear(); } @Override public void close() throws IOException { for (FileSystem fs: fileSystems.values()) fs.close(); } @Override public ClassLoader getClassLoader(Location location) { nullCheck(location); Iterable<? extends Path> path = getLocation(location); if (path == null) return null; ListBuffer<URL> lb = new ListBuffer<URL>(); for (Path p: path) { try { lb.append(p.toUri().toURL()); } catch (MalformedURLException e) { throw new AssertionError(e); } } return getClassLoader(lb.toArray(new URL[lb.size()])); } // <editor-fold defaultstate="collapsed" desc="Location handling"> public boolean hasLocation(Location location) { return (getLocation(location) != null); } public Iterable<? extends Path> getLocation(Location location) { nullCheck(location); lazyInitSearchPaths(); PathsForLocation path = pathsForLocation.get(location); if (path == null && !pathsForLocation.containsKey(location)) { setDefaultForLocation(location); path = pathsForLocation.get(location); } return path; } private Path getOutputLocation(Location location) { Iterable<? extends Path> paths = getLocation(location); return (paths == null ? null : paths.iterator().next()); } public void setLocation(Location location, Iterable<? extends Path> searchPath) throws IOException { nullCheck(location); lazyInitSearchPaths(); if (searchPath == null) { setDefaultForLocation(location); } else { if (location.isOutputLocation()) checkOutputPath(searchPath); PathsForLocation pl = new PathsForLocation(); for (Path p: searchPath) pl.add(p); // TODO -Xlint:path warn if path not found pathsForLocation.put(location, pl); } } private void checkOutputPath(Iterable<? extends Path> searchPath) throws IOException { Iterator<? extends Path> pathIter = searchPath.iterator(); if (!pathIter.hasNext()) throw new IllegalArgumentException("empty path for directory"); Path path = pathIter.next(); if (pathIter.hasNext()) throw new IllegalArgumentException("path too long for directory"); if (!path.exists()) throw new FileNotFoundException(path + ": does not exist"); else if (!isDirectory(path)) throw new IOException(path + ": not a directory"); } private void setDefaultForLocation(Location locn) { Collection<File> files = null; if (locn instanceof StandardLocation) { switch ((StandardLocation) locn) { case CLASS_PATH: files = searchPaths.userClassPath(); break; case PLATFORM_CLASS_PATH: files = searchPaths.bootClassPath(); break; case SOURCE_PATH: files = searchPaths.sourcePath(); break; case CLASS_OUTPUT: { String arg = options.get(D); files = (arg == null ? null : Collections.singleton(new File(arg))); break; } case SOURCE_OUTPUT: { String arg = options.get(S); files = (arg == null ? null : Collections.singleton(new File(arg))); break; } } } PathsForLocation pl = new PathsForLocation(); if (files != null) { for (File f: files) pl.add(f.toPath()); } pathsForLocation.put(locn, pl); } private void lazyInitSearchPaths() { if (!inited) { setDefaultForLocation(PLATFORM_CLASS_PATH); setDefaultForLocation(CLASS_PATH); setDefaultForLocation(SOURCE_PATH); inited = true; } } // where private boolean inited = false; private Map<Location, PathsForLocation> pathsForLocation; private Paths searchPaths; private static class PathsForLocation extends LinkedHashSet<Path> { private static final long serialVersionUID = 6788510222394486733L; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="FileObject handling"> @Override public Path getPath(FileObject fo) { nullCheck(fo); if (!(fo instanceof PathFileObject)) throw new IllegalArgumentException(); return ((PathFileObject) fo).getPath(); } @Override public boolean isSameFile(FileObject a, FileObject b) { nullCheck(a); nullCheck(b); if (!(a instanceof PathFileObject)) throw new IllegalArgumentException("Not supported: " + a); if (!(b instanceof PathFileObject)) throw new IllegalArgumentException("Not supported: " + b); return ((PathFileObject) a).isSameFile((PathFileObject) b); } @Override public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException { // validatePackageName(packageName); nullCheck(packageName); nullCheck(kinds); Iterable<? extends Path> paths = getLocation(location); if (paths == null) return List.nil(); ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>(); for (Path path : paths) list(path, packageName, kinds, recurse, results); return results.toList(); } private void list(Path path, String packageName, final Set<Kind> kinds, boolean recurse, final ListBuffer<JavaFileObject> results) throws IOException { if (!path.exists()) return; final Path pathDir; if (isDirectory(path)) pathDir = path; else { FileSystem fs = getFileSystem(path); if (fs == null) return; pathDir = fs.getRootDirectories().iterator().next(); } String sep = path.getFileSystem().getSeparator(); Path packageDir = packageName.isEmpty() ? pathDir : pathDir.resolve(packageName.replace(".", sep)); if (!packageDir.exists()) return; /* Alternate impl of list, superceded by use of Files.walkFileTree */ // Deque<Path> queue = new LinkedList<Path>(); // queue.add(packageDir); // // Path dir; // while ((dir = queue.poll()) != null) { // DirectoryStream<Path> ds = dir.newDirectoryStream(); // try { // for (Path p: ds) { // String name = p.getName().toString(); // if (isDirectory(p)) { // if (recurse && SourceVersion.isIdentifier(name)) { // queue.add(p); // } // } else { // if (kinds.contains(getKind(name))) { // JavaFileObject fe = // PathFileObject.createDirectoryPathFileObject(this, p, pathDir); // results.append(fe); // } // } // } // } finally { // ds.close(); // } // } int maxDepth = (recurse ? Integer.MAX_VALUE : 1); - Set<FileVisitOption> opts = EnumSet.of(DETECT_CYCLES, FOLLOW_LINKS); + Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS); Files.walkFileTree(packageDir, opts, maxDepth, new SimpleFileVisitor<Path>() { @Override - public FileVisitResult preVisitDirectory(Path dir) { + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if (SourceVersion.isIdentifier(dir.getName().toString())) // JSR 292? return FileVisitResult.CONTINUE; else return FileVisitResult.SKIP_SUBTREE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (attrs.isRegularFile() && kinds.contains(getKind(file.getName().toString()))) { JavaFileObject fe = PathFileObject.createDirectoryPathFileObject( JavacPathFileManager.this, file, pathDir); results.append(fe); } return FileVisitResult.CONTINUE; } }); } @Override public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths( Iterable<? extends Path> paths) { ArrayList<PathFileObject> result; if (paths instanceof Collection<?>) result = new ArrayList<PathFileObject>(((Collection<?>)paths).size()); else result = new ArrayList<PathFileObject>(); for (Path p: paths) result.add(PathFileObject.createSimplePathFileObject(this, nullCheck(p))); return result; } @Override public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) { return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths))); } @Override public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind) throws IOException { return getFileForInput(location, getRelativePath(className, kind)); } @Override public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { return getFileForInput(location, getRelativePath(packageName, relativeName)); } private JavaFileObject getFileForInput(Location location, String relativePath) throws IOException { for (Path p: getLocation(location)) { if (isDirectory(p)) { Path f = resolve(p, relativePath); if (f.exists()) return PathFileObject.createDirectoryPathFileObject(this, f, p); } else { FileSystem fs = getFileSystem(p); if (fs != null) { Path file = getPath(fs, relativePath); if (file.exists()) return PathFileObject.createJarPathFileObject(this, file); } } } return null; } @Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { return getFileForOutput(location, getRelativePath(className, kind), sibling); } @Override public FileObject getFileForOutput(Location location, String packageName, String relativeName, FileObject sibling) throws IOException { return getFileForOutput(location, getRelativePath(packageName, relativeName), sibling); } private JavaFileObject getFileForOutput(Location location, String relativePath, FileObject sibling) { Path dir = getOutputLocation(location); if (dir == null) { if (location == CLASS_OUTPUT) { Path siblingDir = null; if (sibling != null && sibling instanceof PathFileObject) { siblingDir = ((PathFileObject) sibling).getPath().getParent(); } return PathFileObject.createSiblingPathFileObject(this, siblingDir.resolve(getBaseName(relativePath)), relativePath); } else if (location == SOURCE_OUTPUT) { dir = getOutputLocation(CLASS_OUTPUT); } } Path file; if (dir != null) { file = resolve(dir, relativePath); return PathFileObject.createDirectoryPathFileObject(this, file, dir); } else { file = getPath(getDefaultFileSystem(), relativePath); return PathFileObject.createSimplePathFileObject(this, file); } } @Override public String inferBinaryName(Location location, JavaFileObject fo) { nullCheck(fo); // Need to match the path semantics of list(location, ...) Iterable<? extends Path> paths = getLocation(location); if (paths == null) { return null; } if (!(fo instanceof PathFileObject)) throw new IllegalArgumentException(fo.getClass().getName()); return ((PathFileObject) fo).inferBinaryName(paths); } private FileSystem getFileSystem(Path p) throws IOException { FileSystem fs = fileSystems.get(p); if (fs == null) { fs = FileSystems.newFileSystem(p, Collections.<String,Void>emptyMap(), null); fileSystems.put(p, fs); } return fs; } private Map<Path,FileSystem> fileSystems; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Utility methods"> private static String getRelativePath(String className, Kind kind) { return className.replace(".", "/") + kind.extension; } private static String getRelativePath(String packageName, String relativeName) { return packageName.replace(".", "/") + relativeName; } private static String getBaseName(String relativePath) { int lastSep = relativePath.lastIndexOf("/"); return relativePath.substring(lastSep + 1); // safe if "/" not found } private static boolean isDirectory(Path path) throws IOException { BasicFileAttributes attrs = Attributes.readBasicFileAttributes(path); return attrs.isDirectory(); } private static Path getPath(FileSystem fs, String relativePath) { return fs.getPath(relativePath.replace("/", fs.getSeparator())); } private static Path resolve(Path base, String relativePath) { FileSystem fs = base.getFileSystem(); Path rp = fs.getPath(relativePath.replace("/", fs.getSeparator())); return base.resolve(rp); } // </editor-fold> }
false
true
private void list(Path path, String packageName, final Set<Kind> kinds, boolean recurse, final ListBuffer<JavaFileObject> results) throws IOException { if (!path.exists()) return; final Path pathDir; if (isDirectory(path)) pathDir = path; else { FileSystem fs = getFileSystem(path); if (fs == null) return; pathDir = fs.getRootDirectories().iterator().next(); } String sep = path.getFileSystem().getSeparator(); Path packageDir = packageName.isEmpty() ? pathDir : pathDir.resolve(packageName.replace(".", sep)); if (!packageDir.exists()) return; /* Alternate impl of list, superceded by use of Files.walkFileTree */ // Deque<Path> queue = new LinkedList<Path>(); // queue.add(packageDir); // // Path dir; // while ((dir = queue.poll()) != null) { // DirectoryStream<Path> ds = dir.newDirectoryStream(); // try { // for (Path p: ds) { // String name = p.getName().toString(); // if (isDirectory(p)) { // if (recurse && SourceVersion.isIdentifier(name)) { // queue.add(p); // } // } else { // if (kinds.contains(getKind(name))) { // JavaFileObject fe = // PathFileObject.createDirectoryPathFileObject(this, p, pathDir); // results.append(fe); // } // } // } // } finally { // ds.close(); // } // } int maxDepth = (recurse ? Integer.MAX_VALUE : 1); Set<FileVisitOption> opts = EnumSet.of(DETECT_CYCLES, FOLLOW_LINKS); Files.walkFileTree(packageDir, opts, maxDepth, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir) { if (SourceVersion.isIdentifier(dir.getName().toString())) // JSR 292? return FileVisitResult.CONTINUE; else return FileVisitResult.SKIP_SUBTREE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (attrs.isRegularFile() && kinds.contains(getKind(file.getName().toString()))) { JavaFileObject fe = PathFileObject.createDirectoryPathFileObject( JavacPathFileManager.this, file, pathDir); results.append(fe); } return FileVisitResult.CONTINUE; } }); }
private void list(Path path, String packageName, final Set<Kind> kinds, boolean recurse, final ListBuffer<JavaFileObject> results) throws IOException { if (!path.exists()) return; final Path pathDir; if (isDirectory(path)) pathDir = path; else { FileSystem fs = getFileSystem(path); if (fs == null) return; pathDir = fs.getRootDirectories().iterator().next(); } String sep = path.getFileSystem().getSeparator(); Path packageDir = packageName.isEmpty() ? pathDir : pathDir.resolve(packageName.replace(".", sep)); if (!packageDir.exists()) return; /* Alternate impl of list, superceded by use of Files.walkFileTree */ // Deque<Path> queue = new LinkedList<Path>(); // queue.add(packageDir); // // Path dir; // while ((dir = queue.poll()) != null) { // DirectoryStream<Path> ds = dir.newDirectoryStream(); // try { // for (Path p: ds) { // String name = p.getName().toString(); // if (isDirectory(p)) { // if (recurse && SourceVersion.isIdentifier(name)) { // queue.add(p); // } // } else { // if (kinds.contains(getKind(name))) { // JavaFileObject fe = // PathFileObject.createDirectoryPathFileObject(this, p, pathDir); // results.append(fe); // } // } // } // } finally { // ds.close(); // } // } int maxDepth = (recurse ? Integer.MAX_VALUE : 1); Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS); Files.walkFileTree(packageDir, opts, maxDepth, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if (SourceVersion.isIdentifier(dir.getName().toString())) // JSR 292? return FileVisitResult.CONTINUE; else return FileVisitResult.SKIP_SUBTREE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (attrs.isRegularFile() && kinds.contains(getKind(file.getName().toString()))) { JavaFileObject fe = PathFileObject.createDirectoryPathFileObject( JavacPathFileManager.this, file, pathDir); results.append(fe); } return FileVisitResult.CONTINUE; } }); }
diff --git a/maven/maven-launchpad-plugin/src/main/java/org/apache/sling/maven/projectsupport/bundlelist/BaseBundleList.java b/maven/maven-launchpad-plugin/src/main/java/org/apache/sling/maven/projectsupport/bundlelist/BaseBundleList.java index cd838c8e1c..43b78fcade 100644 --- a/maven/maven-launchpad-plugin/src/main/java/org/apache/sling/maven/projectsupport/bundlelist/BaseBundleList.java +++ b/maven/maven-launchpad-plugin/src/main/java/org/apache/sling/maven/projectsupport/bundlelist/BaseBundleList.java @@ -1,92 +1,93 @@ /* * 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.sling.maven.projectsupport.bundlelist; import java.util.List; import org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.Bundle; import org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.BundleList; import org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.StartLevel; public abstract class BaseBundleList { public abstract List<StartLevel> getStartLevels(); public Bundle get(Bundle bundle, boolean compareVersions) { for (StartLevel sl : getStartLevels()) { Bundle foundBundle = sl.getBundle(bundle, compareVersions); if (foundBundle != null) { return foundBundle; } } return null; } public boolean remove(Bundle bundle, boolean compareVersions) { for (StartLevel sl : getStartLevels()) { if (sl.removeBundle(bundle, compareVersions)) { return true; } } return false; } /** * Merge the current bundle list with an additional list. * @see add(Bundle) * * @param bundleList the new bundle list */ public void merge(BundleList bundleList) { for (StartLevel sl : bundleList.getStartLevels()) { for (Bundle bnd : sl.getBundles()) { add(bnd); } } } /** * Add an artifact definition. If it already exists, update the version, but * do not change the start level. * * @param newBnd the bundle to add */ public void add(Bundle newBnd) { Bundle current = get(newBnd, false); if (current != null) { } else { StartLevel startLevel = getOrCreateStartLevel(newBnd.getStartLevel()); startLevel.getBundles().add(newBnd); } } private StartLevel getOrCreateStartLevel(int startLevel) { for (StartLevel sl : getStartLevels()) { if (sl.getLevel() == startLevel) { return sl; } } StartLevel sl = new StartLevel(); + getStartLevels().add(sl); sl.setLevel(startLevel); return sl; } }
true
true
private StartLevel getOrCreateStartLevel(int startLevel) { for (StartLevel sl : getStartLevels()) { if (sl.getLevel() == startLevel) { return sl; } } StartLevel sl = new StartLevel(); sl.setLevel(startLevel); return sl; }
private StartLevel getOrCreateStartLevel(int startLevel) { for (StartLevel sl : getStartLevels()) { if (sl.getLevel() == startLevel) { return sl; } } StartLevel sl = new StartLevel(); getStartLevels().add(sl); sl.setLevel(startLevel); return sl; }
diff --git a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java index 5c409c6f7c..bcaeaff473 100644 --- a/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java +++ b/microsoft-azure-api/src/main/java/com/microsoft/windowsazure/services/blob/client/CloudBlob.java @@ -1,2339 +1,2340 @@ /** * Copyright 2011 Microsoft Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.microsoft.windowsazure.services.blob.client; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import com.microsoft.windowsazure.services.core.storage.AccessCondition; import com.microsoft.windowsazure.services.core.storage.Constants; import com.microsoft.windowsazure.services.core.storage.DoesServiceRequest; import com.microsoft.windowsazure.services.core.storage.LeaseStatus; import com.microsoft.windowsazure.services.core.storage.OperationContext; import com.microsoft.windowsazure.services.core.storage.RetryNoRetry; import com.microsoft.windowsazure.services.core.storage.RetryPolicy; import com.microsoft.windowsazure.services.core.storage.StorageCredentialsSharedAccessSignature; import com.microsoft.windowsazure.services.core.storage.StorageErrorCodeStrings; import com.microsoft.windowsazure.services.core.storage.StorageException; import com.microsoft.windowsazure.services.core.storage.StorageExtendedErrorInformation; import com.microsoft.windowsazure.services.core.storage.utils.Base64; import com.microsoft.windowsazure.services.core.storage.utils.PathUtility; import com.microsoft.windowsazure.services.core.storage.utils.StreamMd5AndLength; import com.microsoft.windowsazure.services.core.storage.utils.UriQueryBuilder; import com.microsoft.windowsazure.services.core.storage.utils.Utility; import com.microsoft.windowsazure.services.core.storage.utils.implementation.ExecutionEngine; import com.microsoft.windowsazure.services.core.storage.utils.implementation.LeaseAction; import com.microsoft.windowsazure.services.core.storage.utils.implementation.StorageOperation; /** * * Represents a Windows Azure blob. This is the base class for the {@link CloudBlockBlob} and {@link CloudPageBlob} * classes. */ public abstract class CloudBlob implements ListBlobItem { /** * Holds the metadata for the blob. */ HashMap<String, String> metadata; /** * Holds the properties of the blob. */ BlobProperties properties; /** * Holds the URI of the blob, Setting this is RESERVED for internal use. */ URI uri; /** * Holds the snapshot ID. */ String snapshotID; /** * Holds the Blobs container Reference. */ private CloudBlobContainer container; /** * Represents the blob's directory. */ protected CloudBlobDirectory parent; /** * Holds the Blobs Name. */ private String name; /** * Represents the blob client. */ protected CloudBlobClient blobServiceClient; /** * Creates an instance of the <code>CloudBlob</code> class. * * @param type * the type of the blob. */ protected CloudBlob(final BlobType type) { this.metadata = new HashMap<String, String>(); this.properties = new BlobProperties(type); } /** * Creates an instance of the <code>CloudBlob</code> class using the specified URI and cloud blob client. * * @param type * the type of the blob. * @param uri * A <code>java.net.URI</code> object that represents the URI to the blob, beginning with the container * name. * @param client * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. * * @throws StorageException * If a storage service error occurred. */ protected CloudBlob(final BlobType type, final URI uri, final CloudBlobClient client) throws StorageException { this(type); Utility.assertNotNull("blobAbsoluteUri", uri); Utility.assertNotNull("serviceClient", client); this.blobServiceClient = client; this.uri = uri; this.parseURIQueryStringAndVerify(uri, client, client.isUsePathStyleUris()); } /** * Creates an instance of the <code>CloudBlob</code> class using the specified URI, cloud blob client, and cloud * blob container. * * @param type * the type of the blob. * @param uri * A <code>java.net.URI</code> object that represents the absolute URI to the blob, beginning with the * container name. * @param client * A {@link CloudBlobClient} object that specifies the endpoint for the Blob service. * @param container * A {@link CloudBlobContainer} object that represents the container to use for the blob. * * @throws StorageException * If a storage service error occurred. */ protected CloudBlob(final BlobType type, final URI uri, final CloudBlobClient client, final CloudBlobContainer container) throws StorageException { this(type, uri, client); this.container = container; } /** * Creates an instance of the <code>CloudBlob</code> class using the specified URI, snapshot ID, and cloud blob * client. * * @param type * the type of the blob. * @param uri * A <code>java.net.URI</code> object that represents the absolute URI to the blob, beginning with the * container name. * @param snapshotID * A <code>String</code> that represents the snapshot version, if applicable. * @param client * A {@link CloudBlobContainer} object that represents the container to use for the blob. * * @throws StorageException * If a storage service error occurred. */ protected CloudBlob(final BlobType type, final URI uri, final String snapshotID, final CloudBlobClient client) throws StorageException { this(type, uri, client); if (snapshotID != null) { if (this.snapshotID != null) { throw new IllegalArgumentException( "Snapshot query parameter is already defined in the blobUri. Either pass in a snapshotTime parameter or use a full URL with a snapshot query parameter."); } else { this.snapshotID = snapshotID; } } } /** * Creates an instance of the <code>CloudBlob</code> class by copying values from another blob. * * @param otherBlob * A <code>CloudBlob</code> object that represents the blob to copy. */ protected CloudBlob(final CloudBlob otherBlob) { this.metadata = new HashMap<String, String>(); this.properties = new BlobProperties(otherBlob.properties); if (otherBlob.metadata != null) { this.metadata = new HashMap<String, String>(); for (final String key : otherBlob.metadata.keySet()) { this.metadata.put(key, otherBlob.metadata.get(key)); } } this.snapshotID = otherBlob.snapshotID; this.uri = otherBlob.uri; this.container = otherBlob.container; this.parent = otherBlob.parent; this.blobServiceClient = otherBlob.blobServiceClient; this.name = otherBlob.name; } /** * Acquires a new lease on the blob. * * @return A <code>String</code> that represents the lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String acquireLease() throws StorageException { return this.acquireLease(null, null, null); } /** * Acquires a new lease on the blob using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>String</code> that represents the lease ID. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final String acquireLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, String> impl = new StorageOperation<CloudBlobClient, CloudBlob, String>( options) { @Override public String execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.ACQUIRE, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); blob.properties.setLeaseStatus(LeaseStatus.LOCKED); return BlobResponse.getLeaseID(request, opContext); } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Asserts that the blob has the correct blob type specified in the blob attributes. * * @throws StorageException * If an incorrect blob type is used. */ protected final void assertCorrectBlobType() throws StorageException { if (this instanceof CloudBlockBlob && this.properties.getBlobType() != BlobType.BLOCK_BLOB) { throw new StorageException( StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, String.format( "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", BlobType.BLOCK_BLOB, this.properties.getBlobType()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } if (this instanceof CloudPageBlob && this.properties.getBlobType() != BlobType.PAGE_BLOB) { throw new StorageException( StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, String.format( "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", BlobType.PAGE_BLOB, this.properties.getBlobType()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } /** * Breaks the lease but ensures that another client cannot acquire a new lease until the current lease period has * expired. * * @return The time, in seconds, remaining in the lease period. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long breakLease() throws StorageException { return this.breakLease(null, null, null); } /** * Breaks the lease, using the specified request options and operation context, but ensures that another client * cannot acquire a new lease until the current lease period has expired. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return The time, in seconds, remaining in the lease period. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long breakLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Long> impl = new StorageOperation<CloudBlobClient, CloudBlob, Long>( options) { @Override public Long execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.BREAK, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { this.setNonExceptionedRetryableFailure(true); return -1L; } blob.updatePropertiesFromResponse(request); final String leaseTime = BlobResponse.getLeaseTime(request, opContext); blob.properties.setLeaseStatus(LeaseStatus.UNLOCKED); return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Copies an existing blob's contents, properties, and metadata to this instance of the <code>CloudBlob</code> * class. * * @param sourceBlob * A <code>CloudBlob</code> object that represents the source blob to copy. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void copyFromBlob(final CloudBlob sourceBlob) throws StorageException { this.copyFromBlob(sourceBlob, null, null, null, null); } /** * Copies an existing blob's contents, properties, and metadata to this instance of the <code>CloudBlob</code> * class, using the specified access conditions, lease ID, request options, and operation context. * * @param sourceBlob * A <code>CloudBlob</code> object that represents the source blob to copy. * @param sourceAccessCondition * An {@link AccessCondition} object that represents the access conditions for the source blob. * @param destinationAccessCondition * An {@link AccessCondition} object that represents the access conditions for the destination blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. * */ @DoesServiceRequest public final void copyFromBlob(final CloudBlob sourceBlob, final AccessCondition sourceAccessCondition, final AccessCondition destinationAccessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.copyFrom(blob.getTransformedAddress(opContext), blobOptions.getTimeoutIntervalInMs(), sourceBlob.getCanonicalName(false), blob.snapshotID, sourceAccessCondition, destinationAccessCondition, blobOptions, opContext); BlobRequest.addMetadata(request, sourceBlob.metadata, opContext); client.getCredentials().signRequest(request, 0); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Creates a snapshot of the blob. * * @return A <code>CloudBlob</code> object that represents the snapshot of the blob. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final CloudBlob createSnapshot() throws StorageException { return this.createSnapshot(null, null, null); } /** * Creates a snapshot of the blob using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>CloudBlob</code> object that represents the snapshot of the blob. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final CloudBlob createSnapshot(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, CloudBlob> impl = new StorageOperation<CloudBlobClient, CloudBlob, CloudBlob>( options) { @Override public CloudBlob execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.snapshot(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } CloudBlob snapshot = null; final String snapshotTime = BlobResponse.getSnapshotTime(request, opContext); if (blob instanceof CloudBlockBlob) { snapshot = new CloudBlockBlob(blob.getUri(), snapshotTime, client); } else if (blob instanceof CloudPageBlob) { snapshot = new CloudPageBlob(blob.getUri(), snapshotTime, client); } blob.updatePropertiesFromResponse(request); return snapshot; } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Deletes the blob. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void delete() throws StorageException { this.delete(DeleteSnapshotsOption.NONE, null, null, null); } /** * Deletes the blob using the specified snapshot and request options, and operation context. * <p> * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value * in the <code>deleteSnapshotsOption</code> parameter to specify how the snapshots should be handled when the blob * is deleted. * * @param deleteSnapshotsOption * A {@link DeleteSnapshotsOption} object that indicates whether to delete only blobs, only snapshots, or * both. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void delete(final DeleteSnapshotsOption deleteSnapshotsOption, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("deleteSnapshotsOption", deleteSnapshotsOption); if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.delete(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, deleteSnapshotsOption, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { this.setNonExceptionedRetryableFailure(true); return null; } return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Deletes the blob if it exists. * <p> * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value * in the <code>deleteSnapshotsOption</code> parameter to specify how the snapshots should be handled when the blob * is deleted. * * @return <code>true</code> if the blob was deleted; otherwise, <code>false</code>. * * @throws StorageException * If a storage service error occurred. * */ @DoesServiceRequest public final boolean deleteIfExists() throws StorageException { return this.deleteIfExists(DeleteSnapshotsOption.NONE, null, null, null); } /** * Deletes the blob if it exists, using the specified snapshot and request options, and operation context. * <p> * A blob that has snapshots cannot be deleted unless the snapshots are also deleted. If a blob has snapshots, use * the {@link DeleteSnapshotsOption#DELETE_SNAPSHOTS_ONLY} or {@link DeleteSnapshotsOption#INCLUDE_SNAPSHOTS} value * in the <code>deleteSnapshotsOption</code> parameter to specify how the snapshots should be handled when the blob * is deleted. * * @param deleteSnapshotsOption * A {@link DeleteSnapshotsOption} object that indicates whether to delete only blobs, only snapshots, or * both. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return <code>true</code> if the blob was deleted; otherwise, <code>false</code> * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final boolean deleteIfExists(final DeleteSnapshotsOption deleteSnapshotsOption, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("deleteSnapshotsOption", deleteSnapshotsOption); if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Boolean> impl = new StorageOperation<CloudBlobClient, CloudBlob, Boolean>( options) { @Override public Boolean execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.delete(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, deleteSnapshotsOption, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); this.setResult(ExecutionEngine.processRequest(request, opContext)); blob.updatePropertiesFromResponse(request); if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_ACCEPTED) { return true; } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return false; } else { this.setNonExceptionedRetryableFailure(true); // return false instead of null to avoid SCA issues return false; } } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Downloads the contents of a blob to a stream. * * @param outStream * An <code>OutputStream</code> object that represents the target stream. * * @throws IOException * If an I/O exception occurred. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void download(final OutputStream outStream) throws StorageException, IOException { this.download(outStream, null, null, null); } /** * Downloads the contents of a blob to a stream using the specified request options and operation context. * * @param outStream * An <code>OutputStream</code> object that represents the target stream. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws IOException * If an I/O exception occurred. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void download(final OutputStream outStream, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); final InputStream streamRef = ExecutionEngine.getInputStream(request, opContext); this.setResult(opContext.getLastResult()); final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); final Boolean validateMD5 = !blobOptions.getDisableContentMD5Validation() && !Utility.isNullOrEmpty(contentMD5); final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); final long expectedLength = Long.parseLong(contentLength); blob.updatePropertiesFromResponse(request); final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMD5, this.getResult(), opContext); ExecutionEngine.getResponseCode(this.getResult(), request, opContext); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } if (descriptor.getLength() != expectedLength) { throw new StorageException( StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "An incorrect number of bytes was read from the connection. The connection may have been closed", Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } if (validateMD5 && !contentMD5.equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", contentMD5, descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } return null; } }; try { // Executed with no retries so that the first failure will move out // to the read Stream. ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, RetryNoRetry.getInstance(), opContext); opContext.setIntermediateMD5(null); } catch (final StorageException ex) { - // Check if users has any retries specified. + // Check if users has any retries specified, Or if the exception is retryable final RetryPolicy dummyPolicy = options.getRetryPolicyFactory().createInstance(opContext); - if (!dummyPolicy.shouldRetry(0, opContext.getLastResult().getStatusCode(), (Exception) ex.getCause(), - opContext).isShouldRetry()) { + if (ex.getHttpStatusCode() == Constants.HeaderConstants.HTTP_UNUSED_306 + || !dummyPolicy.shouldRetry(0, opContext.getLastResult().getStatusCode(), + (Exception) ex.getCause(), opContext).isShouldRetry()) { opContext.setIntermediateMD5(null); throw ex; } // Continuation, fail gracefully into a read stream. This needs to // be outside the operation above as it would get retried resulting // in a nested retry // Copy access condition, and update etag. This will potentially replace the if match value, but not on the // users object. AccessCondition etagLockCondition = new AccessCondition(); etagLockCondition.setIfMatch(this.getProperties().getEtag()); etagLockCondition.setLeaseID(accessCondition.getLeaseID()); // 1. Open Read Stream final BlobInputStream streamRef = this.openInputStream(etagLockCondition, options, opContext); // Cache value indicating if we need final boolean validateMd5 = streamRef.getValidateBlobMd5(); streamRef.setValidateBlobMd5(false); streamRef.mark(Integer.MAX_VALUE); try { // 2. Seek to current position, this will disable read streams // internal content md5 checks. if (opContext.getCurrentOperationByteCount() > 0) { // SCA will say this if a failure as we do not validate the // return of skip. // The Blob class repositioning a virtual pointer and will // always skip the correct // number of bytes. streamRef.skip(opContext.getCurrentOperationByteCount()); } // 3. Continue copying final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMd5, null, opContext); if (validateMd5 && !this.properties.getContentMD5().equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", this.properties.getContentMD5(), descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } catch (final IOException secondEx) { opContext.setIntermediateMD5(null); if (secondEx.getCause() != null && secondEx.getCause() instanceof StorageException) { throw (StorageException) secondEx.getCause(); } else { throw secondEx; } } } } /** * Populates a blob's properties and metadata. * <p> * This method populates the blob's system properties and user-defined metadata. Before reading a blob's properties * or metadata, call this method or its overload to retrieve the latest values for the blob's properties and * metadata from the Windows Azure storage service. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void downloadAttributes() throws StorageException { this.downloadAttributes(null, null, null); } /** * Populates a blob's properties and metadata using the specified request options and operation context. * <p> * This method populates the blob's system properties and user-defined metadata. Before reading a blob's properties * or metadata, call this method or its overload to retrieve the latest values for the blob's properties and * metadata from the Windows Azure storage service. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void downloadAttributes(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.getProperties(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } // Set attributes final BlobAttributes retrievedAttributes = BlobResponse.getAttributes(request, blob.getUri(), blob.snapshotID, opContext); if (retrievedAttributes.getProperties().getBlobType() != blob.properties.getBlobType()) { throw new StorageException( StorageErrorCodeStrings.INCORRECT_BLOB_TYPE, String.format( "Incorrect Blob type, please use the correct Blob type to access a blob on the server. Expected %s, actual %s", blob.properties.getBlobType(), retrievedAttributes.getProperties().getBlobType()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } blob.properties = retrievedAttributes.getProperties(); blob.metadata = retrievedAttributes.getMetadata(); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Downloads a range of bytes from the blob to the given byte buffer. * * @param offset * The byte offset to use as the starting point for the source. * @param length * The number of bytes to read. * @param buffer * The byte buffer, as an array of bytes, to which the blob bytes are downloaded. * @param bufferOffet * The byte offset to use as the starting point for the target. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void downloadRange(final long offset, final int length, final byte[] buffer, final int bufferOffet) throws StorageException { this.downloadRangeInternal(offset, length, buffer, bufferOffet, null, null, null); } /** * Downloads a range of bytes from the blob to the given byte buffer, using the specified request options and * operation context. * * @param offset * The byte offset to use as the starting point for the source. * @param length * The number of bytes to read. * @param buffer * The byte buffer, as an array of bytes, to which the blob bytes are downloaded. * @param bufferOffet * The byte offset to use as the starting point for the target. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void downloadRange(final long offset, final int length, final byte[] buffer, final int bufferOffet, final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) throws StorageException { if (offset < 0 || length <= 0) { throw new IndexOutOfBoundsException(); } Utility.assertNotNull("buffer", buffer); if (length + bufferOffet > buffer.length) { throw new IndexOutOfBoundsException(); } opContext.initialize(); this.downloadRangeInternal(offset, length, buffer, bufferOffet, accessCondition, options, opContext); } /** * Downloads a range of bytes from the blob to the given byte buffer. * * @param blobOffset * the offset of the blob to begin downloading at * @param length * the number of bytes to read * @param buffer * the byte buffer to write to. * @param bufferOffet * the offset in the byte buffer to begin writing. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * An object that specifies any additional options for the request * @param opContext * an object used to track the execution of the operation * @throws StorageException * an exception representing any error which occurred during the operation. */ @DoesServiceRequest protected final void downloadRangeInternal(final long blobOffset, final int length, final byte[] buffer, final int bufferOffset, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (blobOffset < 0 || length <= 0) { throw new IndexOutOfBoundsException(); } if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } options.applyDefaults(this.blobServiceClient); if (options.getUseTransactionalContentMD5() && length > 4 * Constants.MB) { throw new IllegalArgumentException( "Cannot specify x-ms-range-get-content-md5 header on ranges larger than 4 MB. Either use a BlobReadStream via openRead, or disable TransactionalMD5 checking via the BlobRequestOptions."); } final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, blobOffset, length, accessCondition, blobOptions, opContext); if (blobOptions.getUseTransactionalContentMD5()) { request.setRequestProperty(Constants.HeaderConstants.RANGE_GET_CONTENT_MD5, "true"); } client.getCredentials().signRequest(request, -1L); final InputStream sourceStream = ExecutionEngine.getInputStream(request, opContext); this.setResult(opContext.getLastResult()); int totalRead = 0; int nextRead = buffer.length - bufferOffset; int count = sourceStream.read(buffer, bufferOffset, nextRead); while (count > 0) { totalRead += count; nextRead = buffer.length - (bufferOffset + totalRead); if (nextRead == 0) { // check for case where more data is returned if (sourceStream.read(new byte[1], 0, 1) != -1) { throw new StorageException( StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "An incorrect number of bytes was read from the connection. The connection may have been closed", Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } count = sourceStream.read(buffer, bufferOffset + totalRead, nextRead); } ExecutionEngine.getResponseCode(this.getResult(), request, opContext); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_PARTIAL) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); final long expectedLength = Long.parseLong(contentLength); if (totalRead != expectedLength) { throw new StorageException( StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "An incorrect number of bytes was read from the connection. The connection may have been closed", Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } if (blobOptions.getUseTransactionalContentMD5()) { final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); try { final MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(buffer, bufferOffset, length); final String calculatedMD5 = Base64.encode(digest.digest()); if (!contentMD5.equals(calculatedMD5)) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", contentMD5, calculatedMD5), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } catch (final NoSuchAlgorithmException e) { // This wont happen, throw fatal. throw Utility.generateNewUnexpectedStorageException(e); } } return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Checks to see if the blob exists. * * @return <code>true</code> if the blob exists, other wise <code>false</code>. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final boolean exists() throws StorageException { return this.exists(null, null, null); } /** * Checks to see if the blob exists, using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return <code>true</code> if the blob exists, other wise <code>false</code>. * * @throws StorageException * f a storage service error occurred. */ @DoesServiceRequest public final boolean exists(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Boolean> impl = new StorageOperation<CloudBlobClient, CloudBlob, Boolean>( options) { @Override public Boolean execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.getProperties(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_OK) { blob.updatePropertiesFromResponse(request); return Boolean.valueOf(true); } else if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) { return Boolean.valueOf(false); } else { this.setNonExceptionedRetryableFailure(true); // return false instead of null to avoid SCA issues return false; } } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Returns a shared access signature for the blob using the specified shared access policy. Note this does not * contain the leading "?". * * @param policy * A <code>SharedAccessPolicy</code> object that represents the access policy for the shared access * signature. * @return A <code>String</code> that represents the shared access signature. * * @throws IllegalArgumentException * If the credentials are unable to sign the request or if the blob is a snapshot. * @throws InvalidKeyException * If the credentials are invalid. * @throws StorageException * If a storage service error occurred. */ public final String generateSharedAccessSignature(final SharedAccessPolicy policy) throws InvalidKeyException, StorageException { return this.generateSharedAccessSignature(policy, null); } /** * Returns a shared access signature for the blob using the specified shared access policy and operation context. * Note this does not contain the leading "?". * * @param policy * A <code>SharedAccessPolicy</code> object that represents the access policy for the shared access * signature. * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>String</code> that represents the shared access signature. * * @throws IllegalArgumentException * If the credentials are unable to sign the request or if the blob is a snapshot. * @throws InvalidKeyException * If the credentials are invalid. * @throws StorageException * If a storage service error occurred. */ public final String generateSharedAccessSignature(final SharedAccessPolicy policy, OperationContext opContext) throws InvalidKeyException, StorageException { if (opContext == null) { opContext = new OperationContext(); } return this.generateSharedAccessSignatureCore(policy, null, opContext); } /** * Returns a shared access signature for the blob using the specified group policy identifier. Note this does not * contain the leading "?". * * @param groupPolicyIdentifier * A <code>String</code> that represents the container-level access policy. * * @return A <code>String</code> that represents the shared access signature. * * @throws IllegalArgumentException * If the credentials are unable to sign the request or if the blob is a snapshot. * @throws InvalidKeyException * If the credentials are invalid. * @throws StorageException * If a storage service error occurred. */ public final String generateSharedAccessSignature(final String groupPolicyIdentifier) throws InvalidKeyException, StorageException { return this.generateSharedAccessSignature(groupPolicyIdentifier, null); } /** * Returns a shared access signature for the blob using the specified group policy identifier and operation context. * Note this does not contain the leading "?". * * @param groupPolicyIdentifier * A <code>String</code> that represents the container-level access policy. * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>String</code> that represents the shared access signature. * * @throws IllegalArgumentException * If the credentials are unable to sign the request or if the blob is a snapshot. * @throws InvalidKeyException * If the credentials are invalid. * @throws StorageException * If a storage service error occurred. */ public final String generateSharedAccessSignature(final String groupPolicyIdentifier, OperationContext opContext) throws InvalidKeyException, StorageException { if (opContext == null) { opContext = new OperationContext(); } return this.generateSharedAccessSignatureCore(null, groupPolicyIdentifier, opContext); } /** * Returns a shared access signature for the blob using the specified group policy identifier and operation context. * Note this does not contain the leading "?". * * @param policy * A <code>SharedAccessPolicy</code> object that represents the access policy for the shared access * signature. * @param groupPolicyIdentifier * A <code>String</code> that represents the container-level access policy. * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>String</code> that represents the shared access signature. * * @throws IllegalArgumentException * If the credentials are invalid or the blob is a snapshot. * @throws InvalidKeyException * If the credentials are invalid. * @throws StorageException * If a storage service error occurred. */ private String generateSharedAccessSignatureCore(final SharedAccessPolicy policy, final String groupPolicyIdentifier, OperationContext opContext) throws InvalidKeyException, StorageException { if (opContext == null) { opContext = new OperationContext(); } if (!this.blobServiceClient.getCredentials().canCredentialsSignRequest()) { throw new IllegalArgumentException( "Cannot create Shared Access Signature unless the Account Key credentials are used by the BlobServiceClient."); } if (this.isSnapshot()) { throw new IllegalArgumentException( "Cannot create Shared Access Signature for snapshots. Perform the operation on the root blob instead."); } final String resourceName = this.getCanonicalName(true); final String signature = SharedAccessSignatureHelper.generateSharedAccessSignatureHash(policy, groupPolicyIdentifier, resourceName, this.blobServiceClient, opContext); final UriQueryBuilder builder = SharedAccessSignatureHelper.generateSharedAccessSignature(policy, groupPolicyIdentifier, "b", signature); return builder.toString(); } /** * Returns the canonical name of the blob in the format of * <i>/&lt;account-name&gt;/&lt;container-name&gt;/&lt;blob-name&gt;</i>. * <p> * This format is used by both Shared Access and Copy blob operations. * * @param ignoreSnapshotTime * <code>true</code> if the snapshot time is ignored; otherwise, <code>false</code>. * * @return The canonical name in the format of <i>/&lt;account-name&gt;/&lt;container * -name&gt;/&lt;blob-name&gt;</i>. */ String getCanonicalName(final boolean ignoreSnapshotTime) { String canonicalName; if (this.blobServiceClient.isUsePathStyleUris()) { canonicalName = this.getUri().getRawPath(); } else { canonicalName = PathUtility.getCanonicalPathFromCredentials(this.blobServiceClient.getCredentials(), this .getUri().getRawPath()); } if (!ignoreSnapshotTime && this.snapshotID != null) { canonicalName = canonicalName.concat("?snapshot="); canonicalName = canonicalName.concat(this.snapshotID); } return canonicalName; } /** * Returns the blob's container. * * @return A {@link CloudBlobContainer} object that represents the container of the blob. * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ @Override public final CloudBlobContainer getContainer() throws StorageException, URISyntaxException { if (this.container == null) { final URI containerURI = PathUtility.getContainerURI(this.getUri(), this.blobServiceClient.isUsePathStyleUris()); this.container = new CloudBlobContainer(containerURI, this.blobServiceClient); } return this.container; } /** * Returns the metadata for the blob. * * @return A <code>java.util.HashMap</code> object that represents the metadata for the blob. */ public final HashMap<String, String> getMetadata() { return this.metadata; } /** * Returns the name of the blob. * * @return A <code>String</code> that represents the name of the blob. * * @throws URISyntaxException * If the resource URI is invalid. */ public final String getName() throws URISyntaxException { if (Utility.isNullOrEmpty(this.name)) { this.name = PathUtility.getBlobNameFromURI(this.getUri(), this.blobServiceClient.isUsePathStyleUris()); } return this.name; } /** * Returns the blob item's parent. * * @return A {@link CloudBlobDirectory} object that represents the parent directory for the blob. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ @Override public final CloudBlobDirectory getParent() throws URISyntaxException, StorageException { if (this.parent == null) { final URI parentURI = PathUtility.getParentAddress(this.getUri(), this.blobServiceClient.getDirectoryDelimiter(), this.blobServiceClient.isUsePathStyleUris()); this.parent = new CloudBlobDirectory(parentURI, null, this.blobServiceClient); } return this.parent; } /** * Returns the blob's properties. * * @return A {@link BlobProperties} object that represents the properties of the blob. */ public final BlobProperties getProperties() { return this.properties; } /** * Returns the snapshot or shared access signature qualified URI for this blob. * * @return A <code>java.net.URI</code> object that represents the snapshot or shared access signature. * * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ public final URI getQualifiedUri() throws URISyntaxException, StorageException { if (this.isSnapshot()) { return PathUtility.addToQuery(this.getUri(), String.format("snapshot=%s", this.snapshotID)); } else if (this.blobServiceClient.getCredentials() instanceof StorageCredentialsSharedAccessSignature) { return this.blobServiceClient.getCredentials().transformUri(this.getUri()); } else { return this.getUri(); } } /** * Returns the Blob service client associated with the blob. * * @return A {@link CloudBlobClient} object that represents the client. */ public final CloudBlobClient getServiceClient() { return this.blobServiceClient; } /** * Gets the Blob Snapshot ID. * * @return the Blob Snapshot ID. */ public final String getSnapshotID() { return this.snapshotID; } /** * Returns the transformed URI for the resource if the given credentials require transformation. * * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return A <code>java.net.URI</code> object that represents the transformed URI. * * @throws IllegalArgumentException * If the URI is not absolute. * @throws StorageException * If a storage service error occurred. * @throws URISyntaxException * If the resource URI is invalid. */ protected final URI getTransformedAddress(final OperationContext opContext) throws URISyntaxException, StorageException { if (this.blobServiceClient.getCredentials().doCredentialsNeedTransformUri()) { if (this.getUri().isAbsolute()) { return this.blobServiceClient.getCredentials().transformUri(this.getUri(), opContext); } else { final StorageException ex = Utility.generateNewUnexpectedStorageException(null); ex.getExtendedErrorInformation().setErrorMessage("Blob Object relative URIs not supported."); throw ex; } } else { return this.getUri(); } } /** * Returns the URI for this blob. * * @return A <code>java.net.URI</code> object that represents the URI for the blob. */ @Override public final URI getUri() { return this.uri; } /** * Indicates whether this blob is a snapshot. * * @return <code>true</code> if the blob is a snapshot, otherwise <code>false</code>. * * @see DeleteSnapshotsOption */ public final boolean isSnapshot() { return this.snapshotID != null; } /** * Opens a blob input stream to download the blob. * <p> * Use {@link CloudBlobClient#setStreamMinimumReadSizeInBytes} to configure the read size. * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final BlobInputStream openInputStream() throws StorageException { return this.openInputStream(null, null, null); } /** * Opens a blob input stream to download the blob using the specified request options and operation context. * <p> * Use {@link CloudBlobClient#setStreamMinimumReadSizeInBytes} to configure the read size. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final BlobInputStream openInputStream(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } options.applyDefaults(this.blobServiceClient); return new BlobInputStream(this, accessCondition, options, opContext); } /** * Parse Uri for SAS (Shared access signature) information. * * Validate that no other query parameters are passed in. Any SAS information will be recorded as corresponding * credentials instance. If existingClient is passed in, any SAS information found will not be supported. Otherwise * a new client is created based on SAS information or as anonymous credentials. * * @param completeUri * The complete Uri. * @param existingClient * The client to use. * @param usePathStyleUris * If true, path style Uris are used. * @throws StorageException * If a storage service error occurred. * */ private void parseURIQueryStringAndVerify(final URI completeUri, final CloudBlobClient existingClient, final boolean usePathStyleUris) throws StorageException { Utility.assertNotNull("resourceUri", completeUri); if (!completeUri.isAbsolute()) { final String errorMessage = String.format( "Address '%s' is not an absolute address. Relative addresses are not permitted in here.", completeUri.toString()); throw new IllegalArgumentException(errorMessage); } this.uri = PathUtility.stripURIQueryAndFragment(completeUri); final HashMap<String, String[]> queryParameters = PathUtility.parseQueryString(completeUri.getQuery()); final StorageCredentialsSharedAccessSignature sasCreds = SharedAccessSignatureHelper .parseQuery(queryParameters); final String[] snapshotIDs = queryParameters.get(BlobConstants.SNAPSHOT); if (snapshotIDs != null && snapshotIDs.length > 0) { this.snapshotID = snapshotIDs[0]; } if (sasCreds == null) { return; } final Boolean sameCredentials = existingClient == null ? false : Utility.areCredentialsEqual(sasCreds, existingClient.getCredentials()); if (existingClient == null || !sameCredentials) { try { this.blobServiceClient = new CloudBlobClient(new URI(PathUtility.getServiceClientBaseAddress( this.getUri(), usePathStyleUris)), sasCreds); } catch (final URISyntaxException e) { throw Utility.generateNewUnexpectedStorageException(e); } } if (existingClient != null && !sameCredentials) { this.blobServiceClient .setPageBlobStreamWriteSizeInBytes(existingClient.getPageBlobStreamWriteSizeInBytes()); this.blobServiceClient.setSingleBlobPutThresholdInBytes(existingClient.getSingleBlobPutThresholdInBytes()); this.blobServiceClient.setStreamMinimumReadSizeInBytes(existingClient.getStreamMinimumReadSizeInBytes()); this.blobServiceClient.setWriteBlockSizeInBytes(existingClient.getWriteBlockSizeInBytes()); this.blobServiceClient.setConcurrentRequestCount(existingClient.getConcurrentRequestCount()); this.blobServiceClient.setDirectoryDelimiter(existingClient.getDirectoryDelimiter()); this.blobServiceClient.setRetryPolicyFactory(existingClient.getRetryPolicyFactory()); this.blobServiceClient.setTimeoutInMs(existingClient.getTimeoutInMs()); } } void updatePropertiesFromResponse(HttpURLConnection request) { String tempStr = request.getHeaderField(Constants.HeaderConstants.ETAG); // ETag if (!Utility.isNullOrEmpty(tempStr)) { this.getProperties().setEtag(tempStr); } // Last Modified if (0 != request.getLastModified()) { final Calendar lastModifiedCalendar = Calendar.getInstance(Utility.LOCALE_US); lastModifiedCalendar.setTimeZone(Utility.UTC_ZONE); lastModifiedCalendar.setTime(new Date(request.getLastModified())); this.getProperties().setLastModified(lastModifiedCalendar.getTime()); } // using this instead of the request property since the request // property only returns an int. tempStr = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); if (!Utility.isNullOrEmpty(tempStr)) { this.getProperties().setLength(Long.parseLong(tempStr)); } } /** * Releases the lease on the blob. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is * required to be set on the AccessCondition. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void releaseLease(final AccessCondition accessCondition) throws StorageException { this.releaseLease(accessCondition, null, null); } /** * Releases the lease on the blob using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob.The LeaseID is * required to be set on the AccessCondition. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void releaseLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("accessCondition", accessCondition); Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.RELEASE, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); blob.properties.setLeaseStatus(LeaseStatus.UNLOCKED); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Renews an existing lease. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is * required to be set on the AccessCondition. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void renewLease(final AccessCondition accessCondition) throws StorageException { this.renewLease(accessCondition, null, null); } /** * Renews an existing lease using the specified request options and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. The LeaseID is * required to be set on the AccessCondition. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void renewLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { Utility.assertNotNull("accessCondition", accessCondition); Utility.assertNotNullOrEmpty("leaseID", accessCondition.getLeaseID()); if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.RENEW, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Sets the container for the blob. * * @param container * A {@link CloudBlobContainer} object that represents the container being assigned to the blob. */ protected final void setContainer(final CloudBlobContainer container) { this.container = container; } /** * Sets the metadata for the blob. * * @param metadata * A <code>java.util.HashMap</code> object that contains the metadata being assigned to the blob. */ public final void setMetadata(final HashMap<String, String> metadata) { this.metadata = metadata; } /** * Sets the properties for the blob. * * @param properties * A {@link BlobProperties} object that represents the properties being assigned to the blob. */ protected final void setProperties(final BlobProperties properties) { this.properties = properties; } /** * Sets the blob snapshot ID. * * @param snapshotID * A <code>String</code> that represents the snapshot ID being assigned to the blob. */ public final void setSnapshotID(final String snapshotID) { this.snapshotID = snapshotID; } /** * Attempts to break the lease and ensure that another client cannot acquire a new lease until the current lease * period has expired. * * @return Time, in seconds, remaining in the lease period, or -1 if the lease is already broken. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long tryBreakLease() throws StorageException { return this.tryBreakLease(null, null, null); } /** * Attempts to breaks the lease using the specified request options and operation context, and ensure that another * client cannot acquire a new lease until the current lease period has expired. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @return Time, in seconds, remaining in the lease period, -1 if the lease is already broken. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final long tryBreakLease(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Long> impl = new StorageOperation<CloudBlobClient, CloudBlob, Long>( options) { @Override public Long execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.lease(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), LeaseAction.BREAK, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() == HttpURLConnection.HTTP_CONFLICT) { final StorageException potentialConflictException = StorageException.translateException(request, null, opContext); StorageExtendedErrorInformation extendedInfo = potentialConflictException .getExtendedErrorInformation(); if (extendedInfo == null) { // If we cant validate the error then the error must be surfaced to the user. throw potentialConflictException; } if (!extendedInfo.getErrorCode().equals(StorageErrorCodeStrings.LEASE_ALREADY_BROKEN)) { this.setException(potentialConflictException); this.setNonExceptionedRetryableFailure(true); } return -1L; } if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_ACCEPTED) { this.setNonExceptionedRetryableFailure(true); return -1L; } blob.updatePropertiesFromResponse(request); final String leaseTime = BlobResponse.getLeaseTime(request, opContext); return Utility.isNullOrEmpty(leaseTime) ? -1L : Long.parseLong(leaseTime); } }; return ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Uploads the source stream data to the blob. * * @param sourceStream * An <code>InputStream</code> object that represents the source stream to upload. * * @param length * The length of the stream data in bytes, or -1 if unknown. The length must be greater than zero and a * multiple of 512 for page blobs. * * @throws IOException * If an I/O exception occurred. * * @throws StorageException * If a storage service error occurred. * */ @DoesServiceRequest public abstract void upload(InputStream sourceStream, long length) throws StorageException, IOException; /** * Uploads the source stream data to the blob using the specified lease ID, request options, and operation context. * * @param sourceStream * An <code>InputStream</code> object that represents the source stream to upload. * @param length * The length of the stream data in bytes, or -1 if unknown. The length must be greater than zero and a * multiple of 512 for page blobs. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws IOException * If an I/O exception occurred. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public abstract void upload(InputStream sourceStream, long length, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException; /** * Uploads a blob in a single operation. * * @param sourceStream * A <code>InputStream</code> object that represents the source stream to upload. * @param length * The length, in bytes, of the stream, or -1 if unknown. * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws IOException * If an I/O exception occurred. * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest protected final void uploadFullBlob(final InputStream sourceStream, final long length, final AccessCondition accessCondition, final BlobRequestOptions options, final OperationContext opContext) throws StorageException, IOException { // Mark sourceStream for current position. sourceStream.mark(Integer.MAX_VALUE); if (length < 0) { throw new IllegalArgumentException("Invalid stream length, specify a positive number of bytes"); } final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.put(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.properties, blob.properties.getBlobType(), 0, accessCondition, blobOptions, opContext); BlobRequest.addMetadata(request, blob.metadata, opContext); client.getCredentials().signRequest(request, length); final StreamMd5AndLength descriptor = Utility.writeToOutputStream(sourceStream, request.getOutputStream(), length, true, false, null, opContext); if (length != descriptor.getLength()) { throw new StorageException( StorageErrorCodeStrings.INVALID_INPUT, "An incorrect stream length was specified, resulting in an authentication failure. Please specify correct length, or -1.", HttpURLConnection.HTTP_FORBIDDEN, null, null); } this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_CREATED) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Uploads the blob's metadata to the storage service. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void uploadMetadata() throws StorageException { this.uploadMetadata(null, null, null); } /** * Uploads the blob's metadata to the storage service using the specified lease ID, request options, and operation * context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void uploadMetadata(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.setMetadata(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), accessCondition, blobOptions, opContext); BlobRequest.addMetadata(request, blob.metadata, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } /** * Updates the blob's properties to the storage service. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void uploadProperties() throws StorageException { this.uploadProperties(null, null, null); } /** * Updates the blob's properties using the specified lease ID, request options, and operation context. * * @param accessCondition * An {@link AccessCondition} object that represents the access conditions for the blob. * @param options * A {@link BlobRequestOptions} object that specifies any additional options for the request. Specifying * <code>null</code> will use the default request options from the associated service client ( * {@link CloudBlobClient}). * @param opContext * An {@link OperationContext} object that represents the context for the current operation. This object * is used to track requests to the storage service, and to provide additional runtime information about * the operation. * * @throws StorageException * If a storage service error occurred. */ @DoesServiceRequest public final void uploadProperties(final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.setProperties(blob.getTransformedAddress(opContext), this .getRequestOptions().getTimeoutIntervalInMs(), blob.properties, null, accessCondition, blobOptions, opContext); BlobRequest.addMetadata(request, blob.metadata, opContext); client.getCredentials().signRequest(request, 0L); this.setResult(ExecutionEngine.processRequest(request, opContext)); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } blob.updatePropertiesFromResponse(request); return null; } }; ExecutionEngine .executeWithRetry(this.blobServiceClient, this, impl, options.getRetryPolicyFactory(), opContext); } }
false
true
public final void download(final OutputStream outStream, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); final InputStream streamRef = ExecutionEngine.getInputStream(request, opContext); this.setResult(opContext.getLastResult()); final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); final Boolean validateMD5 = !blobOptions.getDisableContentMD5Validation() && !Utility.isNullOrEmpty(contentMD5); final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); final long expectedLength = Long.parseLong(contentLength); blob.updatePropertiesFromResponse(request); final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMD5, this.getResult(), opContext); ExecutionEngine.getResponseCode(this.getResult(), request, opContext); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } if (descriptor.getLength() != expectedLength) { throw new StorageException( StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "An incorrect number of bytes was read from the connection. The connection may have been closed", Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } if (validateMD5 && !contentMD5.equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", contentMD5, descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } return null; } }; try { // Executed with no retries so that the first failure will move out // to the read Stream. ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, RetryNoRetry.getInstance(), opContext); opContext.setIntermediateMD5(null); } catch (final StorageException ex) { // Check if users has any retries specified. final RetryPolicy dummyPolicy = options.getRetryPolicyFactory().createInstance(opContext); if (!dummyPolicy.shouldRetry(0, opContext.getLastResult().getStatusCode(), (Exception) ex.getCause(), opContext).isShouldRetry()) { opContext.setIntermediateMD5(null); throw ex; } // Continuation, fail gracefully into a read stream. This needs to // be outside the operation above as it would get retried resulting // in a nested retry // Copy access condition, and update etag. This will potentially replace the if match value, but not on the // users object. AccessCondition etagLockCondition = new AccessCondition(); etagLockCondition.setIfMatch(this.getProperties().getEtag()); etagLockCondition.setLeaseID(accessCondition.getLeaseID()); // 1. Open Read Stream final BlobInputStream streamRef = this.openInputStream(etagLockCondition, options, opContext); // Cache value indicating if we need final boolean validateMd5 = streamRef.getValidateBlobMd5(); streamRef.setValidateBlobMd5(false); streamRef.mark(Integer.MAX_VALUE); try { // 2. Seek to current position, this will disable read streams // internal content md5 checks. if (opContext.getCurrentOperationByteCount() > 0) { // SCA will say this if a failure as we do not validate the // return of skip. // The Blob class repositioning a virtual pointer and will // always skip the correct // number of bytes. streamRef.skip(opContext.getCurrentOperationByteCount()); } // 3. Continue copying final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMd5, null, opContext); if (validateMd5 && !this.properties.getContentMD5().equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", this.properties.getContentMD5(), descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } catch (final IOException secondEx) { opContext.setIntermediateMD5(null); if (secondEx.getCause() != null && secondEx.getCause() instanceof StorageException) { throw (StorageException) secondEx.getCause(); } else { throw secondEx; } } } }
public final void download(final OutputStream outStream, final AccessCondition accessCondition, BlobRequestOptions options, OperationContext opContext) throws StorageException, IOException { if (opContext == null) { opContext = new OperationContext(); } if (options == null) { options = new BlobRequestOptions(); } opContext.initialize(); options.applyDefaults(this.blobServiceClient); final StorageOperation<CloudBlobClient, CloudBlob, Void> impl = new StorageOperation<CloudBlobClient, CloudBlob, Void>( options) { @Override public Void execute(final CloudBlobClient client, final CloudBlob blob, final OperationContext opContext) throws Exception { final BlobRequestOptions blobOptions = (BlobRequestOptions) this.getRequestOptions(); final HttpURLConnection request = BlobRequest.get(blob.getTransformedAddress(opContext), blobOptions.getTimeoutIntervalInMs(), blob.snapshotID, accessCondition, blobOptions, opContext); client.getCredentials().signRequest(request, -1L); final InputStream streamRef = ExecutionEngine.getInputStream(request, opContext); this.setResult(opContext.getLastResult()); final String contentMD5 = request.getHeaderField(Constants.HeaderConstants.CONTENT_MD5); final Boolean validateMD5 = !blobOptions.getDisableContentMD5Validation() && !Utility.isNullOrEmpty(contentMD5); final String contentLength = request.getHeaderField(Constants.HeaderConstants.CONTENT_LENGTH); final long expectedLength = Long.parseLong(contentLength); blob.updatePropertiesFromResponse(request); final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMD5, this.getResult(), opContext); ExecutionEngine.getResponseCode(this.getResult(), request, opContext); if (this.getResult().getStatusCode() != HttpURLConnection.HTTP_OK) { this.setNonExceptionedRetryableFailure(true); return null; } if (descriptor.getLength() != expectedLength) { throw new StorageException( StorageErrorCodeStrings.OUT_OF_RANGE_INPUT, "An incorrect number of bytes was read from the connection. The connection may have been closed", Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } if (validateMD5 && !contentMD5.equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", contentMD5, descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } return null; } }; try { // Executed with no retries so that the first failure will move out // to the read Stream. ExecutionEngine.executeWithRetry(this.blobServiceClient, this, impl, RetryNoRetry.getInstance(), opContext); opContext.setIntermediateMD5(null); } catch (final StorageException ex) { // Check if users has any retries specified, Or if the exception is retryable final RetryPolicy dummyPolicy = options.getRetryPolicyFactory().createInstance(opContext); if (ex.getHttpStatusCode() == Constants.HeaderConstants.HTTP_UNUSED_306 || !dummyPolicy.shouldRetry(0, opContext.getLastResult().getStatusCode(), (Exception) ex.getCause(), opContext).isShouldRetry()) { opContext.setIntermediateMD5(null); throw ex; } // Continuation, fail gracefully into a read stream. This needs to // be outside the operation above as it would get retried resulting // in a nested retry // Copy access condition, and update etag. This will potentially replace the if match value, but not on the // users object. AccessCondition etagLockCondition = new AccessCondition(); etagLockCondition.setIfMatch(this.getProperties().getEtag()); etagLockCondition.setLeaseID(accessCondition.getLeaseID()); // 1. Open Read Stream final BlobInputStream streamRef = this.openInputStream(etagLockCondition, options, opContext); // Cache value indicating if we need final boolean validateMd5 = streamRef.getValidateBlobMd5(); streamRef.setValidateBlobMd5(false); streamRef.mark(Integer.MAX_VALUE); try { // 2. Seek to current position, this will disable read streams // internal content md5 checks. if (opContext.getCurrentOperationByteCount() > 0) { // SCA will say this if a failure as we do not validate the // return of skip. // The Blob class repositioning a virtual pointer and will // always skip the correct // number of bytes. streamRef.skip(opContext.getCurrentOperationByteCount()); } // 3. Continue copying final StreamMd5AndLength descriptor = Utility.writeToOutputStream(streamRef, outStream, -1, false, validateMd5, null, opContext); if (validateMd5 && !this.properties.getContentMD5().equals(descriptor.getMd5())) { throw new StorageException(StorageErrorCodeStrings.INVALID_MD5, String.format( "Blob data corrupted (integrity check failed), Expected value is %s, retrieved %s", this.properties.getContentMD5(), descriptor.getMd5()), Constants.HeaderConstants.HTTP_UNUSED_306, null, null); } } catch (final IOException secondEx) { opContext.setIntermediateMD5(null); if (secondEx.getCause() != null && secondEx.getCause() instanceof StorageException) { throw (StorageException) secondEx.getCause(); } else { throw secondEx; } } } }
diff --git a/src/Account/AccountForm.java b/src/Account/AccountForm.java index 2995130f..296be4fa 100644 --- a/src/Account/AccountForm.java +++ b/src/Account/AccountForm.java @@ -1,327 +1,328 @@ /* * AccountForm.java * * Created on 20.05.2008, 13:05 * * Copyright (c) 2006-2008, Daniel Apatin (ad), http://apatin.net.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * You can also redistribute and/or modify this program under the * terms of the Psi License, specified in the accompanied COPYING * file, as published by the Psi Project; either dated January 1st, * 2005, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package Account; import xmpp.Account; import Client.*; import Info.Version; import locale.SR; import ui.SplashScreen; import ui.controls.AlertBox; import ui.controls.form.CheckBox; import ui.controls.form.DefForm; import ui.controls.form.LinkString; import ui.controls.form.NumberInput; import ui.controls.form.PasswordInput; import ui.controls.form.TextInput; //#ifdef FILE_IO //# import io.file.browse.Browser; //# import io.file.browse.BrowserListener; //#endif //#if HTTPCONNECT || HTTPPOLL || HTTPBIND //# import javax.microedition.lcdui.TextField; //#endif import xmpp.Jid; /** * * @author ad */ public class AccountForm extends DefForm //#ifdef IMPORT_EXPORT //# implements BrowserListener //#endif { private final AccountSelect accountSelect; private TextInput userbox; private PasswordInput passbox; private TextInput ipbox; private NumberInput portbox; private TextInput resourcebox; private TextInput nickbox; private CheckBox plainPwdbox; private CheckBox compressionBox; //#ifndef WMUC private CheckBox confOnlybox; //#endif private LinkString linkRegister; //#ifdef IMPORT_EXPORT //# private LinkString linkImport; //#endif private NumberInput keepAlive; //#if HTTPPOLL || HTTPCONNECT || HTTPBIND //# private TextInput proxyHost; //# private TextInput proxyPort; //# private TextInput proxyUser; //# private TextInput proxyPass; //# private CheckBox proxybox; //#endif AccountItem item; boolean newaccount; boolean showExtended; LinkString linkShowExtended; LinkString linkSave; private boolean doConnect; /** * Creates a new instance of AccountForm * * @param accountSelect * @param account */ public AccountForm(final AccountSelect accountSelect, AccountItem item) { super(null); this.accountSelect = accountSelect; this.item = item; newaccount = (this.item == null); if (newaccount) { this.item = new AccountItem(new Account()); } mainbar.setElementAt((newaccount) ? SR.MS_NEW_ACCOUNT : (this.item.toString()), 0); userbox = new TextInput(SR.MS_JID, newaccount ? "" : this.item.account.JID.getBare(), null); itemsList.addElement(userbox); passbox = new PasswordInput(SR.MS_PASSWORD, newaccount? "" : this.item.account.password); itemsList.addElement(passbox); nickbox = new TextInput(SR.MS_NICKNAME, this.item.account.nick, null); itemsList.addElement(nickbox); linkRegister = new LinkString(SR.MS_REGISTER_ACCOUNT) { public void doAction() { new AccountRegister(accountSelect); } }; if (newaccount) { itemsList.addElement(linkRegister); } //#ifdef IMPORT_EXPORT //# final BrowserListener listener = this; //# linkImport = new LinkString(SR.MS_LOAD_FROM_FILE) { //# //# public void doAction() { //# new Browser(null, listener, false); //# } //# }; //# itemsList.addElement(linkImport); //#endif linkShowExtended = new LinkString(SR.MS_EXTENDED_SETTINGS) { public void doAction() { showExtended(); } }; itemsList.addElement(linkShowExtended); linkSave = new LinkString(SR.MS_SAVE) { public void doAction() { cmdOk(); } }; itemsList.addElement(linkSave); } public void showExtended() { showExtended = true; itemsList.removeElement(linkShowExtended); itemsList.removeElement(linkSave); if (!newaccount) { itemsList.addElement(linkRegister); } ipbox = new TextInput(SR.MS_HOST_IP, item.account.hostAddr, null); portbox = new NumberInput(SR.MS_PORT, Integer.toString(item.account.port), 0, 65535); plainPwdbox = new CheckBox(SR.MS_PLAIN_PWD, item.account.plainAuth); compressionBox = new CheckBox(SR.MS_COMPRESSION, item.account.useCompression()); //#ifndef WMUC confOnlybox = new CheckBox(SR.MS_CONFERENCES_ONLY, item.account.mucOnly); //#endif //#if HTTPCONNECT //# proxybox = new CheckBox(/* //# * SR.MS_PROXY_ENABLE //# */"Proxy connect", item.account.isEnableProxy()); //#elif HTTPPOLL //# proxybox = new CheckBox("HTTP Polling", item.account.isEnableProxy()); //#elif HTTPBIND //# proxybox = new CheckBox("XMPP BOSH", item.account.isEnableProxy()); //#endif itemsList.addElement(plainPwdbox); itemsList.addElement(compressionBox); //#ifndef WMUC itemsList.addElement(confOnlybox); //#endif //#if HTTPCONNECT || HTTPBIND || HTTPPOLL //# itemsList.addElement(proxybox); //#endif //#ifndef HTTPBIND keepAlive = new NumberInput(SR.MS_KEEPALIVE_PERIOD, Integer.toString(item.account.keepAlivePeriod), 10, 2048);//10, 2096 //#endif - resourcebox = new TextInput(SR.MS_RESOURCE, item.account.JID.resource, null); + resourcebox = new TextInput(SR.MS_RESOURCE, newaccount ? Version.NAME : + item.account.JID.resource, null); //#if HTTPCONNECT //# proxyHost = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy name/IP", item.account.proxyHostAddr, null, TextField.URL); //# proxyPort = new NumberInput(/* //# * SR.MS_PROXY_PORT //# */"Proxy port", Integer.toString(item.account.getProxyPort()), 0, 65535); //# proxyUser = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy user", item.account.getProxyUser(), null, TextField.URL); //# proxyPass = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy pass", item.account.getProxyPass(), null, TextField.URL); //#elif HTTPPOLL //# proxyHost = new TextInput("HTTP Polling URL (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#elif HTTPBIND //# proxyHost = new TextInput("BOSH CM (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#endif itemsList.addElement(ipbox); itemsList.addElement(portbox); //#ifndef HTTPBIND itemsList.addElement(keepAlive); //#endif itemsList.addElement(resourcebox); //#if HTTPCONNECT //# itemsList.addElement(proxyHost); //# itemsList.addElement(proxyPort); //# itemsList.addElement(proxyUser); //# itemsList.addElement(proxyPass); //#elif HTTPPOLL || HTTPBIND //# itemsList.addElement(proxyHost); //#endif itemsList.addElement(linkSave); } public void cmdOk() { String user = userbox.getValue().trim().toLowerCase(); String pass = passbox.getValue(); String resource = Version.NAME; if (resourcebox != null) resource = resourcebox.getValue(); String server = ""; int at = user.indexOf('@'); if (at > -1) { server = user.substring(at + 1); user = user.substring(0, at); } if (server.length() == 0 || user.length() == 0 || pass.length() == 0) { return; } item.account.JID = new Jid(user, server, resource); item.account.password = pass; item.account.nick = nickbox.getValue(); if (showExtended) { String hostname = ipbox.getValue(); item.account.port = Integer.parseInt(portbox.getValue()); item.account.hostAddr = hostname; item.account.plainAuth = plainPwdbox.getValue(); item.account.compression = compressionBox.getValue(); //#ifndef WMUC item.account.mucOnly = confOnlybox.getValue(); //#endif //#if HTTPCONNECT || HTTPPOLL || HTTPBIND //# item.account.setEnableProxy(proxybox.getValue()); //#endif //#if HTTPPOLL || HTTPCONNECT || HTTPBIND //# item.account.proxyHostAddr = proxyHost.getValue(); //#if HTTPCONNECT //# item.account.setProxyPort(Integer.parseInt(proxyPort.getValue())); //# //# item.account.setProxyUser(proxyUser.getValue()); //# item.account.setProxyPass(proxyPass.getValue()); //#endif //#endif //#ifndef HTTPBIND item.account.keepAlivePeriod = Integer.parseInt(keepAlive.getValue()); //#endif } if (newaccount) { accountSelect.itemsList.addElement(item); } accountSelect.rmsUpdate(); accountSelect.commandState(); doConnect = true; destroyView(); item = null; } public void destroyView() { if (newaccount && doConnect) { new AlertBox(SR.MS_CONNECT_TO, item.account.JID.getBare() + "?") { public void yes() { SplashScreen.getInstance().setExit(sd.roster); startLogin(true); } public void no() { startLogin(false); accountSelect.show(); } }; } else { accountSelect.show(); } } private void startLogin(boolean login) { Config.getInstance().accountIndex = accountSelect.itemsList.size() - 1; sd.roster.loadAccount(login, Config.getInstance().accountIndex); SplashScreen.getInstance().destroyView(); } //#ifdef IMPORT_EXPORT //# public void BrowserFilePathNotify(String pathSelected) { //# new IE.Accounts(pathSelected, 0, false); //# accountSelect.loadAccounts(); //# destroyView(); //# } //#endif }
true
true
public void showExtended() { showExtended = true; itemsList.removeElement(linkShowExtended); itemsList.removeElement(linkSave); if (!newaccount) { itemsList.addElement(linkRegister); } ipbox = new TextInput(SR.MS_HOST_IP, item.account.hostAddr, null); portbox = new NumberInput(SR.MS_PORT, Integer.toString(item.account.port), 0, 65535); plainPwdbox = new CheckBox(SR.MS_PLAIN_PWD, item.account.plainAuth); compressionBox = new CheckBox(SR.MS_COMPRESSION, item.account.useCompression()); //#ifndef WMUC confOnlybox = new CheckBox(SR.MS_CONFERENCES_ONLY, item.account.mucOnly); //#endif //#if HTTPCONNECT //# proxybox = new CheckBox(/* //# * SR.MS_PROXY_ENABLE //# */"Proxy connect", item.account.isEnableProxy()); //#elif HTTPPOLL //# proxybox = new CheckBox("HTTP Polling", item.account.isEnableProxy()); //#elif HTTPBIND //# proxybox = new CheckBox("XMPP BOSH", item.account.isEnableProxy()); //#endif itemsList.addElement(plainPwdbox); itemsList.addElement(compressionBox); //#ifndef WMUC itemsList.addElement(confOnlybox); //#endif //#if HTTPCONNECT || HTTPBIND || HTTPPOLL //# itemsList.addElement(proxybox); //#endif //#ifndef HTTPBIND keepAlive = new NumberInput(SR.MS_KEEPALIVE_PERIOD, Integer.toString(item.account.keepAlivePeriod), 10, 2048);//10, 2096 //#endif resourcebox = new TextInput(SR.MS_RESOURCE, item.account.JID.resource, null); //#if HTTPCONNECT //# proxyHost = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy name/IP", item.account.proxyHostAddr, null, TextField.URL); //# proxyPort = new NumberInput(/* //# * SR.MS_PROXY_PORT //# */"Proxy port", Integer.toString(item.account.getProxyPort()), 0, 65535); //# proxyUser = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy user", item.account.getProxyUser(), null, TextField.URL); //# proxyPass = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy pass", item.account.getProxyPass(), null, TextField.URL); //#elif HTTPPOLL //# proxyHost = new TextInput("HTTP Polling URL (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#elif HTTPBIND //# proxyHost = new TextInput("BOSH CM (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#endif itemsList.addElement(ipbox); itemsList.addElement(portbox); //#ifndef HTTPBIND itemsList.addElement(keepAlive); //#endif itemsList.addElement(resourcebox); //#if HTTPCONNECT //# itemsList.addElement(proxyHost); //# itemsList.addElement(proxyPort); //# itemsList.addElement(proxyUser); //# itemsList.addElement(proxyPass); //#elif HTTPPOLL || HTTPBIND //# itemsList.addElement(proxyHost); //#endif itemsList.addElement(linkSave); }
public void showExtended() { showExtended = true; itemsList.removeElement(linkShowExtended); itemsList.removeElement(linkSave); if (!newaccount) { itemsList.addElement(linkRegister); } ipbox = new TextInput(SR.MS_HOST_IP, item.account.hostAddr, null); portbox = new NumberInput(SR.MS_PORT, Integer.toString(item.account.port), 0, 65535); plainPwdbox = new CheckBox(SR.MS_PLAIN_PWD, item.account.plainAuth); compressionBox = new CheckBox(SR.MS_COMPRESSION, item.account.useCompression()); //#ifndef WMUC confOnlybox = new CheckBox(SR.MS_CONFERENCES_ONLY, item.account.mucOnly); //#endif //#if HTTPCONNECT //# proxybox = new CheckBox(/* //# * SR.MS_PROXY_ENABLE //# */"Proxy connect", item.account.isEnableProxy()); //#elif HTTPPOLL //# proxybox = new CheckBox("HTTP Polling", item.account.isEnableProxy()); //#elif HTTPBIND //# proxybox = new CheckBox("XMPP BOSH", item.account.isEnableProxy()); //#endif itemsList.addElement(plainPwdbox); itemsList.addElement(compressionBox); //#ifndef WMUC itemsList.addElement(confOnlybox); //#endif //#if HTTPCONNECT || HTTPBIND || HTTPPOLL //# itemsList.addElement(proxybox); //#endif //#ifndef HTTPBIND keepAlive = new NumberInput(SR.MS_KEEPALIVE_PERIOD, Integer.toString(item.account.keepAlivePeriod), 10, 2048);//10, 2096 //#endif resourcebox = new TextInput(SR.MS_RESOURCE, newaccount ? Version.NAME : item.account.JID.resource, null); //#if HTTPCONNECT //# proxyHost = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy name/IP", item.account.proxyHostAddr, null, TextField.URL); //# proxyPort = new NumberInput(/* //# * SR.MS_PROXY_PORT //# */"Proxy port", Integer.toString(item.account.getProxyPort()), 0, 65535); //# proxyUser = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy user", item.account.getProxyUser(), null, TextField.URL); //# proxyPass = new TextInput(/* //# * SR.MS_PROXY_HOST //# */"Proxy pass", item.account.getProxyPass(), null, TextField.URL); //#elif HTTPPOLL //# proxyHost = new TextInput("HTTP Polling URL (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#elif HTTPBIND //# proxyHost = new TextInput("BOSH CM (http://server.tld:port)", item.account.proxyHostAddr, null, TextField.URL); //#endif itemsList.addElement(ipbox); itemsList.addElement(portbox); //#ifndef HTTPBIND itemsList.addElement(keepAlive); //#endif itemsList.addElement(resourcebox); //#if HTTPCONNECT //# itemsList.addElement(proxyHost); //# itemsList.addElement(proxyPort); //# itemsList.addElement(proxyUser); //# itemsList.addElement(proxyPass); //#elif HTTPPOLL || HTTPBIND //# itemsList.addElement(proxyHost); //#endif itemsList.addElement(linkSave); }
diff --git a/Reddimg/src/net/acuttone/reddimg/views/LinkViewerActivity.java b/Reddimg/src/net/acuttone/reddimg/views/LinkViewerActivity.java index d365d89..6d832a1 100644 --- a/Reddimg/src/net/acuttone/reddimg/views/LinkViewerActivity.java +++ b/Reddimg/src/net/acuttone/reddimg/views/LinkViewerActivity.java @@ -1,268 +1,267 @@ package net.acuttone.reddimg.views; import net.acuttone.reddimg.R; import net.acuttone.reddimg.R.id; import net.acuttone.reddimg.R.layout; import net.acuttone.reddimg.R.menu; import net.acuttone.reddimg.core.ReddimgApp; import net.acuttone.reddimg.core.RedditClient; import net.acuttone.reddimg.core.RedditLink; import net.acuttone.reddimg.prefs.PrefsActivity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; public class LinkViewerActivity extends Activity { public static final String LINK_INDEX = "LINK_INDEX"; private int currentLinkIndex; private ImageView viewBitmap; private ImageView viewLeftArrow; private ImageView viewRightArrow; private TextView textViewTitle; private AsyncTask<Void,Integer,Void> fadeTask; private ImageView viewUpvote; private ImageView viewDownvote; private TextView textviewLoading; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.linkviewer); textViewTitle = (TextView) findViewById(R.id.textViewTitle); textviewLoading = (TextView) findViewById(R.id.textviewLoading); textviewLoading.setText(""); viewBitmap = (ImageView) findViewById(R.id.scrollViewLink).findViewById(R.id.imageViewLink); viewUpvote = (ImageView) findViewById(R.id.imageupvote); viewUpvote.setAlpha(0); viewDownvote = (ImageView) findViewById(R.id.imagedownvote); viewDownvote.setAlpha(0); viewLeftArrow = (ImageView) findViewById(R.id.imageleftarrow); viewRightArrow = (ImageView) findViewById(R.id.imagerightarrow); viewLeftArrow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(currentLinkIndex > 0) { currentLinkIndex--; loadImage(); } } }); viewRightArrow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { currentLinkIndex++; loadImage(); } }); currentLinkIndex = getIntent().getExtras().getInt(LINK_INDEX); loadImage(); } private void loadImage() { AsyncTask<Integer, RedditLink, Object[]> loadTask = new AsyncTask<Integer, RedditLink, Object[]>() { @Override protected void onPreExecute() { super.onPreExecute(); if(fadeTask != null) { fadeTask.cancel(true); } - textviewLoading.setText("Loading links from " - + ReddimgApp.instance().getLinksQueue().getCurrentSubreddit()); + textviewLoading.setText("Loading links..."); viewLeftArrow.setAlpha(0); viewRightArrow.setAlpha(0); recycleBitmap(); } @Override protected Object[] doInBackground(Integer... params) { RedditLink redditLink = ReddimgApp.instance().getLinksQueue().get(params[0]); publishProgress(redditLink); Bitmap bitmap = ReddimgApp.instance().getImageCache().getImage(redditLink.getUrl()); Object [] result = new Object[2]; result[0] = bitmap; result[1] = redditLink; return result; } @Override protected void onProgressUpdate(RedditLink... values) { super.onProgressUpdate(values); RedditLink link = values[0]; updateTitle(link); textviewLoading.setText("Loading " + link.getUrl()); } @Override protected void onPostExecute(Object[] result) { super.onPostExecute(result); textviewLoading.setText(""); Bitmap bitmap = (Bitmap) ((Object []) result)[0]; RedditLink redditLink = (RedditLink) ((Object []) result)[1]; applyImage(bitmap, redditLink); } }; loadTask.execute(currentLinkIndex); } private void applyImage(Bitmap bitmap, RedditLink redditLink) { viewBitmap.setScaleType(ImageView.ScaleType.CENTER_INSIDE); viewBitmap.setAdjustViewBounds(true); viewBitmap.setImageBitmap(bitmap); refreshVoteIndicators(redditLink); fadeTask = new AsyncTask<Void, Integer, Void>() { @Override protected Void doInBackground(Void... params) { for(int alpha = 256; alpha >= 0 && isCancelled() == false; alpha -= 4) { try { Thread.sleep(10); } catch (InterruptedException e) { } publishProgress(alpha); } return null; } @Override protected void onProgressUpdate(Integer... values) { if(isCancelled() == false) { viewLeftArrow.setAlpha(values[0]); viewRightArrow.setAlpha(values[0]); } super.onProgressUpdate(values); } }; fadeTask.execute(null); } private void refreshVoteIndicators(RedditLink redditLink) { if(RedditClient.UPVOTE.equals(redditLink.getVoteStatus())) { viewUpvote.setAlpha(255); viewDownvote.setAlpha(0); } else if(RedditClient.DOWNVOTE.equals(redditLink.getVoteStatus())) { viewUpvote.setAlpha(0); viewDownvote.setAlpha(255); } else { viewUpvote.setAlpha(0); viewDownvote.setAlpha(0); } } @Override protected void onDestroy() { super.onDestroy(); recycleBitmap(); if(fadeTask != null) { fadeTask.cancel(true); } } private void recycleBitmap() { Drawable drawable = viewBitmap.getDrawable(); if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); viewBitmap.setImageBitmap(null); if(bitmap != null && bitmap.isRecycled() == false) { bitmap.recycle(); } } } public void updateTitle(RedditLink link) { StringBuilder sb = new StringBuilder(); SharedPreferences sp = ReddimgApp.instance().getPrefs(); if(sp.getBoolean("showScore", false)) { sb.append("[" + link.getScore() + "] "); } sb.append(link.getTitle()); if(sp.getBoolean("showAuthor", false)) { sb.append(" | by " + link.getAuthor()); } if(sp.getBoolean("showSubreddit", false)) { sb.append(" in " + link.getSubreddit()); } textViewTitle.setText(sb.toString()); int size = Integer.parseInt(sp.getString(PrefsActivity.TITLE_SIZE_KEY, "24")); textViewTitle.setTextSize(size); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = new MenuInflater(this); inflater.inflate(R.menu.menu_linkviewer, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuItem upvoteItem = menu.findItem(R.id.menuitem_upvote); MenuItem downvoteItem = menu.findItem(R.id.menuitem_downvote); if(ReddimgApp.instance().getRedditClient().isLoggedIn()) { upvoteItem.setEnabled(true); downvoteItem.setEnabled(true); } else { upvoteItem.setEnabled(false); downvoteItem.setEnabled(false); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { RedditLink currentLink = null; Intent intent = null; switch (item.getItemId()) { case R.id.menuitem_upvote: currentLink = ReddimgApp.instance().getLinksQueue().get(currentLinkIndex); ReddimgApp.instance().getRedditClient().vote(currentLink, RedditClient.UPVOTE); refreshVoteIndicators(currentLink); return true; case R.id.menuitem_downvote: currentLink = ReddimgApp.instance().getLinksQueue().get(currentLinkIndex); ReddimgApp.instance().getRedditClient().vote(currentLink, RedditClient.DOWNVOTE); refreshVoteIndicators(currentLink); return true; case R.id.menuitem_openimg: currentLink = ReddimgApp.instance().getLinksQueue().get(currentLinkIndex); String imageDiskPath = ReddimgApp.instance().getImageCache().getImageDiskPath(currentLink.getUrl()); Uri uri = Uri.parse("file://" + imageDiskPath); intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(uri, "image/*"); startActivity(intent); return true; case R.id.menuitem_opencomments: currentLink = ReddimgApp.instance().getLinksQueue().get(currentLinkIndex); intent = new Intent(Intent.ACTION_VIEW, Uri.parse(currentLink.getCommentUrl() + ".compact")); startActivity(intent); return true; default: return super.onContextItemSelected(item); } } }
true
true
private void loadImage() { AsyncTask<Integer, RedditLink, Object[]> loadTask = new AsyncTask<Integer, RedditLink, Object[]>() { @Override protected void onPreExecute() { super.onPreExecute(); if(fadeTask != null) { fadeTask.cancel(true); } textviewLoading.setText("Loading links from " + ReddimgApp.instance().getLinksQueue().getCurrentSubreddit()); viewLeftArrow.setAlpha(0); viewRightArrow.setAlpha(0); recycleBitmap(); } @Override protected Object[] doInBackground(Integer... params) { RedditLink redditLink = ReddimgApp.instance().getLinksQueue().get(params[0]); publishProgress(redditLink); Bitmap bitmap = ReddimgApp.instance().getImageCache().getImage(redditLink.getUrl()); Object [] result = new Object[2]; result[0] = bitmap; result[1] = redditLink; return result; } @Override protected void onProgressUpdate(RedditLink... values) { super.onProgressUpdate(values); RedditLink link = values[0]; updateTitle(link); textviewLoading.setText("Loading " + link.getUrl()); } @Override protected void onPostExecute(Object[] result) { super.onPostExecute(result); textviewLoading.setText(""); Bitmap bitmap = (Bitmap) ((Object []) result)[0]; RedditLink redditLink = (RedditLink) ((Object []) result)[1]; applyImage(bitmap, redditLink); } }; loadTask.execute(currentLinkIndex); }
private void loadImage() { AsyncTask<Integer, RedditLink, Object[]> loadTask = new AsyncTask<Integer, RedditLink, Object[]>() { @Override protected void onPreExecute() { super.onPreExecute(); if(fadeTask != null) { fadeTask.cancel(true); } textviewLoading.setText("Loading links..."); viewLeftArrow.setAlpha(0); viewRightArrow.setAlpha(0); recycleBitmap(); } @Override protected Object[] doInBackground(Integer... params) { RedditLink redditLink = ReddimgApp.instance().getLinksQueue().get(params[0]); publishProgress(redditLink); Bitmap bitmap = ReddimgApp.instance().getImageCache().getImage(redditLink.getUrl()); Object [] result = new Object[2]; result[0] = bitmap; result[1] = redditLink; return result; } @Override protected void onProgressUpdate(RedditLink... values) { super.onProgressUpdate(values); RedditLink link = values[0]; updateTitle(link); textviewLoading.setText("Loading " + link.getUrl()); } @Override protected void onPostExecute(Object[] result) { super.onPostExecute(result); textviewLoading.setText(""); Bitmap bitmap = (Bitmap) ((Object []) result)[0]; RedditLink redditLink = (RedditLink) ((Object []) result)[1]; applyImage(bitmap, redditLink); } }; loadTask.execute(currentLinkIndex); }
diff --git a/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java b/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java index 826eeada..85f32164 100644 --- a/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java +++ b/poem-jvm/src/java/org/b3mn/poem/handler/ImageRenderer.java @@ -1,72 +1,72 @@ /*************************************** * Copyright (c) 2008 * Bjoern Wagner * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************/ package org.b3mn.poem.handler; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.batik.transcoder.TranscoderException; import org.b3mn.poem.Identity; import org.b3mn.poem.Representation; import org.b3mn.poem.util.ExportHandler; @ExportHandler(uri="/svg", formatName="SVG", iconUrl="/backend/images/silk/page_white_vector.png") public class ImageRenderer extends HandlerBase { @Override public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) { setResponseHeaders(res); try { Representation representation = object.read(); String SvgRepresentation = representation.getSvg(); if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){ SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " + "xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " + "height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " + "svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" + "Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" + - "Please load the process with the Oryx Editor and push the Save button.</tspan></text></svg>"; + "Please load the process in Oryx Editor and press the Save button.</tspan></text></svg>"; } transcode(SvgRepresentation, res.getOutputStream(), representation); } catch (TranscoderException e) { e.printStackTrace(); } catch (Exception ie) { ie.printStackTrace(); } } protected void setResponseHeaders(HttpServletResponse res) { res.setContentType("image/svg+xml"); res.setStatus(200); } protected void transcode(String in_s, OutputStream out, Representation representation) throws TranscoderException, IOException { out.write(in_s.getBytes("UTF-8")); } }
true
true
public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) { setResponseHeaders(res); try { Representation representation = object.read(); String SvgRepresentation = representation.getSvg(); if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){ SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " + "xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " + "height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " + "svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" + "Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" + "Please load the process with the Oryx Editor and push the Save button.</tspan></text></svg>"; } transcode(SvgRepresentation, res.getOutputStream(), representation); } catch (TranscoderException e) { e.printStackTrace(); } catch (Exception ie) { ie.printStackTrace(); } }
public void doGet(HttpServletRequest req, HttpServletResponse res, Identity subject, Identity object) { setResponseHeaders(res); try { Representation representation = object.read(); String SvgRepresentation = representation.getSvg(); if ((SvgRepresentation == null) || (SvgRepresentation.length() == 0)){ SvgRepresentation = "<svg xmlns=\"http://www.w3.org/2000/svg\" " + "xmlns:oryx=\"http://oryx-editor.org\" id=\"oryx_1\" width=\"800\" " + "height=\"400\" xlink=\"http://www.w3.org/1999/xlink\" " + "svg=\"http://www.w3.org/2000/svg\"><text x=\"30\" y=\"30\" font-size=\"12px\">" + "Sorry, there is no graphical representation available on the server.<tspan x=\"30\" y=\"50\">" + "Please load the process in Oryx Editor and press the Save button.</tspan></text></svg>"; } transcode(SvgRepresentation, res.getOutputStream(), representation); } catch (TranscoderException e) { e.printStackTrace(); } catch (Exception ie) { ie.printStackTrace(); } }
diff --git a/Java/src/nl/captcha/text/producer/DefaultTextProducer.java b/Java/src/nl/captcha/text/producer/DefaultTextProducer.java index 3f23c1a..a9f44e3 100644 --- a/Java/src/nl/captcha/text/producer/DefaultTextProducer.java +++ b/Java/src/nl/captcha/text/producer/DefaultTextProducer.java @@ -1,44 +1,44 @@ package nl.captcha.text.producer; import java.security.SecureRandom; import java.util.Arrays; import java.util.Random; /** * Produces text of a given length from a given array of characters. * * @author <a href="mailto:[email protected]">James Childers</a> * */ public class DefaultTextProducer implements TextProducer { private static final Random _gen = new SecureRandom(); private static final int DEFAULT_LENGTH = 5; private static final char[] DEFAULT_CHARS = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'm', 'n', 'p', 'r', 'w', 'x', 'y', '2', '3', '4', '5', '6', '7', '8', }; private final int _length; private final char[] _srcChars; public DefaultTextProducer() { this(DEFAULT_LENGTH, DEFAULT_CHARS); } public DefaultTextProducer(int length, char[] srcChars) { _length = length; _srcChars = Arrays.copyOf(srcChars, srcChars.length); } @Override public String getText() { int car = _srcChars.length - 1; String capText = ""; for (int i = 0; i < _length; i++) { - capText += _srcChars[_gen.nextInt(car) + 1]; + capText += _srcChars[_gen.nextInt(_srcChars.length)]; } return capText; } }
true
true
public String getText() { int car = _srcChars.length - 1; String capText = ""; for (int i = 0; i < _length; i++) { capText += _srcChars[_gen.nextInt(car) + 1]; } return capText; }
public String getText() { int car = _srcChars.length - 1; String capText = ""; for (int i = 0; i < _length; i++) { capText += _srcChars[_gen.nextInt(_srcChars.length)]; } return capText; }
diff --git a/src/com/android/camera/ui/OtherSettingsPopup.java b/src/com/android/camera/ui/OtherSettingsPopup.java index f9d021f6..34c7e6f8 100644 --- a/src/com/android/camera/ui/OtherSettingsPopup.java +++ b/src/com/android/camera/ui/OtherSettingsPopup.java @@ -1,159 +1,158 @@ /* * 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 android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.android.camera.CameraSettings; import com.android.camera.ListPreference; import com.android.camera.PreferenceGroup; import com.android.camera.R; import java.util.ArrayList; /* A popup window that contains several camera settings. */ public class OtherSettingsPopup extends AbstractSettingPopup implements InLineSettingItem.Listener, AdapterView.OnItemClickListener { @SuppressWarnings("unused") private static final String TAG = "OtherSettingsPopup"; private Listener mListener; private ArrayList<ListPreference> mListItem = new ArrayList<ListPreference>(); static public interface Listener { public void onSettingChanged(); public void onRestorePreferencesClicked(); } private class OtherSettingsAdapter extends ArrayAdapter<ListPreference> { LayoutInflater mInflater; OtherSettingsAdapter() { super(OtherSettingsPopup.this.getContext(), 0, mListItem); mInflater = LayoutInflater.from(getContext()); } private int getSettingLayoutId(ListPreference pref) { // If the preference is null, it will be the only item , i.e. // 'Restore setting' in the popup window. if (pref == null) return R.layout.in_line_setting_restore; // Currently, the RecordLocationPreference is the only setting // which applies the on/off switch. if (CameraSettings.KEY_POWER_SHUTTER.equals(pref.getKey()) || CameraSettings.KEY_RECORD_LOCATION.equals(pref.getKey())) { return R.layout.in_line_setting_switch; } return R.layout.in_line_setting_knob; } @Override public View getView(int position, View convertView, ViewGroup parent) { - if (convertView != null) return convertView; ListPreference pref = mListItem.get(position); int viewLayoutId = getSettingLayoutId(pref); InLineSettingItem view = (InLineSettingItem) mInflater.inflate(viewLayoutId, parent, false); if (viewLayoutId == R.layout.in_line_setting_restore) { view.setId(R.id.restore_default); } view.initialize(pref); // no init for restore one view.setSettingChangedListener(OtherSettingsPopup.this); return view; } } public void setSettingChangedListener(Listener listener) { mListener = listener; } public OtherSettingsPopup(Context context, AttributeSet attrs) { super(context, attrs); } public void initialize(PreferenceGroup group, String[] keys) { // Prepare the setting items. for (int i = 0; i < keys.length; ++i) { ListPreference pref = group.findPreference(keys[i]); if (pref != null) mListItem.add(pref); } // Prepare the restore setting line. mListItem.add(null); ArrayAdapter<ListPreference> mListItemAdapter = new OtherSettingsAdapter(); ((ListView) mSettingList).setAdapter(mListItemAdapter); ((ListView) mSettingList).setOnItemClickListener(this); ((ListView) mSettingList).setSelector(android.R.color.transparent); } @Override public void onSettingChanged() { if (mListener != null) { mListener.onSettingChanged(); } } // Scene mode can override other camera settings (ex: flash mode). public void overrideSettings(final String ... keyvalues) { int count = mSettingList.getChildCount(); for (int i = 0; i < keyvalues.length; i += 2) { String key = keyvalues[i]; String value = keyvalues[i + 1]; for (int j = 0; j < count; j++) { ListPreference pref = mListItem.get(j); if (pref != null && key.equals(pref.getKey())) { InLineSettingItem settingItem = (InLineSettingItem) mSettingList.getChildAt(j); settingItem.overrideSettings(value); } } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if ((position == mListItem.size() - 1) && (mListener != null)) { mListener.onRestorePreferencesClicked(); } } @Override public void reloadPreference() { int count = mSettingList.getChildCount(); for (int i = 0; i < count; i++) { ListPreference pref = mListItem.get(i); if (pref != null) { InLineSettingItem settingItem = (InLineSettingItem) mSettingList.getChildAt(i); settingItem.reloadPreference(); } } } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { if (convertView != null) return convertView; ListPreference pref = mListItem.get(position); int viewLayoutId = getSettingLayoutId(pref); InLineSettingItem view = (InLineSettingItem) mInflater.inflate(viewLayoutId, parent, false); if (viewLayoutId == R.layout.in_line_setting_restore) { view.setId(R.id.restore_default); } view.initialize(pref); // no init for restore one view.setSettingChangedListener(OtherSettingsPopup.this); return view; }
public View getView(int position, View convertView, ViewGroup parent) { ListPreference pref = mListItem.get(position); int viewLayoutId = getSettingLayoutId(pref); InLineSettingItem view = (InLineSettingItem) mInflater.inflate(viewLayoutId, parent, false); if (viewLayoutId == R.layout.in_line_setting_restore) { view.setId(R.id.restore_default); } view.initialize(pref); // no init for restore one view.setSettingChangedListener(OtherSettingsPopup.this); return view; }
diff --git a/src/org/bouncycastle/asn1/BEROctetStringGenerator.java b/src/org/bouncycastle/asn1/BEROctetStringGenerator.java index ab68788e..aa511de5 100644 --- a/src/org/bouncycastle/asn1/BEROctetStringGenerator.java +++ b/src/org/bouncycastle/asn1/BEROctetStringGenerator.java @@ -1,98 +1,100 @@ package org.bouncycastle.asn1; import java.io.IOException; import java.io.OutputStream; public class BEROctetStringGenerator extends BERGenerator { public BEROctetStringGenerator(OutputStream out) throws IOException { super(out); writeBERHeader(DERTags.CONSTRUCTED | DERTags.OCTET_STRING); } public BEROctetStringGenerator( OutputStream out, int tagNo, boolean isExplicit) throws IOException { super(out, tagNo, isExplicit); writeBERHeader(DERTags.CONSTRUCTED | DERTags.OCTET_STRING); } public OutputStream getOctetOutputStream() { return getOctetOutputStream(new byte[1000]); // limit for CER encoding. } public OutputStream getOctetOutputStream( byte[] buf) { return new BufferedBEROctetStream(buf); } private class BufferedBEROctetStream extends OutputStream { private byte[] _buf; private int _off; BufferedBEROctetStream( byte[] buf) { _buf = buf; _off = 0; } public void write( int b) throws IOException { _buf[_off++] = (byte)b; if (_off == _buf.length) { _out.write(new DEROctetString(_buf).getEncoded()); _off = 0; } } public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int numToCopy = Math.min(len, _buf.length - _off); System.arraycopy(b, off, _buf, _off, numToCopy); _off += numToCopy; if (_off < _buf.length) + { break; + } _out.write(new DEROctetString(_buf).getEncoded()); _off = 0; off += numToCopy; len -= numToCopy; } } public void close() throws IOException { if (_off != 0) { byte[] bytes = new byte[_off]; System.arraycopy(_buf, 0, bytes, 0, _off); _out.write(new DEROctetString(bytes).getEncoded()); } writeBEREnd(); } } }
false
true
public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int numToCopy = Math.min(len, _buf.length - _off); System.arraycopy(b, off, _buf, _off, numToCopy); _off += numToCopy; if (_off < _buf.length) break; _out.write(new DEROctetString(_buf).getEncoded()); _off = 0; off += numToCopy; len -= numToCopy; } }
public void write(byte[] b, int off, int len) throws IOException { while (len > 0) { int numToCopy = Math.min(len, _buf.length - _off); System.arraycopy(b, off, _buf, _off, numToCopy); _off += numToCopy; if (_off < _buf.length) { break; } _out.write(new DEROctetString(_buf).getEncoded()); _off = 0; off += numToCopy; len -= numToCopy; } }
diff --git a/src/main/java/net/oneandone/maven/plugins/prerelease/Swap.java b/src/main/java/net/oneandone/maven/plugins/prerelease/Swap.java index 99568bc..128f338 100644 --- a/src/main/java/net/oneandone/maven/plugins/prerelease/Swap.java +++ b/src/main/java/net/oneandone/maven/plugins/prerelease/Swap.java @@ -1,116 +1,117 @@ /** * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.maven.plugins.prerelease; import net.oneandone.maven.plugins.prerelease.core.Archive; import net.oneandone.maven.plugins.prerelease.core.Descriptor; import net.oneandone.maven.plugins.prerelease.core.Target; import net.oneandone.sushi.fs.Node; import net.oneandone.sushi.fs.file.FileNode; import net.oneandone.sushi.fs.filter.Filter; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Wipes archives and moves prereleases to the next storage. You usually have two storages, primary and secondary. * Useful when you use ram disks: use the ramdisk as primary storage, and a hardisk as secondary storage. */ @Mojo(name = "swap", requiresProject = false) public class Swap extends Base { @Override public void doExecute() throws Exception { Set done; List<FileNode> storages; List<Node> archives; Archive archive; String relative; FileNode dest; done = new HashSet<>(); storages = storages(); for (Node storage : storages()) { archives = storage.find("*/*"); for (Node candidate : archives) { if (!candidate.isDirectory()) { continue; } relative = candidate.getRelative(storage); if (!done.add(relative)) { // already processed continue; } archive = Archive.tryOpen(directories(storages, relative)); if (archive == null) { getLog().info("skipped because it is locked: " + relative); } else { try { archive.wipe(keep); for (FileNode src : archive.list().values()) { if (!src.join("prerelease.properties").readString().contains("prerelease=")) { // This property was introduced in 1.6, together with multiple storage support getLog().info("skipped -- prerelease version too old"); continue; } dest = nextStorage(storages, src); if (dest == null) { getLog().info("already in final storage: " + src); } else { + dest = dest.join(relative, src.getName()); dest.getParent().mkdirsOpt(); src.move(dest); getLog().info("swapped " + src.getAbsolute() + " -> " + dest.getAbsolute()); } } } finally { archive.close(); } } } } getLog().info(done.size() + " archives processed."); } private static FileNode nextStorage(List<FileNode> storages, FileNode prerelease) { FileNode storage; for (int i = 0, max = storages.size(); i < max; i++) { storage = storages.get(i); if (prerelease.hasAnchestor(storage)) { if (i + 1 < max) { return storages.get(i + 1); } else { return null; } } } throw new IllegalStateException(prerelease.getAbsolute()); } private static List<FileNode> directories(List<FileNode> storages, String relative) { List<FileNode> result; result = new ArrayList<>(); for (FileNode storage : storages) { result.add(storage.join(relative)); } return result; } }
true
true
public void doExecute() throws Exception { Set done; List<FileNode> storages; List<Node> archives; Archive archive; String relative; FileNode dest; done = new HashSet<>(); storages = storages(); for (Node storage : storages()) { archives = storage.find("*/*"); for (Node candidate : archives) { if (!candidate.isDirectory()) { continue; } relative = candidate.getRelative(storage); if (!done.add(relative)) { // already processed continue; } archive = Archive.tryOpen(directories(storages, relative)); if (archive == null) { getLog().info("skipped because it is locked: " + relative); } else { try { archive.wipe(keep); for (FileNode src : archive.list().values()) { if (!src.join("prerelease.properties").readString().contains("prerelease=")) { // This property was introduced in 1.6, together with multiple storage support getLog().info("skipped -- prerelease version too old"); continue; } dest = nextStorage(storages, src); if (dest == null) { getLog().info("already in final storage: " + src); } else { dest.getParent().mkdirsOpt(); src.move(dest); getLog().info("swapped " + src.getAbsolute() + " -> " + dest.getAbsolute()); } } } finally { archive.close(); } } } } getLog().info(done.size() + " archives processed."); }
public void doExecute() throws Exception { Set done; List<FileNode> storages; List<Node> archives; Archive archive; String relative; FileNode dest; done = new HashSet<>(); storages = storages(); for (Node storage : storages()) { archives = storage.find("*/*"); for (Node candidate : archives) { if (!candidate.isDirectory()) { continue; } relative = candidate.getRelative(storage); if (!done.add(relative)) { // already processed continue; } archive = Archive.tryOpen(directories(storages, relative)); if (archive == null) { getLog().info("skipped because it is locked: " + relative); } else { try { archive.wipe(keep); for (FileNode src : archive.list().values()) { if (!src.join("prerelease.properties").readString().contains("prerelease=")) { // This property was introduced in 1.6, together with multiple storage support getLog().info("skipped -- prerelease version too old"); continue; } dest = nextStorage(storages, src); if (dest == null) { getLog().info("already in final storage: " + src); } else { dest = dest.join(relative, src.getName()); dest.getParent().mkdirsOpt(); src.move(dest); getLog().info("swapped " + src.getAbsolute() + " -> " + dest.getAbsolute()); } } } finally { archive.close(); } } } } getLog().info(done.size() + " archives processed."); }
diff --git a/tests/src/com/android/inputmethod/latin/SuggestHelper.java b/tests/src/com/android/inputmethod/latin/SuggestHelper.java index a845acb9..ed01a753 100644 --- a/tests/src/com/android/inputmethod/latin/SuggestHelper.java +++ b/tests/src/com/android/inputmethod/latin/SuggestHelper.java @@ -1,158 +1,159 @@ /* * 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.inputmethod.latin; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.KeyDetector; import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.LatinKeyboard; import com.android.inputmethod.keyboard.ProximityKeyDetector; import android.content.Context; import android.text.TextUtils; import java.io.File; import java.util.List; public class SuggestHelper { protected final Suggest mSuggest; private final LatinKeyboard mKeyboard; private final KeyDetector mKeyDetector; public SuggestHelper(Context context, int dictionaryId, KeyboardId keyboardId) { mSuggest = new Suggest(context, dictionaryId); mKeyboard = new LatinKeyboard(context, keyboardId); mKeyDetector = new ProximityKeyDetector(); init(); } protected SuggestHelper(Context context, File dictionaryPath, long startOffset, long length, KeyboardId keyboardId) { mSuggest = new Suggest(dictionaryPath, startOffset, length); mKeyboard = new LatinKeyboard(context, keyboardId); mKeyDetector = new ProximityKeyDetector(); init(); } private void init() { mSuggest.setQuickFixesEnabled(false); mSuggest.setCorrectionMode(Suggest.CORRECTION_FULL); mKeyDetector.setKeyboard(mKeyboard, 0, 0); mKeyDetector.setProximityCorrectionEnabled(true); mKeyDetector.setProximityThreshold(KeyDetector.getMostCommonKeyWidth(mKeyboard)); } public void setCorrectionMode(int correctionMode) { mSuggest.setCorrectionMode(correctionMode); } public boolean hasMainDictionary() { return mSuggest.hasMainDictionary(); } private void addKeyInfo(WordComposer word, char c) { final List<Key> keys = mKeyboard.getKeys(); for (final Key key : keys) { if (key.mCode == c) { final int x = key.mX + key.mWidth / 2; final int y = key.mY + key.mHeight / 2; final int[] codes = mKeyDetector.newCodeArray(); mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes); word.add(c, codes, x, y); + return; } } word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); } protected WordComposer createWordComposer(CharSequence s) { WordComposer word = new WordComposer(); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); addKeyInfo(word, c); } return word; } public boolean isValidWord(CharSequence typed) { return mSuggest.isValidWord(typed); } // TODO: This may be slow, but is OK for test so far. public SuggestedWords getSuggestions(CharSequence typed) { return mSuggest.getSuggestions(null, createWordComposer(typed), null); } public CharSequence getFirstSuggestion(CharSequence typed) { WordComposer word = createWordComposer(typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null); // Note that suggestions.getWord(0) is the word user typed. return suggestions.size() > 1 ? suggestions.getWord(1) : null; } public CharSequence getAutoCorrection(CharSequence typed) { WordComposer word = createWordComposer(typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null); // Note that suggestions.getWord(0) is the word user typed. return (suggestions.size() > 1 && mSuggest.hasAutoCorrection()) ? suggestions.getWord(1) : null; } public int getSuggestIndex(CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, null); // Note that suggestions.getWord(0) is the word user typed. for (int i = 1; i < suggestions.size(); i++) { if (TextUtils.equals(suggestions.getWord(i), expected)) return i; } return -1; } private void getBigramSuggestions(CharSequence previous, CharSequence typed) { if (!TextUtils.isEmpty(previous) && (typed.length() > 1)) { WordComposer firstChar = createWordComposer(Character.toString(typed.charAt(0))); mSuggest.getSuggestions(null, firstChar, previous); } } public CharSequence getBigramFirstSuggestion(CharSequence previous, CharSequence typed) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous); return suggestions.size() > 1 ? suggestions.getWord(1) : null; } public CharSequence getBigramAutoCorrection(CharSequence previous, CharSequence typed) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous); return (suggestions.size() > 1 && mSuggest.hasAutoCorrection()) ? suggestions.getWord(1) : null; } public int searchBigramSuggestion(CharSequence previous, CharSequence typed, CharSequence expected) { WordComposer word = createWordComposer(typed); getBigramSuggestions(previous, typed); SuggestedWords suggestions = mSuggest.getSuggestions(null, word, previous); for (int i = 1; i < suggestions.size(); i++) { if (TextUtils.equals(suggestions.getWord(i), expected)) return i; } return -1; } }
true
true
private void addKeyInfo(WordComposer word, char c) { final List<Key> keys = mKeyboard.getKeys(); for (final Key key : keys) { if (key.mCode == c) { final int x = key.mX + key.mWidth / 2; final int y = key.mY + key.mHeight / 2; final int[] codes = mKeyDetector.newCodeArray(); mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes); word.add(c, codes, x, y); } } word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); }
private void addKeyInfo(WordComposer word, char c) { final List<Key> keys = mKeyboard.getKeys(); for (final Key key : keys) { if (key.mCode == c) { final int x = key.mX + key.mWidth / 2; final int y = key.mY + key.mHeight / 2; final int[] codes = mKeyDetector.newCodeArray(); mKeyDetector.getKeyIndexAndNearbyCodes(x, y, codes); word.add(c, codes, x, y); return; } } word.add(c, new int[] { c }, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); }
diff --git a/src/java/net/mojodna/searchable/Searcher.java b/src/java/net/mojodna/searchable/Searcher.java index c54d927..25ebfc6 100644 --- a/src/java/net/mojodna/searchable/Searcher.java +++ b/src/java/net/mojodna/searchable/Searcher.java @@ -1,169 +1,173 @@ package net.mojodna.searchable; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import net.mojodna.searchable.converter.UUIDConverter; import net.mojodna.searchable.example.SearchableBean; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.log4j.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; public class Searcher extends IndexSupport { private static final Logger log = Logger.getLogger( Searcher.class ); static { if ( null == ConvertUtils.lookup( UUID.class ) ) { ConvertUtils.register( new UUIDConverter(), UUID.class ); } } public List<Result> search(final Query query) throws SearchException { IndexSearcher searcher = null; try { searcher = new IndexSearcher( getIndexPath() ); final Hits hits = searcher.search(query); final List<Result> results = new LinkedList<Result>(); for (int i = 0; i < hits.length(); i++) { final Document doc = hits.doc(i); Result result = null; final String className = doc.get( TYPE_FIELD_NAME ); - log.debug("Creating new instance of: " + className); try { try { - final Object o = Class.forName(className).newInstance(); - if ( o instanceof Result ) - result = (Result) o; + if ( null != className ) { + log.debug("Creating new instance of: " + className); + final Object o = Class.forName( className ).newInstance(); + if ( o instanceof Result ) + result = (Result) o; + } else { + result = new GenericResult(); + } } catch (final ClassNotFoundException e) { result = new GenericResult(); } if ( result instanceof Searchable ) { // special handling for searchables final String idField = SearchableBeanUtils.getIdPropertyName( (Searchable) result ); final Map storedFields = new HashMap(); final Enumeration fields = doc.fields(); while (fields.hasMoreElements()) { final Field f = (Field) fields.nextElement(); // exclude private fields if ( !PRIVATE_FIELD_NAMES.contains( f.name() ) ) storedFields.put( f.name(), f.stringValue() ); } result.setStoredFields( storedFields ); final String id = doc.get( ID_FIELD_NAME ); final Field idClass = doc.getField( ID_TYPE_FIELD_NAME ); if ( null != id ) { log.debug("Setting id to '" + id + "' of type " + idClass.stringValue() ); try { final Object idValue = ConvertUtils.convert( id, Class.forName( idClass.stringValue() ) ); PropertyUtils.setSimpleProperty(result, idField, idValue ); } catch (final ClassNotFoundException e) { log.warn("Id type was not a class that could be found: " + idClass.stringValue() ); } } else { log.warn("Id value was null."); } } else { final GenericResult gr = new GenericResult(); gr.setId( doc.get( ID_FIELD_NAME ) ); gr.setType( doc.get( TYPE_FIELD_NAME ) ); result = gr; } } catch (final Exception e) { throw new SearchException("Could not reconstitute resultant object.", e ); } result.setRanking( i ); result.setScore( hits.score( i ) ); results.add( result ); } return results; } catch (final IOException e) { throw new SearchException( e ); } finally { try { if ( null != searcher ) searcher.close(); } catch (final IOException e) { throw new SearchException("Unable to close searcher.", e ); } } } /** * Search query interface. */ public List<Result> search(final String _query) throws SearchException { try { // "description" as a default field means little here final Query query = QueryParser.parse(_query, "description", getAnalyzer() ); final List<Result> results = search( query ); log.debug("Found " + results.size() + " document(s) that matched query '" + _query + "':"); return results; } catch (final ParseException e) { throw new SearchException( e ); } } protected boolean isFieldPresent(final String field) throws IndexException { IndexReader reader = null; try { reader = IndexReader.open( getIndexPath() ); return reader.getFieldNames( true ).contains( field ); } catch (final IOException e) { throw new IndexException( e ); } finally { try { if ( null != reader ) reader.close(); } catch (final IOException e) { throw new IndexException("Unable to close reader.", e ); } } } public static void main(final String[] args) throws Exception { final Searcher s = new Searcher(); final List<Result> results = s.search("bio:kayak"); log.debug( results ); for ( final Result result : results ) { log.debug("Score: " + result.getScore() ); log.debug("Stored fields: " + result.getStoredFields() ); // to test UUIDConverter log.debug("UUID: " + ((SearchableBean) results.get(0)).getUUID() ); } } }
false
true
public List<Result> search(final Query query) throws SearchException { IndexSearcher searcher = null; try { searcher = new IndexSearcher( getIndexPath() ); final Hits hits = searcher.search(query); final List<Result> results = new LinkedList<Result>(); for (int i = 0; i < hits.length(); i++) { final Document doc = hits.doc(i); Result result = null; final String className = doc.get( TYPE_FIELD_NAME ); log.debug("Creating new instance of: " + className); try { try { final Object o = Class.forName(className).newInstance(); if ( o instanceof Result ) result = (Result) o; } catch (final ClassNotFoundException e) { result = new GenericResult(); } if ( result instanceof Searchable ) { // special handling for searchables final String idField = SearchableBeanUtils.getIdPropertyName( (Searchable) result ); final Map storedFields = new HashMap(); final Enumeration fields = doc.fields(); while (fields.hasMoreElements()) { final Field f = (Field) fields.nextElement(); // exclude private fields if ( !PRIVATE_FIELD_NAMES.contains( f.name() ) ) storedFields.put( f.name(), f.stringValue() ); } result.setStoredFields( storedFields ); final String id = doc.get( ID_FIELD_NAME ); final Field idClass = doc.getField( ID_TYPE_FIELD_NAME ); if ( null != id ) { log.debug("Setting id to '" + id + "' of type " + idClass.stringValue() ); try { final Object idValue = ConvertUtils.convert( id, Class.forName( idClass.stringValue() ) ); PropertyUtils.setSimpleProperty(result, idField, idValue ); } catch (final ClassNotFoundException e) { log.warn("Id type was not a class that could be found: " + idClass.stringValue() ); } } else { log.warn("Id value was null."); } } else { final GenericResult gr = new GenericResult(); gr.setId( doc.get( ID_FIELD_NAME ) ); gr.setType( doc.get( TYPE_FIELD_NAME ) ); result = gr; } } catch (final Exception e) { throw new SearchException("Could not reconstitute resultant object.", e ); } result.setRanking( i ); result.setScore( hits.score( i ) ); results.add( result ); } return results; } catch (final IOException e) { throw new SearchException( e ); } finally { try { if ( null != searcher ) searcher.close(); } catch (final IOException e) { throw new SearchException("Unable to close searcher.", e ); } } }
public List<Result> search(final Query query) throws SearchException { IndexSearcher searcher = null; try { searcher = new IndexSearcher( getIndexPath() ); final Hits hits = searcher.search(query); final List<Result> results = new LinkedList<Result>(); for (int i = 0; i < hits.length(); i++) { final Document doc = hits.doc(i); Result result = null; final String className = doc.get( TYPE_FIELD_NAME ); try { try { if ( null != className ) { log.debug("Creating new instance of: " + className); final Object o = Class.forName( className ).newInstance(); if ( o instanceof Result ) result = (Result) o; } else { result = new GenericResult(); } } catch (final ClassNotFoundException e) { result = new GenericResult(); } if ( result instanceof Searchable ) { // special handling for searchables final String idField = SearchableBeanUtils.getIdPropertyName( (Searchable) result ); final Map storedFields = new HashMap(); final Enumeration fields = doc.fields(); while (fields.hasMoreElements()) { final Field f = (Field) fields.nextElement(); // exclude private fields if ( !PRIVATE_FIELD_NAMES.contains( f.name() ) ) storedFields.put( f.name(), f.stringValue() ); } result.setStoredFields( storedFields ); final String id = doc.get( ID_FIELD_NAME ); final Field idClass = doc.getField( ID_TYPE_FIELD_NAME ); if ( null != id ) { log.debug("Setting id to '" + id + "' of type " + idClass.stringValue() ); try { final Object idValue = ConvertUtils.convert( id, Class.forName( idClass.stringValue() ) ); PropertyUtils.setSimpleProperty(result, idField, idValue ); } catch (final ClassNotFoundException e) { log.warn("Id type was not a class that could be found: " + idClass.stringValue() ); } } else { log.warn("Id value was null."); } } else { final GenericResult gr = new GenericResult(); gr.setId( doc.get( ID_FIELD_NAME ) ); gr.setType( doc.get( TYPE_FIELD_NAME ) ); result = gr; } } catch (final Exception e) { throw new SearchException("Could not reconstitute resultant object.", e ); } result.setRanking( i ); result.setScore( hits.score( i ) ); results.add( result ); } return results; } catch (final IOException e) { throw new SearchException( e ); } finally { try { if ( null != searcher ) searcher.close(); } catch (final IOException e) { throw new SearchException("Unable to close searcher.", e ); } } }
diff --git a/src/main/java/org/apache/log4j/net/SyslogAppender.java b/src/main/java/org/apache/log4j/net/SyslogAppender.java index 8ead1437..6ab7eddf 100644 --- a/src/main/java/org/apache/log4j/net/SyslogAppender.java +++ b/src/main/java/org/apache/log4j/net/SyslogAppender.java @@ -1,531 +1,536 @@ /* * 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.log4j.net; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Layout; import org.apache.log4j.helpers.SyslogQuietWriter; import org.apache.log4j.helpers.SyslogWriter; import org.apache.log4j.spi.LoggingEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.net.InetAddress; import java.net.UnknownHostException; import java.io.IOException; // Contributors: Yves Bossel <[email protected]> // Christopher Taylor <[email protected]> /** Use SyslogAppender to send log messages to a remote syslog daemon. @author Ceki G&uuml;lc&uuml; @author Anders Kristensen */ public class SyslogAppender extends AppenderSkeleton { // The following constants are extracted from a syslog.h file // copyrighted by the Regents of the University of California // I hope nobody at Berkley gets offended. /** Kernel messages */ final static public int LOG_KERN = 0; /** Random user-level messages */ final static public int LOG_USER = 1<<3; /** Mail system */ final static public int LOG_MAIL = 2<<3; /** System daemons */ final static public int LOG_DAEMON = 3<<3; /** security/authorization messages */ final static public int LOG_AUTH = 4<<3; /** messages generated internally by syslogd */ final static public int LOG_SYSLOG = 5<<3; /** line printer subsystem */ final static public int LOG_LPR = 6<<3; /** network news subsystem */ final static public int LOG_NEWS = 7<<3; /** UUCP subsystem */ final static public int LOG_UUCP = 8<<3; /** clock daemon */ final static public int LOG_CRON = 9<<3; /** security/authorization messages (private) */ final static public int LOG_AUTHPRIV = 10<<3; /** ftp daemon */ final static public int LOG_FTP = 11<<3; // other codes through 15 reserved for system use /** reserved for local use */ final static public int LOG_LOCAL0 = 16<<3; /** reserved for local use */ final static public int LOG_LOCAL1 = 17<<3; /** reserved for local use */ final static public int LOG_LOCAL2 = 18<<3; /** reserved for local use */ final static public int LOG_LOCAL3 = 19<<3; /** reserved for local use */ final static public int LOG_LOCAL4 = 20<<3; /** reserved for local use */ final static public int LOG_LOCAL5 = 21<<3; /** reserved for local use */ final static public int LOG_LOCAL6 = 22<<3; /** reserved for local use*/ final static public int LOG_LOCAL7 = 23<<3; protected static final int SYSLOG_HOST_OI = 0; protected static final int FACILITY_OI = 1; static final String TAB = " "; // Have LOG_USER as default int syslogFacility = LOG_USER; String facilityStr; boolean facilityPrinting = false; //SyslogTracerPrintWriter stp; SyslogQuietWriter sqw; String syslogHost; /** * If true, the appender will generate the HEADER (timestamp and host name) * part of the syslog packet. * @since 1.2.15 */ private boolean header = false; /** * Date format used if header = true. * @since 1.2.15 */ private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd HH:mm:ss ", Locale.ENGLISH); /** * Host name used to identify messages from this appender. * @since 1.2.15 */ private String localHostname; /** * Set to true after the header of the layout has been sent or if it has none. */ private boolean layoutHeaderChecked = false; public SyslogAppender() { this.initSyslogFacilityStr(); } public SyslogAppender(Layout layout, int syslogFacility) { this.layout = layout; this.syslogFacility = syslogFacility; this.initSyslogFacilityStr(); } public SyslogAppender(Layout layout, String syslogHost, int syslogFacility) { this(layout, syslogFacility); setSyslogHost(syslogHost); } /** Release any resources held by this SyslogAppender. @since 0.8.4 */ synchronized public void close() { closed = true; if (sqw != null) { try { if (layoutHeaderChecked && layout != null && layout.getFooter() != null) { sendLayoutMessage(layout.getFooter()); } sqw.close(); sqw = null; } catch(java.io.InterruptedIOException e) { Thread.currentThread().interrupt(); sqw = null; } catch(IOException e) { sqw = null; } } } private void initSyslogFacilityStr() { facilityStr = getFacilityString(this.syslogFacility); if (facilityStr == null) { System.err.println("\"" + syslogFacility + "\" is an unknown syslog facility. Defaulting to \"USER\"."); this.syslogFacility = LOG_USER; facilityStr = "user:"; } else { facilityStr += ":"; } } /** Returns the specified syslog facility as a lower-case String, e.g. "kern", "user", etc. */ public static String getFacilityString(int syslogFacility) { switch(syslogFacility) { case LOG_KERN: return "kern"; case LOG_USER: return "user"; case LOG_MAIL: return "mail"; case LOG_DAEMON: return "daemon"; case LOG_AUTH: return "auth"; case LOG_SYSLOG: return "syslog"; case LOG_LPR: return "lpr"; case LOG_NEWS: return "news"; case LOG_UUCP: return "uucp"; case LOG_CRON: return "cron"; case LOG_AUTHPRIV: return "authpriv"; case LOG_FTP: return "ftp"; case LOG_LOCAL0: return "local0"; case LOG_LOCAL1: return "local1"; case LOG_LOCAL2: return "local2"; case LOG_LOCAL3: return "local3"; case LOG_LOCAL4: return "local4"; case LOG_LOCAL5: return "local5"; case LOG_LOCAL6: return "local6"; case LOG_LOCAL7: return "local7"; default: return null; } } /** Returns the integer value corresponding to the named syslog facility, or -1 if it couldn't be recognized. @param facilityName one of the strings KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. The matching is case-insensitive. @since 1.1 */ public static int getFacility(String facilityName) { if(facilityName != null) { facilityName = facilityName.trim(); } if("KERN".equalsIgnoreCase(facilityName)) { return LOG_KERN; } else if("USER".equalsIgnoreCase(facilityName)) { return LOG_USER; } else if("MAIL".equalsIgnoreCase(facilityName)) { return LOG_MAIL; } else if("DAEMON".equalsIgnoreCase(facilityName)) { return LOG_DAEMON; } else if("AUTH".equalsIgnoreCase(facilityName)) { return LOG_AUTH; } else if("SYSLOG".equalsIgnoreCase(facilityName)) { return LOG_SYSLOG; } else if("LPR".equalsIgnoreCase(facilityName)) { return LOG_LPR; } else if("NEWS".equalsIgnoreCase(facilityName)) { return LOG_NEWS; } else if("UUCP".equalsIgnoreCase(facilityName)) { return LOG_UUCP; } else if("CRON".equalsIgnoreCase(facilityName)) { return LOG_CRON; } else if("AUTHPRIV".equalsIgnoreCase(facilityName)) { return LOG_AUTHPRIV; } else if("FTP".equalsIgnoreCase(facilityName)) { return LOG_FTP; } else if("LOCAL0".equalsIgnoreCase(facilityName)) { return LOG_LOCAL0; } else if("LOCAL1".equalsIgnoreCase(facilityName)) { return LOG_LOCAL1; } else if("LOCAL2".equalsIgnoreCase(facilityName)) { return LOG_LOCAL2; } else if("LOCAL3".equalsIgnoreCase(facilityName)) { return LOG_LOCAL3; } else if("LOCAL4".equalsIgnoreCase(facilityName)) { return LOG_LOCAL4; } else if("LOCAL5".equalsIgnoreCase(facilityName)) { return LOG_LOCAL5; } else if("LOCAL6".equalsIgnoreCase(facilityName)) { return LOG_LOCAL6; } else if("LOCAL7".equalsIgnoreCase(facilityName)) { return LOG_LOCAL7; } else { return -1; } } private void splitPacket(final String header, final String packet) { int byteCount = packet.getBytes().length; // // if packet is less than RFC 3164 limit // of 1024 bytes, then write it // (must allow for up 5to 5 characters in the PRI section // added by SyslogQuietWriter) if (byteCount <= 1019) { sqw.write(packet); } else { int split = header.length() + (packet.length() - header.length())/2; splitPacket(header, packet.substring(0, split) + "..."); splitPacket(header, header + "..." + packet.substring(split)); } } public void append(LoggingEvent event) { if(!isAsSevereAsThreshold(event.getLevel())) return; // We must not attempt to append if sqw is null. if(sqw == null) { errorHandler.error("No syslog host is set for SyslogAppedender named \""+ this.name+"\"."); return; } if (!layoutHeaderChecked) { if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } String hdr = getPacketHeader(event.timeStamp); - String packet = layout.format(event); + String packet; + if (layout == null) { + packet = String.valueOf(event.getMessage()); + } else { + packet = layout.format(event); + } if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(packet); packet = buf.toString(); } sqw.setLevel(event.getLevel().getSyslogEquivalent()); // // if message has a remote likelihood of exceeding 1024 bytes // when encoded, consider splitting message into multiple packets if (packet.length() > 256) { splitPacket(hdr, packet); } else { sqw.write(packet); } - if (layout.ignoresThrowable()) { + if (layout == null || layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int i = 0; i < s.length; i++) { if (s[i].startsWith("\t")) { sqw.write(hdr+TAB+s[i].substring(1)); } else { sqw.write(hdr+s[i]); } } } } } /** This method returns immediately as options are activated when they are set. */ public void activateOptions() { if (header) { getLocalHostname(); } if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } /** The SyslogAppender requires a layout. Hence, this method returns <code>true</code>. @since 0.8.4 */ public boolean requiresLayout() { return true; } /** The <b>SyslogHost</b> option is the name of the the syslog host where log output should go. A non-default port can be specified by appending a colon and port number to a host name, an IPv4 address or an IPv6 address enclosed in square brackets. <b>WARNING</b> If the SyslogHost is not set, then this appender will fail. */ public void setSyslogHost(final String syslogHost) { this.sqw = new SyslogQuietWriter(new SyslogWriter(syslogHost), syslogFacility, errorHandler); //this.stp = new SyslogTracerPrintWriter(sqw); this.syslogHost = syslogHost; } /** Returns the value of the <b>SyslogHost</b> option. */ public String getSyslogHost() { return syslogHost; } /** Set the syslog facility. This is the <b>Facility</b> option. <p>The <code>facilityName</code> parameter must be one of the strings KERN, USER, MAIL, DAEMON, AUTH, SYSLOG, LPR, NEWS, UUCP, CRON, AUTHPRIV, FTP, LOCAL0, LOCAL1, LOCAL2, LOCAL3, LOCAL4, LOCAL5, LOCAL6, LOCAL7. Case is unimportant. @since 0.8.1 */ public void setFacility(String facilityName) { if(facilityName == null) return; syslogFacility = getFacility(facilityName); if (syslogFacility == -1) { System.err.println("["+facilityName + "] is an unknown syslog facility. Defaulting to [USER]."); syslogFacility = LOG_USER; } this.initSyslogFacilityStr(); // If there is already a sqw, make it use the new facility. if(sqw != null) { sqw.setSyslogFacility(this.syslogFacility); } } /** Returns the value of the <b>Facility</b> option. */ public String getFacility() { return getFacilityString(syslogFacility); } /** If the <b>FacilityPrinting</b> option is set to true, the printed message will include the facility name of the application. It is <em>false</em> by default. */ public void setFacilityPrinting(boolean on) { facilityPrinting = on; } /** Returns the value of the <b>FacilityPrinting</b> option. */ public boolean getFacilityPrinting() { return facilityPrinting; } /** * If true, the appender will generate the HEADER part (that is, timestamp and host name) * of the syslog packet. Default value is false for compatibility with existing behavior, * however should be true unless there is a specific justification. * @since 1.2.15 */ public final boolean getHeader() { return header; } /** * Returns whether the appender produces the HEADER part (that is, timestamp and host name) * of the syslog packet. * @since 1.2.15 */ public final void setHeader(final boolean val) { header = val; } /** * Get the host name used to identify this appender. * @return local host name * @since 1.2.15 */ private String getLocalHostname() { if (localHostname == null) { try { InetAddress addr = InetAddress.getLocalHost(); localHostname = addr.getHostName(); } catch (UnknownHostException uhe) { localHostname = "UNKNOWN_HOST"; } } return localHostname; } /** * Gets HEADER portion of packet. * @param timeStamp number of milliseconds after the standard base time. * @return HEADER portion of packet, will be zero-length string if header is false. * @since 1.2.15 */ private String getPacketHeader(final long timeStamp) { if (header) { StringBuffer buf = new StringBuffer(dateFormat.format(new Date(timeStamp))); // RFC 3164 says leading space, not leading zero on days 1-9 if (buf.charAt(4) == '0') { buf.setCharAt(4, ' '); } buf.append(getLocalHostname()); buf.append(' '); return buf.toString(); } return ""; } /** * Set header or footer of layout. * @param msg message body, may not be null. */ private void sendLayoutMessage(final String msg) { if (sqw != null) { String packet = msg; String hdr = getPacketHeader(new Date().getTime()); if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(msg); packet = buf.toString(); } sqw.setLevel(6); sqw.write(packet); } } }
false
true
void append(LoggingEvent event) { if(!isAsSevereAsThreshold(event.getLevel())) return; // We must not attempt to append if sqw is null. if(sqw == null) { errorHandler.error("No syslog host is set for SyslogAppedender named \""+ this.name+"\"."); return; } if (!layoutHeaderChecked) { if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } String hdr = getPacketHeader(event.timeStamp); String packet = layout.format(event); if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(packet); packet = buf.toString(); } sqw.setLevel(event.getLevel().getSyslogEquivalent()); // // if message has a remote likelihood of exceeding 1024 bytes // when encoded, consider splitting message into multiple packets if (packet.length() > 256) { splitPacket(hdr, packet); } else { sqw.write(packet); } if (layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int i = 0; i < s.length; i++) { if (s[i].startsWith("\t")) { sqw.write(hdr+TAB+s[i].substring(1)); } else { sqw.write(hdr+s[i]); } } } } }
void append(LoggingEvent event) { if(!isAsSevereAsThreshold(event.getLevel())) return; // We must not attempt to append if sqw is null. if(sqw == null) { errorHandler.error("No syslog host is set for SyslogAppedender named \""+ this.name+"\"."); return; } if (!layoutHeaderChecked) { if (layout != null && layout.getHeader() != null) { sendLayoutMessage(layout.getHeader()); } layoutHeaderChecked = true; } String hdr = getPacketHeader(event.timeStamp); String packet; if (layout == null) { packet = String.valueOf(event.getMessage()); } else { packet = layout.format(event); } if(facilityPrinting || hdr.length() > 0) { StringBuffer buf = new StringBuffer(hdr); if(facilityPrinting) { buf.append(facilityStr); } buf.append(packet); packet = buf.toString(); } sqw.setLevel(event.getLevel().getSyslogEquivalent()); // // if message has a remote likelihood of exceeding 1024 bytes // when encoded, consider splitting message into multiple packets if (packet.length() > 256) { splitPacket(hdr, packet); } else { sqw.write(packet); } if (layout == null || layout.ignoresThrowable()) { String[] s = event.getThrowableStrRep(); if (s != null) { for(int i = 0; i < s.length; i++) { if (s[i].startsWith("\t")) { sqw.write(hdr+TAB+s[i].substring(1)); } else { sqw.write(hdr+s[i]); } } } } }
diff --git a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ChoiceLookupTransformer.java b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ChoiceLookupTransformer.java index 0050395ba..889170213 100644 --- a/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ChoiceLookupTransformer.java +++ b/dspace-xmlui/src/main/java/org/dspace/app/xmlui/aspect/general/ChoiceLookupTransformer.java @@ -1,308 +1,307 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.app.xmlui.aspect.general; import java.io.IOException; import java.sql.SQLException; import org.dspace.content.authority.ChoiceAuthorityManager; import org.dspace.content.DCPersonName; import org.dspace.core.ConfigurationManager; import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer; import org.dspace.app.xmlui.utils.UIException; import org.dspace.app.xmlui.wing.Message; import org.dspace.app.xmlui.wing.WingException; import org.dspace.app.xmlui.wing.element.Body; import org.dspace.app.xmlui.wing.element.Composite; import org.dspace.app.xmlui.wing.element.Division; import org.dspace.app.xmlui.wing.element.PageMeta; import org.dspace.app.xmlui.wing.element.Hidden; import org.dspace.app.xmlui.wing.element.List; import org.dspace.app.xmlui.wing.element.Item; import org.dspace.app.xmlui.wing.element.Select; import org.dspace.app.xmlui.wing.element.Text; import org.dspace.app.xmlui.wing.element.Button; import org.dspace.authorize.AuthorizeException; import org.xml.sax.SAXException; /** * Create the "lookup" popup window for Choice Control. It loads a selector * via AJAX request, and transfers values (both text and authority/confidence) * back to the indicated form fields in the window that launched it. * Some necessary logic is in JavaScript, see choice-control.js. * * Expected Parameters: * field - name of metadata field in "_" notation, eg: dc_contributor_author * value - maybe-partial value of field * formID - the @id of <form> tag in calling window containing the inputs we are to set. * valueInput - @name of input field in DOM for value. * authorityInput - @name of input field in DOM for authority value * isRepeating - true if metadata value can be repeated * isName - true if this is a name value (i.e. last/first boxes) * start - starting index, default 0 * limit - maximum values to return, default 0 (none) * * Configuration Properties: * xmlui.lookup.select.size = 12 (default, entries to show in SELECT widget.) * * For each FIELD, e.g. dc.contributor.author, these message properties * will OVERRIDE the corresponding i18n message catalog entries: * xmlui.lookup.field.FIELD.title = title of lookup page * (e.g. xmlui.lookup.field.dc_contributor_author.title = Author..) * xmlui.lookup.field.FIELD.nonauthority = template for "non-authority" label in options * xmlui.lookup.field.FIELD.help = help message for single input * (NOTE this is still required even for name inputs) * xmlui.lookup.field.FIELD.help.last = help message for last name of Name-oriented input * xmlui.lookup.field.FIELD.help.first = help message for first name of Name-oriented input * * @author Larry Stone */ public class ChoiceLookupTransformer extends AbstractDSpaceTransformer { private static final String CONFIG_PREFIX = "xmlui.lookup.field."; /** Language Strings */ private static final String MESSAGE_PREFIX = "xmlui.ChoiceLookupTransformer."; private static final Message T_title = message(MESSAGE_PREFIX+"title"); private static final Message T_add = message(MESSAGE_PREFIX+"add"); private static final Message T_accept = message(MESSAGE_PREFIX+"accept"); private static final Message T_more = message(MESSAGE_PREFIX+"more"); private static final Message T_cancel = message(MESSAGE_PREFIX+"cancel"); private static final Message T_results = message(MESSAGE_PREFIX+"results"); private static final Message T_fail = message(MESSAGE_PREFIX+"fail"); public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { String field = null; String value = null; String formID = null; String confIndicatorID = null; boolean isName = false; boolean isRepeating = false; String valueInput = null; String authorityInput = null; int start = 0; int limit = 0; String collection = null; // HTTP parameters: try { field = parameters.getParameter("field"); value = parameters.getParameter("value"); formID = parameters.getParameter("formID"); confIndicatorID = parameters.getParameter("confIndicatorID"); isName = parameters.getParameterAsBoolean("isName", false); isRepeating = parameters.getParameterAsBoolean("isRepeating", false); valueInput = parameters.getParameter("valueInput"); authorityInput = parameters.getParameter("authorityInput"); String sStart = parameters.getParameter("start"); if (sStart != null) { start = atoi(sStart); } String sLimit = parameters.getParameter("limit"); if (sLimit != null) { limit = atoi(sLimit); } collection = parameters.getParameter("collection"); if (collection == null) { collection = "-1"; } } catch (org.apache.avalon.framework.parameters.ParameterException e) { throw new UIException("Missing a required parameter",e); } Division idiv = body.addInteractiveDivision("lookup", "", "get", "popup"); if (isFieldMessage(field, "title")) { idiv.setHead(getFieldMessage(field, "title")); } else { idiv.setHead(getFieldLabel(field, "title")); } List fl = idiv.addList("choicesList", "form", "choices-lookup"); fl.setHead(T_results); // the <select> tag, and param values Item selectItem = fl.addItem("select", "choices-lookup"); Select s = selectItem.addSelect("chooser", "choices-lookup"); s.setSize(ConfigurationManager.getIntProperty("xmlui.lookup.select.size", 12)); // parameters for javascript Hidden h = selectItem.addHidden("paramField"); h.setValue(field); h = selectItem.addHidden("paramValue"); h.setValue(value); h = selectItem.addHidden("paramIsName"); h.setValue(String.valueOf(isName)); h = selectItem.addHidden("paramIsRepeating"); h.setValue(String.valueOf(isRepeating)); h = selectItem.addHidden("paramValueInput"); h.setValue(valueInput); h = selectItem.addHidden("paramAuthorityInput"); h.setValue(authorityInput); h = selectItem.addHidden("paramStart"); h.setValue(String.valueOf(start)); h = selectItem.addHidden("paramLimit"); h.setValue(String.valueOf(limit)); h = selectItem.addHidden("paramFormID"); h.setValue(formID); h = selectItem.addHidden("paramConfIndicatorID"); h.setValue(confIndicatorID); h = selectItem.addHidden("paramFail"); h.setValue(T_fail); boolean isClosed = ChoiceAuthorityManager.getManager().isClosed(field); h = selectItem.addHidden("paramIsClosed"); h.setValue(String.valueOf(isClosed)); h = selectItem.addHidden("paramCollection"); h.setValue(String.valueOf(collection)); if (!isClosed) { h = selectItem.addHidden("paramNonAuthority"); if (isFieldMessage(field, "nonauthority")) { h.setValue(getFieldMessage(field, "nonauthority")); } else { h.setValue(getFieldLabel(field, "nonauthority")); } } h = selectItem.addHidden("contextPath"); h.setValue(contextPath); // NOTE: the "spinner" indicator image gets added in the XSLT. // the text input(s) Item ti = fl.addItem("textFields", "choices-lookup"); Composite textItem = ti.addComposite("textFieldsComp", "choices-lookup"); Text t1 = textItem.addText("text1", "choices-lookup"); if (isName) { Text t2 = textItem.addText("text2", "choices-lookup"); DCPersonName dp = new DCPersonName(value); t1.setValue(dp.getLastName()); t2.setValue(dp.getFirstNames()); if (isFieldMessage(field, "help.last")) { Message m = getFieldMessage(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } if (isFieldMessage(field, "help.first")) { Message m = getFieldMessage(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } else { String m = getFieldLabel(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } } else { t1.setValue(value); if (isFieldMessage(field, "help")) { Message m = getFieldMessage(field, "help"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help"); t1.setLabel(m); t1.setHelp(m); } } // confirmation buttons Item buttItem = fl.addItem("confirmation", "choices-lookup"); Button accept = buttItem.addButton("accept", "choices-lookup"); accept.setValue(isRepeating ? T_add : T_accept); Button more = buttItem.addButton("more", "choices-lookup"); - more.setDisabled(); more.setValue(T_more); Button cancel = buttItem.addButton("cancel", "choices-lookup"); cancel.setValue(T_cancel); } public void addPageMeta(PageMeta pageMeta) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { // Set the page title pageMeta.addMetadata("title").addContent(T_title); // This invokes magic popup transformation in XSL - "framing.popup" pageMeta.addMetadata("framing","popup").addContent("true"); } /** * Protocol to get custom and/or i18n strings: * For label NAME, * .. if config key xmlui.choices.FIELD.NAME is defined, and starts * with "xmlui.", then it's a message key. * .. if NO config key is defined, look for message * xmlui.ChoiceLookupTransformer.field.FIELD.NAME * .. otherwise take literal value from configuration */ // return true if configured (or lack thereof) value points to Message private boolean isFieldMessage(String field, String name) { String cv = getFieldLabel(field, name); return (cv == null || cv.startsWith("xmlui.")); } // get field-specific label value private String getFieldLabel(String field, String name) { return ConfigurationManager.getProperty(CONFIG_PREFIX+field+"."+name); } // get field-specific label value private Message getFieldMessage(String field, String name) { String cv = getFieldLabel(field, name); if (cv == null) { return message(MESSAGE_PREFIX + "field." + field + "." + name); } else { return message(cv); } } private int atoi(String s) { try { return Integer.parseInt(s); } catch (Exception e) {} return 0; } }
true
true
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { String field = null; String value = null; String formID = null; String confIndicatorID = null; boolean isName = false; boolean isRepeating = false; String valueInput = null; String authorityInput = null; int start = 0; int limit = 0; String collection = null; // HTTP parameters: try { field = parameters.getParameter("field"); value = parameters.getParameter("value"); formID = parameters.getParameter("formID"); confIndicatorID = parameters.getParameter("confIndicatorID"); isName = parameters.getParameterAsBoolean("isName", false); isRepeating = parameters.getParameterAsBoolean("isRepeating", false); valueInput = parameters.getParameter("valueInput"); authorityInput = parameters.getParameter("authorityInput"); String sStart = parameters.getParameter("start"); if (sStart != null) { start = atoi(sStart); } String sLimit = parameters.getParameter("limit"); if (sLimit != null) { limit = atoi(sLimit); } collection = parameters.getParameter("collection"); if (collection == null) { collection = "-1"; } } catch (org.apache.avalon.framework.parameters.ParameterException e) { throw new UIException("Missing a required parameter",e); } Division idiv = body.addInteractiveDivision("lookup", "", "get", "popup"); if (isFieldMessage(field, "title")) { idiv.setHead(getFieldMessage(field, "title")); } else { idiv.setHead(getFieldLabel(field, "title")); } List fl = idiv.addList("choicesList", "form", "choices-lookup"); fl.setHead(T_results); // the <select> tag, and param values Item selectItem = fl.addItem("select", "choices-lookup"); Select s = selectItem.addSelect("chooser", "choices-lookup"); s.setSize(ConfigurationManager.getIntProperty("xmlui.lookup.select.size", 12)); // parameters for javascript Hidden h = selectItem.addHidden("paramField"); h.setValue(field); h = selectItem.addHidden("paramValue"); h.setValue(value); h = selectItem.addHidden("paramIsName"); h.setValue(String.valueOf(isName)); h = selectItem.addHidden("paramIsRepeating"); h.setValue(String.valueOf(isRepeating)); h = selectItem.addHidden("paramValueInput"); h.setValue(valueInput); h = selectItem.addHidden("paramAuthorityInput"); h.setValue(authorityInput); h = selectItem.addHidden("paramStart"); h.setValue(String.valueOf(start)); h = selectItem.addHidden("paramLimit"); h.setValue(String.valueOf(limit)); h = selectItem.addHidden("paramFormID"); h.setValue(formID); h = selectItem.addHidden("paramConfIndicatorID"); h.setValue(confIndicatorID); h = selectItem.addHidden("paramFail"); h.setValue(T_fail); boolean isClosed = ChoiceAuthorityManager.getManager().isClosed(field); h = selectItem.addHidden("paramIsClosed"); h.setValue(String.valueOf(isClosed)); h = selectItem.addHidden("paramCollection"); h.setValue(String.valueOf(collection)); if (!isClosed) { h = selectItem.addHidden("paramNonAuthority"); if (isFieldMessage(field, "nonauthority")) { h.setValue(getFieldMessage(field, "nonauthority")); } else { h.setValue(getFieldLabel(field, "nonauthority")); } } h = selectItem.addHidden("contextPath"); h.setValue(contextPath); // NOTE: the "spinner" indicator image gets added in the XSLT. // the text input(s) Item ti = fl.addItem("textFields", "choices-lookup"); Composite textItem = ti.addComposite("textFieldsComp", "choices-lookup"); Text t1 = textItem.addText("text1", "choices-lookup"); if (isName) { Text t2 = textItem.addText("text2", "choices-lookup"); DCPersonName dp = new DCPersonName(value); t1.setValue(dp.getLastName()); t2.setValue(dp.getFirstNames()); if (isFieldMessage(field, "help.last")) { Message m = getFieldMessage(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } if (isFieldMessage(field, "help.first")) { Message m = getFieldMessage(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } else { String m = getFieldLabel(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } } else { t1.setValue(value); if (isFieldMessage(field, "help")) { Message m = getFieldMessage(field, "help"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help"); t1.setLabel(m); t1.setHelp(m); } } // confirmation buttons Item buttItem = fl.addItem("confirmation", "choices-lookup"); Button accept = buttItem.addButton("accept", "choices-lookup"); accept.setValue(isRepeating ? T_add : T_accept); Button more = buttItem.addButton("more", "choices-lookup"); more.setDisabled(); more.setValue(T_more); Button cancel = buttItem.addButton("cancel", "choices-lookup"); cancel.setValue(T_cancel); }
public void addBody(Body body) throws SAXException, WingException, UIException, SQLException, IOException, AuthorizeException { String field = null; String value = null; String formID = null; String confIndicatorID = null; boolean isName = false; boolean isRepeating = false; String valueInput = null; String authorityInput = null; int start = 0; int limit = 0; String collection = null; // HTTP parameters: try { field = parameters.getParameter("field"); value = parameters.getParameter("value"); formID = parameters.getParameter("formID"); confIndicatorID = parameters.getParameter("confIndicatorID"); isName = parameters.getParameterAsBoolean("isName", false); isRepeating = parameters.getParameterAsBoolean("isRepeating", false); valueInput = parameters.getParameter("valueInput"); authorityInput = parameters.getParameter("authorityInput"); String sStart = parameters.getParameter("start"); if (sStart != null) { start = atoi(sStart); } String sLimit = parameters.getParameter("limit"); if (sLimit != null) { limit = atoi(sLimit); } collection = parameters.getParameter("collection"); if (collection == null) { collection = "-1"; } } catch (org.apache.avalon.framework.parameters.ParameterException e) { throw new UIException("Missing a required parameter",e); } Division idiv = body.addInteractiveDivision("lookup", "", "get", "popup"); if (isFieldMessage(field, "title")) { idiv.setHead(getFieldMessage(field, "title")); } else { idiv.setHead(getFieldLabel(field, "title")); } List fl = idiv.addList("choicesList", "form", "choices-lookup"); fl.setHead(T_results); // the <select> tag, and param values Item selectItem = fl.addItem("select", "choices-lookup"); Select s = selectItem.addSelect("chooser", "choices-lookup"); s.setSize(ConfigurationManager.getIntProperty("xmlui.lookup.select.size", 12)); // parameters for javascript Hidden h = selectItem.addHidden("paramField"); h.setValue(field); h = selectItem.addHidden("paramValue"); h.setValue(value); h = selectItem.addHidden("paramIsName"); h.setValue(String.valueOf(isName)); h = selectItem.addHidden("paramIsRepeating"); h.setValue(String.valueOf(isRepeating)); h = selectItem.addHidden("paramValueInput"); h.setValue(valueInput); h = selectItem.addHidden("paramAuthorityInput"); h.setValue(authorityInput); h = selectItem.addHidden("paramStart"); h.setValue(String.valueOf(start)); h = selectItem.addHidden("paramLimit"); h.setValue(String.valueOf(limit)); h = selectItem.addHidden("paramFormID"); h.setValue(formID); h = selectItem.addHidden("paramConfIndicatorID"); h.setValue(confIndicatorID); h = selectItem.addHidden("paramFail"); h.setValue(T_fail); boolean isClosed = ChoiceAuthorityManager.getManager().isClosed(field); h = selectItem.addHidden("paramIsClosed"); h.setValue(String.valueOf(isClosed)); h = selectItem.addHidden("paramCollection"); h.setValue(String.valueOf(collection)); if (!isClosed) { h = selectItem.addHidden("paramNonAuthority"); if (isFieldMessage(field, "nonauthority")) { h.setValue(getFieldMessage(field, "nonauthority")); } else { h.setValue(getFieldLabel(field, "nonauthority")); } } h = selectItem.addHidden("contextPath"); h.setValue(contextPath); // NOTE: the "spinner" indicator image gets added in the XSLT. // the text input(s) Item ti = fl.addItem("textFields", "choices-lookup"); Composite textItem = ti.addComposite("textFieldsComp", "choices-lookup"); Text t1 = textItem.addText("text1", "choices-lookup"); if (isName) { Text t2 = textItem.addText("text2", "choices-lookup"); DCPersonName dp = new DCPersonName(value); t1.setValue(dp.getLastName()); t2.setValue(dp.getFirstNames()); if (isFieldMessage(field, "help.last")) { Message m = getFieldMessage(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help.last"); t1.setLabel(m); t1.setHelp(m); } if (isFieldMessage(field, "help.first")) { Message m = getFieldMessage(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } else { String m = getFieldLabel(field, "help.first"); t2.setLabel(m); t2.setHelp(m); } } else { t1.setValue(value); if (isFieldMessage(field, "help")) { Message m = getFieldMessage(field, "help"); t1.setLabel(m); t1.setHelp(m); } else { String m = getFieldLabel(field, "help"); t1.setLabel(m); t1.setHelp(m); } } // confirmation buttons Item buttItem = fl.addItem("confirmation", "choices-lookup"); Button accept = buttItem.addButton("accept", "choices-lookup"); accept.setValue(isRepeating ? T_add : T_accept); Button more = buttItem.addButton("more", "choices-lookup"); more.setValue(T_more); Button cancel = buttItem.addButton("cancel", "choices-lookup"); cancel.setValue(T_cancel); }
diff --git a/src/main/java/water/parser/ParseDataset.java b/src/main/java/water/parser/ParseDataset.java index cd364907f..c620a3b34 100644 --- a/src/main/java/water/parser/ParseDataset.java +++ b/src/main/java/water/parser/ParseDataset.java @@ -1,321 +1,329 @@ package water.parser; import java.io.IOException; import java.util.*; import java.util.zip.*; import water.*; import water.H2O.H2OCountedCompleter; import water.parser.DParseTask.Pass; import com.google.common.base.Throwables; import com.google.common.io.Closeables; /** * Helper class to parse an entire ValueArray data, and produce a structured ValueArray result. * * @author <a href="mailto:[email protected]"></a> */ @SuppressWarnings("fallthrough") public final class ParseDataset extends Job { public static enum Compression { NONE, ZIP, GZIP } private final long _total; public final Key _progress; private ParseDataset(Key dest, Key[] keys) { super("Parse", dest); //if( keys.length > 1 ) throw H2O.unimpl(); Value dataset = DKV.get(keys[0]); _total = dataset.length() * Pass.values().length; _progress = Key.make(UUID.randomUUID().toString(), (byte) 0, Key.JOB); UKV.put(_progress, new Progress()); } private ParseDataset(Key dest, Value [] dataset) { super("Parse", dest); long t = dataset[0].length(); for(int i = 1; i < dataset.length; ++i) t += dataset[i].length(); _total = t * Pass.values().length; _progress = Key.make(UUID.randomUUID().toString(), (byte) 0, Key.JOB); UKV.put(_progress, new Progress()); } // Guess public static Compression guessCompressionMethod(Value dataset) { byte[] b = dataset.getFirstBytes(); // First chunk AutoBuffer ab = new AutoBuffer(b); // Look for ZIP magic if( b.length > ZipFile.LOCHDR && ab.get4(0) == ZipFile.LOCSIG ) return Compression.ZIP; if( b.length > 2 && ab.get2(0) == GZIPInputStream.GZIP_MAGIC ) return Compression.GZIP; return Compression.NONE; } // Parse the dataset (uncompressed, zippped) as a CSV-style thingy and // produce a structured dataset as a result. private static void parse(ParseDataset job, Key[] keys, CsvParser.Setup setup) { Value [] dataset = new Value[keys.length]; for(int i = 0; i < keys.length; ++i) dataset[i] = DKV.get(keys[i]); if( dataset[0].isHex() ) throw new IllegalArgumentException("This is a binary structured dataset; " + "parse() only works on text files."); try { // try if it is XLS file first try { parseUncompressed(job, dataset, CustomParser.Type.XLS, setup); return; } catch( Exception e ) { // pass } Compression compression = guessCompressionMethod(dataset[0]); if( compression == Compression.ZIP ) { try { parseUncompressed(job, dataset, CustomParser.Type.XLSX, setup); return; } catch( Exception e ) { // pass } } switch( compression ) { case NONE: parseUncompressed(job, dataset, CustomParser.Type.CSV, setup); break; case ZIP: parseZipped(job, dataset, setup); break; case GZIP: parseGZipped(job, dataset, setup); break; default: throw new Error("Unknown compression of dataset!"); } } catch( java.io.EOFException eof ) { // Unexpected EOF? Assume its a broken file, and toss the whole parse out UKV.put(job.dest(), new Fail(eof.getMessage())); } catch( Exception e ) { UKV.put(job.dest(), new Fail(e.getMessage())); throw Throwables.propagate(e); } finally { job.remove(); } } public static void parse(Key dest, Key[] keys) { ParseDataset job = new ParseDataset(dest, keys); job.start(); parse(job, keys, null); } public static Job forkParseDataset( final Key dest, final Key[] keys, final CsvParser.Setup setup ) { final ParseDataset job = new ParseDataset(dest, keys); job.start(); H2O.submitTask(new H2OCountedCompleter() { @Override public void compute2() { parse(job, keys, setup); tryComplete(); } }); return job; } public static class ParseException extends Exception{ public ParseException(String msg){super(msg);} } public static void parseUncompressed(ParseDataset job, Value [] dataset, CustomParser.Type parserType, CsvParser.Setup setup) throws Exception{ int header = -1; CsvParser.Setup headerSetup = null; if(setup == null){ // Obtain the setup and make sure it is consistent among all values for(int i = 0; i < dataset.length; ++i){ byte [] bits = dataset[i].getFirstBytes(); // Can limit to eg 256*1024 CsvParser.Setup s = CsvParser.guessCsvSetup(bits); if(s._header) { // we expect only one header here if(header < 0){ header = i; } else System.err.println("warning, encoutered multiple headers when parsing multiple files."); } if(setup == null) setup = s; else { // check that the setups are compatible if(s._separator != s._separator) throw new ParseException("incompatible separators (" + setup._separator + ", " + s._separator + ") encoutered when parsing multiple files."); if(setup._data[0].length != s._data[0].length) throw new ParseException("incompatible number of columns (" + setup._data[0].length + ", " + s._data[0].length + ") encoutered when parsing multiple files."); } } if(header >= 0){ // we found a header, put it to the beginning of the array // and make sure the first value gets parsed with header on and the others with header off if(setup._header){ headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } else headerSetup = new CsvParser.Setup(setup._separator,true,setup._data,setup._numlines,setup._bits); Value v = dataset[0]; dataset[0] = dataset[header]; dataset[header] = v; header = 0; } else headerSetup = setup; } else { headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } long nchunks = 0; // count the total number of chunks for(int i = 0; i < dataset.length; ++i){ if(dataset[i].isArray()){ ValueArray ary = dataset[i].get(); nchunks += ary.chunks(); } else nchunks += 1; } int chunks = (int)nchunks; assert chunks == nchunks; // parse the first value - DParseTask phaseOne = DParseTask.createPassOne(dataset[0], job, CustomParser.Type.CSV); + DParseTask phaseOne = DParseTask.createPassOne(dataset[0], job, parserType); int [] startchunks = new int[dataset.length+1]; phaseOne.passOne(headerSetup); + if( (phaseOne._error != null) && !phaseOne._error.isEmpty() ) { + System.err.println(phaseOne._error); + throw new Exception("The dataset format is not recognized/supported"); + } if(dataset.length > 1){ // parse the rest startchunks[1] = phaseOne._nrows.length; phaseOne._nrows = Arrays.copyOf(phaseOne._nrows, chunks); for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = DParseTask.createPassOne(dataset[i], job, CustomParser.Type.CSV); assert(!setup._header); tsk.passOne(setup); + if( (tsk._error != null) && !tsk._error.isEmpty() ) { + System.err.println(phaseOne._error); + throw new Exception("The dataset format is not recognized/supported"); + } startchunks[i+1] = startchunks[i] + tsk._nrows.length; // modified reduction step, compute the compression scheme and the nrows array for (int j = 0; j < tsk._nrows.length; ++j) phaseOne._nrows[j+startchunks[i]] = tsk._nrows[j]; assert tsk._ncolumns == phaseOne._ncolumns; for(int j = 0; j < tsk._ncolumns; ++j) { if(phaseOne._enums[j] != tsk._enums[j]) phaseOne._enums[j].merge(tsk._enums[j]); if(tsk._min[j] < phaseOne._min[j])phaseOne._min[j] = tsk._min[j]; if(tsk._max[j] > phaseOne._max[j])phaseOne._max[j] = tsk._max[j]; if(tsk._scale[j] < phaseOne._scale[j])phaseOne._scale[j] = tsk._scale[j]; if(tsk._colTypes[j] > phaseOne._colTypes[j])phaseOne._colTypes[j] = tsk._colTypes[j]; phaseOne._mean[j] += tsk._mean[j]; phaseOne._invalidValues[j] += tsk._invalidValues[j]; } } } // now do the pass 2 DParseTask phaseTwo = DParseTask.createPassTwo(phaseOne); phaseTwo.passTwo(); if((phaseTwo._error != null) && !phaseTwo._error.isEmpty()) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = new DParseTask(phaseTwo,dataset[i],startchunks[i]); tsk._skipFirstLine = false; tsk.passTwo(); for(int j = 0; j < phaseTwo._ncolumns; ++j){ phaseTwo._sigma[j] += tsk._sigma[j]; phaseTwo._invalidValues[j] += tsk._invalidValues[j]; } if( (tsk._error != null) && !tsk._error.isEmpty() ) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } UKV.remove(dataset[i]._key); } phaseTwo.createValueArrayHeader(); job.remove(); } // Unpack zipped CSV-style structure and call method parseUncompressed(...) // The method exepct a dataset which contains a ZIP file encapsulating one file. public static void parseZipped(ParseDataset job, Value [] dataset, CsvParser.Setup setup) throws IOException { // Dataset contains zipped CSV ZipInputStream zis = null; Key keys [] = new Key[dataset.length]; try{ for(int i = 0; i < dataset.length; ++i){ try { // Create Zip input stream and uncompress the data into a new key <ORIGINAL-KEY-NAME>_UNZIPPED zis = new ZipInputStream(dataset[i].openStream()); // Get the *FIRST* entry ZipEntry ze = zis.getNextEntry(); // There is at least one entry in zip file and it is not a directory. if( ze != null && !ze.isDirectory() ) { keys[i] = Key.make(new String(dataset[i]._key._kb) + "_UNZIPPED"); ValueArray.readPut(keys[i], zis, job); } } finally { Closeables.closeQuietly(zis); } // else it is possible to dive into a directory but in this case I would // prefer to return error since the ZIP file has not expected format } for(int i = 0; i < keys.length; ++i) if( keys[i] == null ) throw new Error("Cannot uncompressed ZIP-compressed dataset!"); parse(job, keys, setup); } finally { for(int i = 0; i < keys.length; ++i) if(keys[i] != null) UKV.remove(keys[i]); } } public static void parseGZipped(ParseDataset job, Value [] dataset, CsvParser.Setup setup) throws IOException { GZIPInputStream gzis = null; Key [] keys = new Key [dataset.length]; try{ try { for(int i = 0; i < dataset.length; ++i){ gzis = new GZIPInputStream(dataset[i].openStream()); keys[i] = ValueArray.readPut(new String(dataset[i]._key._kb) + "_UNZIPPED", gzis); } } finally { Closeables.closeQuietly(gzis); } for(int i = 0; i < keys.length; ++i) if( keys[i] == null ) throw new Error("Cannot uncompressed ZIP-compressed dataset!"); parse(job, keys, setup); }finally { for(int i = 0; i < keys.length; ++i) if(keys[i] != null)UKV.remove(keys[i]); } } // True if the array is all NaNs static boolean allNaNs(double ds[]) { for( double d : ds ) if( !Double.isNaN(d) ) return false; return true; } // Progress (TODO count chunks in VA, unify with models?) static class Progress extends Iced { long _value; } @Override public float progress() { if(_total == 0) return 0; Progress progress = UKV.get(_progress); return (progress != null ? progress._value : 0) / (float) _total; } @Override public void remove() { DKV.remove(_progress); super.remove(); } static final void onProgress(final Key chunk, final Key progress) { assert progress != null; new TAtomic<Progress>() { @Override public Progress atomic(Progress old) { if( old == null ) return null; Value val = DKV.get(chunk); if( val == null ) return null; old._value += val.length(); return old; } }.fork(progress); } }
false
true
public static void parseUncompressed(ParseDataset job, Value [] dataset, CustomParser.Type parserType, CsvParser.Setup setup) throws Exception{ int header = -1; CsvParser.Setup headerSetup = null; if(setup == null){ // Obtain the setup and make sure it is consistent among all values for(int i = 0; i < dataset.length; ++i){ byte [] bits = dataset[i].getFirstBytes(); // Can limit to eg 256*1024 CsvParser.Setup s = CsvParser.guessCsvSetup(bits); if(s._header) { // we expect only one header here if(header < 0){ header = i; } else System.err.println("warning, encoutered multiple headers when parsing multiple files."); } if(setup == null) setup = s; else { // check that the setups are compatible if(s._separator != s._separator) throw new ParseException("incompatible separators (" + setup._separator + ", " + s._separator + ") encoutered when parsing multiple files."); if(setup._data[0].length != s._data[0].length) throw new ParseException("incompatible number of columns (" + setup._data[0].length + ", " + s._data[0].length + ") encoutered when parsing multiple files."); } } if(header >= 0){ // we found a header, put it to the beginning of the array // and make sure the first value gets parsed with header on and the others with header off if(setup._header){ headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } else headerSetup = new CsvParser.Setup(setup._separator,true,setup._data,setup._numlines,setup._bits); Value v = dataset[0]; dataset[0] = dataset[header]; dataset[header] = v; header = 0; } else headerSetup = setup; } else { headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } long nchunks = 0; // count the total number of chunks for(int i = 0; i < dataset.length; ++i){ if(dataset[i].isArray()){ ValueArray ary = dataset[i].get(); nchunks += ary.chunks(); } else nchunks += 1; } int chunks = (int)nchunks; assert chunks == nchunks; // parse the first value DParseTask phaseOne = DParseTask.createPassOne(dataset[0], job, CustomParser.Type.CSV); int [] startchunks = new int[dataset.length+1]; phaseOne.passOne(headerSetup); if(dataset.length > 1){ // parse the rest startchunks[1] = phaseOne._nrows.length; phaseOne._nrows = Arrays.copyOf(phaseOne._nrows, chunks); for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = DParseTask.createPassOne(dataset[i], job, CustomParser.Type.CSV); assert(!setup._header); tsk.passOne(setup); startchunks[i+1] = startchunks[i] + tsk._nrows.length; // modified reduction step, compute the compression scheme and the nrows array for (int j = 0; j < tsk._nrows.length; ++j) phaseOne._nrows[j+startchunks[i]] = tsk._nrows[j]; assert tsk._ncolumns == phaseOne._ncolumns; for(int j = 0; j < tsk._ncolumns; ++j) { if(phaseOne._enums[j] != tsk._enums[j]) phaseOne._enums[j].merge(tsk._enums[j]); if(tsk._min[j] < phaseOne._min[j])phaseOne._min[j] = tsk._min[j]; if(tsk._max[j] > phaseOne._max[j])phaseOne._max[j] = tsk._max[j]; if(tsk._scale[j] < phaseOne._scale[j])phaseOne._scale[j] = tsk._scale[j]; if(tsk._colTypes[j] > phaseOne._colTypes[j])phaseOne._colTypes[j] = tsk._colTypes[j]; phaseOne._mean[j] += tsk._mean[j]; phaseOne._invalidValues[j] += tsk._invalidValues[j]; } } } // now do the pass 2 DParseTask phaseTwo = DParseTask.createPassTwo(phaseOne); phaseTwo.passTwo(); if((phaseTwo._error != null) && !phaseTwo._error.isEmpty()) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = new DParseTask(phaseTwo,dataset[i],startchunks[i]); tsk._skipFirstLine = false; tsk.passTwo(); for(int j = 0; j < phaseTwo._ncolumns; ++j){ phaseTwo._sigma[j] += tsk._sigma[j]; phaseTwo._invalidValues[j] += tsk._invalidValues[j]; } if( (tsk._error != null) && !tsk._error.isEmpty() ) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } UKV.remove(dataset[i]._key); } phaseTwo.createValueArrayHeader(); job.remove(); }
public static void parseUncompressed(ParseDataset job, Value [] dataset, CustomParser.Type parserType, CsvParser.Setup setup) throws Exception{ int header = -1; CsvParser.Setup headerSetup = null; if(setup == null){ // Obtain the setup and make sure it is consistent among all values for(int i = 0; i < dataset.length; ++i){ byte [] bits = dataset[i].getFirstBytes(); // Can limit to eg 256*1024 CsvParser.Setup s = CsvParser.guessCsvSetup(bits); if(s._header) { // we expect only one header here if(header < 0){ header = i; } else System.err.println("warning, encoutered multiple headers when parsing multiple files."); } if(setup == null) setup = s; else { // check that the setups are compatible if(s._separator != s._separator) throw new ParseException("incompatible separators (" + setup._separator + ", " + s._separator + ") encoutered when parsing multiple files."); if(setup._data[0].length != s._data[0].length) throw new ParseException("incompatible number of columns (" + setup._data[0].length + ", " + s._data[0].length + ") encoutered when parsing multiple files."); } } if(header >= 0){ // we found a header, put it to the beginning of the array // and make sure the first value gets parsed with header on and the others with header off if(setup._header){ headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } else headerSetup = new CsvParser.Setup(setup._separator,true,setup._data,setup._numlines,setup._bits); Value v = dataset[0]; dataset[0] = dataset[header]; dataset[header] = v; header = 0; } else headerSetup = setup; } else { headerSetup = setup; setup = new CsvParser.Setup(setup._separator,false,setup._data,setup._numlines,setup._bits); } long nchunks = 0; // count the total number of chunks for(int i = 0; i < dataset.length; ++i){ if(dataset[i].isArray()){ ValueArray ary = dataset[i].get(); nchunks += ary.chunks(); } else nchunks += 1; } int chunks = (int)nchunks; assert chunks == nchunks; // parse the first value DParseTask phaseOne = DParseTask.createPassOne(dataset[0], job, parserType); int [] startchunks = new int[dataset.length+1]; phaseOne.passOne(headerSetup); if( (phaseOne._error != null) && !phaseOne._error.isEmpty() ) { System.err.println(phaseOne._error); throw new Exception("The dataset format is not recognized/supported"); } if(dataset.length > 1){ // parse the rest startchunks[1] = phaseOne._nrows.length; phaseOne._nrows = Arrays.copyOf(phaseOne._nrows, chunks); for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = DParseTask.createPassOne(dataset[i], job, CustomParser.Type.CSV); assert(!setup._header); tsk.passOne(setup); if( (tsk._error != null) && !tsk._error.isEmpty() ) { System.err.println(phaseOne._error); throw new Exception("The dataset format is not recognized/supported"); } startchunks[i+1] = startchunks[i] + tsk._nrows.length; // modified reduction step, compute the compression scheme and the nrows array for (int j = 0; j < tsk._nrows.length; ++j) phaseOne._nrows[j+startchunks[i]] = tsk._nrows[j]; assert tsk._ncolumns == phaseOne._ncolumns; for(int j = 0; j < tsk._ncolumns; ++j) { if(phaseOne._enums[j] != tsk._enums[j]) phaseOne._enums[j].merge(tsk._enums[j]); if(tsk._min[j] < phaseOne._min[j])phaseOne._min[j] = tsk._min[j]; if(tsk._max[j] > phaseOne._max[j])phaseOne._max[j] = tsk._max[j]; if(tsk._scale[j] < phaseOne._scale[j])phaseOne._scale[j] = tsk._scale[j]; if(tsk._colTypes[j] > phaseOne._colTypes[j])phaseOne._colTypes[j] = tsk._colTypes[j]; phaseOne._mean[j] += tsk._mean[j]; phaseOne._invalidValues[j] += tsk._invalidValues[j]; } } } // now do the pass 2 DParseTask phaseTwo = DParseTask.createPassTwo(phaseOne); phaseTwo.passTwo(); if((phaseTwo._error != null) && !phaseTwo._error.isEmpty()) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } for(int i = 1; i < dataset.length; ++i){ DParseTask tsk = new DParseTask(phaseTwo,dataset[i],startchunks[i]); tsk._skipFirstLine = false; tsk.passTwo(); for(int j = 0; j < phaseTwo._ncolumns; ++j){ phaseTwo._sigma[j] += tsk._sigma[j]; phaseTwo._invalidValues[j] += tsk._invalidValues[j]; } if( (tsk._error != null) && !tsk._error.isEmpty() ) { System.err.println(phaseTwo._error); throw new Exception("The dataset format is not recognized/supported"); } UKV.remove(dataset[i]._key); } phaseTwo.createValueArrayHeader(); job.remove(); }
diff --git a/src/com/stickycoding/Rokon/Menu/Menu.java b/src/com/stickycoding/Rokon/Menu/Menu.java index b1cb4f2..b1c41f3 100644 --- a/src/com/stickycoding/Rokon/Menu/Menu.java +++ b/src/com/stickycoding/Rokon/Menu/Menu.java @@ -1,285 +1,286 @@ package com.stickycoding.Rokon.Menu; import android.view.KeyEvent; import com.stickycoding.Rokon.Background; import com.stickycoding.Rokon.Debug; import com.stickycoding.Rokon.Hotspot; import com.stickycoding.Rokon.Rokon; /** * A menu, currently full screen and not in-game only * @author Richard */ public class Menu { public static final int MAX_OBJECTS = 99; private Rokon _rokon; private Background _background; private MenuObject[] _menuObjects = new MenuObject[MAX_OBJECTS]; private boolean _showing = false; private MenuTransition _startTransition = null, _exitTransition = null; private boolean _closingMenu = false; private long _closingMenuTimeout; private Menu _closingMenuNext; /** * Called when the Menu is first shown */ public void onShow() { } /** * Called once, straight after the Menu's start transition ends */ public void onStartTransitionComplete() { } /** * Triggered when a MenuObject is first touched * @param menuObject */ public void onMenuObjectTouchDown(MenuObject menuObject) { } /** * Triggered every time a touch on a MenuObject is detected * @param menuObject */ public void onMenuObjectTouch(MenuObject menuObject) { } /** * Triggered when a touch on a MenuObject ends * @param menuObject */ public void onMenuObjectTouchUp(MenuObject menuObject) { } /** * Called when the Menu's exit transition begins (currently inactive) */ public void onExitTransitionBegin() { } /** * Called when the Menu is closed */ public void onExit() { } /** * Triggered on all key events while the Menu is visible on screen * @param keyCode * @param event */ public void onKey(int keyCode, KeyEvent event) { } private int a; /** * Used to manage animations and sprites, called every time frame renders */ public void loop() { if(_closingMenu) { if(Rokon.time > _closingMenuTimeout) { if(_closingMenuNext == null) _rokon.removeMenu(); else { _rokon.freeze(); _rokon.showMenu(_closingMenuNext); } + onExit(); } return; } for(a = 0; a < _menuObjects.length; a++) if(_menuObjects[a] != null) _menuObjects[a].loop(); if(_startTransition != null) _startTransition.loop(); if(_exitTransition != null) _exitTransition.loop(); } /** * Begins exit transition (currently inactive) */ public void exit() { if(_exitTransition != null) _exitTransition.begin(this); } /** * Removes all MenuObjects from the scene */ public void end() { _rokon.clearScene(); } /** * Clears the scene, adds all MenuObject's, and begins the start transition if needed */ public void show() { _rokon = Rokon.getRokon(); _rokon.pause(); _rokon.freeze(); _rokon.clearScene(); Debug.print("Showing Menu"); if(_background != null) _rokon.setBackground(_background); for(int i = 0; i < _menuObjects.length; i++) if(_menuObjects[i] != null) _menuObjects[i].addToScene(_rokon, this); if(_startTransition != null) _startTransition.begin(this); onShow(); _rokon.unfreeze(); _rokon.unpause(); _showing = true; } /** * Sets the Menu Background * @param background */ public void setBackground(Background background) { _background = background; if(_showing) _rokon.setBackground(background); } /** * @return NULL if none set */ public Background getBackground() { return _background; } /** * @return NULL if none set */ public MenuTransition getStartTransition() { return _startTransition; } /** * @return NULL if none set */ public MenuTransition getExitTransition() { return _exitTransition; } /** * Sets the start transition * @param menuTransition */ public void setStartTransition(MenuTransition menuTransition) { _startTransition = menuTransition; } /** * Sets the exit transition * @param menuTransition */ public void setExitTransition(MenuTransition menuTransition) { _exitTransition = menuTransition; } /** * @param index * @return NULL if not found */ public MenuObject getMenuObject(int index) { return _menuObjects[index]; } /** * @return the number of MenuObject's on this Menu */ public int getMenuObjectCount() { int j = 0; for(int i = 0; i < MAX_OBJECTS; i++) if(_menuObjects[i] != null) j++; return j; } private int _firstEmptyMenuObject() { for(int i = 0; i < MAX_OBJECTS; i++) if(_menuObjects[i] == null) return i; return -1; } /** * Add's a MenuObject to this Menu * @param menuObject */ public void addMenuObject(MenuObject menuObject) { if(getMenuObjectCount() < MAX_OBJECTS) _menuObjects[_firstEmptyMenuObject()] = menuObject; else { Debug.print("TOO MANY MENU OBJECTS"); } } /** * Remove's a MenuObject from this Menu * @param menuObject */ public void removeMenuObject(MenuObject menuObject) { for(int i = 0; i < _menuObjects.length; i++) if(_menuObjects[i] != null && _menuObjects[i].equals(menuObject)) { _menuObjects[i] = null; } } private int b; private boolean _hotspotActive = false; public void onHotspot(Hotspot hotspot) { if(_closingMenu) return; for(b = 0; b < MAX_OBJECTS; b++) if(_menuObjects[b] != null && _menuObjects[b].getHotspot() != null && _menuObjects[b].getHotspot().equals(hotspot)) { _menuObjects[b].touch(_hotspotActive); _hotspotActive = true; break; } } public void resetActiveHotspot() { _hotspotActive = false; } /** * Closes this Menu, and loads up another immediately * @param menu */ public void gotoMenu(Menu menu) { gotoMenu(menu, 0); } /** * Closes this Menu, and loads up another after a specified delay * @param menu * @param delay time to wait before the next Menu is shown, in milliseconds */ public void gotoMenu(Menu menu, int delay) { _closingMenuNext = menu; _closingMenu = true; _closingMenuTimeout = Rokon.time + delay; } /** * Closes this Menu immediately */ public void closeMenu() { closeMenu(0); } /** * Closes this Menu after a specified delay * @param delay time to wait before the Menu is closed, in milliseconds */ public void closeMenu(int delay) { _closingMenuNext = null; _closingMenu = true; _closingMenuTimeout = Rokon.time + delay; } }
true
true
public void loop() { if(_closingMenu) { if(Rokon.time > _closingMenuTimeout) { if(_closingMenuNext == null) _rokon.removeMenu(); else { _rokon.freeze(); _rokon.showMenu(_closingMenuNext); } } return; } for(a = 0; a < _menuObjects.length; a++) if(_menuObjects[a] != null) _menuObjects[a].loop(); if(_startTransition != null) _startTransition.loop(); if(_exitTransition != null) _exitTransition.loop(); }
public void loop() { if(_closingMenu) { if(Rokon.time > _closingMenuTimeout) { if(_closingMenuNext == null) _rokon.removeMenu(); else { _rokon.freeze(); _rokon.showMenu(_closingMenuNext); } onExit(); } return; } for(a = 0; a < _menuObjects.length; a++) if(_menuObjects[a] != null) _menuObjects[a].loop(); if(_startTransition != null) _startTransition.loop(); if(_exitTransition != null) _exitTransition.loop(); }
diff --git a/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java b/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java index 42db8faa..5cd54931 100644 --- a/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java +++ b/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java @@ -1,155 +1,155 @@ package cz.vity.freerapid.plugins.services.depositfiles; import cz.vity.freerapid.plugins.exceptions.*; import cz.vity.freerapid.plugins.webclient.AbstractRunner; import cz.vity.freerapid.plugins.webclient.DownloadState; import cz.vity.freerapid.plugins.webclient.FileState; import cz.vity.freerapid.plugins.webclient.utils.PlugUtils; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import java.io.IOException; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Ladislav Vitasek, Ludek Zika */ class DepositFilesRunner extends AbstractRunner { private final static Logger logger = Logger.getLogger(DepositFilesRunner.class.getName()); private static final String HTTP_DEPOSITFILES = "http://www.depositfiles.com"; @Override public void runCheck() throws Exception { super.runCheck(); fileURL = CheckURL(fileURL); final GetMethod getMethod = getGetMethod(fileURL); getMethod.setFollowRedirects(true); if (makeRequest(getMethod)) { checkNameAndSize(getContentAsString()); } else throw new PluginImplementationException(); } @Override public void run() throws Exception { super.run(); fileURL = CheckURL(fileURL); final GetMethod getMethod = getGetMethod(fileURL); getMethod.setFollowRedirects(true); if (makeRequest(getMethod)) { checkNameAndSize(getContentAsString()); Matcher matcher; if (!getContentAsString().contains("Free downloading mode")) { - matcher = getMatcherAgainstContent("form action=\\\"([^h\\\"][^t\\\"][^t\\\"][^p\\\"][^\\\"]*)\\\""); + matcher = getMatcherAgainstContent("form action=\"(/.+)\" method"); if (!matcher.find()) { checkProblems(); logger.warning(getContentAsString()); throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service"); } String s = matcher.group(1); logger.info("Submit form to - " + s); client.setReferer(fileURL); final PostMethod postMethod = getPostMethod(HTTP_DEPOSITFILES + s); postMethod.addParameter("gateway_result", "1"); if (!makeRequest(postMethod)) { logger.info(getContentAsString()); throw new PluginImplementationException(); } } // <span id="download_waiter_remain">60</span> matcher = getMatcherAgainstContent("download_waiter_remain\">([0-9]+)"); if (!matcher.find()) { checkProblems(); throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content"); } String t = matcher.group(1); int seconds = new Integer(t); logger.info("wait - " + t); matcher = getMatcherAgainstContent("form action=\"([^\"]*)\" method=\"get\""); if (matcher.find()) { t = matcher.group(1); logger.info("Download URL: " + t); downloadTask.sleep(seconds + 1); httpFile.setState(DownloadState.GETTING); final GetMethod method = getGetMethod(t); if (!tryDownloadAndSaveFile(method)) { checkProblems(); throw new IOException("File input stream is empty."); } } else { checkProblems(); logger.info(getContentAsString()); throw new PluginImplementationException(); } } else throw new PluginImplementationException(); } private String CheckURL(String URL) { return URL.replaceFirst("/../files", "/en/files"); } private void checkNameAndSize(String content) throws Exception { if (!content.contains("depositfiles")) { logger.warning(getContentAsString()); throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service"); } if (content.contains("file does not exist")) { throw new URLNotAvailableAnymoreException(String.format("<b>Such file does not exist or it has been removed for infringement of copyrights.</b><br>")); } Matcher matcher = getMatcherAgainstContent("<b>([0-9.]+&nbsp;.B)</b>"); if (matcher.find()) { logger.info("File size " + matcher.group(1)); httpFile.setFileSize(PlugUtils.getFileSizeFromString(matcher.group(1).replaceAll("&nbsp;", ""))); httpFile.setFileState(FileState.CHECKED_AND_EXISTING); } matcher = getMatcherAgainstContent("class\\=\"info[^=]*\\=\"([^\"]*)\""); if (matcher.find()) { final String fn = matcher.group(1); logger.info("File name " + fn); httpFile.setFileName(fn); } else logger.warning("File name was not found" + getContentAsString()); } private void checkProblems() throws ServiceConnectionProblemException, YouHaveToWaitException, URLNotAvailableAnymoreException { Matcher matcher; String content = getContentAsString(); if (content.contains("already downloading")) { throw new ServiceConnectionProblemException(String.format("<b>Your IP is already downloading a file from our system.</b><br>You cannot download more than one file in parallel.")); } matcher = Pattern.compile("Please try in\\s*([0-9]+) minute", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content); if (matcher.find()) { throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 + 20); } matcher = Pattern.compile("Please try in\\s*([0-9]+) hour", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content); if (matcher.find()) { throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 * 60 + 20); } matcher = PlugUtils.matcher("slots[^<]*busy", content); if (matcher.find()) { throw new YouHaveToWaitException(String.format("<b>All downloading slots for your country are busy</b><br>"), 60 * 2); } if (content.contains("file does not exist")) { throw new URLNotAvailableAnymoreException(String.format("<b>Such file does not exist or it has been removed for infringement of copyrights.</b><br>")); } } }
true
true
public void run() throws Exception { super.run(); fileURL = CheckURL(fileURL); final GetMethod getMethod = getGetMethod(fileURL); getMethod.setFollowRedirects(true); if (makeRequest(getMethod)) { checkNameAndSize(getContentAsString()); Matcher matcher; if (!getContentAsString().contains("Free downloading mode")) { matcher = getMatcherAgainstContent("form action=\\\"([^h\\\"][^t\\\"][^t\\\"][^p\\\"][^\\\"]*)\\\""); if (!matcher.find()) { checkProblems(); logger.warning(getContentAsString()); throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service"); } String s = matcher.group(1); logger.info("Submit form to - " + s); client.setReferer(fileURL); final PostMethod postMethod = getPostMethod(HTTP_DEPOSITFILES + s); postMethod.addParameter("gateway_result", "1"); if (!makeRequest(postMethod)) { logger.info(getContentAsString()); throw new PluginImplementationException(); } } // <span id="download_waiter_remain">60</span> matcher = getMatcherAgainstContent("download_waiter_remain\">([0-9]+)"); if (!matcher.find()) { checkProblems(); throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content"); } String t = matcher.group(1); int seconds = new Integer(t); logger.info("wait - " + t); matcher = getMatcherAgainstContent("form action=\"([^\"]*)\" method=\"get\""); if (matcher.find()) { t = matcher.group(1); logger.info("Download URL: " + t); downloadTask.sleep(seconds + 1); httpFile.setState(DownloadState.GETTING); final GetMethod method = getGetMethod(t); if (!tryDownloadAndSaveFile(method)) { checkProblems(); throw new IOException("File input stream is empty."); } } else { checkProblems(); logger.info(getContentAsString()); throw new PluginImplementationException(); } } else throw new PluginImplementationException(); }
public void run() throws Exception { super.run(); fileURL = CheckURL(fileURL); final GetMethod getMethod = getGetMethod(fileURL); getMethod.setFollowRedirects(true); if (makeRequest(getMethod)) { checkNameAndSize(getContentAsString()); Matcher matcher; if (!getContentAsString().contains("Free downloading mode")) { matcher = getMatcherAgainstContent("form action=\"(/.+)\" method"); if (!matcher.find()) { checkProblems(); logger.warning(getContentAsString()); throw new InvalidURLOrServiceProblemException("Invalid URL or unindentified service"); } String s = matcher.group(1); logger.info("Submit form to - " + s); client.setReferer(fileURL); final PostMethod postMethod = getPostMethod(HTTP_DEPOSITFILES + s); postMethod.addParameter("gateway_result", "1"); if (!makeRequest(postMethod)) { logger.info(getContentAsString()); throw new PluginImplementationException(); } } // <span id="download_waiter_remain">60</span> matcher = getMatcherAgainstContent("download_waiter_remain\">([0-9]+)"); if (!matcher.find()) { checkProblems(); throw new ServiceConnectionProblemException("Problem with a connection to service.\nCannot find requested page content"); } String t = matcher.group(1); int seconds = new Integer(t); logger.info("wait - " + t); matcher = getMatcherAgainstContent("form action=\"([^\"]*)\" method=\"get\""); if (matcher.find()) { t = matcher.group(1); logger.info("Download URL: " + t); downloadTask.sleep(seconds + 1); httpFile.setState(DownloadState.GETTING); final GetMethod method = getGetMethod(t); if (!tryDownloadAndSaveFile(method)) { checkProblems(); throw new IOException("File input stream is empty."); } } else { checkProblems(); logger.info(getContentAsString()); throw new PluginImplementationException(); } } else throw new PluginImplementationException(); }
diff --git a/src/main/java/me/greatman/plugins/inn/commands/InnCmd.java b/src/main/java/me/greatman/plugins/inn/commands/InnCmd.java index 283f468..7afc766 100644 --- a/src/main/java/me/greatman/plugins/inn/commands/InnCmd.java +++ b/src/main/java/me/greatman/plugins/inn/commands/InnCmd.java @@ -1,119 +1,120 @@ package me.greatman.plugins.inn.commands; import me.greatman.plugins.inn.IPermissions; import me.greatman.plugins.inn.ITools; import me.greatman.plugins.inn.Inn; import me.greatman.plugins.inn.PlayerData; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.nijikokun.register.payment.Method.MethodAccount; public class InnCmd implements CommandExecutor { private final Inn plugin; public InnCmd(Inn instance) { plugin = instance; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "inn")) { if (args == null || args.length == 0){ sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW)); return true; } if (is(args[0], "help")){ + handled = true; sendMessage(sender, "You are using " + colorizeText(Inn.name, ChatColor.GREEN) + " version " + colorizeText(Inn.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && IPermissions.permission(plugin.getPlayer(sender), "inn create", plugin.getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/inn select",ChatColor.YELLOW) +" - Select a door for Inn usage"); sendMessage(sender,colorizeText("/inn create <Price>",ChatColor.YELLOW) + "- Create a inn door"); } } if (is(args[0], "select")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ Player player = (Player) sender; String playerName = player.getName(); if (!plugin.getPlayerData().containsKey(playerName)) { plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); if (plugin.getPlayerData().get(playerName).isSelecting()) { sender.sendMessage(ChatColor.WHITE + "Inn selection enabled." + ChatColor.DARK_AQUA + " Use " + ChatColor.WHITE + "bare hands " + ChatColor.DARK_AQUA + "to select!"); sender.sendMessage(ChatColor.DARK_AQUA + "Left click the room door"); } else { sender.sendMessage(ChatColor.DARK_AQUA + "Selection disabled"); plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } }else sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); }else if(is(args[0], "create")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ if (args.length == 1){ sendMessage(sender,colorizeText("Syntax: /inn create [Price]",ChatColor.RED)); return true; } if (ITools.isInt(args[1])){ Player player = (Player) sender; String playerName = player.getName(); int[] xyz = plugin.getPlayerData().get(playerName).getPositionA(); int y2 = xyz[1] + 1; String query = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + xyz[1] +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; String query2 = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + y2 +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; Inn.manageSQLite.insertQuery(query); Inn.manageSQLite.insertQuery(query2); MethodAccount playerAccount = plugin.Method.getAccount(playerName); //We check if the player have enough money to create a inn door if (playerAccount.hasEnough(Inn.cost)){ playerAccount.subtract(Inn.cost); plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); sendMessage(sender,colorizeText("Inn room created!",ChatColor.GREEN)); }else sendMessage(sender,colorizeText("You don't have enough money!",ChatColor.RED)); }else sendMessage(sender,colorizeText("Expected integer. Received string.",ChatColor.RED)); } } } return handled; } // Simplifies and shortens the if statements for commands. private boolean is(String entered, String label) { return entered.equalsIgnoreCase(label); } // Checks if the current user is actually a player. private boolean isPlayer(CommandSender sender) { return sender != null && sender instanceof Player; } // Checks if the current user is actually a player and sends a message to that player. private boolean sendMessage(CommandSender sender, String message) { boolean sent = false; if (isPlayer(sender)) { Player player = (Player) sender; player.sendMessage(message); sent = true; } return sent; } public String colorizeText(String text, ChatColor color) { return color + text + ChatColor.WHITE; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "inn")) { if (args == null || args.length == 0){ sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW)); return true; } if (is(args[0], "help")){ sendMessage(sender, "You are using " + colorizeText(Inn.name, ChatColor.GREEN) + " version " + colorizeText(Inn.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && IPermissions.permission(plugin.getPlayer(sender), "inn create", plugin.getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/inn select",ChatColor.YELLOW) +" - Select a door for Inn usage"); sendMessage(sender,colorizeText("/inn create <Price>",ChatColor.YELLOW) + "- Create a inn door"); } } if (is(args[0], "select")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ Player player = (Player) sender; String playerName = player.getName(); if (!plugin.getPlayerData().containsKey(playerName)) { plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); if (plugin.getPlayerData().get(playerName).isSelecting()) { sender.sendMessage(ChatColor.WHITE + "Inn selection enabled." + ChatColor.DARK_AQUA + " Use " + ChatColor.WHITE + "bare hands " + ChatColor.DARK_AQUA + "to select!"); sender.sendMessage(ChatColor.DARK_AQUA + "Left click the room door"); } else { sender.sendMessage(ChatColor.DARK_AQUA + "Selection disabled"); plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } }else sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); }else if(is(args[0], "create")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ if (args.length == 1){ sendMessage(sender,colorizeText("Syntax: /inn create [Price]",ChatColor.RED)); return true; } if (ITools.isInt(args[1])){ Player player = (Player) sender; String playerName = player.getName(); int[] xyz = plugin.getPlayerData().get(playerName).getPositionA(); int y2 = xyz[1] + 1; String query = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + xyz[1] +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; String query2 = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + y2 +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; Inn.manageSQLite.insertQuery(query); Inn.manageSQLite.insertQuery(query2); MethodAccount playerAccount = plugin.Method.getAccount(playerName); //We check if the player have enough money to create a inn door if (playerAccount.hasEnough(Inn.cost)){ playerAccount.subtract(Inn.cost); plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); sendMessage(sender,colorizeText("Inn room created!",ChatColor.GREEN)); }else sendMessage(sender,colorizeText("You don't have enough money!",ChatColor.RED)); }else sendMessage(sender,colorizeText("Expected integer. Received string.",ChatColor.RED)); } } } return handled; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean handled = false; if (is(label, "inn")) { if (args == null || args.length == 0){ sendMessage(sender,colorizeText("/ticket help for help",ChatColor.YELLOW)); return true; } if (is(args[0], "help")){ handled = true; sendMessage(sender, "You are using " + colorizeText(Inn.name, ChatColor.GREEN) + " version " + colorizeText(Inn.version, ChatColor.GREEN) + "."); sendMessage(sender, "Commands:"); if (isPlayer(sender) && IPermissions.permission(plugin.getPlayer(sender), "inn create", plugin.getPlayer(sender).isOp())){ sendMessage(sender,colorizeText("/inn select",ChatColor.YELLOW) +" - Select a door for Inn usage"); sendMessage(sender,colorizeText("/inn create <Price>",ChatColor.YELLOW) + "- Create a inn door"); } } if (is(args[0], "select")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ Player player = (Player) sender; String playerName = player.getName(); if (!plugin.getPlayerData().containsKey(playerName)) { plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); if (plugin.getPlayerData().get(playerName).isSelecting()) { sender.sendMessage(ChatColor.WHITE + "Inn selection enabled." + ChatColor.DARK_AQUA + " Use " + ChatColor.WHITE + "bare hands " + ChatColor.DARK_AQUA + "to select!"); sender.sendMessage(ChatColor.DARK_AQUA + "Left click the room door"); } else { sender.sendMessage(ChatColor.DARK_AQUA + "Selection disabled"); plugin.getPlayerData().put(playerName, new PlayerData(plugin, playerName)); } }else sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED)); }else if(is(args[0], "create")){ handled = true; if (!(sender instanceof Player)){ sendMessage(sender,colorizeText("Only players can use this command.",ChatColor.RED)); return handled; } if (IPermissions.permission(plugin.getPlayer(sender), "inn.create", plugin.getPlayer(sender).isOp())){ if (args.length == 1){ sendMessage(sender,colorizeText("Syntax: /inn create [Price]",ChatColor.RED)); return true; } if (ITools.isInt(args[1])){ Player player = (Player) sender; String playerName = player.getName(); int[] xyz = plugin.getPlayerData().get(playerName).getPositionA(); int y2 = xyz[1] + 1; String query = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + xyz[1] +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; String query2 = "INSERT INTO doors(x,y,z,owner,price) VALUES("+ xyz[0] +"," + y2 +"," + xyz[2] +",'" + playerName + "'," + args[1] + ")"; Inn.manageSQLite.insertQuery(query); Inn.manageSQLite.insertQuery(query2); MethodAccount playerAccount = plugin.Method.getAccount(playerName); //We check if the player have enough money to create a inn door if (playerAccount.hasEnough(Inn.cost)){ playerAccount.subtract(Inn.cost); plugin.getPlayerData().get(playerName).setSelecting(!plugin.getPlayerData().get(playerName).isSelecting()); sendMessage(sender,colorizeText("Inn room created!",ChatColor.GREEN)); }else sendMessage(sender,colorizeText("You don't have enough money!",ChatColor.RED)); }else sendMessage(sender,colorizeText("Expected integer. Received string.",ChatColor.RED)); } } } return handled; }
diff --git a/java/src/main/java/com/taobao/top/link/channel/websocket/WebSocketClient.java b/java/src/main/java/com/taobao/top/link/channel/websocket/WebSocketClient.java index cfbde36..a8f380e 100644 --- a/java/src/main/java/com/taobao/top/link/channel/websocket/WebSocketClient.java +++ b/java/src/main/java/com/taobao/top/link/channel/websocket/WebSocketClient.java @@ -1,98 +1,101 @@ package com.taobao.top.link.channel.websocket; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import org.jboss.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import org.jboss.netty.handler.codec.http.websocketx.WebSocketVersion; import com.taobao.top.link.Logger; import com.taobao.top.link.LoggerFactory; import com.taobao.top.link.Text; import com.taobao.top.link.channel.ChannelException; import com.taobao.top.link.channel.ClientChannel; import com.taobao.top.link.channel.ConnectingChannelHandler; public class WebSocketClient { private static WebSocketClientHandshakerFactory wsFactory = new WebSocketClientHandshakerFactory(); public static ClientChannel connect(LoggerFactory loggerFactory, URI uri, int timeout) throws ChannelException { Logger logger = loggerFactory.create(String.format("WebSocketClientHandler-%s", uri)); WebSocketClientChannel clientChannel = new WebSocketClientChannel(); clientChannel.setUri(uri); ConnectingChannelHandler handler = new ConnectingChannelHandler(); clientChannel.setChannelHandler(handler); WebSocketClientUpstreamHandler wsHandler = new WebSocketClientUpstreamHandler(logger, clientChannel); ClientBootstrap bootstrap = prepareBootstrap(logger, wsHandler); // connect ChannelFuture future = connect(bootstrap, uri); Channel channel = future.getChannel(); // handshake try { WebSocketClientHandshaker handshaker = wsFactory. newHandshaker(uri, WebSocketVersion.V13, null, true, WebSocketClientHelper.getHeaders(uri)); wsHandler.handshaker = handshaker; handshaker.handshake(channel); - synchronized (handler.syncObject) { - handler.syncObject.wait(timeout); + // return maybe fast than call + if (!wsHandler.handshaker.isHandshakeComplete() && handler.error == null) { + synchronized (handler.syncObject) { + handler.syncObject.wait(timeout); + } } } catch (Exception e) { throw new ChannelException(Text.WS_HANDSHAKE_ERROR, e); } if (wsHandler.handshaker.isHandshakeComplete()) return clientChannel; if (handler.error != null) throw new ChannelException(Text.WS_CONNECT_FAIL + ": " + handler.error.getMessage(), handler.error); throw new ChannelException(Text.WS_CONNECT_TIMEOUT); } protected static ChannelFuture connect(ClientBootstrap bootstrap, URI uri) throws ChannelException { try { return bootstrap.connect(parse(uri)).sync(); } catch (Exception e) { throw new ChannelException(Text.WS_CONNECT_ERROR, e); } } protected static InetSocketAddress parse(URI uri) { return new InetSocketAddress(uri.getHost(), uri.getPort() > 0 ? uri.getPort() : 80); } protected static ClientBootstrap prepareBootstrap(Logger logger, WebSocketClientUpstreamHandler wsHandler) { ClientBootstrap bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("reuseAddress", true); final ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); pipeline.addLast("encoder", new HttpRequestEncoder()); if (wsHandler != null) pipeline.addLast("handler", wsHandler); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return pipeline; } }); return bootstrap; } }
true
true
public static ClientChannel connect(LoggerFactory loggerFactory, URI uri, int timeout) throws ChannelException { Logger logger = loggerFactory.create(String.format("WebSocketClientHandler-%s", uri)); WebSocketClientChannel clientChannel = new WebSocketClientChannel(); clientChannel.setUri(uri); ConnectingChannelHandler handler = new ConnectingChannelHandler(); clientChannel.setChannelHandler(handler); WebSocketClientUpstreamHandler wsHandler = new WebSocketClientUpstreamHandler(logger, clientChannel); ClientBootstrap bootstrap = prepareBootstrap(logger, wsHandler); // connect ChannelFuture future = connect(bootstrap, uri); Channel channel = future.getChannel(); // handshake try { WebSocketClientHandshaker handshaker = wsFactory. newHandshaker(uri, WebSocketVersion.V13, null, true, WebSocketClientHelper.getHeaders(uri)); wsHandler.handshaker = handshaker; handshaker.handshake(channel); synchronized (handler.syncObject) { handler.syncObject.wait(timeout); } } catch (Exception e) { throw new ChannelException(Text.WS_HANDSHAKE_ERROR, e); } if (wsHandler.handshaker.isHandshakeComplete()) return clientChannel; if (handler.error != null) throw new ChannelException(Text.WS_CONNECT_FAIL + ": " + handler.error.getMessage(), handler.error); throw new ChannelException(Text.WS_CONNECT_TIMEOUT); }
public static ClientChannel connect(LoggerFactory loggerFactory, URI uri, int timeout) throws ChannelException { Logger logger = loggerFactory.create(String.format("WebSocketClientHandler-%s", uri)); WebSocketClientChannel clientChannel = new WebSocketClientChannel(); clientChannel.setUri(uri); ConnectingChannelHandler handler = new ConnectingChannelHandler(); clientChannel.setChannelHandler(handler); WebSocketClientUpstreamHandler wsHandler = new WebSocketClientUpstreamHandler(logger, clientChannel); ClientBootstrap bootstrap = prepareBootstrap(logger, wsHandler); // connect ChannelFuture future = connect(bootstrap, uri); Channel channel = future.getChannel(); // handshake try { WebSocketClientHandshaker handshaker = wsFactory. newHandshaker(uri, WebSocketVersion.V13, null, true, WebSocketClientHelper.getHeaders(uri)); wsHandler.handshaker = handshaker; handshaker.handshake(channel); // return maybe fast than call if (!wsHandler.handshaker.isHandshakeComplete() && handler.error == null) { synchronized (handler.syncObject) { handler.syncObject.wait(timeout); } } } catch (Exception e) { throw new ChannelException(Text.WS_HANDSHAKE_ERROR, e); } if (wsHandler.handshaker.isHandshakeComplete()) return clientChannel; if (handler.error != null) throw new ChannelException(Text.WS_CONNECT_FAIL + ": " + handler.error.getMessage(), handler.error); throw new ChannelException(Text.WS_CONNECT_TIMEOUT); }
diff --git a/src/brut/androlib/res/decoder/ResFileDecoder.java b/src/brut/androlib/res/decoder/ResFileDecoder.java index 0b54cf4..46f3512 100644 --- a/src/brut/androlib/res/decoder/ResFileDecoder.java +++ b/src/brut/androlib/res/decoder/ResFileDecoder.java @@ -1,111 +1,111 @@ /* * Copyright 2010 Ryszard Wiśniewski <[email protected]>. * * 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. * under the License. */ package brut.androlib.res.decoder; import brut.androlib.AndrolibException; import brut.androlib.err.CantFind9PatchChunk; import brut.androlib.res.data.ResResource; import brut.androlib.res.data.value.ResFileValue; import brut.directory.Directory; import brut.directory.DirectoryException; import java.io.*; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Ryszard Wiśniewski <[email protected]> */ public class ResFileDecoder { private final ResStreamDecoderContainer mDecoders; public ResFileDecoder(ResStreamDecoderContainer decoders) { this.mDecoders = decoders; } public void decode(ResResource res, Directory inDir, Directory outDir) throws AndrolibException { ResFileValue fileValue = (ResFileValue) res.getValue(); String inFileName = fileValue.getStrippedPath(); String outResName = res.getFilePath(); String typeName = res.getResSpec().getType().getName(); String ext = null; String outFileName; int extPos = inFileName.lastIndexOf("."); if (extPos == -1) { outFileName = outResName; } else { ext = inFileName.substring(extPos); outFileName = outResName + ext; } try { if (typeName.equals("raw")) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } if (typeName.equals("drawable")) { if (inFileName.toLowerCase().endsWith(".9.png")) { outFileName = outResName + ".9" + ext; try { decode( inDir, inFileName, outDir, outFileName, "9patch"); return; } catch (CantFind9PatchChunk ex) { LOGGER.log(Level.WARNING, String.format( "Cant find 9patch chunk in file: \"%s\". Renaming it to *.png.", inFileName ), ex); outDir.removeFile(outFileName); outFileName = outResName + ext; } } - if (! ext.equals(".xml")) { + if (! ".xml".equals(ext)) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } } decode(inDir, inFileName, outDir, outFileName, "xml"); } catch (AndrolibException ex) { LOGGER.log(Level.SEVERE, String.format( "Could not decode file \"%s\" to \"%s\"", inFileName, outFileName), ex); } } public void decode(Directory inDir, String inFileName, Directory outDir, String outFileName, String decoder) throws AndrolibException { try { InputStream in = inDir.getFileInput(inFileName); OutputStream out = outDir.getFileOutput(outFileName); mDecoders.decode(in, out, decoder); in.close(); out.close(); } catch (IOException ex) { throw new AndrolibException(ex); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private final static Logger LOGGER = Logger.getLogger(ResFileDecoder.class.getName()); }
true
true
public void decode(ResResource res, Directory inDir, Directory outDir) throws AndrolibException { ResFileValue fileValue = (ResFileValue) res.getValue(); String inFileName = fileValue.getStrippedPath(); String outResName = res.getFilePath(); String typeName = res.getResSpec().getType().getName(); String ext = null; String outFileName; int extPos = inFileName.lastIndexOf("."); if (extPos == -1) { outFileName = outResName; } else { ext = inFileName.substring(extPos); outFileName = outResName + ext; } try { if (typeName.equals("raw")) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } if (typeName.equals("drawable")) { if (inFileName.toLowerCase().endsWith(".9.png")) { outFileName = outResName + ".9" + ext; try { decode( inDir, inFileName, outDir, outFileName, "9patch"); return; } catch (CantFind9PatchChunk ex) { LOGGER.log(Level.WARNING, String.format( "Cant find 9patch chunk in file: \"%s\". Renaming it to *.png.", inFileName ), ex); outDir.removeFile(outFileName); outFileName = outResName + ext; } } if (! ext.equals(".xml")) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } } decode(inDir, inFileName, outDir, outFileName, "xml"); } catch (AndrolibException ex) { LOGGER.log(Level.SEVERE, String.format( "Could not decode file \"%s\" to \"%s\"", inFileName, outFileName), ex); } }
public void decode(ResResource res, Directory inDir, Directory outDir) throws AndrolibException { ResFileValue fileValue = (ResFileValue) res.getValue(); String inFileName = fileValue.getStrippedPath(); String outResName = res.getFilePath(); String typeName = res.getResSpec().getType().getName(); String ext = null; String outFileName; int extPos = inFileName.lastIndexOf("."); if (extPos == -1) { outFileName = outResName; } else { ext = inFileName.substring(extPos); outFileName = outResName + ext; } try { if (typeName.equals("raw")) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } if (typeName.equals("drawable")) { if (inFileName.toLowerCase().endsWith(".9.png")) { outFileName = outResName + ".9" + ext; try { decode( inDir, inFileName, outDir, outFileName, "9patch"); return; } catch (CantFind9PatchChunk ex) { LOGGER.log(Level.WARNING, String.format( "Cant find 9patch chunk in file: \"%s\". Renaming it to *.png.", inFileName ), ex); outDir.removeFile(outFileName); outFileName = outResName + ext; } } if (! ".xml".equals(ext)) { decode(inDir, inFileName, outDir, outFileName, "raw"); return; } } decode(inDir, inFileName, outDir, outFileName, "xml"); } catch (AndrolibException ex) { LOGGER.log(Level.SEVERE, String.format( "Could not decode file \"%s\" to \"%s\"", inFileName, outFileName), ex); } }
diff --git a/src/main/ed/lang/python/PythonJxpSource.java b/src/main/ed/lang/python/PythonJxpSource.java index c72c6c230..204d2356b 100644 --- a/src/main/ed/lang/python/PythonJxpSource.java +++ b/src/main/ed/lang/python/PythonJxpSource.java @@ -1,174 +1,175 @@ // PythonJxpSource.java /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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 ed.lang.python; import java.io.*; import java.util.*; import org.python.core.*; import org.python.Version; import ed.js.*; import ed.js.engine.*; import ed.util.*; import ed.appserver.*; import ed.appserver.jxp.JxpSource; import ed.log.Logger; public class PythonJxpSource extends JxpSource { static { System.setProperty( "python.cachedir", ed.io.WorkingFiles.TMP_DIR + "/jython-cache/" + Version.PY_VERSION ); } public PythonJxpSource( File f , JSFileLibrary lib ){ _file = f; _lib = lib; } protected String getContent(){ throw new RuntimeException( "you can't do this" ); } protected InputStream getInputStream(){ throw new RuntimeException( "you can't do this" ); } public long lastUpdated(Set<Dependency> visitedDeps){ return _file.lastModified(); } public String getName(){ return _file.toString(); } public File getFile(){ return _file; } public synchronized JSFunction getFunction() throws IOException { final PyCode code = _getCode(); return new ed.js.func.JSFunctionCalls0(){ public Object call( Scope s , Object extra[] ){ final AppContext ac = getAppContext(); Scope siteScope; if( ac != null ) siteScope = ac.getScope(); else siteScope = s.getGlobal( true ); SiteSystemState ss = Python.getSiteSystemState( ac , siteScope ); PySystemState pyOld = Py.getSystemState(); ss.flushOld(); + ss.ensurePath( _file.getParent().toString() ); ss.ensurePath( _lib.getRoot().toString() ); ss.ensurePath( _lib.getTopParent().getRoot().toString() ); PyObject globals = ss.globals; PyObject oldFile = globals.__finditem__( "__file__" ); PyObject oldName = globals.__finditem__( "__name__" ); PyObject result = null; try { Py.setSystemState( ss.getPyState() ); //Py.initClassExceptions( globals ); globals.__setitem__( "__file__", Py.newString( _file.toString() ) ); // FIXME: Needs to use path info, so foo/bar.py -> foo.bar // Right now I only want this for _init.py String name = _file.getName(); if( name.endsWith( ".py" ) ) name = name.substring( 0 , name.length() - 3 ); //globals.__setitem__( "__name__", Py.newString( name ) ); PyModule module = new PyModule( name , globals ); PyObject locals = module.__dict__; result = Py.runCode( code, locals, globals ); if( ac != null ) ss.addRecursive( "_init" , ac ); } finally { globalRestore( globals , siteScope , "__file__" , oldFile ); globalRestore( globals , siteScope , "__name__" , oldName ); Py.setSystemState( pyOld ); } if( usePassedInScope() ){ PyObject keys = globals.invoke("keys"); if( ! ( keys instanceof PyList ) ){ throw new RuntimeException("couldn't use passed in scope: keys not dictionary [" + keys.getClass() + "]"); } PyList keysL = (PyList)keys; for(int i = 0; i < keysL.size(); i++){ PyObject key = keysL.pyget(i); if( ! ( key instanceof PyString ) ){ System.out.println("Non-string key in globals : " + key + " [skipping]"); continue; } s.put( key.toString(), Python.toJS( globals.__finditem__(key) ) , true ); } } return Python.toJS( result ); } }; } private void globalRestore( PyObject globals , Scope siteScope , String name , PyObject value ){ if( value != null ){ globals.__setitem__( name , value ); } else{ // FIXME -- delitem should really be deleting from siteScope globals.__delitem__( name ); siteScope.set( name , null ); } } private PyCode _getCode() throws IOException { PyCode c = _code; final long lastModified = _file.lastModified(); if ( c == null || _lastCompile < lastModified ){ c = Python.compile( _file ); _code = c; _lastCompile = lastModified; } return c; } final File _file; final JSFileLibrary _lib; private PyCode _code; private long _lastCompile; void addDependency( String to ){ super.addDependency( new FileDependency( new File( to ) ) ); } // static b/c it has to use ThreadLocal anyway final static Logger _log = Logger.getLogger( "python" ); }
true
true
public synchronized JSFunction getFunction() throws IOException { final PyCode code = _getCode(); return new ed.js.func.JSFunctionCalls0(){ public Object call( Scope s , Object extra[] ){ final AppContext ac = getAppContext(); Scope siteScope; if( ac != null ) siteScope = ac.getScope(); else siteScope = s.getGlobal( true ); SiteSystemState ss = Python.getSiteSystemState( ac , siteScope ); PySystemState pyOld = Py.getSystemState(); ss.flushOld(); ss.ensurePath( _lib.getRoot().toString() ); ss.ensurePath( _lib.getTopParent().getRoot().toString() ); PyObject globals = ss.globals; PyObject oldFile = globals.__finditem__( "__file__" ); PyObject oldName = globals.__finditem__( "__name__" ); PyObject result = null; try { Py.setSystemState( ss.getPyState() ); //Py.initClassExceptions( globals ); globals.__setitem__( "__file__", Py.newString( _file.toString() ) ); // FIXME: Needs to use path info, so foo/bar.py -> foo.bar // Right now I only want this for _init.py String name = _file.getName(); if( name.endsWith( ".py" ) ) name = name.substring( 0 , name.length() - 3 ); //globals.__setitem__( "__name__", Py.newString( name ) ); PyModule module = new PyModule( name , globals ); PyObject locals = module.__dict__; result = Py.runCode( code, locals, globals ); if( ac != null ) ss.addRecursive( "_init" , ac ); } finally { globalRestore( globals , siteScope , "__file__" , oldFile ); globalRestore( globals , siteScope , "__name__" , oldName ); Py.setSystemState( pyOld ); } if( usePassedInScope() ){ PyObject keys = globals.invoke("keys"); if( ! ( keys instanceof PyList ) ){ throw new RuntimeException("couldn't use passed in scope: keys not dictionary [" + keys.getClass() + "]"); } PyList keysL = (PyList)keys; for(int i = 0; i < keysL.size(); i++){ PyObject key = keysL.pyget(i); if( ! ( key instanceof PyString ) ){ System.out.println("Non-string key in globals : " + key + " [skipping]"); continue; } s.put( key.toString(), Python.toJS( globals.__finditem__(key) ) , true ); } } return Python.toJS( result ); } }; }
public synchronized JSFunction getFunction() throws IOException { final PyCode code = _getCode(); return new ed.js.func.JSFunctionCalls0(){ public Object call( Scope s , Object extra[] ){ final AppContext ac = getAppContext(); Scope siteScope; if( ac != null ) siteScope = ac.getScope(); else siteScope = s.getGlobal( true ); SiteSystemState ss = Python.getSiteSystemState( ac , siteScope ); PySystemState pyOld = Py.getSystemState(); ss.flushOld(); ss.ensurePath( _file.getParent().toString() ); ss.ensurePath( _lib.getRoot().toString() ); ss.ensurePath( _lib.getTopParent().getRoot().toString() ); PyObject globals = ss.globals; PyObject oldFile = globals.__finditem__( "__file__" ); PyObject oldName = globals.__finditem__( "__name__" ); PyObject result = null; try { Py.setSystemState( ss.getPyState() ); //Py.initClassExceptions( globals ); globals.__setitem__( "__file__", Py.newString( _file.toString() ) ); // FIXME: Needs to use path info, so foo/bar.py -> foo.bar // Right now I only want this for _init.py String name = _file.getName(); if( name.endsWith( ".py" ) ) name = name.substring( 0 , name.length() - 3 ); //globals.__setitem__( "__name__", Py.newString( name ) ); PyModule module = new PyModule( name , globals ); PyObject locals = module.__dict__; result = Py.runCode( code, locals, globals ); if( ac != null ) ss.addRecursive( "_init" , ac ); } finally { globalRestore( globals , siteScope , "__file__" , oldFile ); globalRestore( globals , siteScope , "__name__" , oldName ); Py.setSystemState( pyOld ); } if( usePassedInScope() ){ PyObject keys = globals.invoke("keys"); if( ! ( keys instanceof PyList ) ){ throw new RuntimeException("couldn't use passed in scope: keys not dictionary [" + keys.getClass() + "]"); } PyList keysL = (PyList)keys; for(int i = 0; i < keysL.size(); i++){ PyObject key = keysL.pyget(i); if( ! ( key instanceof PyString ) ){ System.out.println("Non-string key in globals : " + key + " [skipping]"); continue; } s.put( key.toString(), Python.toJS( globals.__finditem__(key) ) , true ); } } return Python.toJS( result ); } }; }
diff --git a/src/java/org/apache/cassandra/db/HintedHandOffManager.java b/src/java/org/apache/cassandra/db/HintedHandOffManager.java index 7107b58b5..6cd7af2eb 100644 --- a/src/java/org/apache/cassandra/db/HintedHandOffManager.java +++ b/src/java/org/apache/cassandra/db/HintedHandOffManager.java @@ -1,495 +1,495 @@ /* * 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.cassandra.db; import java.io.DataInputStream; import java.io.IOException; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.*; import javax.management.MBeanServer; import javax.management.ObjectName; import com.google.common.collect.ImmutableSortedSet; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.SSTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.filter.IFilter; import org.apache.cassandra.db.filter.NamesQueryFilter; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.gms.ApplicationState; import org.apache.cassandra.gms.FailureDetector; import org.apache.cassandra.gms.Gossiper; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.service.*; import org.apache.cassandra.thrift.*; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.WrappedRunnable; import org.cliffc.high_scale_lib.NonBlockingHashSet; /** * For each endpoint for which we have hints, there is a row in the system hints CF. * The key for this row is ByteBuffer.wrap(string), i.e. "127.0.0.1". * (We have to use String keys for compatibility with OPP.) * SuperColumns in these rows are the mutations to replay, with uuid names: * * <dest token>: { // key * <uuid>: { // supercolumn * mutation: <mutation> // subcolumn * version: <mutation serialization version> * table: <table of hinted mutation> * key: <key of hinted mutation> * } * } * * When FailureDetector signals that a node that was down is back up, we page through * the hinted mutations and send them over one at a time, waiting for * hinted_handoff_throttle_delay in between each. * * deliverHints is also exposed to JMX so it can be run manually if FD ever misses * its cue somehow. */ public class HintedHandOffManager implements HintedHandOffManagerMBean { public static final HintedHandOffManager instance = new HintedHandOffManager(); public static final String HINTS_CF = "HintsColumnFamily"; private static final Logger logger = LoggerFactory.getLogger(HintedHandOffManager.class); private static final int PAGE_SIZE = 128; private static final int LARGE_NUMBER = 65536; // 64k nodes ought to be enough for anybody. // in 0.8, subcolumns were KS-CF bytestrings, and the data was stored in the "normal" storage there. // (so replay always consisted of sending an entire row, // no matter how little was part of the mutation that created the hint.) private static final String SEPARATOR_08 = "-"; private final NonBlockingHashSet<InetAddress> queuedDeliveries = new NonBlockingHashSet<InetAddress>(); private final ExecutorService executor = new JMXEnabledThreadPoolExecutor("HintedHandoff", Thread.MIN_PRIORITY); public void start() { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this, new ObjectName("org.apache.cassandra.db:type=HintedHandoffManager")); } catch (Exception e) { throw new RuntimeException(e); } logger.debug("Created HHOM instance, registered MBean."); Runnable runnable = new Runnable() { public void run() { scheduleAllDeliveries(); } }; StorageService.optionalTasks.scheduleWithFixedDelay(runnable, 10, 10, TimeUnit.MINUTES); } private static void sendMutation(InetAddress endpoint, RowMutation mutation) throws TimeoutException { IWriteResponseHandler responseHandler = WriteResponseHandler.create(endpoint); MessagingService.instance().sendRR(mutation, endpoint, responseHandler); responseHandler.get(); try { Thread.sleep(DatabaseDescriptor.getHintedHandoffThrottleDelay()); } catch (InterruptedException e) { throw new AssertionError(e); } } private static void deleteHint(ByteBuffer tokenBytes, ByteBuffer hintId, long timestamp) throws IOException { RowMutation rm = new RowMutation(Table.SYSTEM_TABLE, tokenBytes); rm.delete(new QueryPath(HINTS_CF, hintId), timestamp); rm.applyUnsafe(); // don't bother with commitlog since we're going to flush as soon as we're done with delivery } public void deleteHintsForEndpoint(final String ipOrHostname) { try { InetAddress endpoint = InetAddress.getByName(ipOrHostname); deleteHintsForEndpoint(endpoint); } catch (UnknownHostException e) { logger.warn("Unable to find "+ipOrHostname+", not a hostname or ipaddr of a node?:"); e.printStackTrace(); throw new RuntimeException(e); } } public void deleteHintsForEndpoint(final InetAddress endpoint) { if (!StorageService.instance.getTokenMetadata().isMember(endpoint)) return; Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint); ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token); final RowMutation rm = new RowMutation(Table.SYSTEM_TABLE, tokenBytes); rm.delete(new QueryPath(HINTS_CF), System.currentTimeMillis()); // execute asynchronously to avoid blocking caller (which may be processing gossip) Runnable runnable = new Runnable() { public void run() { try { logger.info("Deleting any stored hints for " + endpoint); rm.apply(); compact(); } catch (Exception e) { logger.warn("Could not delete hints for " + endpoint + ": " + e); } } }; StorageService.optionalTasks.execute(runnable); } private Future<?> compact() throws ExecutionException, InterruptedException { final ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF); hintStore.forceBlockingFlush(); ArrayList<Descriptor> descriptors = new ArrayList<Descriptor>(); for (SSTable sstable : hintStore.getSSTables()) descriptors.add(sstable.descriptor); return CompactionManager.instance.submitUserDefined(hintStore, descriptors, Integer.MAX_VALUE); } private static boolean pagingFinished(ColumnFamily hintColumnFamily, ByteBuffer startColumn) { // done if no hints found or the start column (same as last column processed in previous iteration) is the only one return hintColumnFamily == null || (hintColumnFamily.getSortedColumns().size() == 1 && hintColumnFamily.getColumn(startColumn) != null); } private int waitForSchemaAgreement(InetAddress endpoint) throws TimeoutException { Gossiper gossiper = Gossiper.instance; int waited = 0; // first, wait for schema to be gossiped. while (gossiper.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.SCHEMA) == null) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new AssertionError(e); } waited += 1000; if (waited > 2 * StorageService.RING_DELAY) throw new TimeoutException("Didin't receive gossiped schema from " + endpoint + " in " + 2 * StorageService.RING_DELAY + "ms"); } waited = 0; // then wait for the correct schema version. // usually we use DD.getDefsVersion, which checks the local schema uuid as stored in the system table. // here we check the one in gossip instead; this serves as a canary to warn us if we introduce a bug that // causes the two to diverge (see CASSANDRA-2946) while (!gossiper.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.SCHEMA).value.equals( gossiper.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddress()).getApplicationState(ApplicationState.SCHEMA).value)) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new AssertionError(e); } waited += 1000; if (waited > 2 * StorageService.RING_DELAY) throw new TimeoutException("Could not reach schema agreement with " + endpoint + " in " + 2 * StorageService.RING_DELAY + "ms"); } logger.debug("schema for {} matches local schema", endpoint); return waited; } private void deliverHintsToEndpoint(InetAddress endpoint) throws IOException, DigestMismatchException, InvalidRequestException, InterruptedException { try { deliverHintsToEndpointInternal(endpoint); } finally { queuedDeliveries.remove(endpoint); } } private void deliverHintsToEndpointInternal(InetAddress endpoint) throws IOException, DigestMismatchException, InvalidRequestException, InterruptedException { ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF); if (hintStore.isEmpty()) return; // nothing to do, don't confuse users by logging a no-op handoff logger.debug("Checking remote({}) schema before delivering hints", endpoint); try { waitForSchemaAgreement(endpoint); } catch (TimeoutException e) { return; } if (!FailureDetector.instance.isAlive(endpoint)) { logger.info("Endpoint {} died before hint delivery, aborting", endpoint); return; } // 1. Get the key of the endpoint we need to handoff // 2. For each column, deserialize the mutation and send it to the endpoint // 3. Delete the subcolumn if the write was successful // 4. Force a flush // 5. Do major compaction to clean up all deletes etc. // find the hints for the node using its token. Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint); logger.info("Started hinted handoff for token: {} with IP: {}", token, endpoint); ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token); DecoratedKey<?> epkey = StorageService.getPartitioner().decorateKey(tokenBytes); int rowsReplayed = 0; ByteBuffer startColumn = ByteBufferUtil.EMPTY_BYTE_BUFFER; int pageSize = PAGE_SIZE; // read less columns (mutations) per page if they are very large if (hintStore.getMeanColumns() > 0) { int averageColumnSize = (int) (hintStore.getMeanRowSize() / hintStore.getMeanColumns()); pageSize = Math.min(PAGE_SIZE, DatabaseDescriptor.getInMemoryCompactionLimit() / averageColumnSize); pageSize = Math.max(2, pageSize); // page size of 1 does not allow actual paging b/c of >= behavior on startColumn logger.debug("average hinted-row column size is {}; using pageSize of {}", averageColumnSize, pageSize); } delivery: while (true) { QueryFilter filter = QueryFilter.getSliceFilter(epkey, new QueryPath(HINTS_CF), startColumn, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, pageSize); ColumnFamily hintsPage = ColumnFamilyStore.removeDeleted(hintStore.getColumnFamily(filter), (int)(System.currentTimeMillis() / 1000)); if (pagingFinished(hintsPage, startColumn)) break; page: for (IColumn hint : hintsPage.getSortedColumns()) { startColumn = hint.name(); for (IColumn subColumn : hint.getSubColumns()) { // both 0.8 and 1.0 column names are UTF8 strings, so this check is safe if (ByteBufferUtil.string(subColumn.name()).contains(SEPARATOR_08)) { logger.debug("0.8-style hint found. This should have been taken care of by purgeIncompatibleHints"); deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); continue page; } } IColumn versionColumn = hint.getSubColumn(ByteBufferUtil.bytes("version")); IColumn tableColumn = hint.getSubColumn(ByteBufferUtil.bytes("table")); IColumn keyColumn = hint.getSubColumn(ByteBufferUtil.bytes("key")); IColumn mutationColumn = hint.getSubColumn(ByteBufferUtil.bytes("mutation")); assert versionColumn != null; assert tableColumn != null; assert keyColumn != null; assert mutationColumn != null; DataInputStream in = new DataInputStream(ByteBufferUtil.inputStream(mutationColumn.value())); RowMutation rm; try { rm = RowMutation.serializer().deserialize(in, ByteBufferUtil.toInt(versionColumn.value())); } catch (UnknownColumnFamilyException e) { - logger_.debug("Skipping delivery of hint for deleted columnfamily", e); + logger.debug("Skipping delivery of hint for deleted columnfamily", e); rm = null; } try { if (rm != null) { sendMutation(endpoint, rm); rowsReplayed++; } deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); } catch (TimeoutException e) { logger.info(String.format("Timed out replaying hints to %s; aborting further deliveries", endpoint)); break delivery; } } } if (rowsReplayed > 0) { try { compact().get(); } catch (Exception e) { throw new RuntimeException(e); } } logger.info(String.format("Finished hinted handoff of %s rows to endpoint %s", rowsReplayed, endpoint)); } /** * Attempt delivery to any node for which we have hints. Necessary since we can generate hints even for * nodes which are never officially down/failed. */ private void scheduleAllDeliveries() { if (logger.isDebugEnabled()) logger.debug("Started scheduleAllDeliveries"); ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF); IPartitioner p = StorageService.getPartitioner(); RowPosition minPos = p.getMinimumToken().minKeyBound(); Range<RowPosition> range = new Range<RowPosition>(minPos, minPos, p); IFilter filter = new NamesQueryFilter(ImmutableSortedSet.<ByteBuffer>of()); List<Row> rows = hintStore.getRangeSlice(null, range, Integer.MAX_VALUE, filter, null); for (Row row : rows) { Token<?> token = StorageService.getPartitioner().getTokenFactory().fromByteArray(row.key.key); InetAddress target = StorageService.instance.getTokenMetadata().getEndpoint(token); // token may have since been removed (in which case we have just read back a tombstone) if (target != null) scheduleHintDelivery(target); } if (logger.isDebugEnabled()) logger.debug("Finished scheduleAllDeliveries"); } /* * This method is used to deliver hints to a particular endpoint. * When we learn that some endpoint is back up we deliver the data * to him via an event driven mechanism. */ public void scheduleHintDelivery(final InetAddress to) { logger.debug("deliverHints to {}", to); if (!queuedDeliveries.add(to)) return; Runnable r = new WrappedRunnable() { public void runMayThrow() throws Exception { deliverHintsToEndpoint(to); } }; executor.execute(r); } public void scheduleHintDelivery(String to) throws UnknownHostException { scheduleHintDelivery(InetAddress.getByName(to)); } public List<String> listEndpointsPendingHints() { List<Row> rows = getHintsSlice(1); // Extract the keys as strings to be reported. LinkedList<String> result = new LinkedList<String>(); for (Row r : rows) { if (r.cf != null) //ignore removed rows result.addFirst(new String(r.key.key.array())); } return result; } public Map<String, Integer> countPendingHints() { List<Row> rows = getHintsSlice(Integer.MAX_VALUE); Map<String, Integer> result = new HashMap<String, Integer>(); for (Row r : rows) { if (r.cf != null) //ignore removed rows result.put(new String(r.key.key.array()), r.cf.getColumnCount()); } return result; } private List<Row> getHintsSlice(int column_count) { // ColumnParent for HintsCF... ColumnParent parent = new ColumnParent(HINTS_CF); // Get count # of columns... SlicePredicate predicate = new SlicePredicate(); SliceRange sliceRange = new SliceRange(); sliceRange.setStart(new byte[0]).setFinish(new byte[0]); sliceRange.setCount(column_count); predicate.setSlice_range(sliceRange); // From keys "" to ""... IPartitioner<?> partitioner = StorageService.getPartitioner(); RowPosition minPos = partitioner.getMinimumToken().minKeyBound(); Range<RowPosition> range = new Range<RowPosition>(minPos, minPos); // Get a bunch of rows! List<Row> rows; try { rows = StorageProxy.getRangeSlice(new RangeSliceCommand("system", parent, predicate, range, null, LARGE_NUMBER), ConsistencyLevel.ONE); } catch (Exception e) { logger.info("HintsCF getEPPendingHints timed out."); throw new RuntimeException(e); } return rows; } }
true
true
private void deliverHintsToEndpointInternal(InetAddress endpoint) throws IOException, DigestMismatchException, InvalidRequestException, InterruptedException { ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF); if (hintStore.isEmpty()) return; // nothing to do, don't confuse users by logging a no-op handoff logger.debug("Checking remote({}) schema before delivering hints", endpoint); try { waitForSchemaAgreement(endpoint); } catch (TimeoutException e) { return; } if (!FailureDetector.instance.isAlive(endpoint)) { logger.info("Endpoint {} died before hint delivery, aborting", endpoint); return; } // 1. Get the key of the endpoint we need to handoff // 2. For each column, deserialize the mutation and send it to the endpoint // 3. Delete the subcolumn if the write was successful // 4. Force a flush // 5. Do major compaction to clean up all deletes etc. // find the hints for the node using its token. Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint); logger.info("Started hinted handoff for token: {} with IP: {}", token, endpoint); ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token); DecoratedKey<?> epkey = StorageService.getPartitioner().decorateKey(tokenBytes); int rowsReplayed = 0; ByteBuffer startColumn = ByteBufferUtil.EMPTY_BYTE_BUFFER; int pageSize = PAGE_SIZE; // read less columns (mutations) per page if they are very large if (hintStore.getMeanColumns() > 0) { int averageColumnSize = (int) (hintStore.getMeanRowSize() / hintStore.getMeanColumns()); pageSize = Math.min(PAGE_SIZE, DatabaseDescriptor.getInMemoryCompactionLimit() / averageColumnSize); pageSize = Math.max(2, pageSize); // page size of 1 does not allow actual paging b/c of >= behavior on startColumn logger.debug("average hinted-row column size is {}; using pageSize of {}", averageColumnSize, pageSize); } delivery: while (true) { QueryFilter filter = QueryFilter.getSliceFilter(epkey, new QueryPath(HINTS_CF), startColumn, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, pageSize); ColumnFamily hintsPage = ColumnFamilyStore.removeDeleted(hintStore.getColumnFamily(filter), (int)(System.currentTimeMillis() / 1000)); if (pagingFinished(hintsPage, startColumn)) break; page: for (IColumn hint : hintsPage.getSortedColumns()) { startColumn = hint.name(); for (IColumn subColumn : hint.getSubColumns()) { // both 0.8 and 1.0 column names are UTF8 strings, so this check is safe if (ByteBufferUtil.string(subColumn.name()).contains(SEPARATOR_08)) { logger.debug("0.8-style hint found. This should have been taken care of by purgeIncompatibleHints"); deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); continue page; } } IColumn versionColumn = hint.getSubColumn(ByteBufferUtil.bytes("version")); IColumn tableColumn = hint.getSubColumn(ByteBufferUtil.bytes("table")); IColumn keyColumn = hint.getSubColumn(ByteBufferUtil.bytes("key")); IColumn mutationColumn = hint.getSubColumn(ByteBufferUtil.bytes("mutation")); assert versionColumn != null; assert tableColumn != null; assert keyColumn != null; assert mutationColumn != null; DataInputStream in = new DataInputStream(ByteBufferUtil.inputStream(mutationColumn.value())); RowMutation rm; try { rm = RowMutation.serializer().deserialize(in, ByteBufferUtil.toInt(versionColumn.value())); } catch (UnknownColumnFamilyException e) { logger_.debug("Skipping delivery of hint for deleted columnfamily", e); rm = null; } try { if (rm != null) { sendMutation(endpoint, rm); rowsReplayed++; } deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); } catch (TimeoutException e) { logger.info(String.format("Timed out replaying hints to %s; aborting further deliveries", endpoint)); break delivery; } } } if (rowsReplayed > 0) { try { compact().get(); } catch (Exception e) { throw new RuntimeException(e); } } logger.info(String.format("Finished hinted handoff of %s rows to endpoint %s", rowsReplayed, endpoint)); }
private void deliverHintsToEndpointInternal(InetAddress endpoint) throws IOException, DigestMismatchException, InvalidRequestException, InterruptedException { ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF); if (hintStore.isEmpty()) return; // nothing to do, don't confuse users by logging a no-op handoff logger.debug("Checking remote({}) schema before delivering hints", endpoint); try { waitForSchemaAgreement(endpoint); } catch (TimeoutException e) { return; } if (!FailureDetector.instance.isAlive(endpoint)) { logger.info("Endpoint {} died before hint delivery, aborting", endpoint); return; } // 1. Get the key of the endpoint we need to handoff // 2. For each column, deserialize the mutation and send it to the endpoint // 3. Delete the subcolumn if the write was successful // 4. Force a flush // 5. Do major compaction to clean up all deletes etc. // find the hints for the node using its token. Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint); logger.info("Started hinted handoff for token: {} with IP: {}", token, endpoint); ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token); DecoratedKey<?> epkey = StorageService.getPartitioner().decorateKey(tokenBytes); int rowsReplayed = 0; ByteBuffer startColumn = ByteBufferUtil.EMPTY_BYTE_BUFFER; int pageSize = PAGE_SIZE; // read less columns (mutations) per page if they are very large if (hintStore.getMeanColumns() > 0) { int averageColumnSize = (int) (hintStore.getMeanRowSize() / hintStore.getMeanColumns()); pageSize = Math.min(PAGE_SIZE, DatabaseDescriptor.getInMemoryCompactionLimit() / averageColumnSize); pageSize = Math.max(2, pageSize); // page size of 1 does not allow actual paging b/c of >= behavior on startColumn logger.debug("average hinted-row column size is {}; using pageSize of {}", averageColumnSize, pageSize); } delivery: while (true) { QueryFilter filter = QueryFilter.getSliceFilter(epkey, new QueryPath(HINTS_CF), startColumn, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, pageSize); ColumnFamily hintsPage = ColumnFamilyStore.removeDeleted(hintStore.getColumnFamily(filter), (int)(System.currentTimeMillis() / 1000)); if (pagingFinished(hintsPage, startColumn)) break; page: for (IColumn hint : hintsPage.getSortedColumns()) { startColumn = hint.name(); for (IColumn subColumn : hint.getSubColumns()) { // both 0.8 and 1.0 column names are UTF8 strings, so this check is safe if (ByteBufferUtil.string(subColumn.name()).contains(SEPARATOR_08)) { logger.debug("0.8-style hint found. This should have been taken care of by purgeIncompatibleHints"); deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); continue page; } } IColumn versionColumn = hint.getSubColumn(ByteBufferUtil.bytes("version")); IColumn tableColumn = hint.getSubColumn(ByteBufferUtil.bytes("table")); IColumn keyColumn = hint.getSubColumn(ByteBufferUtil.bytes("key")); IColumn mutationColumn = hint.getSubColumn(ByteBufferUtil.bytes("mutation")); assert versionColumn != null; assert tableColumn != null; assert keyColumn != null; assert mutationColumn != null; DataInputStream in = new DataInputStream(ByteBufferUtil.inputStream(mutationColumn.value())); RowMutation rm; try { rm = RowMutation.serializer().deserialize(in, ByteBufferUtil.toInt(versionColumn.value())); } catch (UnknownColumnFamilyException e) { logger.debug("Skipping delivery of hint for deleted columnfamily", e); rm = null; } try { if (rm != null) { sendMutation(endpoint, rm); rowsReplayed++; } deleteHint(tokenBytes, hint.name(), hint.maxTimestamp()); } catch (TimeoutException e) { logger.info(String.format("Timed out replaying hints to %s; aborting further deliveries", endpoint)); break delivery; } } } if (rowsReplayed > 0) { try { compact().get(); } catch (Exception e) { throw new RuntimeException(e); } } logger.info(String.format("Finished hinted handoff of %s rows to endpoint %s", rowsReplayed, endpoint)); }
diff --git a/src/Menue.java b/src/Menue.java index bef1484..8f3311d 100644 --- a/src/Menue.java +++ b/src/Menue.java @@ -1,49 +1,50 @@ import java.awt.event.KeyEvent; public class Menue { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub StdDraw.clear(); StdDraw.setPenRadius(.01); + StdDraw.setPenColor(); double x=0.75; double y=0.75; while (true) { StdDraw.show(0); StdDraw.clear(); StdDraw.square(.5, .5, .5); StdDraw.line(0, .5, 1, .5); StdDraw.text(0.5, 0.75, "Start"); StdDraw.text(0.5, 0.25, "Beenden"); StdDraw.point(x, y); if (StdDraw.isKeyPressed(KeyEvent.VK_ENTER)) if (y>0.5) //Start gedr�ckt { Level1.main(args); break; } else System.exit(0); if (StdDraw.isKeyPressed(KeyEvent.VK_UP)) { y=.75; } else if (StdDraw.isKeyPressed(KeyEvent.VK_DOWN)) { y=.25; } } } }
true
true
public static void main(String[] args) { // TODO Auto-generated method stub StdDraw.clear(); StdDraw.setPenRadius(.01); double x=0.75; double y=0.75; while (true) { StdDraw.show(0); StdDraw.clear(); StdDraw.square(.5, .5, .5); StdDraw.line(0, .5, 1, .5); StdDraw.text(0.5, 0.75, "Start"); StdDraw.text(0.5, 0.25, "Beenden"); StdDraw.point(x, y); if (StdDraw.isKeyPressed(KeyEvent.VK_ENTER)) if (y>0.5) //Start gedr�ckt { Level1.main(args); break; } else System.exit(0); if (StdDraw.isKeyPressed(KeyEvent.VK_UP)) { y=.75; } else if (StdDraw.isKeyPressed(KeyEvent.VK_DOWN)) { y=.25; } } }
public static void main(String[] args) { // TODO Auto-generated method stub StdDraw.clear(); StdDraw.setPenRadius(.01); StdDraw.setPenColor(); double x=0.75; double y=0.75; while (true) { StdDraw.show(0); StdDraw.clear(); StdDraw.square(.5, .5, .5); StdDraw.line(0, .5, 1, .5); StdDraw.text(0.5, 0.75, "Start"); StdDraw.text(0.5, 0.25, "Beenden"); StdDraw.point(x, y); if (StdDraw.isKeyPressed(KeyEvent.VK_ENTER)) if (y>0.5) //Start gedr�ckt { Level1.main(args); break; } else System.exit(0); if (StdDraw.isKeyPressed(KeyEvent.VK_UP)) { y=.75; } else if (StdDraw.isKeyPressed(KeyEvent.VK_DOWN)) { y=.25; } } }
diff --git a/DistFileSystem/src/distclient/ClntCheckPosition.java b/DistFileSystem/src/distclient/ClntCheckPosition.java index e5dcf43..f84616f 100644 --- a/DistFileSystem/src/distclient/ClntCheckPosition.java +++ b/DistFileSystem/src/distclient/ClntCheckPosition.java @@ -1,116 +1,117 @@ package distclient; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import distconfig.ConnectionCodes; import distconfig.Constants; import distconfig.DistConfig; import distnodelisting.NodeSearchTable; public class ClntCheckPosition implements Runnable { private String host; private Client client; private int id; public ClntCheckPosition(String host, Client client){ this(host, client.getId(), client); } public ClntCheckPosition(String host, int id, Client client){ this.host = host; this.client = client; this.id = Integer.parseInt(NodeSearchTable.get_Instance().get_ownID()); } @Override public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); + System.out.println("Position Code " + tmpline); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); client.setId(nextTestId); System.out.println("next IP = " + nextTestIp); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; //client.addTask(new ClntCheckPosition(nextTestIp, client)); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
true
true
public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); client.setId(nextTestId); System.out.println("next IP = " + nextTestIp); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; //client.addTask(new ClntCheckPosition(nextTestIp, client)); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public void run() { try { DistConfig distConfig = DistConfig.get_Instance(); System.out.println("Connecting"); Socket sock = new Socket(host, distConfig.get_servPortNumber()); sock.setSoTimeout(5000); System.out.println("Connected"); BufferedOutputStream bos = new BufferedOutputStream ( sock.getOutputStream()); System.out.println("Got OutputStream"); PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got PrintWriter"); BufferedReader in = new BufferedReader ( new InputStreamReader ( sock.getInputStream())); System.out.println("Got InputStream"); System.out.println("Sending Code"); outStream.println(ConnectionCodes.CHECKPOSITION); outStream.flush(); ObjectInputStream ois = new ObjectInputStream(sock.getInputStream()); System.out.println("Got Object InputStream"); System.out.println("Getting Ack"); System.out.println(in.readLine()); System.out.println("Sending my ID as " + id); outStream.println(Integer.toString(id)); outStream.flush(); String tmpline = in.readLine(); System.out.println("Position Code " + tmpline); if (Integer.parseInt(tmpline) == ConnectionCodes.NEWID) { id = Integer.parseInt(in.readLine()); NodeSearchTable.get_Instance().set_own(Integer.toString(id), NodeSearchTable.get_Instance().get_ownIPAddress()); client.setId(id); System.out.println("New ID = " + id); tmpline = in.readLine(); System.out.printf("Received Code %s\n", tmpline); } if ( Integer.parseInt(tmpline) == ConnectionCodes.CORRECTPOSITION) { String[] predecessor = (String[])ois.readObject(); System.out.println("Correct Position"); System.out.println("Pred ID = " + predecessor[Constants.ID]); System.out.println("Pred IP = " + predecessor[Constants.IP_ADDRESS]); String[] successor = (String[])ois.readObject(); System.out.println("Next ID = " + successor[Constants.ID]); System.out.println("Next IP = " + successor[Constants.IP_ADDRESS]); client.setPredecessor(predecessor); client.setSuccessor(successor); } else { int nextTestId = Integer.parseInt(in.readLine()); String nextTestIp = in.readLine(); System.out.println("Wrong Position"); System.out.println("next ID = " + nextTestId); client.setId(nextTestId); System.out.println("next IP = " + nextTestIp); ClntCheckPosition ccp = new ClntCheckPosition (nextTestIp, client); ccp.run(); ccp = null; //client.addTask(new ClntCheckPosition(nextTestIp, client)); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
diff --git a/twitter4j-core/src/main/java/twitter4j/TwitterStream.java b/twitter4j-core/src/main/java/twitter4j/TwitterStream.java index d3694e1a..6e6a7bd1 100644 --- a/twitter4j-core/src/main/java/twitter4j/TwitterStream.java +++ b/twitter4j-core/src/main/java/twitter4j/TwitterStream.java @@ -1,477 +1,479 @@ /* Copyright (c) 2007-2010, Yusuke Yamamoto All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Yusuke Yamamoto nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package twitter4j; import twitter4j.conf.Configuration; import twitter4j.conf.ConfigurationContext; import twitter4j.http.Authorization; import twitter4j.internal.http.HttpClientWrapper; import twitter4j.internal.http.HttpClientWrapperConfiguration; import twitter4j.internal.http.HttpParameter; import twitter4j.internal.logging.Logger; import java.io.IOException; import java.util.Map; /** * A java representation of the <a href="http://apiwiki.twitter.com/Streaming-API-Documentation">Twitter Streaming API</a><br> * Note that this class is NOT compatible with Google App Engine as GAE is not capable of handling requests longer than 30 seconds. * * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.0.4 */ public final class TwitterStream extends TwitterBase implements java.io.Serializable { private final HttpClientWrapper http; private static final Logger logger = Logger.getLogger(TwitterStream.class); private StatusListener statusListener; private StreamHandlingThread handler = null; private static final long serialVersionUID = -762817147320767897L; /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream() { super(ConfigurationContext.getInstance()); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @param screenName screen name * @param password password * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream(String screenName, String password) { super(ConfigurationContext.getInstance(), screenName, password); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /** * Constructs a TwitterStream instance. UserID and password should be provided by either twitter4j.properties or system property. * since Twitter4J 2.0.10 * @param screenName screen name * @param password password * @param listener listener * @deprecated use {@link TwitterStreamFactory#getInstance()} instead. */ public TwitterStream(String screenName, String password, StatusListener listener) { super(ConfigurationContext.getInstance(), screenName, password); this.statusListener = listener; http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); ensureBasicEnabled(); } /*package*/ TwitterStream(Configuration conf, Authorization auth, StatusListener listener) { super(conf, auth); http = new HttpClientWrapper(new StreamingReadTimeoutConfiguration(conf)); this.statusListener = listener; ensureBasicEnabled(); } /* Streaming API */ /** * Starts listening on all public statuses. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the firehose. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/firehose">Twitter API Wiki / Streaming API Documentation - firehose</a> * @since Twitter4J 2.0.4 */ public void firehose(final int count) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFirehoseStream(count); } }); } /** * Returns a status stream of all public statuses. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the firehose. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/firehose">Twitter API Wiki / Streaming API Documentation - firehose</a> * @since Twitter4J 2.0.4 */ public StatusStream getFirehoseStream(int count) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/firehose.json" , new HttpParameter[]{new HttpParameter("count" , String.valueOf(count))}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on all public statuses containing links. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the links stream. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/links">Twitter API Wiki / Streaming API Documentation - links</a> * @since Twitter4J 2.1.1 */ public void links(final int count) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getLinksStream(count); } }); } /** * Returns a status stream of all public statuses containing links. Available only to approved parties and requires a signed agreement to access. Please do not contact us about access to the links stream. If your service warrants access to it, we'll contact you. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/links">Twitter API Wiki / Streaming API Documentation - links</a> * @since Twitter4J 2.1.1 */ public StatusStream getLinksStream(int count) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/links.json" , new HttpParameter[]{new HttpParameter("count" , String.valueOf(count))}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on all retweets. The retweet stream is not a generally available resource. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. As of 9/11/2009, the site-wide retweet feature has not yet launched, so there are currently few, if any, retweets on this stream. * * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/retweet">Twitter API Wiki / Streaming API Documentation - retweet</a> * @since Twitter4J 2.0.10 */ public void retweet() { ensureBasicEnabled(); startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getRetweetStream(); } }); } /** * Returns a stream of all retweets. The retweet stream is not a generally available resource. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case. As of 9/11/2009, the site-wide retweet feature has not yet launched, so there are currently few, if any, retweets on this stream. * * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/retweet">Twitter API Wiki / Streaming API Documentation - retweet</a> * @since Twitter4J 2.0.10 */ public StatusStream getRetweetStream() throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/retweet.json" , new HttpParameter[]{}, auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Starts listening on random sample of all public statuses. The default access level provides a small proportion of the Firehose. The "Gardenhose" access level provides a proportion more suitable for data mining and research applications that desire a larger proportion to be statistically significant sample. * * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/sample">Twitter API Wiki / Streaming API Documentation - sample</a> * @since Twitter4J 2.0.10 */ public void sample() { ensureBasicEnabled(); startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getSampleStream(); } }); } /** * Returns a stream of random sample of all public statuses. The default access level provides a small proportion of the Firehose. The "Gardenhose" access level provides a proportion more suitable for data mining and research applications that desire a larger proportion to be statistically significant sample. * * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#Sampling">Twitter API Wiki / Streaming API Documentation - Sampling</a> * @since Twitter4J 2.0.10 */ public StatusStream getSampleStream() throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.get(conf.getStreamBaseURL() + "statuses/sample.json" , auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Start consuming public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param query Filter query * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.1.2 */ public void filter(final FilterQuery query) throws TwitterException { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFilterStream(query); } }); } /** * Returns public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param query Filter query * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.1.2 */ public StatusStream getFilterStream(FilterQuery query) throws TwitterException { ensureBasicEnabled(); try { return new StatusStreamImpl(http.post(conf.getStreamBaseURL() + "statuses/filter.json" , query.asHttpParameterArray(), auth)); } catch (IOException e) { throw new TwitterException(e); } } /** * Start consuming public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param count Indicates the number of previous statuses to stream before transitioning to the live stream. * @param follow Specifies the users, by ID, to receive public tweets from. * @param track Specifies keywords to track. * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.0.10 * @deprecated use {@link #filter(FilterQuery)} instead */ public void filter(final int count, final int[] follow, final String[] track) { startHandler(new StreamHandlingThread() { public StatusStream getStream() throws TwitterException { return getFilterStream(count, follow, track); } }); } /** * Returns public statuses that match one or more filter predicates. At least one predicate parameter, follow, locations, or track must be specified. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Placing long parameters in the URL may cause the request to be rejected for excessive URL length.<br> * The default access level allows up to 200 track keywords, 400 follow userids and 10 1-degree location boxes. Increased access levels allow 80,000 follow userids ("shadow" role), 400,000 follow userids ("birddog" role), 10,000 track keywords ("restricted track" role), 200,000 track keywords ("partner track" role), and 200 10-degree location boxes ("locRestricted" role). Increased track access levels also pass a higher proportion of statuses before limiting the stream. * * @param follow Specifies the users, by ID, to receive public tweets from. * @return StatusStream * @throws TwitterException when Twitter service or network is unavailable * @see twitter4j.StatusStream * @see <a href="http://apiwiki.twitter.com/Streaming-API-Documentation#statuses/filter">Twitter API Wiki / Streaming API Documentation - filter</a> * @since Twitter4J 2.0.10 * @deprecated use {@link #getFilterStream(FilterQuery)} instead */ public StatusStream getFilterStream(int count, int[] follow, String[] track) throws TwitterException { return getFilterStream(new FilterQuery(count, follow, track, null)); } private synchronized void startHandler(StreamHandlingThread handler) { cleanup(); if (null == statusListener) { throw new IllegalStateException("StatusListener is not set."); } this.handler = handler; this.handler.start(); } public synchronized void cleanup() { if (null != handler) { try { handler.close(); } catch (IOException ignore) { } } } public void setStatusListener(StatusListener statusListener) { this.statusListener = statusListener; } /* http://apiwiki.twitter.com/Streaming-API-Documentation#Connecting When a network error (TCP/IP level) is encountered, back off linearly. Perhaps start at 250 milliseconds, double, and cap at 16 seconds When a HTTP error (> 200) is returned, back off exponentially. Perhaps start with a 10 second wait, double on each subsequent failure, and finally cap the wait at 240 seconds. Consider sending an alert to a human operator after multiple HTTP errors, as there is probably a client configuration issue that is unlikely to be resolved without human intervention. There's not much point in polling any faster in the face of HTTP error codes and your client is may run afoul of a rate limit. */ private static final int TCP_ERROR_INITIAL_WAIT = 250; private static final int TCP_ERROR_WAIT_CAP = 16 * 1000; private static final int HTTP_ERROR_INITIAL_WAIT = 10 * 1000; private static final int HTTP_ERROR_WAIT_CAP = 240 * 1000; abstract class StreamHandlingThread extends Thread { StatusStream stream = null; private static final String NAME = "Twitter Stream Handling Thread"; private boolean closed = false; StreamHandlingThread() { super(NAME + "[initializing]"); } public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { - if (0 == timeToSleep && te.getStatusCode() > 200) { - timeToSleep = HTTP_ERROR_INITIAL_WAIT; - } else { - timeToSleep = TCP_ERROR_INITIAL_WAIT; + if (0 == timeToSleep) { + if (te.getStatusCode() > 200) { + timeToSleep = HTTP_ERROR_INITIAL_WAIT; + } else { + timeToSleep = TCP_ERROR_INITIAL_WAIT; + } } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } } public synchronized void close() throws IOException { setStatus("[disposing thread]"); closed = true; } private void setStatus(String message) { String actualMessage = NAME + message; setName(actualMessage); logger.debug(actualMessage); } abstract StatusStream getStream() throws TwitterException; } } class StreamingReadTimeoutConfiguration implements HttpClientWrapperConfiguration { Configuration nestedConf; StreamingReadTimeoutConfiguration(Configuration httpConf) { this.nestedConf = httpConf; } public String getHttpProxyHost() { return nestedConf.getHttpProxyHost(); } public int getHttpProxyPort() { return nestedConf.getHttpProxyPort(); } public String getHttpProxyUser() { return nestedConf.getHttpProxyUser(); } public String getHttpProxyPassword() { return nestedConf.getHttpProxyPassword(); } public int getHttpConnectionTimeout() { return nestedConf.getHttpConnectionTimeout(); } public int getHttpReadTimeout() { // this is the trick that overrides connection timeout return nestedConf.getHttpStreamingReadTimeout(); } public int getHttpRetryCount() { return nestedConf.getHttpRetryCount(); } public int getHttpRetryIntervalSeconds() { return nestedConf.getHttpRetryIntervalSeconds(); } public Map<String, String> getRequestHeaders() { return nestedConf.getRequestHeaders(); } }
true
true
public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { if (0 == timeToSleep && te.getStatusCode() > 200) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } else { timeToSleep = TCP_ERROR_INITIAL_WAIT; } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } }
public void run() { int timeToSleep = 0; while (!closed) { try { if (!closed && null == stream) { // try establishing connection setStatus("[Establishing connection]"); stream = getStream(); // connection established successfully timeToSleep = 0; setStatus("[Receiving stream]"); while (!closed) { stream.next(statusListener); } } } catch (TwitterException te) { if (!closed) { if (0 == timeToSleep) { if (te.getStatusCode() > 200) { timeToSleep = HTTP_ERROR_INITIAL_WAIT; } else { timeToSleep = TCP_ERROR_INITIAL_WAIT; } } // there was a problem establishing the connection, or the connection closed by peer if (!closed) { // wait for a moment not to overload Twitter API setStatus("[Waiting for " + (timeToSleep) + " milliseconds]"); try { Thread.sleep(timeToSleep); } catch (InterruptedException ignore) { } timeToSleep = Math.min(timeToSleep * 2, (te.getStatusCode() > 200) ? HTTP_ERROR_WAIT_CAP : TCP_ERROR_WAIT_CAP); } stream = null; logger.debug(te.getMessage()); statusListener.onException(te); } } } try { this.stream.close(); } catch (IOException ignore) { } }
diff --git a/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java index 4744a316..1ba23eb1 100644 --- a/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java +++ b/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java @@ -1,72 +1,72 @@ /* * AggressiveExtractorHTML * * $Id$ * * Created on Jan 6, 2004 * * Copyright (C) 2004 Internet Archive. * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.archive.modules.extractor; import java.util.logging.Logger; import org.archive.modules.ProcessorURI; /** * Extended version of ExtractorHTML with more aggressive javascript link * extraction where javascript code is parsed first with general HTML tags * regexp, and than by javascript speculative link regexp. * * @author Igor Ranitovic * */ public class AggressiveExtractorHTML extends ExtractorHTML { private static final long serialVersionUID = 3L; static Logger logger = Logger.getLogger(AggressiveExtractorHTML.class.getName()); public AggressiveExtractorHTML() { } protected void processScript(ProcessorURI curi, CharSequence sequence, int endOfOpenTag) { super.processScript(curi, sequence, endOfOpenTag); // then, proccess entire javascript code as html code // this may cause a lot of false positves processGeneralTag(curi, sequence.subSequence(0,6), sequence.subSequence(endOfOpenTag, sequence.length())); } /* (non-Javadoc) * @see org.archive.crawler.framework.Processor#report() */ public String report() { StringBuffer ret = new StringBuffer(256); - ret.append("Processor: org.archive.crawler.extractor.ExtractorHTML2\n"); + ret.append("Processor: "+AggressiveExtractorHTML.class.getName()+"\n"); ret.append(" Function: Link extraction on HTML documents " + "(including embedded CSS)\n"); ret.append(" ProcessorURRIs handled: " + numberOfCURIsHandled + "\n"); ret.append(" Links extracted: " + numberOfLinksExtracted + "\n\n"); return ret.toString(); } }
true
true
public String report() { StringBuffer ret = new StringBuffer(256); ret.append("Processor: org.archive.crawler.extractor.ExtractorHTML2\n"); ret.append(" Function: Link extraction on HTML documents " + "(including embedded CSS)\n"); ret.append(" ProcessorURRIs handled: " + numberOfCURIsHandled + "\n"); ret.append(" Links extracted: " + numberOfLinksExtracted + "\n\n"); return ret.toString(); }
public String report() { StringBuffer ret = new StringBuffer(256); ret.append("Processor: "+AggressiveExtractorHTML.class.getName()+"\n"); ret.append(" Function: Link extraction on HTML documents " + "(including embedded CSS)\n"); ret.append(" ProcessorURRIs handled: " + numberOfCURIsHandled + "\n"); ret.append(" Links extracted: " + numberOfLinksExtracted + "\n\n"); return ret.toString(); }
diff --git a/bcel-builder/src/org/aspectj/apache/bcel/classfile/GenericSignatureParser.java b/bcel-builder/src/org/aspectj/apache/bcel/classfile/GenericSignatureParser.java index 230a055c1..4ad1b9a1b 100644 --- a/bcel-builder/src/org/aspectj/apache/bcel/classfile/GenericSignatureParser.java +++ b/bcel-builder/src/org/aspectj/apache/bcel/classfile/GenericSignatureParser.java @@ -1,369 +1,391 @@ /* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.apache.bcel.classfile; import java.util.ArrayList; import java.util.List; import org.aspectj.apache.bcel.classfile.Signature.ArrayTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.ClassTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.FieldTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.FormalTypeParameter; import org.aspectj.apache.bcel.classfile.Signature.MethodTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.SimpleClassTypeSignature; import org.aspectj.apache.bcel.classfile.Signature.TypeArgument; import org.aspectj.apache.bcel.classfile.Signature.TypeSignature; import org.aspectj.apache.bcel.classfile.Signature.TypeVariableSignature; import org.aspectj.apache.bcel.classfile.Signature.BaseTypeSignature; /** * Parses the generic signature attribute as defined in the JVM spec. */ public class GenericSignatureParser { private String[] tokenStream; // for parse in flight private int tokenIndex = 0; /** * AMC. * Parse the signature string interpreting it as a ClassSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public Signature.ClassSignature parseAsClassSignature(String sig) { tokenStream = tokenize(sig); tokenIndex = 0; Signature.ClassSignature classSig = new Signature.ClassSignature(); // FormalTypeParameters-opt if (maybeEat("<")) { List formalTypeParametersList = new ArrayList(); do { formalTypeParametersList.add(parseFormalTypeParameter()); } while (!maybeEat(">")); classSig.formalTypeParameters = new FormalTypeParameter[formalTypeParametersList.size()]; formalTypeParametersList.toArray(classSig.formalTypeParameters); } classSig.superclassSignature = parseClassTypeSignature(); List superIntSigs = new ArrayList(); while (tokenIndex < tokenStream.length) { superIntSigs.add(parseClassTypeSignature()); } classSig.superInterfaceSignatures = new ClassTypeSignature[superIntSigs.size()]; superIntSigs.toArray(classSig.superInterfaceSignatures); return classSig; } /** * AMC. * Parse the signature string interpreting it as a MethodTypeSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public MethodTypeSignature parseAsMethodSignature(String sig) { tokenStream = tokenize(sig); tokenIndex = 0; FormalTypeParameter[] formals = new FormalTypeParameter[0]; TypeSignature[] params = new TypeSignature[0]; TypeSignature returnType = null; FieldTypeSignature[] throwsSigs = new FieldTypeSignature[0]; // FormalTypeParameters-opt if (maybeEat("<")) { List formalTypeParametersList = new ArrayList(); do { formalTypeParametersList.add(parseFormalTypeParameter()); } while (!maybeEat(">")); formals = new FormalTypeParameter[formalTypeParametersList.size()]; formalTypeParametersList.toArray(formals); } // Parameters eat("("); List paramList = new ArrayList(); while(!maybeEat(")")) { FieldTypeSignature fsig = parseFieldTypeSignature(true); if (fsig != null) { paramList.add(fsig); } else { paramList.add(new Signature.BaseTypeSignature(eatIdentifier())); } } params = new TypeSignature[paramList.size()]; paramList.toArray(params); // return type returnType = parseFieldTypeSignature(true); if (returnType == null) returnType = new Signature.BaseTypeSignature(eatIdentifier()); // throws List throwsList = new ArrayList(); while (maybeEat("^")) { FieldTypeSignature fsig = parseFieldTypeSignature(false); throwsList.add(fsig); } throwsSigs = new FieldTypeSignature[throwsList.size()]; throwsList.toArray(throwsSigs); return new Signature.MethodTypeSignature(formals,params,returnType,throwsSigs); } /** * AMC. * Parse the signature string interpreting it as a FieldTypeSignature according to * the grammar defined in Section 4.4.4 of the JVM specification. */ public FieldTypeSignature parseAsFieldSignature(String sig) { tokenStream = tokenize(sig); tokenIndex = 0; return parseFieldTypeSignature(false); } private FormalTypeParameter parseFormalTypeParameter() { FormalTypeParameter ftp = new FormalTypeParameter(); // Identifier ftp.identifier = eatIdentifier(); // ClassBound eat(":"); ftp.classBound = parseFieldTypeSignature(true); if (ftp.classBound == null) { ftp.classBound = new ClassTypeSignature("Ljava/lang/Object;","Object"); } // Optional InterfaceBounds List optionalBounds = new ArrayList(); while (maybeEat(":")) { optionalBounds.add(parseFieldTypeSignature(false)); } ftp.interfaceBounds = new FieldTypeSignature[optionalBounds.size()]; optionalBounds.toArray(ftp.interfaceBounds); return ftp; } private FieldTypeSignature parseFieldTypeSignature(boolean isOptional) { if (isOptional) { // anything other than 'L', 'T' or '[' and we're out of here if (!tokenStream[tokenIndex].startsWith("L") && !tokenStream[tokenIndex].startsWith("T") && !tokenStream[tokenIndex].startsWith("[")) { return null; } } if (maybeEat("[")) { return parseArrayTypeSignature(); } else if (tokenStream[tokenIndex].startsWith("L")) { return parseClassTypeSignature(); } else if (tokenStream[tokenIndex].startsWith("T")) { return parseTypeVariableSignature(); } else { throw new IllegalStateException("Expection [,L, or T, but found " + tokenStream[tokenIndex]); } } private ArrayTypeSignature parseArrayTypeSignature() { // opening [ already eaten FieldTypeSignature fieldType = parseFieldTypeSignature(true); if (fieldType != null) { return new ArrayTypeSignature(fieldType); } else { // must be BaseType array return new ArrayTypeSignature(new BaseTypeSignature(eatIdentifier())); } } // L PackageSpecifier* SimpleClassTypeSignature ClassTypeSignature* ; private ClassTypeSignature parseClassTypeSignature() { SimpleClassTypeSignature outerType = null; SimpleClassTypeSignature[] nestedTypes = new SimpleClassTypeSignature[0]; StringBuffer ret = new StringBuffer(); String identifier = eatIdentifier(); ret.append(identifier); while (maybeEat("/")) { ret.append("/"); // dont forget this... ret.append(eatIdentifier()); } identifier = ret.toString(); // now we have either a "." indicating the start of a nested type, // or a "<" indication type arguments, or ";" and we are done. while (!maybeEat(";")) { if (maybeEat(".")) { // outer type completed outerType = new SimpleClassTypeSignature(identifier); List nestedTypeList = new ArrayList(); do { ret.append("."); SimpleClassTypeSignature sig = parseSimpleClassTypeSignature(); ret.append(sig.toString()); nestedTypeList.add(ret); } while(maybeEat(".")); nestedTypes = new SimpleClassTypeSignature[nestedTypeList.size()]; nestedTypeList.toArray(nestedTypes); } else if (tokenStream[tokenIndex].equals("<")) { ret.append("<"); TypeArgument[] tArgs = maybeParseTypeArguments(); for (int i=0; i < tArgs.length; i++) { ret.append(tArgs[i].toString()); } ret.append(">"); outerType = new SimpleClassTypeSignature(identifier,tArgs); // now parse possible nesteds... List nestedTypeList = new ArrayList(); while (maybeEat(".")) { ret.append("."); SimpleClassTypeSignature sig = parseSimpleClassTypeSignature(); ret.append(sig.toString()); nestedTypeList.add(ret); } nestedTypes = new SimpleClassTypeSignature[nestedTypeList.size()]; nestedTypeList.toArray(nestedTypes); } else { throw new IllegalStateException("Expecting .,<, or ;, but found " + tokenStream[tokenIndex]); } } ret.append(";"); if (outerType == null) outerType = new SimpleClassTypeSignature(ret.toString()); return new ClassTypeSignature(ret.toString(),outerType,nestedTypes); } private SimpleClassTypeSignature parseSimpleClassTypeSignature() { String identifier = eatIdentifier(); TypeArgument[] tArgs = maybeParseTypeArguments(); if (tArgs != null) { return new SimpleClassTypeSignature(identifier,tArgs); } else { return new SimpleClassTypeSignature(identifier); } } private TypeArgument parseTypeArgument() { boolean isPlus = false; boolean isMinus = false; if (maybeEat("*")) { return new TypeArgument(); } else if (maybeEat("+")) { isPlus = true; } else if (maybeEat("-")) { isMinus = true; } FieldTypeSignature sig = parseFieldTypeSignature(false); return new TypeArgument(isPlus,isMinus,sig); } private TypeArgument[] maybeParseTypeArguments() { if (maybeEat("<")) { List typeArgs = new ArrayList(); do { TypeArgument arg = parseTypeArgument(); typeArgs.add(arg); } while(!maybeEat(">")); TypeArgument[] tArgs = new TypeArgument[typeArgs.size()]; typeArgs.toArray(tArgs); return tArgs; } else { return null; } } private TypeVariableSignature parseTypeVariableSignature() { TypeVariableSignature tv = new TypeVariableSignature(eatIdentifier()); eat(";"); return tv; } private boolean maybeEat(String token) { if (tokenStream.length <= tokenIndex) return false; if (tokenStream[tokenIndex].equals(token)) { tokenIndex++; return true; } return false; } private void eat(String token) { if (!tokenStream[tokenIndex].equals(token)) { throw new IllegalStateException("Expecting " + token + " but found " + tokenStream[tokenIndex]); } tokenIndex++; } private String eatIdentifier() { return tokenStream[tokenIndex++]; } /** * non-private for test visibility * Splits a string containing a generic signature into tokens for consumption * by the parser. */ public String[] tokenize(String signatureString) { char[] chars = signatureString.toCharArray(); int index = 0; List tokens = new ArrayList(); StringBuffer identifier = new StringBuffer(); + boolean inParens = false; + boolean couldSeePrimitive = false; do { switch (chars[index]) { case '<' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("<"); break; case '>' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(">"); break; case ':' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(":"); break; case '/' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("/"); + couldSeePrimitive = false; break; case ';' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(";"); + couldSeePrimitive = true; break; case '^': if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("^"); break; case '+': tokens.add("+"); break; case '-': tokens.add("-"); break; case '*': tokens.add("*"); break; case '.' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("."); break; case '(' : tokens.add("("); + inParens = true; + couldSeePrimitive = true; break; case ')' : tokens.add(")"); + inParens = false; break; case '[' : tokens.add("["); break; + case 'B' : + case 'C' : + case 'D' : + case 'F' : + case 'I' : + case 'J' : + case 'S' : + case 'V' : + case 'Z' : + if (inParens && couldSeePrimitive && identifier.length() == 0) { + tokens.add(new String("" + chars[index])); + } else { + identifier.append(chars[index]); + } + break; default : identifier.append(chars[index]); } } while((++index) < chars.length); if (identifier.length() > 0) tokens.add(identifier.toString()); String [] tokenArray = new String[tokens.size()]; tokens.toArray(tokenArray); return tokenArray; } }
false
true
public String[] tokenize(String signatureString) { char[] chars = signatureString.toCharArray(); int index = 0; List tokens = new ArrayList(); StringBuffer identifier = new StringBuffer(); do { switch (chars[index]) { case '<' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("<"); break; case '>' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(">"); break; case ':' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(":"); break; case '/' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("/"); break; case ';' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(";"); break; case '^': if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("^"); break; case '+': tokens.add("+"); break; case '-': tokens.add("-"); break; case '*': tokens.add("*"); break; case '.' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("."); break; case '(' : tokens.add("("); break; case ')' : tokens.add(")"); break; case '[' : tokens.add("["); break; default : identifier.append(chars[index]); } } while((++index) < chars.length); if (identifier.length() > 0) tokens.add(identifier.toString()); String [] tokenArray = new String[tokens.size()]; tokens.toArray(tokenArray); return tokenArray; }
public String[] tokenize(String signatureString) { char[] chars = signatureString.toCharArray(); int index = 0; List tokens = new ArrayList(); StringBuffer identifier = new StringBuffer(); boolean inParens = false; boolean couldSeePrimitive = false; do { switch (chars[index]) { case '<' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("<"); break; case '>' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(">"); break; case ':' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(":"); break; case '/' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("/"); couldSeePrimitive = false; break; case ';' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add(";"); couldSeePrimitive = true; break; case '^': if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("^"); break; case '+': tokens.add("+"); break; case '-': tokens.add("-"); break; case '*': tokens.add("*"); break; case '.' : if (identifier.length() > 0) tokens.add(identifier.toString()); identifier = new StringBuffer(); tokens.add("."); break; case '(' : tokens.add("("); inParens = true; couldSeePrimitive = true; break; case ')' : tokens.add(")"); inParens = false; break; case '[' : tokens.add("["); break; case 'B' : case 'C' : case 'D' : case 'F' : case 'I' : case 'J' : case 'S' : case 'V' : case 'Z' : if (inParens && couldSeePrimitive && identifier.length() == 0) { tokens.add(new String("" + chars[index])); } else { identifier.append(chars[index]); } break; default : identifier.append(chars[index]); } } while((++index) < chars.length); if (identifier.length() > 0) tokens.add(identifier.toString()); String [] tokenArray = new String[tokens.size()]; tokens.toArray(tokenArray); return tokenArray; }
diff --git a/loci/visbio/view/CaptureHandler.java b/loci/visbio/view/CaptureHandler.java index 2fe8d5f0e..6d8c41ee1 100644 --- a/loci/visbio/view/CaptureHandler.java +++ b/loci/visbio/view/CaptureHandler.java @@ -1,502 +1,504 @@ // // CaptureHandler.java // /* VisBio application for visualization of multidimensional biological image data. Copyright (C) 2002-2004 Curtis Rueden. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.visbio.view; import ij.*; import ij.io.FileSaver; import java.awt.Image; import java.io.IOException; import java.io.File; import java.rmi.RemoteException; import java.util.Vector; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import loci.visbio.SystemManager; import loci.visbio.WindowManager; import loci.visbio.state.*; import loci.visbio.util.VisUtil; import org.w3c.dom.Element; import visad.*; import visad.data.avi.AVIForm; import visad.util.*; /** Provides logic for capturing display screenshots and movies. */ public class CaptureHandler implements Saveable { // -- Fields - GUI components -- /** Associated display window. */ protected DisplayWindow window; /** GUI controls for capture handler. */ protected CapturePanel panel; /** File chooser for snapshot output. */ protected JFileChooser imageBox; /** File chooser for movie output. */ protected JFileChooser movieBox; // -- Fields - initial state -- /** List of positions. */ protected Vector positions; /** Movie speed. */ protected int movieSpeed; /** Movie frames per second. */ protected int movieFPS; /** Whether transitions use a smoothing sine function. */ protected boolean movieSmooth; // -- Constructor -- /** Creates a display capture handler. */ public CaptureHandler(DisplayWindow dw) { window = dw; positions = new Vector(); } // -- CaptureHandler API methods -- /** Gets positions on the list. */ public Vector getPositions() { return panel == null ? positions : panel.getCaptureWindow().getPositions(); } /** Gets movie speed. */ public int getSpeed() { return panel == null ? movieSpeed : panel.getCaptureWindow().getSpeed(); } /** Gets movie frames per second. */ public int getFPS() { return panel == null ? movieFPS : panel.getCaptureWindow().getFPS(); } /** Gets whether transitions use a smoothing sine function. */ public boolean isSmooth() { return panel == null ? movieSmooth : panel.getCaptureWindow().isSmooth(); } /** Gets associated display window. */ public DisplayWindow getWindow() { return window; } /** Gets GUI controls for this capture handler. */ public CapturePanel getPanel() { return panel; } /** Gets a snapshot of the display. */ public Image getSnapshot() { return window.getDisplay().getImage(); } /** Saves a snapshot of the display to a file specified by the user. */ public void saveSnapshot() { CaptureWindow captureWindow = panel.getCaptureWindow(); int rval = imageBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; // determine file type String file = imageBox.getSelectedFile().getPath(); String ext = ""; int dot = file.lastIndexOf("."); if (dot >= 0) ext = file.substring(dot + 1).toLowerCase(); boolean tiff = ext.equals("tif") || ext.equals("tiff"); boolean jpeg = ext.equals("jpg") || ext.equals("jpeg"); FileFilter filter = imageBox.getFileFilter(); String desc = filter.getDescription(); if (desc.startsWith("JPEG")) { if (!jpeg) { file += ".jpg"; jpeg = true; } } else if (desc.startsWith("TIFF")) { if (!tiff) { file += ".tif"; tiff = true; } } if (!tiff && !jpeg) { JOptionPane.showMessageDialog(captureWindow, "Invalid filename (" + file + "): extension must indicate TIFF or JPEG format.", "Cannot export snapshot", JOptionPane.ERROR_MESSAGE); return; } // save file in a separate thread final String filename = file; final boolean isTiff = tiff, isJpeg = jpeg; new Thread("VisBio-SnapshotThread-" + window.getName()) { public void run() { FileSaver saver = new FileSaver(new ImagePlus("null", getSnapshot())); if (isTiff) saver.saveAsTiff(filename); else if (isJpeg) saver.saveAsJpeg(filename); } }.start(); } /** Sends a snapshot of the display to ImageJ. */ public void sendToImageJ() { new Thread("VisBio-SendToImageJThread-" + window.getName()) { public void run() { ImageJ ij = IJ.getInstance(); if (ij == null || (ij != null && !ij.isShowing())) { // create new ImageJ instance File dir = new File(System.getProperty("user.dir")); File newDir = new File(dir.getParentFile().getParentFile(), "ij"); System.setProperty("user.dir", newDir.getPath()); new ImageJ(null); System.setProperty("user.dir", dir.getPath()); // display ImageJ warning OptionManager om = (OptionManager) window.getVisBio().getManager(OptionManager.class); om.checkWarning(DisplayManager.WARN_IMAGEJ, false, "Quitting ImageJ may also shut down VisBio, with no\n" + "warning or opportunity to save your work. Similarly,\n" + "quitting VisBio will shut down ImageJ without warning.\n" + "Please remember to save your work in both programs\n" + "before closing either one."); } new ImagePlus("VisBio snapshot", getSnapshot()).show(); } }.start(); } /** Creates a movie of the given transformation sequence. */ public void captureMovie(Vector matrices, double secPerTrans, int framesPerSec, boolean sine, boolean movie) { CaptureWindow captureWindow = panel.getCaptureWindow(); final int size = matrices.size(); if (size < 1) { JOptionPane.showMessageDialog(captureWindow, "Must have at least " + "two display positions on the list.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final DisplayImpl d = window.getDisplay(); if (d == null) { JOptionPane.showMessageDialog(captureWindow, "Display not found.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final ProjectionControl pc = d.getProjectionControl(); final int fps = framesPerSec; final int framesPerTrans = (int) (framesPerSec * secPerTrans); final int total = (size - 1) * framesPerTrans + 1; // get output filename(s) from the user String file = null; int dot = -1; boolean tiff = false, jpeg = false; if (movie) { int rval = movieBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = movieBox.getSelectedFile().getPath(); if (file.indexOf(".") < 0) file = file + ".avi"; } else { int rval = imageBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = imageBox.getSelectedFile().getPath(); String ext = ""; dot = file.lastIndexOf("."); if (dot >= 0) ext = file.substring(dot + 1).toLowerCase(); tiff = ext.equals("tif") || ext.equals("tiff"); jpeg = ext.equals("jpg") || ext.equals("jpeg"); FileFilter filter = imageBox.getFileFilter(); String desc = filter.getDescription(); if (desc.startsWith("JPEG")) { if (!jpeg) { file += ".jpg"; jpeg = true; + dot = file.lastIndexOf("."); } } else if (desc.startsWith("TIFF")) { if (!tiff) { file += ".tif"; tiff = true; + dot = file.lastIndexOf("."); } } if (!tiff && !jpeg) { JOptionPane.showMessageDialog(captureWindow, "Invalid filename (" + file + "): extension must be TIFF or JPEG.", "Cannot create image sequence", JOptionPane.ERROR_MESSAGE); return; } } // capture image sequence in a separate thread final boolean aviMovie = movie; final String filename = file; final int dotIndex = dot; final boolean isTiff = tiff, isJpeg = jpeg; final Vector pos = matrices; final int frm = framesPerTrans; final boolean doSine = sine; new Thread("VisBio-CaptureThread-" + window.getName()) { public void run() { WindowManager wm = (WindowManager) window.getVisBio().getManager(WindowManager.class); wm.setWaitCursor(true); // step incremental from position to position, grabbing images double[] mxStart = (double[]) pos.elementAt(0); Image[] images = new Image[total]; int count = 0; for (int i=1; i<size; i++) { double[] mxEnd = (double[]) pos.elementAt(i); double[] mx = new double[mxStart.length]; for (int j=0; j<frm; j++) { setProgress(100 * count / total, "Capturing image " + (count + 1) + "/" + total); double p = (double) j / frm; if (doSine) p = sine(p); for (int k=0; k<mx.length; k++) { mx[k] = p * (mxEnd[k] - mxStart[k]) + mxStart[k]; } images[count++] = captureImage(pc, mx, d); } mxStart = mxEnd; } // cap off last frame setProgress(100, "Capturing image " + total + "/" + total); images[count] = captureImage(pc, mxStart, d); // save movie data if (aviMovie) { try { // convert image frames into VisAD data objects FlatField[] ff = new FlatField[total]; for (int i=0; i<total; i++) { setProgress(100 * i / total, "Processing image " + (i + 1) + "/" + total); ff[i] = DataUtility.makeField(images[i]); } setProgress(100, "Saving movie"); // compile frames into a single data object RealType index = RealType.getRealType("index"); FieldImpl field = VisUtil.makeField(ff, index); // write data out to AVI file AVIForm saver = new AVIForm(); saver.setFrameRate(fps); saver.save(filename, field, true); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } catch (IOException exc) { exc.printStackTrace(); } } else { for (int i=0; i<total; i++) { String num = "" + (i + 1); int len = ("" + total).length(); while (num.length() < len) num = "0" + num; String s = filename.substring(0, dotIndex) + num + filename.substring(dotIndex); setProgress(100 * i / total, "Saving " + new File(s).getName() + " (" + (i + 1) + "/" + total + ")"); FileSaver saver = new FileSaver(new ImagePlus("null", images[i])); if (isTiff) saver.saveAsTiff(s); else if (isJpeg) saver.saveAsJpeg(s); } } // clean up setProgress(100, "Finishing up"); images = null; SystemManager.gc(); setProgress(0, ""); wm.setWaitCursor(false); } }.start(); } // -- CaptureHandler API methods - state logic -- /** Tests whether two objects are in equivalent states. */ public boolean matches(CaptureHandler handler) { if (handler == null) return false; Vector vo = getPositions(); Vector vn = handler.getPositions(); if (vo == null && vn != null) return false; if (vo != null && !vo.equals(vn)) return false; if (getSpeed() != handler.getSpeed() || getFPS() != handler.getFPS() || isSmooth() != handler.isSmooth()) { return false; } return true; } /** * Modifies this object's state to match that of the given object. * If the argument is null, the object is initialized according to * its current state instead. */ public void initState(CaptureHandler handler) { if (handler != null) { // merge old and new position vectors Vector vo = getPositions(); Vector vn = handler.getPositions(); StateManager.mergeStates(vo, vn); positions = vn; // set other parameters movieSpeed = handler.getSpeed(); movieFPS = handler.getFPS(); movieSmooth = handler.isSmooth(); } if (panel == null) { panel = new CapturePanel(this); // snapshot file chooser imageBox = new JFileChooser(); imageBox.addChoosableFileFilter(new ExtensionFileFilter( new String[] {"jpg", "jpeg"}, "JPEG files")); imageBox.addChoosableFileFilter(new ExtensionFileFilter( new String[] {"tif", "tiff"}, "TIFF files")); // movie file chooser movieBox = new JFileChooser(); movieBox.addChoosableFileFilter(new ExtensionFileFilter( new String[] {"avi"}, "AVI movies")); } // set capture window state to match CaptureWindow captureWindow = panel.getCaptureWindow(); captureWindow.setPositions(positions); captureWindow.setSpeed(movieSpeed); captureWindow.setFPS(movieFPS); captureWindow.setSmooth(movieSmooth); } // -- Saveable API methods -- /** Writes the current state to the given DOM element ("Display"). */ public void saveState(Element el) throws SaveException { /* CTR TODO for v3.00 final CaptureWindow captureWindow = panel.getCaptureWindow(); Vector pos = captureWindow.getPositions(); int speed = captureWindow.getSpeed(); int fps = captureWindow.getFPS(); boolean smooth = captureWindow.isSmooth(); // save display positions int numPositions = pos.size(); window.setAttr("positions", "" + numPositions); for (int i=0; i<numPositions; i++) { DisplayPosition position = (DisplayPosition) pos.elementAt(i); position.saveState(window, "position" + i); } // save other parameters window.setAttr("movieSpeed", "" + speed); window.setAttr("movieFPS", "" + fps); window.setAttr("movieSmooth", "" + smooth); */ } /** Restores the current state from the given DOM element ("Display"). */ public void restoreState(Element el) throws SaveException { /* CTR TODO for v3.00 final int numPositions = Integer.parseInt(window.getAttr("positions")); Vector vn = new Vector(numPositions); for (int i=0; i<numPositions; i++) { DisplayPosition position = new DisplayPosition(); position.restoreState(window, "position" + i); vn.add(position); } Vector vo = getPositions(); if (vo != null) StateManager.mergeStates(vo, vn); movieSpeed = Integer.parseInt(window.getAttr("movieSpeed")); movieFPS = Integer.parseInt(window.getAttr("movieFPS")); movieSmooth = window.getAttr("movieSmooth").equalsIgnoreCase("true"); */ } // -- Helper methods -- /** * Takes a snapshot of the given display * with the specified projection matrix. */ protected Image captureImage(ProjectionControl pc, double[] mx, DisplayImpl d) { Image image = null; try { pc.setMatrix(mx); // HACK - lame, stupid waiting trick to capture images properly try { Thread.sleep(100); } catch (InterruptedException exc) { exc.printStackTrace(); } image = d.getImage(false); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } catch (IOException exc) { exc.printStackTrace(); } return image; } /** Sets capture panel's progress bar percentage value and message. */ protected void setProgress(int percent, String message) { final int value = percent; final String msg = message; Util.invoke(false, new Runnable() { public void run() { CaptureWindow window = panel.getCaptureWindow(); window.setProgressValue(value); if (msg != null) window.setProgressMessage(msg); } }); } // -- Utility methods -- /** Evaluates a smooth sine function at the given value. */ protected static double sine(double x) { // [0, 1] -> [-pi/2, pi/2] -> [0, 1] return (Math.sin(Math.PI * (x - 0.5)) + 1) / 2; } }
false
true
public void captureMovie(Vector matrices, double secPerTrans, int framesPerSec, boolean sine, boolean movie) { CaptureWindow captureWindow = panel.getCaptureWindow(); final int size = matrices.size(); if (size < 1) { JOptionPane.showMessageDialog(captureWindow, "Must have at least " + "two display positions on the list.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final DisplayImpl d = window.getDisplay(); if (d == null) { JOptionPane.showMessageDialog(captureWindow, "Display not found.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final ProjectionControl pc = d.getProjectionControl(); final int fps = framesPerSec; final int framesPerTrans = (int) (framesPerSec * secPerTrans); final int total = (size - 1) * framesPerTrans + 1; // get output filename(s) from the user String file = null; int dot = -1; boolean tiff = false, jpeg = false; if (movie) { int rval = movieBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = movieBox.getSelectedFile().getPath(); if (file.indexOf(".") < 0) file = file + ".avi"; } else { int rval = imageBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = imageBox.getSelectedFile().getPath(); String ext = ""; dot = file.lastIndexOf("."); if (dot >= 0) ext = file.substring(dot + 1).toLowerCase(); tiff = ext.equals("tif") || ext.equals("tiff"); jpeg = ext.equals("jpg") || ext.equals("jpeg"); FileFilter filter = imageBox.getFileFilter(); String desc = filter.getDescription(); if (desc.startsWith("JPEG")) { if (!jpeg) { file += ".jpg"; jpeg = true; } } else if (desc.startsWith("TIFF")) { if (!tiff) { file += ".tif"; tiff = true; } } if (!tiff && !jpeg) { JOptionPane.showMessageDialog(captureWindow, "Invalid filename (" + file + "): extension must be TIFF or JPEG.", "Cannot create image sequence", JOptionPane.ERROR_MESSAGE); return; } } // capture image sequence in a separate thread final boolean aviMovie = movie; final String filename = file; final int dotIndex = dot; final boolean isTiff = tiff, isJpeg = jpeg; final Vector pos = matrices; final int frm = framesPerTrans; final boolean doSine = sine; new Thread("VisBio-CaptureThread-" + window.getName()) { public void run() { WindowManager wm = (WindowManager) window.getVisBio().getManager(WindowManager.class); wm.setWaitCursor(true); // step incremental from position to position, grabbing images double[] mxStart = (double[]) pos.elementAt(0); Image[] images = new Image[total]; int count = 0; for (int i=1; i<size; i++) { double[] mxEnd = (double[]) pos.elementAt(i); double[] mx = new double[mxStart.length]; for (int j=0; j<frm; j++) { setProgress(100 * count / total, "Capturing image " + (count + 1) + "/" + total); double p = (double) j / frm; if (doSine) p = sine(p); for (int k=0; k<mx.length; k++) { mx[k] = p * (mxEnd[k] - mxStart[k]) + mxStart[k]; } images[count++] = captureImage(pc, mx, d); } mxStart = mxEnd; } // cap off last frame setProgress(100, "Capturing image " + total + "/" + total); images[count] = captureImage(pc, mxStart, d); // save movie data if (aviMovie) { try { // convert image frames into VisAD data objects FlatField[] ff = new FlatField[total]; for (int i=0; i<total; i++) { setProgress(100 * i / total, "Processing image " + (i + 1) + "/" + total); ff[i] = DataUtility.makeField(images[i]); } setProgress(100, "Saving movie"); // compile frames into a single data object RealType index = RealType.getRealType("index"); FieldImpl field = VisUtil.makeField(ff, index); // write data out to AVI file AVIForm saver = new AVIForm(); saver.setFrameRate(fps); saver.save(filename, field, true); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } catch (IOException exc) { exc.printStackTrace(); } } else { for (int i=0; i<total; i++) { String num = "" + (i + 1); int len = ("" + total).length(); while (num.length() < len) num = "0" + num; String s = filename.substring(0, dotIndex) + num + filename.substring(dotIndex); setProgress(100 * i / total, "Saving " + new File(s).getName() + " (" + (i + 1) + "/" + total + ")"); FileSaver saver = new FileSaver(new ImagePlus("null", images[i])); if (isTiff) saver.saveAsTiff(s); else if (isJpeg) saver.saveAsJpeg(s); } } // clean up setProgress(100, "Finishing up"); images = null; SystemManager.gc(); setProgress(0, ""); wm.setWaitCursor(false); } }.start(); }
public void captureMovie(Vector matrices, double secPerTrans, int framesPerSec, boolean sine, boolean movie) { CaptureWindow captureWindow = panel.getCaptureWindow(); final int size = matrices.size(); if (size < 1) { JOptionPane.showMessageDialog(captureWindow, "Must have at least " + "two display positions on the list.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final DisplayImpl d = window.getDisplay(); if (d == null) { JOptionPane.showMessageDialog(captureWindow, "Display not found.", "Cannot record movie", JOptionPane.ERROR_MESSAGE); return; } final ProjectionControl pc = d.getProjectionControl(); final int fps = framesPerSec; final int framesPerTrans = (int) (framesPerSec * secPerTrans); final int total = (size - 1) * framesPerTrans + 1; // get output filename(s) from the user String file = null; int dot = -1; boolean tiff = false, jpeg = false; if (movie) { int rval = movieBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = movieBox.getSelectedFile().getPath(); if (file.indexOf(".") < 0) file = file + ".avi"; } else { int rval = imageBox.showSaveDialog(captureWindow); if (rval != JFileChooser.APPROVE_OPTION) return; file = imageBox.getSelectedFile().getPath(); String ext = ""; dot = file.lastIndexOf("."); if (dot >= 0) ext = file.substring(dot + 1).toLowerCase(); tiff = ext.equals("tif") || ext.equals("tiff"); jpeg = ext.equals("jpg") || ext.equals("jpeg"); FileFilter filter = imageBox.getFileFilter(); String desc = filter.getDescription(); if (desc.startsWith("JPEG")) { if (!jpeg) { file += ".jpg"; jpeg = true; dot = file.lastIndexOf("."); } } else if (desc.startsWith("TIFF")) { if (!tiff) { file += ".tif"; tiff = true; dot = file.lastIndexOf("."); } } if (!tiff && !jpeg) { JOptionPane.showMessageDialog(captureWindow, "Invalid filename (" + file + "): extension must be TIFF or JPEG.", "Cannot create image sequence", JOptionPane.ERROR_MESSAGE); return; } } // capture image sequence in a separate thread final boolean aviMovie = movie; final String filename = file; final int dotIndex = dot; final boolean isTiff = tiff, isJpeg = jpeg; final Vector pos = matrices; final int frm = framesPerTrans; final boolean doSine = sine; new Thread("VisBio-CaptureThread-" + window.getName()) { public void run() { WindowManager wm = (WindowManager) window.getVisBio().getManager(WindowManager.class); wm.setWaitCursor(true); // step incremental from position to position, grabbing images double[] mxStart = (double[]) pos.elementAt(0); Image[] images = new Image[total]; int count = 0; for (int i=1; i<size; i++) { double[] mxEnd = (double[]) pos.elementAt(i); double[] mx = new double[mxStart.length]; for (int j=0; j<frm; j++) { setProgress(100 * count / total, "Capturing image " + (count + 1) + "/" + total); double p = (double) j / frm; if (doSine) p = sine(p); for (int k=0; k<mx.length; k++) { mx[k] = p * (mxEnd[k] - mxStart[k]) + mxStart[k]; } images[count++] = captureImage(pc, mx, d); } mxStart = mxEnd; } // cap off last frame setProgress(100, "Capturing image " + total + "/" + total); images[count] = captureImage(pc, mxStart, d); // save movie data if (aviMovie) { try { // convert image frames into VisAD data objects FlatField[] ff = new FlatField[total]; for (int i=0; i<total; i++) { setProgress(100 * i / total, "Processing image " + (i + 1) + "/" + total); ff[i] = DataUtility.makeField(images[i]); } setProgress(100, "Saving movie"); // compile frames into a single data object RealType index = RealType.getRealType("index"); FieldImpl field = VisUtil.makeField(ff, index); // write data out to AVI file AVIForm saver = new AVIForm(); saver.setFrameRate(fps); saver.save(filename, field, true); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } catch (IOException exc) { exc.printStackTrace(); } } else { for (int i=0; i<total; i++) { String num = "" + (i + 1); int len = ("" + total).length(); while (num.length() < len) num = "0" + num; String s = filename.substring(0, dotIndex) + num + filename.substring(dotIndex); setProgress(100 * i / total, "Saving " + new File(s).getName() + " (" + (i + 1) + "/" + total + ")"); FileSaver saver = new FileSaver(new ImagePlus("null", images[i])); if (isTiff) saver.saveAsTiff(s); else if (isJpeg) saver.saveAsJpeg(s); } } // clean up setProgress(100, "Finishing up"); images = null; SystemManager.gc(); setProgress(0, ""); wm.setWaitCursor(false); } }.start(); }
diff --git a/app/src/processing/app/tools/AutoFormat.java b/app/src/processing/app/tools/AutoFormat.java index a8260bf40..904962914 100644 --- a/app/src/processing/app/tools/AutoFormat.java +++ b/app/src/processing/app/tools/AutoFormat.java @@ -1,941 +1,942 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2005-06 Ben Fry and Casey Reas Copyright (c) 2003 Martin Gomez, Ateneo de Manila University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app.tools; import processing.app.*; import java.io.*; /** * Alternate handler for dealing with auto format. * Contributed by Martin Gomez, additional bug fixes by Ben Fry. */ public class AutoFormat { Editor editor; static final int BLOCK_MAXLEN = 1024; StringBuffer strOut; //String formattedText; int indentValue; String indentChar; //String uhOh = null; //String theStuff; int EOF; BufferedInputStream bin = null; int nBytesRead, indexBlock, lineLength, lineNumber; byte bArray[]; String strBlock; int s_level[]; int c_level; int sp_flg[][]; int s_ind[][]; int s_if_lev[]; int s_if_flg[]; int if_lev, if_flg, level; int ind[]; int e_flg, paren; static int p_flg[]; char l_char, p_char; int a_flg, q_flg, ct; int s_tabs[][]; String w_if_, w_else, w_for, w_ds, w_case, w_cpp_comment, w_jdoc; int jdoc, j; char string[]; byte bstring[]; byte bblank; char cc; int s_flg, b_flg; int peek; char peekc; int tabs; char next_char, last_char; char lastc0, lastc1; char c, c0; char w_kptr; String line_feed; //static int outfil; // temporary public AutoFormat(Editor editor) { this.editor = editor; } public void comment() throws IOException { int save_s_flg; save_s_flg = s_flg; int done = 0; c = string[j++] = getchr(); // extra char while (done == 0) { c = string[j++] = getchr(); while ((c != '/') && (j < string.length)) { if(c == '\n' || c == '\r') { lineNumber++; putcoms(); s_flg = 1; } c = string[j++] = getchr(); } //String tmpstr = new String(string); if (j>1 && string[j-2] == '*') { done = 1; jdoc = 0; } } putcoms(); s_flg = save_s_flg; jdoc = 0; return; } public char get_string() throws IOException { char ch; ch = '*'; while (true) { switch (ch) { default: ch = string[j++] = getchr(); if (ch == '\\') { string[j++] = getchr(); break; } if (ch == '\'' || ch == '"') { cc = string[j++] = getchr(); while (cc != ch) { if (cc == '\\') string[j++] = getchr(); cc = string[j++] = getchr(); } break; } if (ch == '\n' || ch == '\r') { indent_puts(); a_flg = 1; break; } else { return(ch); } } } } public void indent_puts() { string[j] = '\0'; if (j > 0) { if (s_flg != 0) { if((tabs > 0) && (string[0] != '{') && (a_flg == 1)) { tabs++; } p_tabs(); s_flg = 0; if ((tabs > 0) && (string[0] != '{') && (a_flg == 1)) { tabs--; } a_flg = 0; } String j_string = new String(string); strOut.append(j_string.substring(0,j)); for (int i=0; i<j; i++) string[i] = '\0'; j = 0; } else { if (s_flg != 0) { s_flg = 0; a_flg = 0; } } } //public void fprintf(int outfil, String out_string) { public void fprintf(String out_string) { //int out_len = out_string.length(); //String j_string = new String(string); strOut.append(out_string); } public int grabLines() { return lineNumber; } /* special edition of put string for comment processing */ public void putcoms() { int i = 0; int sav_s_flg = s_flg; if(j > 0) { if(s_flg != 0) { p_tabs(); s_flg = 0; } string[j] = '\0'; i = 0; while (string[i] == ' ') i++; if (lookup_com(w_jdoc) == 1) jdoc = 1; String strBuffer = new String(string,0,j); if (string[i] == '/' && string[i+1]=='*') { if ((last_char != ';') && (sav_s_flg==1) ) { //fprintf(outfil, strBuffer.substring(i,j)); fprintf(strBuffer.substring(i,j)); } else { //fprintf(outfil, strBuffer); fprintf(strBuffer); } } else { if (string[i]=='*' || jdoc == 0) //fprintf (outfil, " "+strBuffer.substring(i,j)); fprintf (" "+strBuffer.substring(i,j)); else //fprintf (outfil, " * "+strBuffer.substring(i,j)); fprintf (" * "+strBuffer.substring(i,j)); } j = 0; string[0] = '\0'; } } public void cpp_comment() throws IOException { c = getchr(); while(c != '\n' && c != '\r' && j<133) { string[j++] = c; c = getchr(); } lineNumber++; indent_puts(); s_flg = 1; } /* expand indentValue into tabs and spaces */ public void p_tabs() { int i,k; if (tabs<0) tabs = 0; if (tabs==0) return; i = tabs * indentValue; // calc number of spaces //j = i/8; /* calc number of tab chars */ for (k=0; k < i; k++) { strOut.append(indentChar); } } public char getchr() throws IOException { if((peek < 0) && (last_char != ' ') && (last_char != '\t')) { if((last_char != '\n') && (last_char != '\r')) p_char = last_char; } if(peek > 0) /* char was read previously */ { last_char = peekc; peek = -1; } else /* read next char in string */ { indexBlock++; if (indexBlock >= lineLength) { for (int ib=0; ib<nBytesRead; ib++) bArray[ib] = '\0'; lineLength = nBytesRead = 0; //try /* to get the next block */ //{ if (bin.available() > 0) { nBytesRead = bin.read(bArray); lineLength = nBytesRead; strBlock = new String(bArray); indexBlock = 0; last_char = strBlock.charAt(indexBlock); peek = -1; peekc = '`'; } else { //System.out.println("eof a"); EOF = 1; peekc = '\0'; } //} //catch(IOException ioe) //{ //System.out.println(ioe.toString()); //} } else { last_char = strBlock.charAt(indexBlock); } } peek = -1; if (last_char == '\r') { last_char = getchr(); } return last_char; } /* else processing */ public void gotelse() { tabs = s_tabs[c_level][if_lev]; p_flg[level] = sp_flg[c_level][if_lev]; ind[level] = s_ind[c_level][if_lev]; if_flg = 1; } /* read to new_line */ public int getnl() throws IOException { int save_s_flg; save_s_flg = tabs; peekc = getchr(); //while ((peekc == '\t' || peekc == ' ') && // (j < string.length)) { while (peekc == '\t' || peekc == ' ') { string[j++] = peekc; peek = -1; peekc = '`'; peekc = getchr(); peek = 1; } peek = 1; if (peekc == '/') { peek = -1; peekc = '`'; peekc = getchr(); if (peekc == '*') { string[j++] = '/'; string[j++] = '*'; peek = -1; peekc = '`'; comment(); } else if (peekc == '/') { string[j++] = '/'; string[j++] = '/'; peek = -1; peekc = '`'; cpp_comment(); return (1); } else { string[j++] = '/'; peek = 1; } } peekc = getchr(); if(peekc == '\n') { lineNumber++; peek = -1; peekc = '`'; tabs = save_s_flg; return(1); } else { peek = 1; } return 0; } public int lookup (String keyword) { char r; int l,kk; //,k,i; String j_string = new String(string); if (j<1) return (0); kk=0; while(string[kk] == ' ')kk++; l=0; l = j_string.indexOf(keyword); if (l<0 || l!=kk) { return 0; } r = string[kk+keyword.length()]; if(r >= 'a' && r <= 'z') return(0); if(r >= 'A' && r <= 'Z') return(0); if(r >= '0' && r <= '9') return(0); if(r == '_' || r == '&') return(0); return (1); } public int lookup_com (String keyword) { //char r; int l,kk; //,k,i; String j_string = new String(string); if (j<1) return (0); kk=0; while(string[kk] == ' ')kk++; l=0; l = j_string.indexOf(keyword); if (l<0 || l!=kk) { return 0; } return (1); } public void show() { StringBuffer onechar; - String originalText = editor.getText(); + // Adding an additional newline as a hack around other errors + String originalText = editor.getText() + "\n"; strOut = new StringBuffer(); indentValue = Preferences.getInteger("editor.tabs.size"); indentChar = new String(" "); lineNumber = 0; //BLOCK_MAXLEN = 256; c_level = if_lev = level = e_flg = paren = 0; a_flg = q_flg = j = b_flg = tabs = 0; if_flg = peek = -1; peekc = '`'; s_flg = 1; bblank = ' '; jdoc = 0; s_level = new int[10]; sp_flg = new int[20][10]; s_ind = new int[20][10]; s_if_lev = new int[10]; s_if_flg = new int[10]; ind = new int[10]; p_flg = new int[10]; s_tabs = new int[20][10]; w_else = new String ("else"); w_if_ = new String ("if"); w_for = new String ("for"); w_ds = new String ("default"); w_case = new String ("case"); w_cpp_comment = new String ("//"); w_jdoc = new String ("/**"); line_feed = new String ("\n"); // read as long as there is something to read EOF = 0; // = 1 set in getchr when EOF bArray = new byte[BLOCK_MAXLEN]; string = new char[BLOCK_MAXLEN]; try { // the whole process // open for input ByteArrayInputStream in = new ByteArrayInputStream(originalText.getBytes()); // add buffering to that InputStream bin = new BufferedInputStream(in); for (int ib = 0; ib < BLOCK_MAXLEN; ib++) bArray[ib] = '\0'; lineLength = nBytesRead = 0; // read up a block - remember how many bytes read nBytesRead = bin.read(bArray); strBlock = new String(bArray); lineLength = nBytesRead; lineNumber = 1; indexBlock = -1; j = 0; while (EOF == 0) { c = getchr(); switch(c) { default: string[j++] = c; if(c != ',') { l_char = c; } break; case ' ': case '\t': if(lookup(w_else) == 1) { gotelse(); if(s_flg == 0 || j > 0)string[j++] = c; indent_puts(); s_flg = 0; break; } if(s_flg == 0 || j > 0)string[j++] = c; break; case '\r': // <CR> for MS Windows 95 case '\n': lineNumber++; if (EOF==1) { break; } //String j_string = new String(string); e_flg = lookup(w_else); if(e_flg == 1) gotelse(); if (lookup_com(w_cpp_comment) == 1) { if (string[j] == '\n') { string[j] = '\0'; j--; } } indent_puts(); //fprintf(outfil, line_feed); fprintf(line_feed); s_flg = 1; if(e_flg == 1) { p_flg[level]++; tabs++; } else if(p_char == l_char) { a_flg = 1; } break; case '{': if(lookup(w_else) == 1)gotelse(); s_if_lev[c_level] = if_lev; s_if_flg[c_level] = if_flg; if_lev = if_flg = 0; c_level++; if(s_flg == 1 && p_flg[level] != 0) { p_flg[level]--; tabs--; } string[j++] = c; indent_puts(); getnl() ; indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); tabs++; s_flg = 1; if(p_flg[level] > 0) { ind[level] = 1; level++; s_level[level] = c_level; } break; case '}': c_level--; if (c_level < 0) { EOF = 1; //System.out.println("eof b"); string[j++] = c; indent_puts(); break; } if ((if_lev = s_if_lev[c_level]-1) < 0) if_lev = 0; if_flg = s_if_flg[c_level]; indent_puts(); tabs--; p_tabs(); peekc = getchr(); if( peekc == ';') { onechar = new StringBuffer(); onechar.append(c); // the } onechar.append(';'); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = -1; peekc = '`'; } else { onechar = new StringBuffer(); onechar.append(c); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(c_level < s_level[level]) if(level > 0) level--; if(ind[level] != 0) { tabs -= p_flg[level]; p_flg[level] = 0; ind[level] = 0; } break; case '"': case '\'': string[j++] = c; cc = getchr(); while(cc != c) { // max. length of line should be 256 string[j++] = cc; if(cc == '\\') { cc = string[j++] = getchr(); } if(cc == '\n') { lineNumber++; indent_puts(); s_flg = 1; } cc = getchr(); } string[j++] = cc; if(getnl() == 1) { l_char = cc; peek = 1; peekc = '\n'; } break; case ';': string[j++] = c; indent_puts(); if(p_flg[level] > 0 && ind[level] == 0) { tabs -= p_flg[level]; p_flg[level] = 0; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(if_lev > 0) if(if_flg == 1) { if_lev--; if_flg = 0; } else if_lev = 0; break; case '\\': string[j++] = c; string[j++] = getchr(); break; case '?': q_flg = 1; string[j++] = c; break; case ':': string[j++] = c; peekc = getchr(); if(peekc == ':') { indent_puts(); //fprintf (outfil,":"); fprintf(":"); peek = -1; peekc = '`'; break; } else { //int double_colon = 0; peek = 1; } if(q_flg == 1) { q_flg = 0; break; } if(lookup(w_ds) == 0 && lookup(w_case) == 0) { s_flg = 0; indent_puts(); } else { tabs--; indent_puts(); tabs++; } peekc = getchr(); if(peekc == ';') { //fprintf(outfil,";"); fprintf(";"); peek = -1; peekc = '`'; } else { peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; break; case '/': c0 = string[j]; string[j++] = c; peekc = getchr(); if(peekc == '/') { string[j++] = peekc; peekc = '`'; peek = -1; cpp_comment(); //fprintf(outfil,"\n"); fprintf("\n"); break; } else { peek = 1; } if(peekc != '*') { break; } else { if (j > 0) string[j--] = '\0'; if (j > 0) indent_puts(); string[j++] = '/'; string[j++] = '*'; peek = -1; peekc = '`'; comment(); break; } case '#': string[j++] = c; cc = getchr(); while(cc != '\n') { string[j++] = cc; cc = getchr(); } string[j++] = cc; s_flg = 0; indent_puts(); s_flg = 1; break; case ')': paren--; if (paren < 0) { EOF = 1; //System.out.println("eof c"); } string[j++] = c; indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; if(paren != 0) { a_flg = 1; } else if(tabs > 0) { p_flg[level]++; tabs++; ind[level] = 0; } } break; case '(': string[j++] = c; paren++; if ((lookup(w_for) == 1)) { c = get_string(); while(c != ';') c = get_string(); ct=0; int for_done = 0; while (for_done==0) { c = get_string(); while(c != ')') { if(c == '(') ct++; c = get_string(); } if(ct != 0) { ct--; } else for_done = 1; } // endwhile for_done paren--; if (paren < 0) { EOF = 1; //System.out.println("eof d"); } indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; p_flg[level]++; tabs++; ind[level] = 0; } break; } if(lookup(w_if_) == 1) { indent_puts(); s_tabs[c_level][if_lev] = tabs; sp_flg[c_level][if_lev] = p_flg[level]; s_ind[c_level][if_lev] = ind[level]; if_lev++; if_flg = 1; } } // end switch //System.out.println("string len is " + string.length); //if (EOF == 1) System.out.println(string); //String j_string = new String(string); } // end while not EOF /* int bad; while ((bad = bin.read()) != -1) { System.out.print((char) bad); } */ /* char bad; //while ((bad = getchr()) != 0) { while (true) { getchr(); if (peek != -1) { System.out.print(last_char); } else { break; } } */ // save current (rough) selection point int selectionEnd = editor.getSelectionStop(); // make sure the caret would be past the end of the text if (strOut.length() < selectionEnd - 1) { selectionEnd = strOut.length() - 1; } bin.close(); // close buff String formattedText = strOut.toString(); if (formattedText.equals(originalText)) { editor.statusNotice("No changes necessary for Auto Format."); } else if (paren != 0) { // warn user if there are too many parens in either direction editor.statusError("Auto Format Canceled: Too many " + ((paren < 0) ? "right" : "left") + " parentheses."); } else if (c_level != 0) { // check braces only if parens are ok editor.statusError("Auto Format Canceled: Too many " + ((c_level < 0) ? "right" : "left") + " curly braces."); } else { // replace with new bootiful text // selectionEnd hopefully at least in the neighborhood editor.setText(formattedText); editor.setSelection(selectionEnd, selectionEnd); editor.getSketch().setModified(true); // mark as finished editor.statusNotice("Auto Format finished."); } } catch (Exception e) { editor.statusError(e); } } }
true
true
public void show() { StringBuffer onechar; String originalText = editor.getText(); strOut = new StringBuffer(); indentValue = Preferences.getInteger("editor.tabs.size"); indentChar = new String(" "); lineNumber = 0; //BLOCK_MAXLEN = 256; c_level = if_lev = level = e_flg = paren = 0; a_flg = q_flg = j = b_flg = tabs = 0; if_flg = peek = -1; peekc = '`'; s_flg = 1; bblank = ' '; jdoc = 0; s_level = new int[10]; sp_flg = new int[20][10]; s_ind = new int[20][10]; s_if_lev = new int[10]; s_if_flg = new int[10]; ind = new int[10]; p_flg = new int[10]; s_tabs = new int[20][10]; w_else = new String ("else"); w_if_ = new String ("if"); w_for = new String ("for"); w_ds = new String ("default"); w_case = new String ("case"); w_cpp_comment = new String ("//"); w_jdoc = new String ("/**"); line_feed = new String ("\n"); // read as long as there is something to read EOF = 0; // = 1 set in getchr when EOF bArray = new byte[BLOCK_MAXLEN]; string = new char[BLOCK_MAXLEN]; try { // the whole process // open for input ByteArrayInputStream in = new ByteArrayInputStream(originalText.getBytes()); // add buffering to that InputStream bin = new BufferedInputStream(in); for (int ib = 0; ib < BLOCK_MAXLEN; ib++) bArray[ib] = '\0'; lineLength = nBytesRead = 0; // read up a block - remember how many bytes read nBytesRead = bin.read(bArray); strBlock = new String(bArray); lineLength = nBytesRead; lineNumber = 1; indexBlock = -1; j = 0; while (EOF == 0) { c = getchr(); switch(c) { default: string[j++] = c; if(c != ',') { l_char = c; } break; case ' ': case '\t': if(lookup(w_else) == 1) { gotelse(); if(s_flg == 0 || j > 0)string[j++] = c; indent_puts(); s_flg = 0; break; } if(s_flg == 0 || j > 0)string[j++] = c; break; case '\r': // <CR> for MS Windows 95 case '\n': lineNumber++; if (EOF==1) { break; } //String j_string = new String(string); e_flg = lookup(w_else); if(e_flg == 1) gotelse(); if (lookup_com(w_cpp_comment) == 1) { if (string[j] == '\n') { string[j] = '\0'; j--; } } indent_puts(); //fprintf(outfil, line_feed); fprintf(line_feed); s_flg = 1; if(e_flg == 1) { p_flg[level]++; tabs++; } else if(p_char == l_char) { a_flg = 1; } break; case '{': if(lookup(w_else) == 1)gotelse(); s_if_lev[c_level] = if_lev; s_if_flg[c_level] = if_flg; if_lev = if_flg = 0; c_level++; if(s_flg == 1 && p_flg[level] != 0) { p_flg[level]--; tabs--; } string[j++] = c; indent_puts(); getnl() ; indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); tabs++; s_flg = 1; if(p_flg[level] > 0) { ind[level] = 1; level++; s_level[level] = c_level; } break; case '}': c_level--; if (c_level < 0) { EOF = 1; //System.out.println("eof b"); string[j++] = c; indent_puts(); break; } if ((if_lev = s_if_lev[c_level]-1) < 0) if_lev = 0; if_flg = s_if_flg[c_level]; indent_puts(); tabs--; p_tabs(); peekc = getchr(); if( peekc == ';') { onechar = new StringBuffer(); onechar.append(c); // the } onechar.append(';'); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = -1; peekc = '`'; } else { onechar = new StringBuffer(); onechar.append(c); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(c_level < s_level[level]) if(level > 0) level--; if(ind[level] != 0) { tabs -= p_flg[level]; p_flg[level] = 0; ind[level] = 0; } break; case '"': case '\'': string[j++] = c; cc = getchr(); while(cc != c) { // max. length of line should be 256 string[j++] = cc; if(cc == '\\') { cc = string[j++] = getchr(); } if(cc == '\n') { lineNumber++; indent_puts(); s_flg = 1; } cc = getchr(); } string[j++] = cc; if(getnl() == 1) { l_char = cc; peek = 1; peekc = '\n'; } break; case ';': string[j++] = c; indent_puts(); if(p_flg[level] > 0 && ind[level] == 0) { tabs -= p_flg[level]; p_flg[level] = 0; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(if_lev > 0) if(if_flg == 1) { if_lev--; if_flg = 0; } else if_lev = 0; break; case '\\': string[j++] = c; string[j++] = getchr(); break; case '?': q_flg = 1; string[j++] = c; break; case ':': string[j++] = c; peekc = getchr(); if(peekc == ':') { indent_puts(); //fprintf (outfil,":"); fprintf(":"); peek = -1; peekc = '`'; break; } else { //int double_colon = 0; peek = 1; } if(q_flg == 1) { q_flg = 0; break; } if(lookup(w_ds) == 0 && lookup(w_case) == 0) { s_flg = 0; indent_puts(); } else { tabs--; indent_puts(); tabs++; } peekc = getchr(); if(peekc == ';') { //fprintf(outfil,";"); fprintf(";"); peek = -1; peekc = '`'; } else { peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; break; case '/': c0 = string[j]; string[j++] = c; peekc = getchr(); if(peekc == '/') { string[j++] = peekc; peekc = '`'; peek = -1; cpp_comment(); //fprintf(outfil,"\n"); fprintf("\n"); break; } else { peek = 1; } if(peekc != '*') { break; } else { if (j > 0) string[j--] = '\0'; if (j > 0) indent_puts(); string[j++] = '/'; string[j++] = '*'; peek = -1; peekc = '`'; comment(); break; } case '#': string[j++] = c; cc = getchr(); while(cc != '\n') { string[j++] = cc; cc = getchr(); } string[j++] = cc; s_flg = 0; indent_puts(); s_flg = 1; break; case ')': paren--; if (paren < 0) { EOF = 1; //System.out.println("eof c"); } string[j++] = c; indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; if(paren != 0) { a_flg = 1; } else if(tabs > 0) { p_flg[level]++; tabs++; ind[level] = 0; } } break; case '(': string[j++] = c; paren++; if ((lookup(w_for) == 1)) { c = get_string(); while(c != ';') c = get_string(); ct=0; int for_done = 0; while (for_done==0) { c = get_string(); while(c != ')') { if(c == '(') ct++; c = get_string(); } if(ct != 0) { ct--; } else for_done = 1; } // endwhile for_done paren--; if (paren < 0) { EOF = 1; //System.out.println("eof d"); } indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; p_flg[level]++; tabs++; ind[level] = 0; } break; } if(lookup(w_if_) == 1) { indent_puts(); s_tabs[c_level][if_lev] = tabs; sp_flg[c_level][if_lev] = p_flg[level]; s_ind[c_level][if_lev] = ind[level]; if_lev++; if_flg = 1; } } // end switch //System.out.println("string len is " + string.length); //if (EOF == 1) System.out.println(string); //String j_string = new String(string); } // end while not EOF /* int bad; while ((bad = bin.read()) != -1) { System.out.print((char) bad); } */ /* char bad; //while ((bad = getchr()) != 0) { while (true) { getchr(); if (peek != -1) { System.out.print(last_char); } else { break; } } */ // save current (rough) selection point int selectionEnd = editor.getSelectionStop(); // make sure the caret would be past the end of the text if (strOut.length() < selectionEnd - 1) { selectionEnd = strOut.length() - 1; } bin.close(); // close buff String formattedText = strOut.toString(); if (formattedText.equals(originalText)) { editor.statusNotice("No changes necessary for Auto Format."); } else if (paren != 0) { // warn user if there are too many parens in either direction editor.statusError("Auto Format Canceled: Too many " + ((paren < 0) ? "right" : "left") + " parentheses."); } else if (c_level != 0) { // check braces only if parens are ok editor.statusError("Auto Format Canceled: Too many " + ((c_level < 0) ? "right" : "left") + " curly braces."); } else { // replace with new bootiful text // selectionEnd hopefully at least in the neighborhood editor.setText(formattedText); editor.setSelection(selectionEnd, selectionEnd); editor.getSketch().setModified(true); // mark as finished editor.statusNotice("Auto Format finished."); } } catch (Exception e) {
public void show() { StringBuffer onechar; // Adding an additional newline as a hack around other errors String originalText = editor.getText() + "\n"; strOut = new StringBuffer(); indentValue = Preferences.getInteger("editor.tabs.size"); indentChar = new String(" "); lineNumber = 0; //BLOCK_MAXLEN = 256; c_level = if_lev = level = e_flg = paren = 0; a_flg = q_flg = j = b_flg = tabs = 0; if_flg = peek = -1; peekc = '`'; s_flg = 1; bblank = ' '; jdoc = 0; s_level = new int[10]; sp_flg = new int[20][10]; s_ind = new int[20][10]; s_if_lev = new int[10]; s_if_flg = new int[10]; ind = new int[10]; p_flg = new int[10]; s_tabs = new int[20][10]; w_else = new String ("else"); w_if_ = new String ("if"); w_for = new String ("for"); w_ds = new String ("default"); w_case = new String ("case"); w_cpp_comment = new String ("//"); w_jdoc = new String ("/**"); line_feed = new String ("\n"); // read as long as there is something to read EOF = 0; // = 1 set in getchr when EOF bArray = new byte[BLOCK_MAXLEN]; string = new char[BLOCK_MAXLEN]; try { // the whole process // open for input ByteArrayInputStream in = new ByteArrayInputStream(originalText.getBytes()); // add buffering to that InputStream bin = new BufferedInputStream(in); for (int ib = 0; ib < BLOCK_MAXLEN; ib++) bArray[ib] = '\0'; lineLength = nBytesRead = 0; // read up a block - remember how many bytes read nBytesRead = bin.read(bArray); strBlock = new String(bArray); lineLength = nBytesRead; lineNumber = 1; indexBlock = -1; j = 0; while (EOF == 0) { c = getchr(); switch(c) { default: string[j++] = c; if(c != ',') { l_char = c; } break; case ' ': case '\t': if(lookup(w_else) == 1) { gotelse(); if(s_flg == 0 || j > 0)string[j++] = c; indent_puts(); s_flg = 0; break; } if(s_flg == 0 || j > 0)string[j++] = c; break; case '\r': // <CR> for MS Windows 95 case '\n': lineNumber++; if (EOF==1) { break; } //String j_string = new String(string); e_flg = lookup(w_else); if(e_flg == 1) gotelse(); if (lookup_com(w_cpp_comment) == 1) { if (string[j] == '\n') { string[j] = '\0'; j--; } } indent_puts(); //fprintf(outfil, line_feed); fprintf(line_feed); s_flg = 1; if(e_flg == 1) { p_flg[level]++; tabs++; } else if(p_char == l_char) { a_flg = 1; } break; case '{': if(lookup(w_else) == 1)gotelse(); s_if_lev[c_level] = if_lev; s_if_flg[c_level] = if_flg; if_lev = if_flg = 0; c_level++; if(s_flg == 1 && p_flg[level] != 0) { p_flg[level]--; tabs--; } string[j++] = c; indent_puts(); getnl() ; indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); tabs++; s_flg = 1; if(p_flg[level] > 0) { ind[level] = 1; level++; s_level[level] = c_level; } break; case '}': c_level--; if (c_level < 0) { EOF = 1; //System.out.println("eof b"); string[j++] = c; indent_puts(); break; } if ((if_lev = s_if_lev[c_level]-1) < 0) if_lev = 0; if_flg = s_if_flg[c_level]; indent_puts(); tabs--; p_tabs(); peekc = getchr(); if( peekc == ';') { onechar = new StringBuffer(); onechar.append(c); // the } onechar.append(';'); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = -1; peekc = '`'; } else { onechar = new StringBuffer(); onechar.append(c); //fprintf(outfil, onechar.toString()); fprintf(onechar.toString()); peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(c_level < s_level[level]) if(level > 0) level--; if(ind[level] != 0) { tabs -= p_flg[level]; p_flg[level] = 0; ind[level] = 0; } break; case '"': case '\'': string[j++] = c; cc = getchr(); while(cc != c) { // max. length of line should be 256 string[j++] = cc; if(cc == '\\') { cc = string[j++] = getchr(); } if(cc == '\n') { lineNumber++; indent_puts(); s_flg = 1; } cc = getchr(); } string[j++] = cc; if(getnl() == 1) { l_char = cc; peek = 1; peekc = '\n'; } break; case ';': string[j++] = c; indent_puts(); if(p_flg[level] > 0 && ind[level] == 0) { tabs -= p_flg[level]; p_flg[level] = 0; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; if(if_lev > 0) if(if_flg == 1) { if_lev--; if_flg = 0; } else if_lev = 0; break; case '\\': string[j++] = c; string[j++] = getchr(); break; case '?': q_flg = 1; string[j++] = c; break; case ':': string[j++] = c; peekc = getchr(); if(peekc == ':') { indent_puts(); //fprintf (outfil,":"); fprintf(":"); peek = -1; peekc = '`'; break; } else { //int double_colon = 0; peek = 1; } if(q_flg == 1) { q_flg = 0; break; } if(lookup(w_ds) == 0 && lookup(w_case) == 0) { s_flg = 0; indent_puts(); } else { tabs--; indent_puts(); tabs++; } peekc = getchr(); if(peekc == ';') { //fprintf(outfil,";"); fprintf(";"); peek = -1; peekc = '`'; } else { peek = 1; } getnl(); indent_puts(); //fprintf(outfil,"\n"); fprintf("\n"); s_flg = 1; break; case '/': c0 = string[j]; string[j++] = c; peekc = getchr(); if(peekc == '/') { string[j++] = peekc; peekc = '`'; peek = -1; cpp_comment(); //fprintf(outfil,"\n"); fprintf("\n"); break; } else { peek = 1; } if(peekc != '*') { break; } else { if (j > 0) string[j--] = '\0'; if (j > 0) indent_puts(); string[j++] = '/'; string[j++] = '*'; peek = -1; peekc = '`'; comment(); break; } case '#': string[j++] = c; cc = getchr(); while(cc != '\n') { string[j++] = cc; cc = getchr(); } string[j++] = cc; s_flg = 0; indent_puts(); s_flg = 1; break; case ')': paren--; if (paren < 0) { EOF = 1; //System.out.println("eof c"); } string[j++] = c; indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; if(paren != 0) { a_flg = 1; } else if(tabs > 0) { p_flg[level]++; tabs++; ind[level] = 0; } } break; case '(': string[j++] = c; paren++; if ((lookup(w_for) == 1)) { c = get_string(); while(c != ';') c = get_string(); ct=0; int for_done = 0; while (for_done==0) { c = get_string(); while(c != ')') { if(c == '(') ct++; c = get_string(); } if(ct != 0) { ct--; } else for_done = 1; } // endwhile for_done paren--; if (paren < 0) { EOF = 1; //System.out.println("eof d"); } indent_puts(); if(getnl() == 1) { peekc = '\n'; peek = 1; p_flg[level]++; tabs++; ind[level] = 0; } break; } if(lookup(w_if_) == 1) { indent_puts(); s_tabs[c_level][if_lev] = tabs; sp_flg[c_level][if_lev] = p_flg[level]; s_ind[c_level][if_lev] = ind[level]; if_lev++; if_flg = 1; } } // end switch //System.out.println("string len is " + string.length); //if (EOF == 1) System.out.println(string); //String j_string = new String(string); } // end while not EOF /* int bad; while ((bad = bin.read()) != -1) { System.out.print((char) bad); } */ /* char bad; //while ((bad = getchr()) != 0) { while (true) { getchr(); if (peek != -1) { System.out.print(last_char); } else { break; } } */ // save current (rough) selection point int selectionEnd = editor.getSelectionStop(); // make sure the caret would be past the end of the text if (strOut.length() < selectionEnd - 1) { selectionEnd = strOut.length() - 1; } bin.close(); // close buff String formattedText = strOut.toString(); if (formattedText.equals(originalText)) { editor.statusNotice("No changes necessary for Auto Format."); } else if (paren != 0) { // warn user if there are too many parens in either direction editor.statusError("Auto Format Canceled: Too many " + ((paren < 0) ? "right" : "left") + " parentheses."); } else if (c_level != 0) { // check braces only if parens are ok editor.statusError("Auto Format Canceled: Too many " + ((c_level < 0) ? "right" : "left") + " curly braces."); } else { // replace with new bootiful text // selectionEnd hopefully at least in the neighborhood editor.setText(formattedText); editor.setSelection(selectionEnd, selectionEnd); editor.getSketch().setModified(true); // mark as finished editor.statusNotice("Auto Format finished."); } } catch (Exception e) {
diff --git a/src/frontend/DrawingPanel.java b/src/frontend/DrawingPanel.java index 022be17..7c3eccc 100644 --- a/src/frontend/DrawingPanel.java +++ b/src/frontend/DrawingPanel.java @@ -1,155 +1,161 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package frontend; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import javax.swing.JPanel; import manager.DiagramModifyAction; import manager.DiagramProject; import backend.*; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Polygon; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.QuadCurve2D; /** * * @author Eddie */ public class DrawingPanel extends JPanel { private Diagram _diagram; public Line2D.Double _progressLine; private Polygon _startSymbol; public DrawingPanel() { _diagram = new Diagram(); this.setBackground(Color.WHITE); } public Diagram getDiagram() { return _diagram; } private void clearAll(){ for (Node n : _diagram.getNodes()){ n.setSelected(false); } for (Edge e : _diagram.getEdges()){ e.setSelected(false); } } public Node addNode(Point p) { clearAll(); Node n = new Node(p.x,p.y, this); _diagram.addNode(n); if (_diagram.getNodes().size() == 1) { n.setStart(true); } repaint(); return n; } public void addEdge(Node n1, Node n2) { if (n1 != null && n2 != null) { clearAll(); // DiagramProject dp = new DiagramProject(); // dp.modify(new DiagramModifyAction() { // // @Override // public boolean modify(Diagram diagram) { // Edge e = new Edge(n1,n2,n1.getCenter(),n2.getCenter()); // diagram.addEdge(e); // return false; // } // // @Override // public String message() { // // TODO Auto-generated method stub // return null; // } // }); Edge e = new Edge(n1,n2,n1.getCenter(),n2.getCenter(), this); n1.addConnected(e); n2.addConnected(e); _diagram.addEdge(e); repaint(); } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; for (Node n : _diagram.getNodes()){ if (n.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(3)); g2.fill(n.getResize()); g2.draw(n.getResize()); } if (n.getCurrent()) { g2.setColor(java.awt.Color.PINK); } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); if (n.isStart()) { _startSymbol = new Polygon(); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius()),(int) (n.getCenter().y)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y + 10)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y - 10)); g2.draw(_startSymbol); } if (n.isEnd()) { double newRad = n.getRadius()-4; double x = n.getCenter().x; double y = n.getCenter().y; g2.draw(new Ellipse2D.Double(x-newRad,y-newRad,newRad*2,newRad*2)); } + if (n.getCurrent()) { + g2.setColor(java.awt.Color.PINK); + } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } for (Edge e: _diagram.getEdges()) { if(e.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(2)); } + if (e.getCurrent()) { + g2.setColor(java.awt.Color.PINK); + } g2.draw(e.resetLine()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } if (_progressLine != null) g2.draw(_progressLine); } }
false
true
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; for (Node n : _diagram.getNodes()){ if (n.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(3)); g2.fill(n.getResize()); g2.draw(n.getResize()); } if (n.getCurrent()) { g2.setColor(java.awt.Color.PINK); } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); if (n.isStart()) { _startSymbol = new Polygon(); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius()),(int) (n.getCenter().y)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y + 10)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y - 10)); g2.draw(_startSymbol); } if (n.isEnd()) { double newRad = n.getRadius()-4; double x = n.getCenter().x; double y = n.getCenter().y; g2.draw(new Ellipse2D.Double(x-newRad,y-newRad,newRad*2,newRad*2)); } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } for (Edge e: _diagram.getEdges()) { if(e.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(2)); } g2.draw(e.resetLine()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } if (_progressLine != null) g2.draw(_progressLine); }
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; for (Node n : _diagram.getNodes()){ if (n.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(3)); g2.fill(n.getResize()); g2.draw(n.getResize()); } if (n.getCurrent()) { g2.setColor(java.awt.Color.PINK); } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); if (n.isStart()) { _startSymbol = new Polygon(); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius()),(int) (n.getCenter().y)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y + 10)); _startSymbol.addPoint((int)(n.getCenter().x - n.getRadius() - 20),(int) (n.getCenter().y - 10)); g2.draw(_startSymbol); } if (n.isEnd()) { double newRad = n.getRadius()-4; double x = n.getCenter().x; double y = n.getCenter().y; g2.draw(new Ellipse2D.Double(x-newRad,y-newRad,newRad*2,newRad*2)); } if (n.getCurrent()) { g2.setColor(java.awt.Color.PINK); } g2.draw(n.resetCircle()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } for (Edge e: _diagram.getEdges()) { if(e.isSelected()){ g2.setColor(java.awt.Color.BLUE); g2.setStroke(new BasicStroke(2)); } if (e.getCurrent()) { g2.setColor(java.awt.Color.PINK); } g2.draw(e.resetLine()); g2.setColor(java.awt.Color.BLACK); g2.setStroke(new BasicStroke(1)); } if (_progressLine != null) g2.draw(_progressLine); }
diff --git a/sql12/fw/src/net/sourceforge/squirrel_sql/fw/sql/QueryTokenizer.java b/sql12/fw/src/net/sourceforge/squirrel_sql/fw/sql/QueryTokenizer.java index 0a6c40bf0..9d3aa6f93 100755 --- a/sql12/fw/src/net/sourceforge/squirrel_sql/fw/sql/QueryTokenizer.java +++ b/sql12/fw/src/net/sourceforge/squirrel_sql/fw/sql/QueryTokenizer.java @@ -1,445 +1,445 @@ package net.sourceforge.squirrel_sql.fw.sql; /* * Copyright (C) 2001-2003 Johan Compagner * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sourceforge.squirrel_sql.fw.preferences.IQueryTokenizerPreferenceBean; import net.sourceforge.squirrel_sql.fw.util.StringUtilities; import net.sourceforge.squirrel_sql.fw.util.log.ILogger; import net.sourceforge.squirrel_sql.fw.util.log.LoggerController; public class QueryTokenizer implements IQueryTokenizer { protected ArrayList<String> _queries = new ArrayList<String>(); protected Iterator<String> _queryIterator; protected String _querySep = null; protected String _lineCommentBegin = null; protected boolean _removeMultiLineComment = true; protected ITokenizerFactory _tokenizerFactory = null; /** Logger for this class. */ private final static ILogger s_log = LoggerController.createLogger(QueryTokenizer.class); public QueryTokenizer() {} public QueryTokenizer(String querySep, String lineCommentBegin, boolean removeMultiLineComment) { _querySep = querySep; _lineCommentBegin = lineCommentBegin; _removeMultiLineComment = removeMultiLineComment; setFactory(); } public QueryTokenizer(IQueryTokenizerPreferenceBean prefs) { this(prefs.getStatementSeparator(), prefs.getLineComment(), prefs.isRemoveMultiLineComments()); } /** * Sets the ITokenizerFactory which is used to create additional instances * of the IQueryTokenizer - this is used for handling file includes * recursively. */ protected void setFactory() { _tokenizerFactory = new ITokenizerFactory() { public IQueryTokenizer getTokenizer() { return new QueryTokenizer(); } }; } private int getLenOfQuerySepIfAtLastCharOfQuerySep(String sql, int i, String querySep, boolean inLiteral) { if(inLiteral) { return -1; } char c = sql.charAt(i); if(1 == querySep.length() && c == querySep.charAt(0)) { return 1; } else { int fromIndex = i - querySep.length(); if(0 > fromIndex) { return -1; } int querySepIndex = sql.indexOf(querySep, fromIndex); if(0 > querySepIndex) { return -1; } if(Character.isWhitespace(c)) { if(querySepIndex + querySep.length() == i) { if(0 == querySepIndex) { return querySep.length() + 1; } else if(Character.isWhitespace(sql.charAt(querySepIndex - 1))) { return querySep.length() + 2; } } } else if(sql.length() -1 == i) { if(querySepIndex + querySep.length() - 1 == i) { if(0 == querySepIndex) { return querySep.length(); } else if(Character.isWhitespace(sql.charAt(querySepIndex - 1))) { return querySep.length() + 1; } } } return -1; } } public boolean hasQuery() { return _queryIterator.hasNext(); } public String nextQuery() { return _queryIterator.next(); } public void setScriptToTokenize(String script) { _queries.clear(); String MULTI_LINE_COMMENT_END = "*/"; String MULTI_LINE_COMMENT_BEGIN = "/*"; script = script.replace('\r', ' '); StringBuffer curQuery = new StringBuffer(); boolean isInLiteral = false; boolean isInMultiLineComment = false; boolean isInLineComment = false; int literalSepCount = 0; for (int i = 0; i < script.length(); ++i) { char c = script.charAt(i); if(false == isInLiteral) { /////////////////////////////////////////////////////////// // Handling of comments // We look backwards if(isInLineComment && script.startsWith("\n", i - "\n".length())) { isInLineComment = false; } // We look backwards if(isInMultiLineComment && script.startsWith(MULTI_LINE_COMMENT_END, i - MULTI_LINE_COMMENT_END.length())) { isInMultiLineComment = false; } if(false == isInLineComment && false == isInMultiLineComment) { // We look forward isInMultiLineComment = script.startsWith(MULTI_LINE_COMMENT_BEGIN, i); isInLineComment = script.startsWith(_lineCommentBegin, i); if(isInMultiLineComment && _removeMultiLineComment) { // skip ahead so the cursor is now immediately after the begin comment string i+=MULTI_LINE_COMMENT_BEGIN.length()+1; } } if((isInMultiLineComment && _removeMultiLineComment) || isInLineComment) { // This is responsible that comments are not in curQuery continue; } // //////////////////////////////////////////////////////////// } curQuery.append(c); if ('\'' == c) { if(false == isInLiteral) { isInLiteral = true; } else { ++literalSepCount; } } else { if(0 != literalSepCount % 2) { isInLiteral = false; } literalSepCount = 0; } int querySepLen = getLenOfQuerySepIfAtLastCharOfQuerySep(script, i, _querySep, isInLiteral); - if(-1 < querySepLen) + if(-1 < querySepLen && !isInMultiLineComment) { int newLength = curQuery.length() - querySepLen; if(-1 < newLength && curQuery.length() > newLength) { curQuery.setLength(newLength); String newQuery = curQuery.toString().trim(); if(0 < newQuery.length()) { _queries.add(curQuery.toString().trim()); } } curQuery.setLength(0); } } String lastQuery = curQuery.toString().trim(); if(0 < lastQuery.length()) { _queries.add(lastQuery.trim()); } _queryIterator = _queries.iterator(); } /** * Returns the number of queries that the tokenizer found in the script * given in the last call to setScriptToTokenize, or 0 if * setScriptToTokenize has not yet been called. */ public int getQueryCount() { if (_queries == null) { return 0; } return _queries.size(); } public static void main(String[] args) { //String sql = "A'''' sss ; GO ;; GO'"; //String sql = "A\n--x\n--y\n/*\nB"; //String sql = "GO GO"; String sql = "@c:\\tools\\sql\\file.sql"; QueryTokenizer qt = new QueryTokenizer("GO", "--", true); qt.setScriptToTokenize(sql); while(qt.hasQuery()) { System.out.println(">" + qt.nextQuery() + "<"); } } /** * @return the query statement separator */ public String getQuerySep() { return _querySep; } /** * @param sep the value to use for the query statement separator */ public void setQuerySep(String sep) { _querySep = sep; } /** * @return the _lineCommentBegin */ public String getLineCommentBegin() { return _lineCommentBegin; } /** * @param commentBegin the _lineCommentBegin to set */ public void setLineCommentBegin(String commentBegin) { _lineCommentBegin = commentBegin; } /** * @return the _removeMultiLineComment */ public boolean isRemoveMultiLineComment() { return _removeMultiLineComment; } @Override public TokenizerSessPropsInteractions getTokenizerSessPropsInteractions() { return new TokenizerSessPropsInteractions(); } /** * @param multiLineComment the _removeMultiLineComment to set */ public void setRemoveMultiLineComment(boolean multiLineComment) { _removeMultiLineComment = multiLineComment; } /** * This uses statements that begin with scriptIncludePrefix to indicate * that the following text is a filename containing SQL statements that * should be loaded. * * @param scriptIncludePrefix the * @param lineCommentBegin * @param removeMultiLineComment */ protected void expandFileIncludes(String scriptIncludePrefix) { if (scriptIncludePrefix == null) { s_log.error("scriptIncludePrefix cannot be null "); return; } ArrayList<String> tmp = new ArrayList<String>(); for (Iterator<String> iter = _queries.iterator(); iter.hasNext();) { String sql = iter.next(); if (sql.startsWith(scriptIncludePrefix)) { try { String filename = sql.substring(scriptIncludePrefix.length()); List<String> fileSQL = getStatementsFromIncludeFile(filename); tmp.addAll(fileSQL); } catch (Exception e) { s_log.error( "Unexpected error while attempting to include file " + "from "+sql, e); } } else { tmp.add(sql); } } _queries = tmp; } protected List<String> getStatementsFromIncludeFile(String filename) throws Exception { if (filename.startsWith("'")) { filename = filename.substring(1); } if (filename.endsWith("'")) { filename = StringUtilities.chop(filename); } if (filename.endsWith("\n")) { filename = StringUtilities.chop(filename); } ArrayList<String> result = new ArrayList<String>(); if (s_log.isDebugEnabled()) { s_log.debug("Attemping to open file '"+filename+"'"); } File f = new File(filename); /* if (f.canRead()) { */ StringBuffer fileLines = new StringBuffer(); try { BufferedReader reader = new BufferedReader(new FileReader(f)); String next = reader.readLine(); while (next != null) { fileLines.append(next); fileLines.append("\n"); next = reader.readLine(); } } catch (Exception e) { s_log.error( "Unexpected exception while reading lines from file " + "("+filename+")", e); } if (fileLines.toString().length() > 0) { IQueryTokenizer qt = null; if (_tokenizerFactory != null) { qt = _tokenizerFactory.getTokenizer(); } else { qt = new QueryTokenizer(_querySep, _lineCommentBegin, _removeMultiLineComment); } qt.setScriptToTokenize(fileLines.toString()); while (qt.hasQuery()) { String sql = qt.nextQuery(); result.add(sql); } } /* } else { s_log.error("Unable to open file: "+filename+" for reading"); } */ return result; } /* (non-Javadoc) * @see net.sourceforge.squirrel_sql.fw.sql.IQueryTokenizer#getSQLStatementSeparator() */ public String getSQLStatementSeparator() { return _querySep; } }
true
true
public void setScriptToTokenize(String script) { _queries.clear(); String MULTI_LINE_COMMENT_END = "*/"; String MULTI_LINE_COMMENT_BEGIN = "/*"; script = script.replace('\r', ' '); StringBuffer curQuery = new StringBuffer(); boolean isInLiteral = false; boolean isInMultiLineComment = false; boolean isInLineComment = false; int literalSepCount = 0; for (int i = 0; i < script.length(); ++i) { char c = script.charAt(i); if(false == isInLiteral) { /////////////////////////////////////////////////////////// // Handling of comments // We look backwards if(isInLineComment && script.startsWith("\n", i - "\n".length())) { isInLineComment = false; } // We look backwards if(isInMultiLineComment && script.startsWith(MULTI_LINE_COMMENT_END, i - MULTI_LINE_COMMENT_END.length())) { isInMultiLineComment = false; } if(false == isInLineComment && false == isInMultiLineComment) { // We look forward isInMultiLineComment = script.startsWith(MULTI_LINE_COMMENT_BEGIN, i); isInLineComment = script.startsWith(_lineCommentBegin, i); if(isInMultiLineComment && _removeMultiLineComment) { // skip ahead so the cursor is now immediately after the begin comment string i+=MULTI_LINE_COMMENT_BEGIN.length()+1; } } if((isInMultiLineComment && _removeMultiLineComment) || isInLineComment) { // This is responsible that comments are not in curQuery continue; } // //////////////////////////////////////////////////////////// } curQuery.append(c); if ('\'' == c) { if(false == isInLiteral) { isInLiteral = true; } else { ++literalSepCount; } } else { if(0 != literalSepCount % 2) { isInLiteral = false; } literalSepCount = 0; } int querySepLen = getLenOfQuerySepIfAtLastCharOfQuerySep(script, i, _querySep, isInLiteral); if(-1 < querySepLen) { int newLength = curQuery.length() - querySepLen; if(-1 < newLength && curQuery.length() > newLength) { curQuery.setLength(newLength); String newQuery = curQuery.toString().trim(); if(0 < newQuery.length()) { _queries.add(curQuery.toString().trim()); } } curQuery.setLength(0); } } String lastQuery = curQuery.toString().trim(); if(0 < lastQuery.length()) { _queries.add(lastQuery.trim()); } _queryIterator = _queries.iterator(); }
public void setScriptToTokenize(String script) { _queries.clear(); String MULTI_LINE_COMMENT_END = "*/"; String MULTI_LINE_COMMENT_BEGIN = "/*"; script = script.replace('\r', ' '); StringBuffer curQuery = new StringBuffer(); boolean isInLiteral = false; boolean isInMultiLineComment = false; boolean isInLineComment = false; int literalSepCount = 0; for (int i = 0; i < script.length(); ++i) { char c = script.charAt(i); if(false == isInLiteral) { /////////////////////////////////////////////////////////// // Handling of comments // We look backwards if(isInLineComment && script.startsWith("\n", i - "\n".length())) { isInLineComment = false; } // We look backwards if(isInMultiLineComment && script.startsWith(MULTI_LINE_COMMENT_END, i - MULTI_LINE_COMMENT_END.length())) { isInMultiLineComment = false; } if(false == isInLineComment && false == isInMultiLineComment) { // We look forward isInMultiLineComment = script.startsWith(MULTI_LINE_COMMENT_BEGIN, i); isInLineComment = script.startsWith(_lineCommentBegin, i); if(isInMultiLineComment && _removeMultiLineComment) { // skip ahead so the cursor is now immediately after the begin comment string i+=MULTI_LINE_COMMENT_BEGIN.length()+1; } } if((isInMultiLineComment && _removeMultiLineComment) || isInLineComment) { // This is responsible that comments are not in curQuery continue; } // //////////////////////////////////////////////////////////// } curQuery.append(c); if ('\'' == c) { if(false == isInLiteral) { isInLiteral = true; } else { ++literalSepCount; } } else { if(0 != literalSepCount % 2) { isInLiteral = false; } literalSepCount = 0; } int querySepLen = getLenOfQuerySepIfAtLastCharOfQuerySep(script, i, _querySep, isInLiteral); if(-1 < querySepLen && !isInMultiLineComment) { int newLength = curQuery.length() - querySepLen; if(-1 < newLength && curQuery.length() > newLength) { curQuery.setLength(newLength); String newQuery = curQuery.toString().trim(); if(0 < newQuery.length()) { _queries.add(curQuery.toString().trim()); } } curQuery.setLength(0); } } String lastQuery = curQuery.toString().trim(); if(0 < lastQuery.length()) { _queries.add(lastQuery.trim()); } _queryIterator = _queries.iterator(); }
diff --git a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java index 404b005..a97fb31 100644 --- a/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java +++ b/osmdroid-android/src/org/osmdroid/views/overlay/ItemizedOverlay.java @@ -1,283 +1,283 @@ // Created by plusminus on 23:18:23 - 02.10.2008 package org.osmdroid.views.overlay; import java.util.ArrayList; import org.osmdroid.ResourceProxy; import org.osmdroid.views.MapView; import org.osmdroid.views.MapView.Projection; import org.osmdroid.views.overlay.OverlayItem.HotspotPlace; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; /** * Draws a list of {@link OverlayItem} as markers to a map. The item with the lowest index is drawn * as last and therefore the 'topmost' marker. It also gets checked for onTap first. This class is * generic, because you then you get your custom item-class passed back in onTap(). * * @author Marc Kurtz * @author Nicolas Gramlich * @author Theodore Hong * @author Fred Eisele * * @param <Item> */ public abstract class ItemizedOverlay<Item extends OverlayItem> extends Overlay implements Overlay.Snappable { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final Drawable mDefaultMarker; private final ArrayList<Item> mInternalItemList; private final Rect mRect = new Rect(); private final Point mCurScreenCoords = new Point(); protected boolean mDrawFocusedItem = true; private Item mFocusedItem; // =========================================================== // Abstract methods // =========================================================== /** * Method by which subclasses create the actual Items. This will only be called from populate() * we'll cache them for later use. */ protected abstract Item createItem(int i); /** * The number of items in this overlay. */ public abstract int size(); // =========================================================== // Constructors // =========================================================== public ItemizedOverlay(final Drawable pDefaultMarker, final ResourceProxy pResourceProxy) { super(pResourceProxy); if (pDefaultMarker == null) { throw new IllegalArgumentException("You must pass a default marker to ItemizedOverlay."); } this.mDefaultMarker = pDefaultMarker; mInternalItemList = new ArrayList<Item>(); } // =========================================================== // Methods from SuperClass/Interfaces (and supporting methods) // =========================================================== /** * Draw a marker on each of our items. populate() must have been called first.<br/> * <br/> * The marker will be drawn twice for each Item in the Overlay--once in the shadow phase, skewed * and darkened, then again in the non-shadow phase. The bottom-center of the marker will be * aligned with the geographical coordinates of the Item.<br/> * <br/> * The order of drawing may be changed by overriding the getIndexToDraw(int) method. An item may * provide an alternate marker via its OverlayItem.getMarker(int) method. If that method returns * null, the default marker is used.<br/> * <br/> * The focused item is always drawn last, which puts it visually on top of the other items.<br/> * * @param canvas * the Canvas upon which to draw. Note that this may already have a transformation * applied, so be sure to leave it the way you found it * @param mapView * the MapView that requested the draw. Use MapView.getProjection() to convert * between on-screen pixels and latitude/longitude pairs * @param shadow * if true, draw the shadow layer. If false, draw the overlay contents. */ @Override public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) { if (shadow) { return; } final Projection pj = mapView.getProjection(); final int size = this.mInternalItemList.size() - 1; /* Draw in backward cycle, so the items with the least index are on the front. */ for (int i = size; i >= 0; i--) { final Item item = getItem(i); pj.toMapPixels(item.mGeoPoint, mCurScreenCoords); onDrawItem(canvas, item, mCurScreenCoords); } } // =========================================================== // Methods // =========================================================== /** * Utility method to perform all processing on a new ItemizedOverlay. Subclasses provide Items * through the createItem(int) method. The subclass should call this as soon as it has data, * before anything else gets called. */ protected final void populate() { final int size = size(); mInternalItemList.clear(); mInternalItemList.ensureCapacity(size); for (int a = 0; a < size; a++) { mInternalItemList.add(createItem(a)); } } /** * Returns the Item at the given index. * * @param position * the position of the item to return * @return the Item of the given index. */ public final Item getItem(final int position) { return mInternalItemList.get(position); } /** * Draws an item located at the provided screen coordinates to the canvas. * * @param canvas * what the item is drawn upon * @param item * the item to be drawn * @param curScreenCoords * the screen coordinates of the item */ protected void onDrawItem(final Canvas canvas, final Item item, final Point curScreenCoords) { final int state = (mDrawFocusedItem && (mFocusedItem == item) ? OverlayItem.ITEM_STATE_FOCUSED_MASK : 0); final Drawable marker = (item.getMarker(state) == null) ? getDefaultMarker(state) : item .getMarker(state); final HotspotPlace hotspot = item.getMarkerHotspot(); boundToHotspot(marker, hotspot); // draw it Overlay.drawAt(canvas, marker, curScreenCoords.x, curScreenCoords.y, false); } private Drawable getDefaultMarker(final int state) { OverlayItem.setState(mDefaultMarker, state); return mDefaultMarker; } /** * See if a given hit point is within the bounds of an item's marker. Override to modify the way * an item is hit tested. The hit point is relative to the marker's bounds. The default * implementation just checks to see if the hit point is within the touchable bounds of the * marker. * * @param item * the item to hit test * @param marker * the item's marker * @param hitX * x coordinate of point to check * @param hitY * y coordinate of point to check * @return true if the hit point is within the marker */ protected boolean hitTest(final Item item, final android.graphics.drawable.Drawable marker, final int hitX, final int hitY) { return marker.getBounds().contains(hitX, hitY); } /** * Set whether or not to draw the focused item. The default is to draw it, but some clients may * prefer to draw the focused item themselves. */ public void setDrawFocusedItem(final boolean drawFocusedItem) { mDrawFocusedItem = drawFocusedItem; } /** * If the given Item is found in the overlay, force it to be the current focus-bearer. Any * registered {@link ItemizedOverlay#OnFocusChangeListener} will be notified. This does not move * the map, so if the Item isn't already centered, the user may get confused. If the Item is not * found, this is a no-op. You can also pass null to remove focus. */ public void setFocus(final Item item) { mFocusedItem = item; } /** * * @return the currently-focused item, or null if no item is currently focused. */ public Item getFocus() { return mFocusedItem; } /** * Adjusts a drawable's bounds so that (0,0) is a pixel in the location described by the hotspot * parameter. Useful for "pin"-like graphics. For convenience, returns the same drawable that * was passed in. * * @param marker * the drawable to adjust * @param hotspot * the hotspot for the drawable * @return the same drawable that was passed in. */ protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) { final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale); final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale); mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight); if (hotspot == null) { hotspot = HotspotPlace.BOTTOM_CENTER; } switch (hotspot) { default: case NONE: break; case CENTER: mRect.offset(-markerWidth / 2, -markerHeight / 2); break; case BOTTOM_CENTER: mRect.offset(-markerWidth / 2, -markerHeight); break; case TOP_CENTER: mRect.offset(-markerWidth / 2, 0); break; case RIGHT_CENTER: mRect.offset(-markerWidth, -markerHeight / 2); break; case LEFT_CENTER: mRect.offset(0, -markerHeight / 2); break; case UPPER_RIGHT_CORNER: mRect.offset(-markerWidth, 0); break; case LOWER_RIGHT_CORNER: mRect.offset(-markerWidth, -markerHeight); break; case UPPER_LEFT_CORNER: mRect.offset(0, 0); break; case LOWER_LEFT_CORNER: - mRect.offset(0, markerHeight); /// TODO test - should this be -markerHeight ??? + mRect.offset(0, -markerHeight); break; } marker.setBounds(mRect); return marker; } }
true
true
protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) { final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale); final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale); mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight); if (hotspot == null) { hotspot = HotspotPlace.BOTTOM_CENTER; } switch (hotspot) { default: case NONE: break; case CENTER: mRect.offset(-markerWidth / 2, -markerHeight / 2); break; case BOTTOM_CENTER: mRect.offset(-markerWidth / 2, -markerHeight); break; case TOP_CENTER: mRect.offset(-markerWidth / 2, 0); break; case RIGHT_CENTER: mRect.offset(-markerWidth, -markerHeight / 2); break; case LEFT_CENTER: mRect.offset(0, -markerHeight / 2); break; case UPPER_RIGHT_CORNER: mRect.offset(-markerWidth, 0); break; case LOWER_RIGHT_CORNER: mRect.offset(-markerWidth, -markerHeight); break; case UPPER_LEFT_CORNER: mRect.offset(0, 0); break; case LOWER_LEFT_CORNER: mRect.offset(0, markerHeight); /// TODO test - should this be -markerHeight ??? break; } marker.setBounds(mRect); return marker; }
protected synchronized Drawable boundToHotspot(final Drawable marker, HotspotPlace hotspot) { final int markerWidth = (int) (marker.getIntrinsicWidth() * mScale); final int markerHeight = (int) (marker.getIntrinsicHeight() * mScale); mRect.set(0, 0, 0 + markerWidth, 0 + markerHeight); if (hotspot == null) { hotspot = HotspotPlace.BOTTOM_CENTER; } switch (hotspot) { default: case NONE: break; case CENTER: mRect.offset(-markerWidth / 2, -markerHeight / 2); break; case BOTTOM_CENTER: mRect.offset(-markerWidth / 2, -markerHeight); break; case TOP_CENTER: mRect.offset(-markerWidth / 2, 0); break; case RIGHT_CENTER: mRect.offset(-markerWidth, -markerHeight / 2); break; case LEFT_CENTER: mRect.offset(0, -markerHeight / 2); break; case UPPER_RIGHT_CORNER: mRect.offset(-markerWidth, 0); break; case LOWER_RIGHT_CORNER: mRect.offset(-markerWidth, -markerHeight); break; case UPPER_LEFT_CORNER: mRect.offset(0, 0); break; case LOWER_LEFT_CORNER: mRect.offset(0, -markerHeight); break; } marker.setBounds(mRect); return marker; }
diff --git a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/NoIncludeTag.java b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/NoIncludeTag.java index 4775eb0d..90a9ddad 100644 --- a/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/NoIncludeTag.java +++ b/jamwiki-core/src/main/java/org/jamwiki/parser/jflex/NoIncludeTag.java @@ -1,46 +1,48 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version of the GNU Lesser General * Public License as published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.parser.jflex; import org.jamwiki.parser.ParserInput; import org.jamwiki.parser.ParserOutput; import org.jamwiki.parser.ParserTag; import org.jamwiki.utils.WikiLogger; /** * This class parses nowiki tags of the form <code>&lt;noinclude&gt;content&lt;/noinclude&gt;</code>. */ public class NoIncludeTag implements ParserTag { private static final WikiLogger logger = WikiLogger.getLogger(NoIncludeTag.class.getName()); /** * Parse a call to a Mediawiki noinclude tag of the form * "<noinclude>text</noinclude>" and return the resulting output. */ public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) throws Exception { if (mode <= JFlexParser.MODE_MINIMAL) { return raw; } if (parserInput.getTemplateDepth() > 0) { // no content is returned when called from a template return ""; } - // anything else then strip tags and return - return ParserUtil.tagContent(raw); + String content = ParserUtil.tagContent(raw); + // run the pre-processor against the noinclude content + JFlexParser parser = new JFlexParser(parserInput); + return parser.parseFragment(parserOutput, content, JFlexParser.MODE_PREPROCESS); } }
true
true
public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) throws Exception { if (mode <= JFlexParser.MODE_MINIMAL) { return raw; } if (parserInput.getTemplateDepth() > 0) { // no content is returned when called from a template return ""; } // anything else then strip tags and return return ParserUtil.tagContent(raw); }
public String parse(ParserInput parserInput, ParserOutput parserOutput, int mode, String raw) throws Exception { if (mode <= JFlexParser.MODE_MINIMAL) { return raw; } if (parserInput.getTemplateDepth() > 0) { // no content is returned when called from a template return ""; } String content = ParserUtil.tagContent(raw); // run the pre-processor against the noinclude content JFlexParser parser = new JFlexParser(parserInput); return parser.parseFragment(parserOutput, content, JFlexParser.MODE_PREPROCESS); }
diff --git a/src/jvm/backtype/storm/Config.java b/src/jvm/backtype/storm/Config.java index d68de398..e5008e96 100644 --- a/src/jvm/backtype/storm/Config.java +++ b/src/jvm/backtype/storm/Config.java @@ -1,376 +1,376 @@ package backtype.storm; import backtype.storm.serialization.ISerialization; import backtype.storm.serialization.SerializationFactory; import java.util.HashMap; import java.util.Map; /** * Topology configs are specified as a plain old map. This class provides a * convenient way to create a topology config map by providing setter methods for * all the configs that can be set. It also makes it easier to do things like add * serializations. * * <p>This class also provides constants for all the configurations possible on a Storm * cluster and Storm topology. Default values for these configs can be found in * defaults.yaml.</p> * * <p>Note that you may put other configurations in any of the configs. Storm * will ignore anything it doesn't recognize, but your topologies are free to make * use of them by reading them in the prepare method of Bolts or the open method of * Spouts. .</p> */ public class Config extends HashMap<String, Object> { /** * A list of hosts of ZooKeeper servers used to manage the cluster. */ public static String STORM_ZOOKEEPER_SERVERS = "storm.zookeeper.servers"; /** * The port Storm will use to connect to each of the ZooKeeper servers. */ public static String STORM_ZOOKEEPER_PORT = "storm.zookeeper.port"; /** * A directory on the local filesystem used by Storm for any local * filesystem usage it needs. The directory must exist and the Storm daemons must * have permission to read/write from this location. */ public static String STORM_LOCAL_DIR = "storm.local.dir"; /** * The mode this Storm cluster is running in. Either "distributed" or "local". */ public static String STORM_CLUSTER_MODE = "storm.cluster.mode"; /** * Whether or not to use ZeroMQ for messaging in local mode. If this is set * to false, then Storm will use a pure-Java messaging system. The purpose * of this flag is to make it easy to run Storm in local mode by eliminating * the need for native dependencies, which can be difficult to install. * * Defaults to false. */ public static String STORM_LOCAL_MODE_ZMQ = "storm.local.mode.zmq"; /** * The root location at which Storm stores data in ZooKeeper. */ public static String STORM_ZOOKEEPER_ROOT = "storm.zookeeper.root"; /** * The timeout for clients to ZooKeeper. */ public static String STORM_ZOOKEEPER_SESSION_TIMEOUT = "storm.zookeeper.session.timeout"; /** * The id assigned to a running topology. The id is the storm name with a unique nonce appended. */ public static String STORM_ID = "storm.id"; /** * The host that the master server is running on. */ public static String NIMBUS_HOST = "nimbus.host"; /** * Which port the Thrift interface of Nimbus should run on. Clients should * connect to this port to upload jars and submit topologies. */ public static String NIMBUS_THRIFT_PORT = "nimbus.thrift.port"; /** * This parameter is used by the storm-deploy project to configure the * jvm options for the nimbus daemon. */ public static String NIMBUS_CHILDOPTS = "nimbus.childopts"; /** * How long without heartbeating a task can go before nimbus will consider the * task dead and reassign it to another location. */ public static String NIMBUS_TASK_TIMEOUT_SECS = "nimbus.task.timeout.secs"; /** * How often nimbus should wake up to check heartbeats and do reassignments. Note * that if a machine ever goes down Nimbus will immediately wake up and take action. * This parameter is for checking for failures when there's no explicit event like that * occuring. */ public static String NIMBUS_MONITOR_FREQ_SECS = "nimbus.monitor.freq.secs"; /** * How long before a supervisor can go without heartbeating before nimbus considers it dead * and stops assigning new work to it. */ public static String NIMBUS_SUPERVISOR_TIMEOUT_SECS = "nimbus.supervisor.timeout.secs"; /** * A special timeout used when a task is initially launched. During launch, this is the timeout * used until the first heartbeat, overriding nimbus.task.timeout.secs. * * <p>A separate timeout exists for launch because there can be quite a bit of overhead * to launching new JVM's and configuring them.</p> */ public static String NIMBUS_TASK_LAUNCH_SECS = "nimbus.task.launch.secs"; /** * Whether or not nimbus should reassign tasks if it detects that a task goes down. * Defaults to true, and it's not recommended to change this value. */ public static String NIMBUS_REASSIGN = "nimbus.reassign"; /** * During upload/download with the master, how long an upload or download connection is idle * before nimbus considers it dead and drops the connection. */ public static String NIMBUS_FILE_COPY_EXPIRATION_SECS = "nimbus.file.copy.expiration.secs"; /** * A list of ports that can run workers on this supervisor. Each worker uses one port, and * the supervisor will only run one worker per port. Use this configuration to tune * how many workers run on each machine. */ public static String SUPERVISOR_SLOTS_PORTS = "supervisor.slots.ports"; /** * This parameter is used by the storm-deploy project to configure the * jvm options for the supervisor daemon. */ public static String SUPERVISOR_CHILDOPTS = "supervisor.childopts"; /** * How long a worker can go without heartbeating before the supervisor tries to * restart the worker process. */ public static String SUPERVISOR_WORKER_TIMEOUT_SECS = "supervisor.worker.timeout.secs"; /** * How long a worker can go without heartbeating during the initial launch before * the supervisor tries to restart the worker process. This value override * supervisor.worker.timeout.secs during launch because there is additional * overhead to starting and configuring the JVM on launch. */ public static String SUPERVISOR_WORKER_START_TIMEOUT_SECS = "supervisor.worker.start.timeout.secs"; /** * Whether or not the supervisor should launch workers assigned to it. Defaults * to true -- and you should probably never change this value. This configuration * is used in the Storm unit tests. */ public static String SUPERVISOR_ENABLE = "supervisor.enable"; /** * how often the supervisor sends a heartbeat to the master. */ public static String SUPERVISOR_HEARTBEAT_FREQUENCY_SECS = "supervisor.heartbeat.frequency.secs"; /** * How often the supervisor checks the worker heartbeats to see if any of them * need to be restarted. */ public static String SUPERVISOR_MONITOR_FREQUENCY_SECS = "supervisor.monitor.frequency.secs"; /** * The jvm opts provided to workers launched by this supervisor. */ public static String WORKER_CHILDOPTS = "worker.childopts"; /** * How often this worker should heartbeat to the supervisor. */ public static String WORKER_HEARTBEAT_FREQUENCY_SECS = "worker.heartbeat.frequency.secs"; /** * How often a task should heartbeat its status to the master. */ public static String TASK_HEARTBEAT_FREQUENCY_SECS = "task.heartbeat.frequency.secs"; /** * How often a task should sync its connections with other tasks (if a task is * reassigned, the other tasks sending messages to it need to refresh their connections). * In general though, when a reassignment happens other tasks will be notified * almost immediately. This configuration is here just in case that notification doesn't * come through. */ public static String TASK_REFRESH_POLL_SECS = "task.refresh.poll.secs"; /** * When set to true, Storm will log every message that's emitted. */ public static String TOPOLOGY_DEBUG = "topology.debug"; /** * Whether or not the master should optimize topologies by running multiple * tasks in a single thread where appropriate. */ public static String TOPOLOGY_OPTIMIZE = "topology.optimize"; /** * How many processes should be spawned around the cluster to execute this * topology. Each process will execute some number of tasks as threads within * them. This parameter should be used in conjunction with the parallelism hints * on each component in the topology to tune the performance of a topology. */ public static String TOPOLOGY_WORKERS = "topology.workers"; /** * How many acker tasks should be spawned for the topology. An acker task keeps * track of a subset of the tuples emitted by spouts and detects when a spout * tuple is fully processed. When an acker task detects that a spout tuple * is finished, it sends a message to the spout to acknowledge the tuple. The * number of ackers should be scaled with the amount of throughput going * through the cluster for the topology. Typically, you don't need that many * ackers though. * * <p>If this is set to 0, then Storm will immediately ack tuples as soon * as they come off the spout, effectively disabling reliability.</p> */ public static String TOPOLOGY_ACKERS = "topology.ackers"; /** * The maximum amount of time given to the topology to fully process a message * emitted by a spout. If the message is not acked within this time frame, Storm * will fail the message on the spout. Some spouts implementations will then replay * the message at a later time. */ public static String TOPOLOGY_MESSAGE_TIMEOUT_SECS = "topology.message.timeout.secs"; /** * A map from unique tokens to the name of classes that implement custom serializations. Tokens * must 33 or greater. Custom serializations are implemented using the * {@link backtype.storm.serialization.ISerialization} interface. The unique tokens you provide * are what are serialized on the wire so that Storm can identify the types of fields. Storm * forces this optimization on you because otherwise it would have to write the class name, * which would be terribly inefficient. After you register serializations through this config, * Storm will make use of them automatically. */ public static String TOPOLOGY_SERIALIZATIONS = "topology.serializations"; /** * Whether or not Storm should skip the loading of a serialization for which it * does not have the code. Otherwise, the task will fail to load and will throw * an error at runtime. The use case of this is if you want to declare your serializations * on the storm.yaml files on the cluster rather than every single time you submit a topology. * Different applications may use different serializations and so a single application may not * have the code for the other serializers used by other apps. By setting this config to true, * Storm will ignore that it doesn't have those other serializations rather than throw an error. */ public static String TOPOLOGY_SKIP_MISSING_SERIALIZATIONS= "topology.skip.missing.serializations"; /** * The maximum parallelism allowed for a component in this topology. This configuration is * typically used in testing to limit the number of threads spawned in local mode. */ public static String TOPOLOGY_MAX_TASK_PARALLELISM="topology.max.task.parallelism"; /** * The maximum parallelism allowed for a component in this topology. This configuration is * typically used in testing to limit the number of threads spawned in local mode. */ public static String TOPOLOGY_MAX_SPOUT_PENDING="topology.max.spout.pending"; /** * The maximum amount of time a component gives a source of state to synchronize before it requests * synchronization again. */ public static String TOPOLOGY_STATE_SYNCHRONIZATION_TIMEOUT_SECS="topology.state.synchronization.timeout.secs"; /** * The percentage of tuples to sample to produce stats for a task. */ public static String TOPOLOGY_STATS_SAMPLE_RATE="topology.stats.sample.rate"; /** * The number of threads that should be used by the zeromq context in each worker process. */ public static String ZMQ_THREADS = "zmq.threads"; /** * How long a connection should retry sending messages to a target host when * the connection is closed. This is an advanced configuration and can almost * certainly be ignored. */ public static String ZMQ_LINGER_MILLIS = "zmq.linger.millis"; /** * This value is passed to spawned JVMs (e.g., Nimbus, Supervisor, and Workers) * for the java.library.path value. java.library.path tells the JVM where * to look for native libraries. It is necessary to set this config correctly since * Storm uses the ZeroMQ and JZMQ native libs. */ public static String JAVA_LIBRARY_PATH = "java.library.path"; public void setDebug(boolean isOn) { put(Config.TOPOLOGY_DEBUG, isOn); } public void setOptimize(boolean isOn) { put(Config.TOPOLOGY_OPTIMIZE, isOn); } public void setNumWorkers(int workers) { put(Config.TOPOLOGY_WORKERS, workers); } public void setNumAckers(int numTasks) { put(Config.TOPOLOGY_ACKERS, numTasks); } public void setMessageTimeoutSecs(int secs) { put(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS, secs); } - public void addSerialization(int token, Class<ISerialization> serialization) { + public void addSerialization(int token, Class<? extends ISerialization> serialization) { if(!containsKey(Config.TOPOLOGY_SERIALIZATIONS)) { put(Config.TOPOLOGY_SERIALIZATIONS, new HashMap()); } Map<Integer, String> sers = (Map<Integer, String>) get(Config.TOPOLOGY_SERIALIZATIONS); if(token<=SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY) { throw new IllegalArgumentException("User serialization tokens must be greater than " + SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY); } if(sers.containsKey(token)) { throw new IllegalArgumentException("All serialization tokens must be unique. Found duplicate token: " + token); } sers.put(token, serialization.getName()); } public void setSkipMissingSerializations(boolean skip) { put(Config.TOPOLOGY_SKIP_MISSING_SERIALIZATIONS, skip); } public void setMaxTaskParallelism(int max) { put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, max); } public void setMaxSpoutPending(int max) { put(Config.TOPOLOGY_MAX_SPOUT_PENDING, max); } public void setStatsSampleRate(double rate) { put(Config.TOPOLOGY_STATS_SAMPLE_RATE, rate); } }
true
true
public void addSerialization(int token, Class<ISerialization> serialization) { if(!containsKey(Config.TOPOLOGY_SERIALIZATIONS)) { put(Config.TOPOLOGY_SERIALIZATIONS, new HashMap()); } Map<Integer, String> sers = (Map<Integer, String>) get(Config.TOPOLOGY_SERIALIZATIONS); if(token<=SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY) { throw new IllegalArgumentException("User serialization tokens must be greater than " + SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY); } if(sers.containsKey(token)) { throw new IllegalArgumentException("All serialization tokens must be unique. Found duplicate token: " + token); } sers.put(token, serialization.getName()); }
public void addSerialization(int token, Class<? extends ISerialization> serialization) { if(!containsKey(Config.TOPOLOGY_SERIALIZATIONS)) { put(Config.TOPOLOGY_SERIALIZATIONS, new HashMap()); } Map<Integer, String> sers = (Map<Integer, String>) get(Config.TOPOLOGY_SERIALIZATIONS); if(token<=SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY) { throw new IllegalArgumentException("User serialization tokens must be greater than " + SerializationFactory.SERIALIZATION_TOKEN_BOUNDARY); } if(sers.containsKey(token)) { throw new IllegalArgumentException("All serialization tokens must be unique. Found duplicate token: " + token); } sers.put(token, serialization.getName()); }
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromWSDLTest.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromWSDLTest.java index c869bf34..d6efcbce 100644 --- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromWSDLTest.java +++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromWSDLTest.java @@ -1,273 +1,273 @@ /******************************************************************************* * Copyright (c) 2011 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is 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: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.ws.ui.bot.test.webservice.eap; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.Result; import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.ui.bot.ext.SWTBotExt; import org.jboss.tools.ui.bot.ext.SWTUtilExt; import org.jboss.tools.ui.bot.ext.Timing; import org.jboss.tools.ui.bot.ext.config.Annotations.Require; import org.jboss.tools.ui.bot.ext.config.Annotations.Server; import org.jboss.tools.ui.bot.ext.helper.ContextMenuHelper; import org.jboss.tools.ws.ui.bot.test.WSAllBotTests; import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.WsWizardBase.Slider_Level; import org.jboss.tools.ws.ui.bot.test.webservice.TopDownWSTest; import org.jboss.tools.ws.ui.bot.test.webservice.WebServiceTestBase; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runners.Suite.SuiteClasses; /** * Test operates on creating non-trivial EAP project from wsdl file * @author jlukas * */ @SuiteClasses({ WSAllBotTests.class, EAPCompAllTests.class }) @Require(perspective="Java EE", server=@Server) // (type=ServerType.EAP, // version = "5.1", operator = ">=")) public class EAPFromWSDLTest extends WebServiceTestBase { private static boolean servicePassed = false; @Before @Override public void setup() { if (!projectExists(getWsProjectName())) { projectHelper.createProject(getWsProjectName()); } if (!projectExists(getWsClientProjectName())) { projectHelper.createProject(getWsClientProjectName()); } } @After @Override public void cleanup() { LOGGER.info("overridden"); } @AfterClass public static void x() { LOGGER.info("x"); servers.removeAllProjectsFromServer(); } @Override protected String getWsProjectName() { return "AreaWSProject"; } @Override protected String getEarProjectName() { return getWsProjectName() + "EAR"; } protected String getWsClientProjectName() { return "AreaWSClientProject"; } protected String getClientEarProjectName() { return getWsClientProjectName() + "EAR"; } @Override protected String getWsPackage() { return "org.jboss.ws"; } @Override protected String getWsName() { return "AreaService"; } @Override protected Slider_Level getLevel() { return Slider_Level.DEPLOY; } @Test public void testService() { topDownWS(TopDownWSTest.class.getResourceAsStream("/resources/jbossws/AreaService.wsdl"), getWsPackage()); IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(getWsProjectName()); IFile f = project.getFile("src/" + getWsPackage().replace(".", "/") - + "/AreaServiceImpl.java"); + + "/impl" + "/AreaServiceImpl.java"); /* * workaround when package is not typed */ if (f == null) { f = project.getFile("src/" + "org.tempuri.areaservice" + "/AreaServiceImpl.java"); } String content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content .contains("public class AreaServiceImpl implements AreaService {")); Assert.assertTrue(content .contains("public float calculateRectArea(Dimensions parameters)")); replaceContent(f, "/resources/jbossws/AreaWS.java.ws"); f = project.getFile("WebContent/WEB-INF/web.xml"); content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content - .contains("<servlet-class>org.jboss.ws.AreaServiceImpl</servlet-class>")); + .contains("<servlet-class>org.jboss.ws.impl.AreaServiceImpl</servlet-class>")); Assert.assertTrue(content .contains("<url-pattern>/AreaService</url-pattern>")); deploymentHelper.runProject(getEarProjectName()); deploymentHelper.assertServiceDeployed(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()), 10000); servicePassed = true; } @Test public void testClient() { Assert.assertTrue("service must exist", servicePassed); clientHelper.createClient(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()), getWsClientProjectName(), Slider_Level.DEVELOP, "org.jboss.wsclient"); IProject p = ResourcesPlugin.getWorkspace().getRoot() .getProject(getWsClientProjectName()); String pkg = "org/jboss/wsclient"; String cls = "src/" + pkg + "/AreaService.java"; Assert.assertTrue(p.getFile(cls).exists()); cls = "src/" + pkg + "/clientsample/ClientSample.java"; IFile f = p.getFile(cls); Assert.assertTrue(f.exists()); replaceContent(f, "/resources/jbossws/clientsample.java.ws"); /* * workaround for https://issues.jboss.org/browse/JBIDE-9817 */ projectExplorer.selectProject(getWsClientProjectName()); SWTBotTree tree = projectExplorer.bot().tree(); SWTBotTreeItem item = tree.getTreeItem(getWsClientProjectName()); item.expand(); removeRuntimeLibrary(tree, item, bot, util); eclipse.runJavaApplication(getWsClientProjectName(), "org.jboss.wsclient.clientsample.ClientSample", null); util.waitForNonIgnoredJobs(); bot.sleep(15 * TIME_1S); String output = console.getConsoleText(); LOGGER.info(output); Assert.assertTrue(output, output.contains("Server said: 37.5")); Assert.assertTrue(output.contains("Server said: 3512.3699")); } private void replaceContent(IFile f, String content) { try { f.delete(true, new NullProgressMonitor()); } catch (CoreException ce) { LOGGER.log(Level.WARNING, ce.getMessage(), ce); } InputStream is = null; try { is = EAPFromWSDLTest.class.getResourceAsStream(content); f.create(is, true, new NullProgressMonitor()); } catch (CoreException ce) { LOGGER.log(Level.WARNING, ce.getMessage(), ce); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // ignore } } } try { ResourcesPlugin .getWorkspace() .getRoot() .refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, new NullProgressMonitor()); } catch (CoreException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } util.waitForNonIgnoredJobs(); bot.sleep(TIME_1S); } private void removeRuntimeLibrary(final SWTBotTree tree, SWTBotTreeItem item, SWTBotExt bot, SWTUtilExt util) { nodeContextMenu(tree, item, "Build Path", "Configure Build Path...") .click(); bot.activeShell().activate(); bot.tabItem("Libraries").activate(); assertTrue(!bot.button("Remove").isEnabled()); try { findSelectEnterpriseRuntimeLibrary(bot); assertTrue(bot.button("Remove").isEnabled()); bot.button("Remove").click(); bot.button("OK").click(); bot.sleep(Timing.time2S()); util.waitForNonIgnoredJobs(); } catch (Exception e) { e.printStackTrace(); bot.button("Cancel").click(); } } private void findSelectEnterpriseRuntimeLibrary(SWTBotExt bot) throws Exception { SWTBotTree libraryTree = bot.tree(1); boolean libraryFound = false; for (SWTBotTreeItem libraryItem : libraryTree.getAllItems()) { if (libraryItem.getText().contains( "JBoss Enterprise Application Platform")) { libraryTree.select(libraryItem); libraryFound = true; break; } } if (!libraryFound) throw new RuntimeException("No runtime library has been found"); } private SWTBotMenu nodeContextMenu(final SWTBotTree tree, SWTBotTreeItem item, final String... menu) { assert menu.length > 0; ContextMenuHelper.prepareTreeItemForContextMenu(tree, item); return UIThreadRunnable.syncExec(new Result<SWTBotMenu>() { public SWTBotMenu run() { SWTBotMenu m = new SWTBotMenu(ContextMenuHelper.getContextMenu( tree, menu[0], false)); for (int i = 1; i < menu.length; i++) { m = m.menu(menu[i]); } return m; } }); } }
false
true
public void testService() { topDownWS(TopDownWSTest.class.getResourceAsStream("/resources/jbossws/AreaService.wsdl"), getWsPackage()); IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(getWsProjectName()); IFile f = project.getFile("src/" + getWsPackage().replace(".", "/") + "/AreaServiceImpl.java"); /* * workaround when package is not typed */ if (f == null) { f = project.getFile("src/" + "org.tempuri.areaservice" + "/AreaServiceImpl.java"); } String content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content .contains("public class AreaServiceImpl implements AreaService {")); Assert.assertTrue(content .contains("public float calculateRectArea(Dimensions parameters)")); replaceContent(f, "/resources/jbossws/AreaWS.java.ws"); f = project.getFile("WebContent/WEB-INF/web.xml"); content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content .contains("<servlet-class>org.jboss.ws.AreaServiceImpl</servlet-class>")); Assert.assertTrue(content .contains("<url-pattern>/AreaService</url-pattern>")); deploymentHelper.runProject(getEarProjectName()); deploymentHelper.assertServiceDeployed(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()), 10000); servicePassed = true; }
public void testService() { topDownWS(TopDownWSTest.class.getResourceAsStream("/resources/jbossws/AreaService.wsdl"), getWsPackage()); IProject project = ResourcesPlugin.getWorkspace().getRoot() .getProject(getWsProjectName()); IFile f = project.getFile("src/" + getWsPackage().replace(".", "/") + "/impl" + "/AreaServiceImpl.java"); /* * workaround when package is not typed */ if (f == null) { f = project.getFile("src/" + "org.tempuri.areaservice" + "/AreaServiceImpl.java"); } String content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content .contains("public class AreaServiceImpl implements AreaService {")); Assert.assertTrue(content .contains("public float calculateRectArea(Dimensions parameters)")); replaceContent(f, "/resources/jbossws/AreaWS.java.ws"); f = project.getFile("WebContent/WEB-INF/web.xml"); content = resourceHelper.readFile(f); Assert.assertNotNull(content); Assert.assertTrue(content .contains("<servlet-class>org.jboss.ws.impl.AreaServiceImpl</servlet-class>")); Assert.assertTrue(content .contains("<url-pattern>/AreaService</url-pattern>")); deploymentHelper.runProject(getEarProjectName()); deploymentHelper.assertServiceDeployed(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()), 10000); servicePassed = true; }
diff --git a/TwirlTestTest/src/com/secondhand/model/PowerUpTest.java b/TwirlTestTest/src/com/secondhand/model/PowerUpTest.java index 4d390285..ddbd396b 100644 --- a/TwirlTestTest/src/com/secondhand/model/PowerUpTest.java +++ b/TwirlTestTest/src/com/secondhand/model/PowerUpTest.java @@ -1,18 +1,18 @@ package com.secondhand.model; import com.badlogic.gdx.math.Vector2; import com.secondhand.model.PowerUp.Effect; import junit.framework.TestCase; public class PowerUpTest extends TestCase { public void testConstructor() { - PowerUp pu1 = new PowerUp(new Vector2(),5,Effect.SCORE_UP) {}; - PowerUp pu2 = new PowerUp(new Vector2(),5,Effect.SPEED_UP) {}; + PowerUp pu1 = new PowerUp(new Vector2(),5,Effect.SCORE_UP,null) {}; + PowerUp pu2 = new PowerUp(new Vector2(),5,Effect.SPEED_UP,null) {}; assertEquals(pu1.getEffect(), Effect.SCORE_UP); assertEquals(pu2.getEffect(), Effect.SPEED_UP); } }
true
true
public void testConstructor() { PowerUp pu1 = new PowerUp(new Vector2(),5,Effect.SCORE_UP) {}; PowerUp pu2 = new PowerUp(new Vector2(),5,Effect.SPEED_UP) {}; assertEquals(pu1.getEffect(), Effect.SCORE_UP); assertEquals(pu2.getEffect(), Effect.SPEED_UP); }
public void testConstructor() { PowerUp pu1 = new PowerUp(new Vector2(),5,Effect.SCORE_UP,null) {}; PowerUp pu2 = new PowerUp(new Vector2(),5,Effect.SPEED_UP,null) {}; assertEquals(pu1.getEffect(), Effect.SCORE_UP); assertEquals(pu2.getEffect(), Effect.SPEED_UP); }
diff --git a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java index b83ca760..adb36009 100644 --- a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java +++ b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java @@ -1,151 +1,151 @@ package com.metaweb.gridworks.clustering.binning; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeMap; import java.util.Map.Entry; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import com.metaweb.gridworks.browsing.Engine; import com.metaweb.gridworks.browsing.FilteredRows; import com.metaweb.gridworks.browsing.RowVisitor; import com.metaweb.gridworks.clustering.Clusterer; import com.metaweb.gridworks.model.Cell; import com.metaweb.gridworks.model.Project; import com.metaweb.gridworks.model.Row; public class BinningClusterer extends Clusterer { private Keyer _keyer; static protected Map<String, Keyer> _keyers = new HashMap<String, Keyer>(); List<Map<String,Integer>> _clusters; static { _keyers.put("fingerprint", new FingerprintKeyer()); _keyers.put("ngram-fingerprint", new NGramFingerprintKeyer()); _keyers.put("metaphone", new MetaphoneKeyer()); _keyers.put("double-metaphone", new DoubleMetaphoneKeyer()); _keyers.put("soundex", new SoundexKeyer()); } class BinningRowVisitor implements RowVisitor { Keyer _keyer; Object[] _params; JSONObject _config; Map<String,Map<String,Integer>> _map = new HashMap<String,Map<String,Integer>>(); public BinningRowVisitor(Keyer k, JSONObject o) { _keyer = k; _config = o; if (k instanceof NGramFingerprintKeyer) { try { int size = _config.getJSONObject("params").getInt("ngram-size"); _params = new Object[1]; _params[0] = size; } catch (JSONException e) { //Gridworks.warn("No params specified, using default"); } } } public boolean visit(Project project, int rowIndex, Row row, boolean contextual) { - Cell cell = row.cells.get(_colindex); + Cell cell = row.getCell(_colindex); if (cell != null && cell.value != null) { String v = cell.value.toString(); String s = (v instanceof String) ? ((String) v) : v.toString(); String key = _keyer.key(s,_params); if (_map.containsKey(key)) { Map<String,Integer> m = _map.get(key); if (m.containsKey(v)) { m.put(v, m.get(v) + 1); } else { m.put(v,1); } } else { Map<String,Integer> m = new TreeMap<String,Integer>(); m.put(v,0); _map.put(key, m); } } return false; } public Map<String,Map<String,Integer>> getMap() { return _map; } } public class SizeComparator implements Comparator<Map<String,Integer>> { public int compare(Map<String,Integer> o1, Map<String,Integer> o2) { int s1 = o1.size(); int s2 = o2.size(); if (o1 == o2) { int total1 = 0; for (int i : o1.values()) { total1 += i; } int total2 = 0; for (int i : o2.values()) { total2 += i; } return total2 - total1; } else { return s2 - s1; } } } public class EntriesComparator implements Comparator<Entry<String,Integer>> { public int compare(Entry<String,Integer> o1, Entry<String,Integer> o2) { return o2.getValue() - o1.getValue(); } } public void initializeFromJSON(Project project, JSONObject o) throws Exception { super.initializeFromJSON(project, o); _keyer = _keyers.get(o.getString("function").toLowerCase()); } public void computeClusters(Engine engine) { BinningRowVisitor visitor = new BinningRowVisitor(_keyer,_config); FilteredRows filteredRows = engine.getAllFilteredRows(true); filteredRows.accept(_project, visitor); Map<String,Map<String,Integer>> map = visitor.getMap(); _clusters = new ArrayList<Map<String,Integer>>(map.values()); Collections.sort(_clusters, new SizeComparator()); } public void write(JSONWriter writer, Properties options) throws JSONException { EntriesComparator c = new EntriesComparator(); writer.array(); for (Map<String,Integer> m : _clusters) { if (m.size() > 1) { writer.array(); List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(m.entrySet()); Collections.sort(entries,c); for (Entry<String,Integer> e : entries) { writer.object(); writer.key("v"); writer.value(e.getKey()); writer.key("c"); writer.value(e.getValue()); writer.endObject(); } writer.endArray(); } } writer.endArray(); } }
true
true
public boolean visit(Project project, int rowIndex, Row row, boolean contextual) { Cell cell = row.cells.get(_colindex); if (cell != null && cell.value != null) { String v = cell.value.toString(); String s = (v instanceof String) ? ((String) v) : v.toString(); String key = _keyer.key(s,_params); if (_map.containsKey(key)) { Map<String,Integer> m = _map.get(key); if (m.containsKey(v)) { m.put(v, m.get(v) + 1); } else { m.put(v,1); } } else { Map<String,Integer> m = new TreeMap<String,Integer>(); m.put(v,0); _map.put(key, m); } } return false; }
public boolean visit(Project project, int rowIndex, Row row, boolean contextual) { Cell cell = row.getCell(_colindex); if (cell != null && cell.value != null) { String v = cell.value.toString(); String s = (v instanceof String) ? ((String) v) : v.toString(); String key = _keyer.key(s,_params); if (_map.containsKey(key)) { Map<String,Integer> m = _map.get(key); if (m.containsKey(v)) { m.put(v, m.get(v) + 1); } else { m.put(v,1); } } else { Map<String,Integer> m = new TreeMap<String,Integer>(); m.put(v,0); _map.put(key, m); } } return false; }
diff --git a/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java b/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java index a56950ae..438e3b1e 100644 --- a/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java +++ b/src/uk/me/parabola/mkgmap/reader/osm/SeaGenerator.java @@ -1,895 +1,897 @@ /* * Copyright (C) 2010. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 or * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ package uk.me.parabola.mkgmap.reader.osm; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import uk.me.parabola.imgfmt.MapFailedException; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.LineClipper; import uk.me.parabola.mkgmap.osmstyle.StyleImpl; import uk.me.parabola.util.EnhancedProperties; /** * Code to generate sea polygons from the coastline ways. * * Currently there are a number of different options. * Should pick one that works well and make it the default. * */ public class SeaGenerator extends OsmReadingHooksAdaptor { private static final Logger log = Logger.getLogger(SeaGenerator.class); private boolean generateSeaUsingMP = true; private int maxCoastlineGap; private boolean allowSeaSectors = true; private boolean extendSeaSectors; private String[] landTag = { "natural", "land" }; private boolean floodblocker = false; private int fbGap = 40; private double fbRatio = 0.5d; private int fbThreshold = 20; private boolean fbDebug = false; private ElementSaver saver; private List<Way> shoreline = new ArrayList<Way>(); private boolean roadsReachBoundary; // todo needs setting somehow private boolean generateSeaBackground = true; private String[] coastlineFilenames; private StyleImpl fbRules; /** * Sort out options from the command line. * Returns true only if the option to generate the sea is active, so that * the whole thing is omitted if not used. */ public boolean init(ElementSaver saver, EnhancedProperties props) { this.saver = saver; String gs = props.getProperty("generate-sea", null); boolean generateSea = gs != null; if(generateSea) { for(String o : gs.split(",")) { if("no-mp".equals(o) || "polygon".equals(o) || "polygons".equals(o)) generateSeaUsingMP = false; else if("multipolygon".equals(o)) generateSeaUsingMP = true; else if(o.startsWith("close-gaps=")) maxCoastlineGap = (int)Double.parseDouble(o.substring(11)); else if("no-sea-sectors".equals(o)) allowSeaSectors = false; else if("extend-sea-sectors".equals(o)) { allowSeaSectors = false; extendSeaSectors = true; } else if(o.startsWith("land-tag=")) landTag = o.substring(9).split("="); else if("floodblocker".equals(o)) floodblocker = true; else if(o.startsWith("fbgap=")) fbGap = (int)Double.parseDouble(o.substring("fbgap=".length())); else if(o.startsWith("fbratio=")) fbRatio = Double.parseDouble(o.substring("fbratio=".length())); else if(o.startsWith("fbthres=")) fbThreshold = (int)Double.parseDouble(o.substring("fbthres=".length())); else if("fbdebug".equals(o)) fbDebug = true; else { if(!"help".equals(o)) System.err.println("Unknown sea generation option '" + o + "'"); System.err.println("Known sea generation options are:"); System.err.println(" multipolygon use a multipolygon (default)"); System.err.println(" polygons | no-mp use polygons rather than a multipolygon"); System.err.println(" no-sea-sectors disable use of \"sea sectors\""); System.err.println(" extend-sea-sectors extend coastline to reach border"); System.err.println(" land-tag=TAG=VAL tag to use for land polygons (default natural=land)"); System.err.println(" close-gaps=NUM close gaps in coastline that are less than this distance (metres)"); System.err.println(" floodblocker enable the floodblocker (for multipolgon only)"); System.err.println(" fbgap=NUM points closer to the coastline are ignored for flood blocking (default 40)"); System.err.println(" fbthres=NUM min points contained in a polygon to be flood blocked (default 20)"); System.err.println(" fbratio=NUM min ratio (points/area size) for flood blocking (default 0.5)"); } } if (floodblocker) { try { fbRules = new StyleImpl(null, "floodblocker"); } catch (FileNotFoundException e) { log.error("Cannot load file floodblocker rules. Continue floodblocking disabled."); floodblocker = false; } } String coastlineFileOpt = props.getProperty("coastlinefile", null); if (coastlineFileOpt != null) { coastlineFilenames = coastlineFileOpt.split(","); CoastlineFileLoader.getCoastlineLoader().setCoastlineFiles( coastlineFilenames); CoastlineFileLoader.getCoastlineLoader().loadCoastlines(); log.info("Coastlines loaded"); } else { coastlineFilenames = null; } } return generateSea; } public Set<String> getUsedTags() { HashSet<String> usedTags = new HashSet<String>(); if (coastlineFilenames == null) { usedTags.add("natural"); } if (floodblocker) { usedTags.addAll(fbRules.getUsedTags()); } if (log.isDebugEnabled()) log.debug("Sea generator used tags: "+usedTags); return usedTags; } /** * Test to see if the way is part of the shoreline and if it is * we save it. * @param way The way to test. */ public void onAddWay(Way way) { String natural = way.getTag("natural"); if(natural != null) { if("coastline".equals(natural)) { way.deleteTag("natural"); if (coastlineFilenames == null) shoreline.add(way); } else if (natural.contains(";")) { // cope with compound tag value String others = null; boolean foundCoastline = false; for(String n : natural.split(";")) { if("coastline".equals(n.trim())) foundCoastline = true; else if(others == null) others = n; else others += ";" + n; } if(foundCoastline) { way.deleteTag("natural"); if(others != null) way.addTag("natural", others); if (coastlineFilenames == null) shoreline.add(way); } } } } /** * Joins the given segments to closed ways as good as possible. * @param segments a list of closed and unclosed ways * @return a list of ways completely joined */ public static ArrayList<Way> joinWays(Collection<Way> segments) { ArrayList<Way> joined = new ArrayList<Way>((int)Math.ceil(segments.size()*0.5)); Map<Coord, Way> beginMap = new HashMap<Coord, Way>(); for (Way w : segments) { if (w.isClosed()) { joined.add(w); } else { List<Coord> points = w.getPoints(); beginMap.put(points.get(0), w); } } segments.clear(); int merged = 1; while (merged > 0) { merged = 0; for (Way w1 : beginMap.values()) { if (w1.isClosed()) { // this should not happen log.error("joinWays2: Way "+w1+" is closed but contained in the begin map"); joined.add(w1); beginMap.remove(w1.getPoints().get(0)); merged=1; break; } List<Coord> points1 = w1.getPoints(); Way w2 = beginMap.get(points1.get(points1.size() - 1)); if (w2 != null) { log.info("merging: ", beginMap.size(), w1.getId(), w2.getId()); List<Coord> points2 = w2.getPoints(); Way wm; if (FakeIdGenerator.isFakeId(w1.getId())) { wm = w1; } else { wm = new Way(FakeIdGenerator.makeFakeId()); wm.getPoints().addAll(points1); beginMap.put(points1.get(0), wm); } wm.getPoints().addAll(points2.subList(1, points2.size())); beginMap.remove(points2.get(0)); merged++; if (wm.isClosed()) { joined.add(wm); beginMap.remove(wm.getPoints().get(0)); } break; } } } log.info(joined.size(),"closed ways.",beginMap.size(),"unclosed ways."); joined.addAll(beginMap.values()); return joined; } /** * All done, process the saved shoreline information and construct the polygons. */ public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); - coastRel.setFloodBlockerGap(fbGap); - coastRel.setFloodBlockerRatio(fbRatio); - coastRel.setFloodBlockerThreshold(fbThreshold); - coastRel.setFloodBlockerRules(fbRules.getWayRules()); - coastRel.setLandTag(landTag[0], landTag[1]); - coastRel.setDebug(fbDebug); + if (floodblocker) { + coastRel.setFloodBlockerGap(fbGap); + coastRel.setFloodBlockerRatio(fbRatio); + coastRel.setFloodBlockerThreshold(fbThreshold); + coastRel.setFloodBlockerRules(fbRules.getWayRules()); + coastRel.setLandTag(landTag[0], landTag[1]); + coastRel.setDebug(fbDebug); + } saver.addRelation(coastRel); } } /** * Clip the shoreline ways to the bounding box of the map. * @param shoreline All the the ways making up the coast. * @param bounds The map bounds. */ private void clipShorlineSegments(List<Way> shoreline, Area bounds) { List<Way> toBeRemoved = new ArrayList<Way>(); List<Way> toBeAdded = new ArrayList<Way>(); for (Way segment : shoreline) { List<Coord> points = segment.getPoints(); List<List<Coord>> clipped = LineClipper.clip(bounds, points); if (clipped != null) { log.info("clipping", segment); toBeRemoved.add(segment); for (List<Coord> pts : clipped) { long id = FakeIdGenerator.makeFakeId(); Way shore = new Way(id, pts); toBeAdded.add(shore); } } } log.info("clipping: adding ", toBeAdded.size(), ", removing ", toBeRemoved.size()); shoreline.removeAll(toBeRemoved); shoreline.addAll(toBeAdded); } /** * Pick out the islands and save them for later. They are removed from the * shore line list and added to the island list. * * @param shoreline The collected shore line ways. * @param seaBounds The map boundary. * @param islands The islands are saved to this list. */ private void handleIslands(List<Way> shoreline, Area seaBounds, List<Way> islands) { Iterator<Way> it = shoreline.iterator(); while (it.hasNext()) { Way w = it.next(); if (w.isClosed()) { log.info("adding island", w); islands.add(w); it.remove(); } } closeGaps(shoreline, seaBounds); // there may be more islands now it = shoreline.iterator(); while (it.hasNext()) { Way w = it.next(); if (w.isClosed()) { log.debug("island after concatenating"); islands.add(w); it.remove(); } } } private boolean createInnerWays(Area seaBounds, List<Way> islands, SortedMap<EdgeHit, Way> hitMap) { NavigableSet<EdgeHit> hits = (NavigableSet<EdgeHit>) hitMap.keySet(); boolean shorelineReachesBoundary = false; while (!hits.isEmpty()) { long id = FakeIdGenerator.makeFakeId(); Way w = new Way(id); saver.addWay(w); EdgeHit hit = hits.first(); EdgeHit hFirst = hit; do { Way segment = hitMap.get(hit); log.info("current hit:", hit); EdgeHit hNext; if (segment != null) { // add the segment and get the "ending hit" log.info("adding:", segment); for(Coord p : segment.getPoints()) w.addPointIfNotEqualToLastPoint(p); hNext = getEdgeHit(seaBounds, segment.getPoints().get(segment.getPoints().size()-1)); } else { w.addPointIfNotEqualToLastPoint(hit.getPoint(seaBounds)); hNext = hits.higher(hit); if (hNext == null) hNext = hFirst; Coord p; if (hit.compareTo(hNext) < 0) { log.info("joining: ", hit, hNext); for (int i=hit.edge; i<hNext.edge; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } } else if (hit.compareTo(hNext) > 0) { log.info("joining: ", hit, hNext); for (int i=hit.edge; i<4; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } for (int i=0; i<hNext.edge; i++) { EdgeHit corner = new EdgeHit(i, 1.0); p = corner.getPoint(seaBounds); log.debug("way: ", corner, p); w.addPointIfNotEqualToLastPoint(p); } } w.addPointIfNotEqualToLastPoint(hNext.getPoint(seaBounds)); } hits.remove(hit); hit = hNext; } while (!hits.isEmpty() && !hit.equals(hFirst)); if (!w.isClosed()) w.getPoints().add(w.getPoints().get(0)); log.info("adding non-island landmass, hits.size()=" + hits.size()); islands.add(w); shorelineReachesBoundary = true; } return shorelineReachesBoundary; } /** * An 'anti-island' is something that has been detected as an island, but the water * is on the inside. I think you would call this a lake. * @param seaRelation The relation holding the sea. Only set if we are using multi-polygons for * the sea. * @param islands The island list that was found earlier. * @return The so-called anti-islands. */ private List<Way> removeAntiIslands(Relation seaRelation, List<Way> islands) { List<Way> antiIslands = new ArrayList<Way>(); for (Way w : islands) { if (!FakeIdGenerator.isFakeId(w.getId())) { Way w1 = new Way(FakeIdGenerator.makeFakeId()); w1.getPoints().addAll(w.getPoints()); // only copy the name tags for(String tag : w) if(tag.equals("name") || tag.endsWith(":name")) w1.addTag(tag, w.getTag(tag)); w = w1; } // determine where the water is if (w.clockwise()) { // water on the inside of the poly, it's an // "anti-island" so tag with natural=water (to // make it visible above the land) w.addTag("natural", "water"); antiIslands.add(w); saver.addWay(w); } else { // water on the outside of the poly, it's an island w.addTag(landTag[0], landTag[1]); saver.addWay(w); if(generateSeaUsingMP) { // create a "inner" way for each island seaRelation.addElement("inner", w); } } } islands.removeAll(antiIslands); return antiIslands; } /** * Find the points where the remaining shore line segments intersect with the * map boundary. * * @param shoreline The remaining shore line segments. * @param seaBounds The map boundary. * @param seaRelation If we are using a multi-polygon, this is it. Otherwise it will be null. * @return A map of the 'hits' where the shore line intersects the boundary. */ private SortedMap<EdgeHit, Way> findIntesectionPoints(List<Way> shoreline, Area seaBounds, Relation seaRelation) { assert !generateSeaUsingMP || seaRelation != null; SortedMap<EdgeHit, Way> hitMap = new TreeMap<EdgeHit, Way>(); for (Way w : shoreline) { List<Coord> points = w.getPoints(); Coord pStart = points.get(0); Coord pEnd = points.get(points.size()-1); EdgeHit hStart = getEdgeHit(seaBounds, pStart); EdgeHit hEnd = getEdgeHit(seaBounds, pEnd); if (hStart == null || hEnd == null) { /* * This problem occurs usually when the shoreline is cut by osmosis (e.g. country-extracts from geofabrik) * There are two possibilities to solve this problem: * 1. Close the way and treat it as an island. This is sometimes the best solution (Germany: Usedom at the * border to Poland) * 2. Create a "sea sector" only for this shoreline segment. This may also be the best solution * (see German border to the Netherlands where the shoreline continues in the Netherlands) * The first choice may lead to "flooded" areas, the second may lead to "triangles". * * Usually, the first choice is appropriate if the segment is "nearly" closed. */ double length = 0; Coord p0 = pStart; for (Coord p1 : points.subList(1, points.size()-1)) { length += p0.distance(p1); p0 = p1; } boolean nearlyClosed = pStart.distance(pEnd) < 0.1 * length; if (nearlyClosed) { // close the way points.add(pStart); if(!FakeIdGenerator.isFakeId(w.getId())) { Way w1 = new Way(FakeIdGenerator.makeFakeId()); w1.getPoints().addAll(w.getPoints()); // only copy the name tags for(String tag : w) if(tag.equals("name") || tag.endsWith(":name")) w1.addTag(tag, w.getTag(tag)); w = w1; } w.addTag(landTag[0], landTag[1]); saver.addWay(w); if(generateSeaUsingMP) { seaRelation.addElement("inner", w); } } else if(allowSeaSectors) { long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); sea.getPoints().addAll(points); sea.addPoint(new Coord(pEnd.getLatitude(), pStart.getLongitude())); sea.addPoint(pStart); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) seaRelation.addElement("outer", sea); generateSeaBackground = false; } else if (extendSeaSectors) { // create additional points at next border to prevent triangles from point 2 if (null == hStart) { hStart = getNextEdgeHit(seaBounds, pStart); w.getPoints().add(0, hStart.getPoint(seaBounds)); } if (null == hEnd) { hEnd = getNextEdgeHit(seaBounds, pEnd); w.getPoints().add(hEnd.getPoint(seaBounds)); } log.debug("hits (second try): ", hStart, hEnd); hitMap.put(hStart, w); hitMap.put(hEnd, null); } else { // show the coastline even though we can't produce // a polygon for the land w.addTag("natural", "coastline"); saver.addWay(w); } } else { log.debug("hits: ", hStart, hEnd); hitMap.put(hStart, w); hitMap.put(hEnd, null); } } return hitMap; } /** * Specifies where an edge of the bounding box is hit. */ private static class EdgeHit implements Comparable<EdgeHit> { private final int edge; private final double t; EdgeHit(int edge, double t) { this.edge = edge; this.t = t; } public int compareTo(EdgeHit o) { if (edge < o.edge) return -1; else if (edge > o.edge) return +1; else if (t > o.t) return +1; else if (t < o.t) return -1; else return 0; } public boolean equals(Object o) { if (o instanceof EdgeHit) { EdgeHit h = (EdgeHit) o; return (h.edge == edge && Double.compare(h.t, t) == 0); } else return false; } private Coord getPoint(Area a) { log.info("getPoint: ", this, a); switch (edge) { case 0: return new Coord(a.getMinLat(), (int) (a.getMinLong() + t * (a.getMaxLong()-a.getMinLong()))); case 1: return new Coord((int)(a.getMinLat() + t * (a.getMaxLat()-a.getMinLat())), a.getMaxLong()); case 2: return new Coord(a.getMaxLat(), (int)(a.getMaxLong() - t * (a.getMaxLong()-a.getMinLong()))); case 3: return new Coord((int)(a.getMaxLat() - t * (a.getMaxLat()-a.getMinLat())), a.getMinLong()); default: throw new MapFailedException("illegal state"); } } public String toString() { return "EdgeHit " + edge + "@" + t; } } private EdgeHit getEdgeHit(Area a, Coord p) { return getEdgeHit(a, p, 10); } private EdgeHit getEdgeHit(Area a, Coord p, int tolerance) { int lat = p.getLatitude(); int lon = p.getLongitude(); int minLat = a.getMinLat(); int maxLat = a.getMaxLat(); int minLong = a.getMinLong(); int maxLong = a.getMaxLong(); log.info(String.format("getEdgeHit: (%d %d) (%d %d %d %d)", lat, lon, minLat, minLong, maxLat, maxLong)); if (lat <= minLat+tolerance) { return new EdgeHit(0, ((double)(lon - minLong))/(maxLong-minLong)); } else if (lon >= maxLong-tolerance) { return new EdgeHit(1, ((double)(lat - minLat))/(maxLat-minLat)); } else if (lat >= maxLat-tolerance) { return new EdgeHit(2, ((double)(maxLong - lon))/(maxLong-minLong)); } else if (lon <= minLong+tolerance) { return new EdgeHit(3, ((double)(maxLat - lat))/(maxLat-minLat)); } else return null; } /** * Find the nearest edge for supplied Coord p. */ private EdgeHit getNextEdgeHit(Area a, Coord p) { int lat = p.getLatitude(); int lon = p.getLongitude(); int minLat = a.getMinLat(); int maxLat = a.getMaxLat(); int minLong = a.getMinLong(); int maxLong = a.getMaxLong(); log.info(String.format("getNextEdgeHit: (%d %d) (%d %d %d %d)", lat, lon, minLat, minLong, maxLat, maxLong)); // shortest distance to border (init with distance to southern border) int min = lat - minLat; // number of edge as used in getEdgeHit. // 0 = southern // 1 = eastern // 2 = northern // 3 = western edge of Area a int i = 0; // normalized position at border (0..1) double l = ((double)(lon - minLong))/(maxLong-minLong); // now compare distance to eastern border with already known distance if (maxLong - lon < min) { // update data if distance is shorter min = maxLong - lon; i = 1; l = ((double)(lat - minLat))/(maxLat-minLat); } // same for northern border if (maxLat - lat < min) { min = maxLat - lat; i = 2; l = ((double)(maxLong - lon))/(maxLong-minLong); } // same for western border if (lon - minLong < min) { i = 3; l = ((double)(maxLat - lat))/(maxLat-minLat); } // now created the EdgeHit for found values return new EdgeHit(i, l); } private void closeGaps(List<Way> ways, Area bounds) { // join up coastline segments whose end points are less than // maxCoastlineGap metres apart if (maxCoastlineGap > 0) { boolean changed = true; while (changed) { changed = false; for (Way w1 : ways) { if(w1.isClosed()) continue; List<Coord> points1 = w1.getPoints(); Coord w1e = points1.get(points1.size() - 1); if(bounds.onBoundary(w1e)) continue; Way nearest = null; double smallestGap = Double.MAX_VALUE; for (Way w2 : ways) { if(w1 == w2 || w2.isClosed()) continue; List<Coord> points2 = w2.getPoints(); Coord w2s = points2.get(0); if(bounds.onBoundary(w2s)) continue; double gap = w1e.distance(w2s); if(gap < smallestGap) { nearest = w2; smallestGap = gap; } } if (nearest != null && smallestGap < maxCoastlineGap) { Coord w2s = nearest.getPoints().get(0); log.warn("Bridging " + (int)smallestGap + "m gap in coastline from " + w1e.toOSMURL() + " to " + w2s.toOSMURL()); Way wm; if (FakeIdGenerator.isFakeId(w1.getId())) { wm = w1; } else { wm = new Way(FakeIdGenerator.makeFakeId()); ways.remove(w1); ways.add(wm); wm.getPoints().addAll(points1); wm.copyTags(w1); } wm.getPoints().addAll(nearest.getPoints()); ways.remove(nearest); // make a line that shows the filled gap Way w = new Way(FakeIdGenerator.makeFakeId()); w.addTag("natural", "mkgmap:coastline-gap"); w.addPoint(w1e); w.addPoint(w2s); saver.addWay(w); changed = true; break; } } } } } }
true
true
public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); coastRel.setFloodBlockerGap(fbGap); coastRel.setFloodBlockerRatio(fbRatio); coastRel.setFloodBlockerThreshold(fbThreshold); coastRel.setFloodBlockerRules(fbRules.getWayRules()); coastRel.setLandTag(landTag[0], landTag[1]); coastRel.setDebug(fbDebug); saver.addRelation(coastRel); } }
public void end() { Area seaBounds = saver.getBoundingBox(); if (coastlineFilenames == null) { log.info("Shorelines before join", shoreline.size()); shoreline = joinWays(shoreline); } else { shoreline.addAll(CoastlineFileLoader.getCoastlineLoader() .getCoastlines(seaBounds)); log.info("Shorelines from extra file:", shoreline.size()); } int closedS = 0; int unclosedS = 0; for (Way w : shoreline) { if (w.isClosed()) { closedS++; } else { unclosedS++; } } log.info("Closed shorelines", closedS); log.info("Unclosed shorelines", unclosedS); // clip all shoreline segments clipShorlineSegments(shoreline, seaBounds); log.info("generating sea, seaBounds=", seaBounds); int minLat = seaBounds.getMinLat(); int maxLat = seaBounds.getMaxLat(); int minLong = seaBounds.getMinLong(); int maxLong = seaBounds.getMaxLong(); Coord nw = new Coord(minLat, minLong); Coord ne = new Coord(minLat, maxLong); Coord sw = new Coord(maxLat, minLong); Coord se = new Coord(maxLat, maxLong); if(shoreline.isEmpty()) { // no sea required // even though there is no sea, generate a land // polygon so that the tile's background colour will // match the land colour on the tiles that do contain // some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); // no matter if the multipolygon option is used it is // only necessary to create a land polygon saver.addWay(land); // nothing more to do return; } long multiId = FakeIdGenerator.makeFakeId(); Relation seaRelation = null; if(generateSeaUsingMP) { log.debug("Generate seabounds relation",multiId); seaRelation = new GeneralRelation(multiId); seaRelation.addTag("type", "multipolygon"); seaRelation.addTag("natural", "sea"); } List<Way> islands = new ArrayList<Way>(); // handle islands (closed shoreline components) first (they're easy) handleIslands(shoreline, seaBounds, islands); // the remaining shoreline segments should intersect the boundary // find the intersection points and store them in a SortedMap SortedMap<EdgeHit, Way> hitMap = findIntesectionPoints(shoreline, seaBounds, seaRelation); // now construct inner ways from these segments boolean shorelineReachesBoundary = createInnerWays(seaBounds, islands, hitMap); if(!shorelineReachesBoundary && roadsReachBoundary) { // try to avoid tiles being flooded by anti-lakes or other // bogus uses of natural=coastline generateSeaBackground = false; } List<Way> antiIslands = removeAntiIslands(seaRelation, islands); if (islands.isEmpty()) { // the tile doesn't contain any islands so we can assume // that it's showing a land mass that contains some // enclosed sea areas - in which case, we don't want a sea // coloured background generateSeaBackground = false; } if (generateSeaBackground) { // the background is sea so all anti-islands should be // contained by land otherwise they won't be visible for (Way ai : antiIslands) { boolean containedByLand = false; for(Way i : islands) { if(i.containsPointsOf(ai)) { containedByLand = true; break; } } if (!containedByLand) { // found an anti-island that is not contained by // land so convert it back into an island ai.deleteTag("natural"); ai.addTag(landTag[0], landTag[1]); if (generateSeaUsingMP) { // create a "inner" way for the island assert seaRelation != null; seaRelation.addElement("inner", ai); } log.warn("Converting anti-island starting at", ai.getPoints().get(0).toOSMURL() , "into an island as it is surrounded by water"); } } long seaId = FakeIdGenerator.makeFakeId(); Way sea = new Way(seaId); // the sea background area must be a little bigger than all // inner land areas. this is a workaround for a mp shortcoming: // mp is not able to combine outer and inner if they intersect // or have overlaying lines // the added area will be clipped later by the style generator sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addPoint(new Coord(sw.getLatitude() + 1, sw.getLongitude() - 1)); sea.addPoint(new Coord(se.getLatitude() + 1, se.getLongitude() + 1)); sea.addPoint(new Coord(ne.getLatitude() - 1, ne.getLongitude() + 1)); sea.addPoint(new Coord(nw.getLatitude() - 1, nw.getLongitude() - 1)); sea.addTag("natural", "sea"); log.info("sea: ", sea); saver.addWay(sea); if(generateSeaUsingMP) { assert seaRelation != null; seaRelation.addElement("outer", sea); } } else { // background is land // generate a land polygon so that the tile's // background colour will match the land colour on the // tiles that do contain some sea long landId = FakeIdGenerator.makeFakeId(); Way land = new Way(landId); land.addPoint(nw); land.addPoint(sw); land.addPoint(se); land.addPoint(ne); land.addPoint(nw); land.addTag(landTag[0], landTag[1]); saver.addWay(land); if (generateSeaUsingMP) { seaRelation.addElement("inner", land); } } if (generateSeaUsingMP) { SeaPolygonRelation coastRel = saver.createSeaPolyRelation(seaRelation); coastRel.setFloodBlocker(floodblocker); if (floodblocker) { coastRel.setFloodBlockerGap(fbGap); coastRel.setFloodBlockerRatio(fbRatio); coastRel.setFloodBlockerThreshold(fbThreshold); coastRel.setFloodBlockerRules(fbRules.getWayRules()); coastRel.setLandTag(landTag[0], landTag[1]); coastRel.setDebug(fbDebug); } saver.addRelation(coastRel); } }
diff --git a/zxingorg/src/com/google/zxing/web/DecodeServlet.java b/zxingorg/src/com/google/zxing/web/DecodeServlet.java index e3245c1d..70a35556 100644 --- a/zxingorg/src/com/google/zxing/web/DecodeServlet.java +++ b/zxingorg/src/com/google/zxing/web/DecodeServlet.java @@ -1,402 +1,405 @@ /* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.web; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.GlobalHistogramBinarizer; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.multi.GenericMultipleBarcodeReader; import com.google.zxing.multi.MultipleBarcodeReader; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.Header; import org.apache.http.HttpMessage; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.HttpEntity; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import java.awt.color.CMMException; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link HttpServlet} which decodes images containing barcodes. Given a URL, it will * retrieve the image and decode it. It can also process image files uploaded via POST. * * @author Sean Owen */ public final class DecodeServlet extends HttpServlet { // No real reason to let people upload more than a 2MB image private static final long MAX_IMAGE_SIZE = 2000000L; // No real reason to deal with more than maybe 2 megapixels private static final int MAX_PIXELS = 1 << 21; private static final Logger log = Logger.getLogger(DecodeServlet.class.getName()); static final Hashtable<DecodeHintType, Object> HINTS; static final Hashtable<DecodeHintType, Object> HINTS_PURE; static { HINTS = new Hashtable<DecodeHintType, Object>(5); HINTS.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); Collection<BarcodeFormat> possibleFormats = new Vector<BarcodeFormat>(); possibleFormats.add(BarcodeFormat.UPC_A); possibleFormats.add(BarcodeFormat.UPC_E); possibleFormats.add(BarcodeFormat.EAN_8); possibleFormats.add(BarcodeFormat.EAN_13); possibleFormats.add(BarcodeFormat.CODE_39); possibleFormats.add(BarcodeFormat.CODE_128); possibleFormats.add(BarcodeFormat.ITF); possibleFormats.add(BarcodeFormat.RSS14); possibleFormats.add(BarcodeFormat.QR_CODE); possibleFormats.add(BarcodeFormat.DATAMATRIX); possibleFormats.add(BarcodeFormat.PDF417); HINTS.put(DecodeHintType.POSSIBLE_FORMATS, possibleFormats); HINTS_PURE = new Hashtable<DecodeHintType, Object>(HINTS); HINTS_PURE.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE); } private HttpParams params; private SchemeRegistry registry; private DiskFileItemFactory diskFileItemFactory; @Override public void init(ServletConfig servletConfig) { Logger logger = Logger.getLogger("com.google.zxing"); logger.addHandler(new ServletContextLogHandler(servletConfig.getServletContext())); params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); diskFileItemFactory = new DiskFileItemFactory(); log.info("DecodeServlet configured"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.length() == 0) { log.fine("URI was empty"); response.sendRedirect("badurl.jspx"); return; } imageURIString = imageURIString.trim(); if (!(imageURIString.startsWith("http://") || imageURIString.startsWith("https://"))) { imageURIString = "http://" + imageURIString; } URI imageURI; try { imageURI = new URI(imageURIString); } catch (URISyntaxException urise) { log.fine("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } ClientConnectionManager connectionManager = new SingleClientConnManager(params, registry); HttpClient client = new DefaultHttpClient(connectionManager, params); HttpUriRequest getRequest = new HttpGet(imageURI); getRequest.addHeader("Connection", "close"); // Avoids CLOSE_WAIT socket issue? try { HttpResponse getResponse; try { getResponse = client.execute(getRequest); } catch (IllegalArgumentException iae) { // Thrown if hostname is bad or null log.fine(iae.toString()); getRequest.abort(); response.sendRedirect("badurl.jspx"); return; } catch (IOException ioe) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.fine(ioe.toString()); getRequest.abort(); response.sendRedirect("badurl.jspx"); return; } if (getResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { log.fine("Unsuccessful return code: " + getResponse.getStatusLine().getStatusCode()); response.sendRedirect("badurl.jspx"); return; } if (!isSizeOK(getResponse)) { log.fine("Too large"); response.sendRedirect("badimage.jspx"); return; } log.info("Decoding " + imageURI); HttpEntity entity = getResponse.getEntity(); InputStream is = entity.getContent(); try { processStream(is, request, response); } finally { entity.consumeContent(); is.close(); } } finally { connectionManager.shutdown(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { log.fine("File upload was not multipart"); response.sendRedirect("badimage.jspx"); return; } ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setFileSizeMax(MAX_IMAGE_SIZE); // Parse the request try { for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { if (!item.isFormField()) { if (item.getSize() <= MAX_IMAGE_SIZE) { log.info("Decoding uploaded file"); InputStream is = item.getInputStream(); try { processStream(is, request, response); } finally { is.close(); } } else { log.fine("Too large"); response.sendRedirect("badimage.jspx"); } break; } } } catch (FileUploadException fue) { log.fine(fue.toString()); response.sendRedirect("badimage.jspx"); } } private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } - if (image == null || - image.getHeight() <= 1 || image.getWidth() <= 1 || + if (image == null) { + response.sendRedirect("badimage.jspx"); + return; + } + if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } } private static void handleException(ReaderException re, HttpServletResponse response) throws IOException { if (re instanceof NotFoundException) { log.info("Not found: " + re); response.sendRedirect("notfound.jspx"); } else if (re instanceof FormatException) { log.info("Format problem: " + re); response.sendRedirect("format.jspx"); } else if (re instanceof ChecksumException) { log.info("Checksum problem: " + re); response.sendRedirect("format.jspx"); } else { log.info("Unknown problem: " + re); response.sendRedirect("notfound.jspx"); } } private static boolean isSizeOK(HttpMessage getResponse) { Header lengthHeader = getResponse.getLastHeader("Content-Length"); if (lengthHeader != null) { long length = Long.parseLong(lengthHeader.getValue()); if (length > MAX_IMAGE_SIZE) { return false; } } return true; } @Override public void destroy() { log.config("DecodeServlet shutting down..."); } }
true
true
private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } if (image == null || image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
private static void processStream(InputStream is, ServletRequest request, HttpServletResponse response) throws ServletException, IOException { BufferedImage image; try { image = ImageIO.read(is); } catch (IOException ioe) { log.fine(ioe.toString()); // Includes javax.imageio.IIOException response.sendRedirect("badimage.jspx"); return; } catch (CMMException cmme) { log.fine(cmme.toString()); // Have seen this in logs response.sendRedirect("badimage.jspx"); return; } catch (IllegalArgumentException iae) { log.fine(iae.toString()); // Have seen this in logs for some JPEGs response.sendRedirect("badimage.jspx"); return; } if (image == null) { response.sendRedirect("badimage.jspx"); return; } if (image.getHeight() <= 1 || image.getWidth() <= 1 || image.getHeight() * image.getWidth() > MAX_PIXELS) { log.fine("Dimensions too large: " + image.getWidth() + 'x' + image.getHeight()); response.sendRedirect("badimage.jspx"); return; } Reader reader = new MultiFormatReader(); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = new ArrayList<Result>(1); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } if (request.getParameter("full") == null) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF8"); Writer out = new OutputStreamWriter(response.getOutputStream(), "UTF8"); try { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } finally { out.close(); } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
diff --git a/src/com/modcrafting/diablodrops/drops/DropUtils.java b/src/com/modcrafting/diablodrops/drops/DropUtils.java index 29ed21d..1ad358e 100644 --- a/src/com/modcrafting/diablodrops/drops/DropUtils.java +++ b/src/com/modcrafting/diablodrops/drops/DropUtils.java @@ -1,733 +1,740 @@ package com.modcrafting.diablodrops.drops; import java.util.Random; import org.bukkit.Material; public class DropUtils { Random gen = new Random(); /** * Returns an array of Materials that the plugin can use * * @return all items that the plugin can use */ public Material[] allItems() { return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_PICKAXE, Material.DIAMOND_SPADE, Material.DIAMOND_AXE, - Material.DIAMOND_HOE, Material.IRON_SWORD, - Material.IRON_PICKAXE, Material.IRON_SPADE, Material.IRON_AXE, - Material.IRON_HOE, Material.GOLD_SWORD, Material.GOLD_PICKAXE, - Material.GOLD_SPADE, Material.GOLD_AXE, Material.GOLD_HOE, + Material.DIAMOND_HOE, + Material.IRON_SWORD, Material.IRON_PICKAXE, + Material.IRON_SPADE, Material.IRON_AXE, + Material.IRON_HOE, + Material.GOLD_SWORD, Material.GOLD_PICKAXE, + Material.GOLD_SPADE, Material.GOLD_AXE, + Material.GOLD_HOE, Material.STONE_SWORD, Material.STONE_PICKAXE, - Material.STONE_SPADE, Material.STONE_AXE, Material.STONE_HOE, + Material.STONE_SPADE, Material.STONE_AXE, + Material.STONE_HOE, Material.WOOD_SWORD, Material.WOOD_PICKAXE, - Material.WOOD_SPADE, Material.WOOD_AXE, Material.WOOD_HOE, + Material.WOOD_SPADE, Material.WOOD_AXE, + Material.WOOD_HOE, Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS, - Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.BOW + Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, + Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, + Material.BOW }; } /** * Returns the helmet, chestplate, leggings, and boots of a random material * type * * @return the helmet, chestplate, leggings, and boots of a random material */ public Material[] armorPicker() { switch (gen.nextInt(5)) { case 0: return diamondArmor(); case 1: return ironArmor(); case 2: return chainmailArmor(); case 3: return goldArmor(); case 4: return leatherArmor(); default: return null; } } /** * Returns the helmet, chestplate, leggings, and boots * * @return helmet, chestplate, leggings, and boots */ public Material[] chainmailArmor() { return new Material[] { Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS }; } /** * Returns the helmet, chestplate, leggings, and boots * * @return helmet, chestplate, leggings, and boots */ public Material[] diamondArmor() { return new Material[] { Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS }; } /** * Returns a kind of diamond tool * 1 - DIAMOND_SWORD * 2 - DIAMOND_PICKAXE * 3 - DIAMOND_SPADE * 4 - DIAMOND_AXE * 5 - DIAMOND_HOE * * @param kind * to return * @return kind of diamond tool */ public Material diamondWeapon(int num) { switch (num) { case 1: return Material.DIAMOND_SWORD; case 2: return Material.DIAMOND_PICKAXE; case 3: return Material.DIAMOND_SPADE; case 4: return Material.DIAMOND_AXE; case 5: return Material.DIAMOND_HOE; default: return null; } } /** * Gets a random kind of boot * * @return random kind of boot */ public Material getBoots() { switch (gen.nextInt(5)) { case 0: return Material.LEATHER_BOOTS; case 1: return Material.GOLD_BOOTS; case 2: return Material.CHAINMAIL_BOOTS; case 3: return Material.IRON_BOOTS; case 4: return Material.DIAMOND_BOOTS; default: return null; } } /** * Gets random kind of chestplate * * @return random kind of chestplate */ public Material getChestPlate() { switch (gen.nextInt(5)) { case 0: return Material.LEATHER_CHESTPLATE; case 1: return Material.GOLD_CHESTPLATE; case 2: return Material.CHAINMAIL_CHESTPLATE; case 3: return Material.IRON_CHESTPLATE; case 4: return Material.DIAMOND_CHESTPLATE; default: return null; } } /** * Gets random kind of helmet * * @return random kind of helmet */ public Material getHelmet() { switch (gen.nextInt(5)) { case 0: return Material.LEATHER_HELMET; case 1: return Material.GOLD_HELMET; case 2: return Material.CHAINMAIL_HELMET; case 3: return Material.IRON_HELMET; case 4: return Material.DIAMOND_HELMET; default: return null; } } /** * Gets random kind of leggings * * @return random kind of leggings */ public Material getLeggings() { switch (gen.nextInt(5)) { case 0: return Material.LEATHER_LEGGINGS; case 1: return Material.GOLD_LEGGINGS; case 2: return Material.CHAINMAIL_LEGGINGS; case 3: return Material.IRON_LEGGINGS; case 4: return Material.DIAMOND_LEGGINGS; default: return null; } } /** * Gets random kind of sword * * @return random kind of sword */ public Material getSword() { switch (gen.nextInt(5)) { case 0: return Material.WOOD_SWORD; case 1: return Material.STONE_SWORD; case 2: return Material.GOLD_SWORD; case 3: return Material.IRON_SWORD; case 4: return Material.DIAMOND_SWORD; default: return null; } } /** * Gets random kind of pickaxe * * @return random kind of pickaxe */ public Material getPickaxe() { switch (gen.nextInt(5)) { case 0: return Material.WOOD_PICKAXE; case 1: return Material.STONE_PICKAXE; case 2: return Material.GOLD_PICKAXE; case 3: return Material.IRON_PICKAXE; case 4: return Material.DIAMOND_PICKAXE; default: return null; } } /** * Gets random type of axe * * @return random type of axe */ public Material getAxe() { switch (gen.nextInt(5)) { case 0: return Material.WOOD_AXE; case 1: return Material.STONE_AXE; case 2: return Material.GOLD_AXE; case 3: return Material.IRON_AXE; case 4: return Material.DIAMOND_AXE; default: return null; } } /** * Gets random kind of spade * * @return random kind of spade */ public Material getSpade() { switch (gen.nextInt(5)) { case 0: return Material.WOOD_SPADE; case 1: return Material.STONE_SPADE; case 2: return Material.GOLD_SPADE; case 3: return Material.IRON_SPADE; case 4: return Material.DIAMOND_SPADE; default: return null; } } /** * Gets random kind of hoe * * @return random kind of hoe */ public Material getHoe() { switch (gen.nextInt(5)) { case 0: return Material.WOOD_HOE; case 1: return Material.STONE_HOE; case 2: return Material.GOLD_HOE; case 3: return Material.IRON_HOE; case 4: return Material.DIAMOND_HOE; default: return null; } } /** * Returns the helmet, chestplate, leggings, and boots * * @return helmet, chestplate, leggings, and boots */ public Material[] goldArmor() { return new Material[] { Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS }; } /** * Returns a kind of gold tool * 1 - GOLD_SWORD * 2 - GOLD_PICKAXE * 3 - GOLD_SPADE * 4 - GOLD_AXE * 5 - GOLD_HOE * * @param kind * to return * @return kind of gold tool */ public Material goldWeapon(int num) { switch (num) { case 1: return Material.GOLD_SWORD; case 2: return Material.GOLD_PICKAXE; case 3: return Material.GOLD_SPADE; case 4: return Material.GOLD_AXE; case 5: return Material.GOLD_HOE; default: return null; } } /** * Returns the helmet, chestplate, leggings, and boots * * @return helmet, chestplate, leggings, and boots */ public Material[] ironArmor() { return new Material[] { Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS }; } /** * Returns a kind of iron tool * 1 - IRON_SWORD * 2 - IRON_PICKAXE * 3 - IRON_SPADE * 4 - IRON_AXE * 5 - IRON_HOE * * @param kind * to return * @return kind of iron tool */ public Material ironWeapon(int num) { switch (num) { case 1: return Material.IRON_SWORD; case 2: return Material.IRON_PICKAXE; case 3: return Material.IRON_SPADE; case 4: return Material.IRON_AXE; case 5: return Material.IRON_HOE; default: return null; } } /** * Is material a piece of armor? * * @param material * to check * @return is armor or not */ public boolean isArmor(Material mat) { if (isHelmet(mat) || isBoots(mat) || isChestPlate(mat) || isLeggings(mat)) { return true; } return false; } /** * Is material an axe? * * @param material * to check * @return is axe or not */ public boolean isAxe(Material mat) { if (mat.equals(Material.WOOD_AXE) || mat.equals(Material.STONE_AXE) || mat.equals(Material.GOLD_AXE) || mat.equals(Material.IRON_AXE) || mat.equals(Material.DIAMOND_AXE)) return true; return false; } /** * Is material boots? * * @param material * to check * @return is boots or not */ public boolean isBoots(Material mat) { if (mat.equals(Material.LEATHER_BOOTS) || mat.equals(Material.GOLD_BOOTS) || mat.equals(Material.CHAINMAIL_BOOTS) || mat.equals(Material.IRON_BOOTS) || mat.equals(Material.DIAMOND_BOOTS)) { return true; } return false; } /** * Is material a chestplate? * * @param material * to check * @return is chestplate or not */ public boolean isChestPlate(Material mat) { if (mat.equals(Material.LEATHER_CHESTPLATE) || mat.equals(Material.GOLD_CHESTPLATE) || mat.equals(Material.CHAINMAIL_CHESTPLATE) || mat.equals(Material.IRON_CHESTPLATE) || mat.equals(Material.DIAMOND_CHESTPLATE)) { return true; } return false; } /** * Is material a helmet? * * @param material * to check * @return is helmet or not */ public boolean isHelmet(Material mat) { if (mat.equals(Material.LEATHER_HELMET) || mat.equals(Material.GOLD_HELMET) || mat.equals(Material.CHAINMAIL_HELMET) || mat.equals(Material.IRON_HELMET) || mat.equals(Material.DIAMOND_HELMET)) { return true; } return false; } /** * Is material a hoe? * * @param material * to check * @return is hoe or not */ public boolean isHoe(Material mat) { if (mat.equals(Material.WOOD_HOE) || mat.equals(Material.STONE_HOE) || mat.equals(Material.GOLD_HOE) || mat.equals(Material.IRON_HOE) || mat.equals(Material.DIAMOND_HOE)) return true; return false; } /** * Is material leggings? * * @param material * to check * @return is leggings or not */ public boolean isLeggings(Material mat) { if (mat.equals(Material.LEATHER_LEGGINGS) || mat.equals(Material.GOLD_LEGGINGS) || mat.equals(Material.CHAINMAIL_LEGGINGS) || mat.equals(Material.IRON_LEGGINGS) || mat.equals(Material.DIAMOND_LEGGINGS)) { return true; } return false; } /** * Is material a pickaxe? * * @param material * to check * @return is pickaxe or not */ public boolean isPickaxe(Material mat) { if (mat.equals(Material.WOOD_PICKAXE) || mat.equals(Material.STONE_PICKAXE) || mat.equals(Material.GOLD_PICKAXE) || mat.equals(Material.IRON_PICKAXE) || mat.equals(Material.DIAMOND_PICKAXE)) return true; return false; } /** * Is material a spade? * * @param material * to check * @return is spade or not */ public boolean isSpade(Material mat) { if (mat.equals(Material.WOOD_SPADE) || mat.equals(Material.STONE_SPADE) || mat.equals(Material.GOLD_SPADE) || mat.equals(Material.IRON_SPADE) || mat.equals(Material.DIAMOND_SPADE)) return true; return false; } /** * Is material a sword? * * @param material * to check * @return is sword or not */ public boolean isSword(Material mat) { if (mat.equals(Material.WOOD_SWORD) || mat.equals(Material.STONE_SWORD) || mat.equals(Material.GOLD_SWORD) || mat.equals(Material.IRON_SWORD) || mat.equals(Material.DIAMOND_SWORD)) return true; return false; } /** * Is material an tool? * * @param material * to check * @return is tool or not */ public boolean isTool(Material mat) { if (isSword(mat) || isSpade(mat) || isAxe(mat) || isPickaxe(mat) || isHoe(mat) || mat.equals(Material.BOW)) return true; return false; } /** * Returns the helmet, chestplate, leggings, and boots * * @return helmet, chestplate, leggings, and boots */ public Material[] leatherArmor() { return new Material[] { Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS }; } /** * Get a random weapon * * @return a random weapon */ public Material weaponPicker() { switch (gen.nextInt(6)) { case 0: return diamondWeapon(gen.nextInt(5)); case 1: return ironWeapon(gen.nextInt(5)); case 2: return goldWeapon(gen.nextInt(5)); case 3: return stoneWeapon(gen.nextInt(5)); case 4: return woodWeapon(gen.nextInt(5)); case 5: return Material.BOW; default: return null; } } /** * Returns a kind of stone tool * 1 - STONE_SWORD * 2 - STONE_PICKAXE * 3 - STONE_SPADE * 4 - STONE_AXE * 5 - STONE_HOE * * @param kind * to return * @return kind of stone tool */ public Material stoneWeapon(int num) { switch (num) { case 1: return Material.STONE_SWORD; case 2: return Material.STONE_PICKAXE; case 3: return Material.STONE_SPADE; case 4: return Material.STONE_AXE; case 5: return Material.STONE_HOE; default: return null; } } /** * Returns a kind of wood tool * 1 - WOOD_SWORD * 2 - WOOD_PICKAXE * 3 - WOOD_SPADE * 4 - WOOD_AXE * 5 - WOOD_HOE * * @param kind * to return * @return kind of wood tool */ public Material woodWeapon(int num) { switch (num) { case 1: return Material.WOOD_SWORD; case 2: return Material.WOOD_PICKAXE; case 3: return Material.WOOD_SPADE; case 4: return Material.WOOD_AXE; case 5: return Material.WOOD_HOE; default: return null; } } }
false
true
public Material[] allItems() { return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_PICKAXE, Material.DIAMOND_SPADE, Material.DIAMOND_AXE, Material.DIAMOND_HOE, Material.IRON_SWORD, Material.IRON_PICKAXE, Material.IRON_SPADE, Material.IRON_AXE, Material.IRON_HOE, Material.GOLD_SWORD, Material.GOLD_PICKAXE, Material.GOLD_SPADE, Material.GOLD_AXE, Material.GOLD_HOE, Material.STONE_SWORD, Material.STONE_PICKAXE, Material.STONE_SPADE, Material.STONE_AXE, Material.STONE_HOE, Material.WOOD_SWORD, Material.WOOD_PICKAXE, Material.WOOD_SPADE, Material.WOOD_AXE, Material.WOOD_HOE, Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.BOW }; }
public Material[] allItems() { return new Material[] { Material.DIAMOND_SWORD, Material.DIAMOND_PICKAXE, Material.DIAMOND_SPADE, Material.DIAMOND_AXE, Material.DIAMOND_HOE, Material.IRON_SWORD, Material.IRON_PICKAXE, Material.IRON_SPADE, Material.IRON_AXE, Material.IRON_HOE, Material.GOLD_SWORD, Material.GOLD_PICKAXE, Material.GOLD_SPADE, Material.GOLD_AXE, Material.GOLD_HOE, Material.STONE_SWORD, Material.STONE_PICKAXE, Material.STONE_SPADE, Material.STONE_AXE, Material.STONE_HOE, Material.WOOD_SWORD, Material.WOOD_PICKAXE, Material.WOOD_SPADE, Material.WOOD_AXE, Material.WOOD_HOE, Material.DIAMOND_HELMET, Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.IRON_HELMET, Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.CHAINMAIL_HELMET, Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.GOLD_HELMET, Material.GOLD_CHESTPLATE, Material.GOLD_LEGGINGS, Material.GOLD_BOOTS, Material.LEATHER_HELMET, Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.BOW }; }
diff --git a/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/jobs/PartitionsDiffComputer.java b/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/jobs/PartitionsDiffComputer.java index c21f8e53d..b501e330f 100644 --- a/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/jobs/PartitionsDiffComputer.java +++ b/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/jobs/PartitionsDiffComputer.java @@ -1,493 +1,494 @@ /* * 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.directory.studio.apacheds.configuration.v2.jobs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.directory.api.ldap.model.entry.Attribute; import org.apache.directory.api.ldap.model.entry.DefaultAttribute; import org.apache.directory.api.ldap.model.entry.DefaultModification; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.entry.Modification; import org.apache.directory.api.ldap.model.entry.ModificationOperation; import org.apache.directory.api.ldap.model.entry.Value; import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; import org.apache.directory.api.ldap.model.filter.FilterParser; import org.apache.directory.api.ldap.model.ldif.ChangeType; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.message.AliasDerefMode; import org.apache.directory.api.ldap.model.message.SearchScope; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.schema.AttributeType; import org.apache.directory.api.ldap.model.schema.UsageEnum; import org.apache.directory.server.core.api.entry.ClonedServerEntry; import org.apache.directory.server.core.api.filtering.EntryFilteringCursor; import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext; import org.apache.directory.server.core.api.interceptor.context.SearchOperationContext; import org.apache.directory.server.core.api.partition.Partition; public class PartitionsDiffComputer { /** The original partition */ private Partition originalPartition; /** The destination partition */ private Partition destinationPartition; public PartitionsDiffComputer() { } public PartitionsDiffComputer( Partition originalPartition, Partition destinationPartition ) { this.originalPartition = originalPartition; this.destinationPartition = destinationPartition; } public List<LdifEntry> computeModifications() throws Exception { // Using the original partition suffix as base // '*' for all user attributes, '+' for all operational attributes return computeModifications( originalPartition.getSuffixDn(), new String[] { "*", "+" } ); //$NON-NLS-1$ //$NON-NLS-2$ } public List<LdifEntry> computeModifications( String[] attributeIds ) throws Exception { return computeModifications( originalPartition.getSuffixDn(), attributeIds ); } public List<LdifEntry> computeModifications( Dn baseDn, String[] attributeIds ) throws Exception { // Checking partitions checkPartitions(); return comparePartitions( baseDn, attributeIds ); } /** * Checks the partitions. * * @throws PartitionsDiffException */ private void checkPartitions() throws PartitionsDiffException { // Checking the original partition if ( originalPartition == null ) { throw new PartitionsDiffException( "The original partition must not be 'null'." ); //$NON-NLS-1$ } else { if ( !originalPartition.isInitialized() ) { throw new PartitionsDiffException( "The original partition must be intialized." ); //$NON-NLS-1$ } else if ( originalPartition.getSuffixDn() == null ) { throw new PartitionsDiffException( "The original suffix is null." ); //$NON-NLS-1$ } } // Checking the destination partition if ( destinationPartition == null ) { throw new PartitionsDiffException( "The destination partition must not be 'null'." ); //$NON-NLS-1$ } else { if ( !destinationPartition.isInitialized() ) { throw new PartitionsDiffException( "The destination partition must be intialized." ); //$NON-NLS-1$ } else if ( destinationPartition.getSuffixDn() == null ) { throw new PartitionsDiffException( "The destination suffix is null." ); //$NON-NLS-1$ } } } /** * Compare the two partitions. * * @param baseDn * the base Dn * @param attributeIds * the IDs of the attributes * @return * a list containing LDIF entries with all modifications * @throws Exception */ public List<LdifEntry> comparePartitions( Dn baseDn, String[] attributeIds ) throws PartitionsDiffException { // Creating the list containing all modifications List<LdifEntry> modifications = new ArrayList<LdifEntry>(); try { // Looking up the original base entry Entry originalBaseEntry = originalPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( originalBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the original partition." ); //$NON-NLS-1$ } // Creating the list containing all the original entries to be processed // and adding it the original base entry List<Entry> originalEntries = new ArrayList<Entry>(); originalEntries.add( originalBaseEntry ); // Looping until all original entries are being processed while ( originalEntries.size() > 0 ) { // Getting the first original entry from the list Entry originalEntry = originalEntries.remove( 0 ); // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( originalEntry.getDn() ); // Looking for the equivalent entry in the destination partition Entry destinationEntry = destinationPartition.lookup( new LookupOperationContext( null, originalEntry .getDn(), attributeIds ) ); if ( destinationEntry != null ) { // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Modify ); // Comparing both entries compareEntries( originalEntry, destinationEntry, modificationEntry ); } else { // The original entry is no longer present in the destination partition // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Delete ); } // Checking if modifications occurred on the original entry ChangeType modificationEntryChangeType = modificationEntry.getChangeType(); if ( modificationEntryChangeType != ChangeType.None ) { if ( modificationEntryChangeType == ChangeType.Delete || ( modificationEntryChangeType == ChangeType.Modify && modificationEntry .getModifications().size() > 0 ) ) { // Adding the modification entry to the list modifications.add( modificationEntry ); } } // Creating a search operation context to get the children of the current entry SearchOperationContext soc = new SearchOperationContext( null, originalEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = originalPartition.search( soc ); while ( cursor.next() ) { originalEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } // Reversing the list to allow deletion of leafs first (otherwise we would be deleting // higher nodes with children first). // Order for modified entries does not matter. Collections.reverse( modifications ); // Looking up the destination base entry Entry destinationBaseEntry = destinationPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( destinationBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the destination partition." ); //$NON-NLS-1$ } // Creating the list containing all the destination entries to be processed // and adding it the destination base entry List<Entry> destinationEntries = new ArrayList<Entry>(); destinationEntries.add( originalBaseEntry ); // Looping until all destination entries are being processed while ( destinationEntries.size() > 0 ) { // Getting the first destination entry from the list Entry destinationEntry = destinationEntries.remove( 0 ); // Looking for the equivalent entry in the destination partition Entry originalEntry = originalPartition.lookup( new LookupOperationContext( null, destinationEntry .getDn(), attributeIds ) ); // We're only looking for new entries, modified or removed // entries have already been computed if ( originalEntry == null ) { // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( destinationEntry.getDn() ); // Setting the changetype to addition modificationEntry.setChangeType( ChangeType.Add ); // Copying attributes for ( Attribute attribute : destinationEntry ) { modificationEntry.addAttribute( attribute ); } // Adding the modification entry to the list modifications.add( modificationEntry ); } // Creating a search operation context to get the children of the current entry - SearchOperationContext soc = new SearchOperationContext( null, originalEntry.getDn(), + SearchOperationContext soc = new SearchOperationContext( null, destinationEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = destinationPartition.search( soc ); while ( cursor.next() ) { destinationEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } } catch ( Exception e ) { + // e.printStackTrace(); throw new PartitionsDiffException( e ); } return modifications; } /** * Compares the two given entries. * * @param originalEntry * the original entry * @param destinationEntry * the destination entry * @param modificationEntry * the modification LDIF entry holding the modifications * between both entries */ private void compareEntries( Entry originalEntry, Entry destinationEntry, LdifEntry modificationEntry ) { // Creating a list to store the already evaluated attribute type List<AttributeType> evaluatedATs = new ArrayList<AttributeType>(); // Checking attributes of the original entry for ( Attribute originalAttribute : originalEntry ) { AttributeType originalAttributeType = originalAttribute.getAttributeType(); // We're only working on 'userApplications' attributes if ( originalAttributeType.getUsage() == UsageEnum.USER_APPLICATIONS ) { Attribute destinationAttribute = destinationEntry.get( originalAttributeType ); if ( destinationAttribute == null ) { // Creating a modification for the removed AT Modification modification = new DefaultModification(); modification.setOperation( ModificationOperation.REMOVE_ATTRIBUTE ); modification.setAttribute( new DefaultAttribute( originalAttribute.getAttributeType() ) ); modificationEntry.addModification( modification ); } else { // Comparing both attributes compareAttributes( originalAttribute, destinationAttribute, modificationEntry ); } evaluatedATs.add( originalAttributeType ); } } // Checking attributes of the destination entry for ( Attribute destinationAttribute : destinationEntry ) { AttributeType destinationAttributeType = destinationAttribute.getAttributeType(); // We're only working on 'userApplications' attributes if ( destinationAttributeType.getUsage() == UsageEnum.USER_APPLICATIONS ) { // Checking if the current AT has already been evaluated if ( !evaluatedATs.contains( destinationAttributeType ) ) { // Creating a modification for the added AT Modification modification = new DefaultModification(); modification.setOperation( ModificationOperation.ADD_ATTRIBUTE ); Attribute attribute = new DefaultAttribute( destinationAttributeType ); modification.setAttribute( attribute ); for ( Value<?> value : destinationAttribute ) { try { attribute.add( value ); } catch ( LdapInvalidAttributeValueException liave ) { // TODO : handle the exception } } modificationEntry.addModification( modification ); } } } } /** * Compares the two given attributes. * * @param originalAttribute * the original attribute * @param destinationAttribute * the destination attribute * @param modificationEntry * the modification LDIF entry holding the modifications * between both attributes */ private void compareAttributes( Attribute originalAttribute, Attribute destinationAttribute, LdifEntry modificationEntry ) { // Creating a list to store the already evaluated values List<Value<?>> evaluatedValues = new ArrayList<Value<?>>(); // Checking values of the original attribute for ( Value<?> originalValue : originalAttribute ) { if ( !destinationAttribute.contains( originalValue ) ) { // Creating a modification for the removed AT value Modification modification = new DefaultModification(); modification.setOperation( ModificationOperation.REMOVE_ATTRIBUTE ); Attribute attribute = new DefaultAttribute( originalAttribute.getAttributeType() ); modification.setAttribute( attribute ); try { attribute.add( originalValue ); } catch ( LdapInvalidAttributeValueException liave ) { // TODO : handle the exception } modificationEntry.addModification( modification ); } evaluatedValues.add( originalValue ); } // Checking values of the destination attribute for ( Value<?> destinationValue : destinationAttribute ) { if ( !evaluatedValues.contains( destinationValue ) ) { // Creating a modification for the added AT value Modification modification = new DefaultModification(); modification.setOperation( ModificationOperation.ADD_ATTRIBUTE ); Attribute attribute = new DefaultAttribute( originalAttribute.getAttributeType() ); modification.setAttribute( attribute ); try { attribute.add( destinationValue ); } catch ( LdapInvalidAttributeValueException liave ) { // TODO : handle the exception } modificationEntry.addModification( modification ); } } } /** * Gets the original partition. * * @return * the original partition */ public Partition getOriginalPartition() { return originalPartition; } /** * Sets the original partition. * * @param originalPartition * the original partition */ public void setOriginalPartition( Partition originalPartition ) { this.originalPartition = originalPartition; } /** * Gets the destination partition. * * @return * the destination partition */ public Partition getDestinationPartition() { return destinationPartition; } /** * Sets the destination partition. * * @param destinationPartition * the destination partition */ public void setDestinationPartition( Partition destinationPartition ) { this.destinationPartition = destinationPartition; } }
false
true
public List<LdifEntry> comparePartitions( Dn baseDn, String[] attributeIds ) throws PartitionsDiffException { // Creating the list containing all modifications List<LdifEntry> modifications = new ArrayList<LdifEntry>(); try { // Looking up the original base entry Entry originalBaseEntry = originalPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( originalBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the original partition." ); //$NON-NLS-1$ } // Creating the list containing all the original entries to be processed // and adding it the original base entry List<Entry> originalEntries = new ArrayList<Entry>(); originalEntries.add( originalBaseEntry ); // Looping until all original entries are being processed while ( originalEntries.size() > 0 ) { // Getting the first original entry from the list Entry originalEntry = originalEntries.remove( 0 ); // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( originalEntry.getDn() ); // Looking for the equivalent entry in the destination partition Entry destinationEntry = destinationPartition.lookup( new LookupOperationContext( null, originalEntry .getDn(), attributeIds ) ); if ( destinationEntry != null ) { // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Modify ); // Comparing both entries compareEntries( originalEntry, destinationEntry, modificationEntry ); } else { // The original entry is no longer present in the destination partition // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Delete ); } // Checking if modifications occurred on the original entry ChangeType modificationEntryChangeType = modificationEntry.getChangeType(); if ( modificationEntryChangeType != ChangeType.None ) { if ( modificationEntryChangeType == ChangeType.Delete || ( modificationEntryChangeType == ChangeType.Modify && modificationEntry .getModifications().size() > 0 ) ) { // Adding the modification entry to the list modifications.add( modificationEntry ); } } // Creating a search operation context to get the children of the current entry SearchOperationContext soc = new SearchOperationContext( null, originalEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = originalPartition.search( soc ); while ( cursor.next() ) { originalEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } // Reversing the list to allow deletion of leafs first (otherwise we would be deleting // higher nodes with children first). // Order for modified entries does not matter. Collections.reverse( modifications ); // Looking up the destination base entry Entry destinationBaseEntry = destinationPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( destinationBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the destination partition." ); //$NON-NLS-1$ } // Creating the list containing all the destination entries to be processed // and adding it the destination base entry List<Entry> destinationEntries = new ArrayList<Entry>(); destinationEntries.add( originalBaseEntry ); // Looping until all destination entries are being processed while ( destinationEntries.size() > 0 ) { // Getting the first destination entry from the list Entry destinationEntry = destinationEntries.remove( 0 ); // Looking for the equivalent entry in the destination partition Entry originalEntry = originalPartition.lookup( new LookupOperationContext( null, destinationEntry .getDn(), attributeIds ) ); // We're only looking for new entries, modified or removed // entries have already been computed if ( originalEntry == null ) { // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( destinationEntry.getDn() ); // Setting the changetype to addition modificationEntry.setChangeType( ChangeType.Add ); // Copying attributes for ( Attribute attribute : destinationEntry ) { modificationEntry.addAttribute( attribute ); } // Adding the modification entry to the list modifications.add( modificationEntry ); } // Creating a search operation context to get the children of the current entry SearchOperationContext soc = new SearchOperationContext( null, originalEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = destinationPartition.search( soc ); while ( cursor.next() ) { destinationEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } } catch ( Exception e ) { throw new PartitionsDiffException( e ); } return modifications; }
public List<LdifEntry> comparePartitions( Dn baseDn, String[] attributeIds ) throws PartitionsDiffException { // Creating the list containing all modifications List<LdifEntry> modifications = new ArrayList<LdifEntry>(); try { // Looking up the original base entry Entry originalBaseEntry = originalPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( originalBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the original partition." ); //$NON-NLS-1$ } // Creating the list containing all the original entries to be processed // and adding it the original base entry List<Entry> originalEntries = new ArrayList<Entry>(); originalEntries.add( originalBaseEntry ); // Looping until all original entries are being processed while ( originalEntries.size() > 0 ) { // Getting the first original entry from the list Entry originalEntry = originalEntries.remove( 0 ); // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( originalEntry.getDn() ); // Looking for the equivalent entry in the destination partition Entry destinationEntry = destinationPartition.lookup( new LookupOperationContext( null, originalEntry .getDn(), attributeIds ) ); if ( destinationEntry != null ) { // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Modify ); // Comparing both entries compareEntries( originalEntry, destinationEntry, modificationEntry ); } else { // The original entry is no longer present in the destination partition // Setting the changetype to delete modificationEntry.setChangeType( ChangeType.Delete ); } // Checking if modifications occurred on the original entry ChangeType modificationEntryChangeType = modificationEntry.getChangeType(); if ( modificationEntryChangeType != ChangeType.None ) { if ( modificationEntryChangeType == ChangeType.Delete || ( modificationEntryChangeType == ChangeType.Modify && modificationEntry .getModifications().size() > 0 ) ) { // Adding the modification entry to the list modifications.add( modificationEntry ); } } // Creating a search operation context to get the children of the current entry SearchOperationContext soc = new SearchOperationContext( null, originalEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = originalPartition.search( soc ); while ( cursor.next() ) { originalEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } // Reversing the list to allow deletion of leafs first (otherwise we would be deleting // higher nodes with children first). // Order for modified entries does not matter. Collections.reverse( modifications ); // Looking up the destination base entry Entry destinationBaseEntry = destinationPartition .lookup( new LookupOperationContext( null, baseDn, attributeIds ) ); if ( destinationBaseEntry == null ) { throw new PartitionsDiffException( "Unable to find the base entry in the destination partition." ); //$NON-NLS-1$ } // Creating the list containing all the destination entries to be processed // and adding it the destination base entry List<Entry> destinationEntries = new ArrayList<Entry>(); destinationEntries.add( originalBaseEntry ); // Looping until all destination entries are being processed while ( destinationEntries.size() > 0 ) { // Getting the first destination entry from the list Entry destinationEntry = destinationEntries.remove( 0 ); // Looking for the equivalent entry in the destination partition Entry originalEntry = originalPartition.lookup( new LookupOperationContext( null, destinationEntry .getDn(), attributeIds ) ); // We're only looking for new entries, modified or removed // entries have already been computed if ( originalEntry == null ) { // Creating a modification entry to hold all modifications LdifEntry modificationEntry = new LdifEntry(); modificationEntry.setDn( destinationEntry.getDn() ); // Setting the changetype to addition modificationEntry.setChangeType( ChangeType.Add ); // Copying attributes for ( Attribute attribute : destinationEntry ) { modificationEntry.addAttribute( attribute ); } // Adding the modification entry to the list modifications.add( modificationEntry ); } // Creating a search operation context to get the children of the current entry SearchOperationContext soc = new SearchOperationContext( null, destinationEntry.getDn(), SearchScope.ONELEVEL, FilterParser.parse( originalPartition.getSchemaManager(), "(objectClass=*)" ), attributeIds ); soc.setAliasDerefMode( AliasDerefMode.DEREF_ALWAYS ); // Looking for the children of the current entry EntryFilteringCursor cursor = destinationPartition.search( soc ); while ( cursor.next() ) { destinationEntries.add( ( ( ClonedServerEntry ) cursor.get() ).getClonedEntry() ); } } } catch ( Exception e ) { // e.printStackTrace(); throw new PartitionsDiffException( e ); } return modifications; }
diff --git a/src/main/java/org/cojen/tupl/Database.java b/src/main/java/org/cojen/tupl/Database.java index a40f056d..8276cb32 100644 --- a/src/main/java/org/cojen/tupl/Database.java +++ b/src/main/java/org/cojen/tupl/Database.java @@ -1,3682 +1,3682 @@ /* * Copyright 2011-2013 Brian S O'Neill * * 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.cojen.tupl; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.Writer; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.TreeMap; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.Lock; import static java.lang.System.arraycopy; import static java.util.Arrays.fill; import org.cojen.tupl.io.CauseCloseable; import org.cojen.tupl.io.FileFactory; import org.cojen.tupl.io.OpenOption; import org.cojen.tupl.io.PageArray; import static org.cojen.tupl.Node.*; import static org.cojen.tupl.Utils.*; /** * Main database class, containing a collection of transactional indexes. Call * {@link #open open} to obtain a Database instance. Examples: * * <p>Open a non-durable database, limited to a max size of 100MB: * * <pre> * DatabaseConfig config = new DatabaseConfig().maxCacheSize(100_000_000); * Database db = Database.open(config); * </pre> * * <p>Open a regular database, setting the minimum cache size to ensure enough * memory is initially available. A weak {@link DurabilityMode durability mode} * offers the best transactional commit performance. * * <pre> * DatabaseConfig config = new DatabaseConfig() * .baseFilePath("/var/lib/tupl/myapp") * .minCacheSize(100_000_000) * .durabilityMode(DurabilityMode.NO_FLUSH); * * Database db = Database.open(config); * </pre> * * <p>The following files are created by the above example: * * <ul> * <li><code>/var/lib/tupl/myapp.db</code> &ndash; primary data file * <li><code>/var/lib/tupl/myapp.info</code> &ndash; text file describing the database configuration * <li><code>/var/lib/tupl/myapp.lock</code> &ndash; lock file to ensure that at most one process can have the database open * <li><code>/var/lib/tupl/myapp.redo.0</code> &ndash; first transaction redo log file * </ul> * * <p>New redo log files are created by {@link #checkpoint checkpoints}, which * also delete the old files. When {@link #beginSnapshot snapshots} are in * progress, one or more numbered temporary files are created. For example: * <code>/var/lib/tupl/myapp.temp.123</code>. * * @author Brian S O'Neill * @see DatabaseConfig */ public final class Database implements CauseCloseable { private static final int DEFAULT_CACHED_NODES = 1000; // +2 for registry and key map root nodes, +1 for one user index, and +2 // for usage list to function correctly. It always assumes that the least // recently used node points to a valid, more recently used node. private static final int MIN_CACHED_NODES = 5; // Approximate byte overhead per node. Influenced by many factors, // including pointer size and child node references. This estimate assumes // 32-bit pointers. private static final int NODE_OVERHEAD = 100; private static final String INFO_FILE_SUFFIX = ".info"; private static final String LOCK_FILE_SUFFIX = ".lock"; static final String REDO_FILE_SUFFIX = ".redo."; private static int nodeCountFromBytes(long bytes, int pageSize) { if (bytes <= 0) { return 0; } pageSize += NODE_OVERHEAD; bytes += pageSize - 1; if (bytes <= 0) { // Overflow. return Integer.MAX_VALUE; } long count = bytes / pageSize; return count <= Integer.MAX_VALUE ? (int) count : Integer.MAX_VALUE; } private static long byteCountFromNodes(int nodes, int pageSize) { return nodes * (long) (pageSize + NODE_OVERHEAD); } private static final int ENCODING_VERSION = 20130112; private static final int I_ENCODING_VERSION = 0; private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4; private static final int I_MASTER_UNDO_LOG_PAGE_ID = I_ROOT_PAGE_ID + 8; private static final int I_TRANSACTION_ID = I_MASTER_UNDO_LOG_PAGE_ID + 8; private static final int I_CHECKPOINT_NUMBER = I_TRANSACTION_ID + 8; private static final int I_REDO_TXN_ID = I_CHECKPOINT_NUMBER + 8; private static final int I_REDO_POSITION = I_REDO_TXN_ID + 8; private static final int I_REPL_ENCODING = I_REDO_POSITION + 8; private static final int HEADER_SIZE = I_REPL_ENCODING + 8; private static final int DEFAULT_PAGE_SIZE = 4096; private static final int MINIMUM_PAGE_SIZE = 512; private static final int MAXIMUM_PAGE_SIZE = 65536; private static final int OPEN_REGULAR = 0, OPEN_DESTROY = 1, OPEN_TEMP = 2; final EventListener mEventListener; private final File mBaseFile; private final LockedFile mLockFile; final DurabilityMode mDurabilityMode; final long mDefaultLockTimeoutNanos; final LockManager mLockManager; final RedoWriter mRedoWriter; final PageDb mPageDb; final int mPageSize; private final BufferPool mSpareBufferPool; private final Latch mUsageLatch; private int mMaxNodeCount; private int mNodeCount; private Node mMostRecentlyUsed; private Node mLeastRecentlyUsed; private final Lock mSharedCommitLock; // Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock. private byte mCommitState; // Is false for empty databases which have never checkpointed. private volatile boolean mHasCheckpointed = true; // Typically opposite of mCommitState, or negative if checkpoint is not in // progress. Indicates which nodes are being flushed by the checkpoint. private volatile int mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; private static final int CHECKPOINT_FLUSH_PREPARE = -2, CHECKPOINT_NOT_FLUSHING = -1; // The root tree, which maps tree ids to other tree root node ids. private final Tree mRegistry; static final byte KEY_TYPE_INDEX_NAME = 0; // prefix for name to id mapping static final byte KEY_TYPE_INDEX_ID = 1; // prefix for id to name mapping static final byte KEY_TYPE_TREE_ID_MASK = 2; // full key for random tree id mask static final byte KEY_TYPE_NEXT_TREE_ID = 3; // full key for tree id sequence // Various mappings, defined by KEY_TYPE_ fields. private final Tree mRegistryKeyMap; private final Latch mOpenTreesLatch; // Maps tree names to open trees. private final Map<byte[], TreeRef> mOpenTrees; private final LHashTable.Obj<TreeRef> mOpenTreesById; private final ReferenceQueue<Tree> mOpenTreesRefQueue; private final PageAllocator mAllocator; final FragmentCache mFragmentCache; final int mMaxFragmentedEntrySize; // Fragmented values which are transactionally deleted go here. private volatile FragmentedTrash mFragmentedTrash; // Pre-calculated maximum capacities for inode levels. private final long[] mFragmentInodeLevelCaps; private final Object mTxnIdLock = new Object(); // The following fields are guarded by mTxnIdLock. private long mTxnId; private UndoLog mTopUndoLog; private int mUndoLogCount; private final Object mCheckpointLock = new Object(); private long mLastCheckpointNanos; private volatile Checkpointer mCheckpointer; private final TempFileManager mTempFileManager; volatile boolean mClosed; volatile Throwable mClosedCause; private static final AtomicReferenceFieldUpdater<Database, Throwable> cClosedCauseUpdater = AtomicReferenceFieldUpdater.newUpdater(Database.class, Throwable.class, "mClosedCause"); /** * Open a database, creating it if necessary. */ public static Database open(DatabaseConfig config) throws IOException { config = config.clone(); Database db = new Database(config, OPEN_REGULAR); db.finishInit(config); return db; } /** * Delete the contents of an existing database, and replace it with an * empty one. When using a raw block device for the data file, this method * must be used to format it. */ public static Database destroy(DatabaseConfig config) throws IOException { config = config.clone(); if (config.mReadOnly) { throw new IllegalArgumentException("Cannot destroy read-only database"); } Database db = new Database(config, OPEN_DESTROY); db.finishInit(config); return db; } /** * @param config base file is set as a side-effect */ static Tree openTemp(TempFileManager tfm, DatabaseConfig config) throws IOException { File file = tfm.createTempFile(); config.baseFile(file); config.dataFile(file); config.createFilePath(false); config.durabilityMode(DurabilityMode.NO_FLUSH); Database db = new Database(config, OPEN_TEMP); tfm.register(file, db); db.mCheckpointer = new Checkpointer(db, config); db.mCheckpointer.start(); return db.mRegistry; } /** * @param config unshared config */ private Database(DatabaseConfig config, int openMode) throws IOException { config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener); mBaseFile = config.mBaseFile; final File[] dataFiles = config.dataFiles(); int pageSize = config.mPageSize; boolean explicitPageSize = true; if (pageSize <= 0) { config.pageSize(pageSize = DEFAULT_PAGE_SIZE); explicitPageSize = false; } else if (pageSize < MINIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE); } else if (pageSize > MAXIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE); } else if ((pageSize & 1) != 0) { throw new IllegalArgumentException ("Page size must be even: " + pageSize); } int minCache, maxCache; cacheSize: { long minCachedBytes = Math.max(0, config.mMinCachedBytes); long maxCachedBytes = Math.max(0, config.mMaxCachedBytes); if (maxCachedBytes == 0) { maxCachedBytes = minCachedBytes; if (maxCachedBytes == 0) { minCache = maxCache = DEFAULT_CACHED_NODES; break cacheSize; } } if (minCachedBytes > maxCachedBytes) { throw new IllegalArgumentException ("Minimum cache size exceeds maximum: " + minCachedBytes + " > " + maxCachedBytes); } minCache = nodeCountFromBytes(minCachedBytes, pageSize); maxCache = nodeCountFromBytes(maxCachedBytes, pageSize); minCache = Math.max(MIN_CACHED_NODES, minCache); maxCache = Math.max(MIN_CACHED_NODES, maxCache); } // Update config such that info file is correct. config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize); config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize); mUsageLatch = new Latch(); mMaxNodeCount = maxCache; mDurabilityMode = config.mDurabilityMode; mDefaultLockTimeoutNanos = config.mLockTimeoutNanos; mLockManager = new LockManager(config.mLockUpgradeRule, mDefaultLockTimeoutNanos); if (mBaseFile != null && !config.mReadOnly && config.mMkdirs) { FileFactory factory = config.mFileFactory; File baseDir = mBaseFile.getParentFile(); if (factory == null) { baseDir.mkdirs(); } else { factory.createDirectories(baseDir); } if (dataFiles != null) { for (File f : dataFiles) { File dataDir = f.getParentFile(); if (factory == null) { dataDir.mkdirs(); } else { factory.createDirectories(dataDir); } } } } try { // Create lock file, preventing database from being opened multiple times. if (mBaseFile == null || openMode == OPEN_TEMP) { mLockFile = null; } else { File lockFile = new File(mBaseFile.getPath() + LOCK_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null && !config.mReadOnly) { factory.createFile(lockFile); } mLockFile = new LockedFile(lockFile, config.mReadOnly); } if (openMode == OPEN_DESTROY) { deleteRedoLogFiles(); } if (dataFiles == null) { PageArray dataPageArray = config.mDataPageArray; if (dataPageArray == null) { mPageDb = new NonPageDb(pageSize); } else { mPageDb = DurablePageDb.open (dataPageArray, config.mCrypto, openMode == OPEN_DESTROY); } } else { EnumSet<OpenOption> options = config.createOpenOptions(); mPageDb = DurablePageDb.open (explicitPageSize, pageSize, dataFiles, config.mFileFactory, options, config.mCrypto, openMode == OPEN_DESTROY); } // Actual page size might differ from configured size. config.pageSize(mPageSize = mPageDb.pageSize()); // Write info file of properties, after database has been opened and after page // size is truly known. if (mBaseFile != null && openMode != OPEN_TEMP && !config.mReadOnly) { File infoFile = new File(mBaseFile.getPath() + INFO_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null) { factory.createFile(infoFile); } Writer w = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8")); try { config.writeInfo(w); } finally { w.close(); } } mSharedCommitLock = mPageDb.sharedCommitLock(); // Pre-allocate nodes. They are automatically added to the usage // list, and so nothing special needs to be done to allow them to // get used. Since the initial state is clean, evicting these // nodes does nothing. long cacheInitStart = 0; if (mEventListener != null) { mEventListener.notify(EventType.CACHE_INIT_BEGIN, "Initializing %1$d cached nodes", minCache); cacheInitStart = System.nanoTime(); } try { for (int i=minCache; --i>=0; ) { allocLatchedNode(true).releaseExclusive(); } } catch (OutOfMemoryError e) { mMostRecentlyUsed = null; mLeastRecentlyUsed = null; throw new OutOfMemoryError ("Unable to allocate the minimum required number of cached nodes: " + - minCache + " (" + (minCache * (pageSize + NODE_OVERHEAD)) + " bytes)"); + minCache + " (" + (minCache * (long) (pageSize + NODE_OVERHEAD)) + " bytes)"); } if (mEventListener != null) { double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0; mEventListener.notify(EventType.CACHE_INIT_COMPLETE, "Cache initialization completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } int spareBufferCount = Runtime.getRuntime().availableProcessors(); mSpareBufferPool = new BufferPool(mPageSize, spareBufferCount); mSharedCommitLock.lock(); try { mCommitState = CACHED_DIRTY_0; } finally { mSharedCommitLock.unlock(); } byte[] header = new byte[HEADER_SIZE]; mPageDb.readExtraCommitData(header); // Also verifies the database and replication encodings. Node rootNode = loadRegistryRoot(header, config.mReplManager); mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, rootNode); mOpenTreesLatch = new Latch(); if (openMode == OPEN_TEMP) { mOpenTrees = Collections.emptyMap(); mOpenTreesById = new LHashTable.Obj<TreeRef>(0); mOpenTreesRefQueue = null; } else { mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE); mOpenTreesById = new LHashTable.Obj<TreeRef>(16); mOpenTreesRefQueue = new ReferenceQueue<Tree>(); } synchronized (mTxnIdLock) { mTxnId = decodeLongLE(header, I_TRANSACTION_ID); } long redoNum = decodeLongLE(header, I_CHECKPOINT_NUMBER); long redoPos = decodeLongLE(header, I_REDO_POSITION); long redoTxnId = decodeLongLE(header, I_REDO_TXN_ID); if (openMode == OPEN_TEMP) { mRegistryKeyMap = null; } else { mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true); } mAllocator = new PageAllocator(mPageDb); if (mBaseFile == null) { // Non-durable database never evicts anything. mFragmentCache = new FragmentMap(); } else { // Regular database evicts automatically. mFragmentCache = new FragmentCache(this, mMaxNodeCount); } if (openMode != OPEN_TEMP) { Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false); if (tree != null) { mFragmentedTrash = new FragmentedTrash(tree); } } // Limit maximum fragmented entry size to guarantee that 2 entries // fit. Each also requires 2 bytes for pointer and up to 3 bytes // for value length field. mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1; mFragmentInodeLevelCaps = calculateInodeLevelCaps(mPageSize); long recoveryStart = 0; if (mBaseFile == null || openMode == OPEN_TEMP) { mRedoWriter = null; } else { // Perform recovery by examining redo and undo logs. if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin"); recoveryStart = System.nanoTime(); } LHashTable.Obj<Transaction> txns = new LHashTable.Obj<Transaction>(16); { long masterNodeId = decodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID); if (masterNodeId != 0) { if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs"); } UndoLog.recoverMasterUndoLog(this, masterNodeId) .recoverTransactions(txns, LockMode.UPGRADABLE_READ, 0L); } } ReplicationManager rm = config.mReplManager; if (rm != null) { rm.start(redoPos); ReplRedoEngine engine = new ReplRedoEngine (rm, config.mMaxReplicaThreads, this, txns); mRedoWriter = engine.initWriter(redoNum); // Cannot start recovery until constructor is finished and final field // values are visible to other threads. Pass the state to the caller // through the config object. config.mReplRecoveryStartNanos = recoveryStart; config.mReplInitialTxnId = redoTxnId; } else { long logId = redoNum; // Make sure old redo logs are deleted. Process might have exited // before last checkpoint could delete them. for (int i=1; i<=2; i++) { RedoLog.deleteOldFile(config.mBaseFile, logId - i); } RedoLogApplier applier = new RedoLogApplier(this, txns); RedoLog replayLog = new RedoLog(config, logId, redoPos); // As a side-effect, log id is set one higher than last file scanned. Set<File> redoFiles = replayLog.replay (applier, mEventListener, EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d"); boolean doCheckpoint = !redoFiles.isEmpty(); // Avoid re-using transaction ids used by recovery. redoTxnId = applier.mHighestTxnId; if (redoTxnId != 0) { synchronized (mTxnIdLock) { // Subtract for modulo comparison. if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) { mTxnId = redoTxnId; } } } if (txns.size() > 0) { // Rollback or truncate all remaining transactions. They were never // explicitly rolled back, or they were committed but not cleaned up. if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_PROCESS_REMAINING, "Processing remaining transactions"); } txns.traverse(new LHashTable.Visitor <LHashTable.ObjEntry<Transaction>, IOException>() { public boolean visit(LHashTable.ObjEntry<Transaction> entry) throws IOException { entry.value.recoveryCleanup(); return false; } }); doCheckpoint = true; } // New redo logs begin with identifiers one higher than last scanned. mRedoWriter = new RedoLog(config, replayLog); // FIXME: If any exception is thrown before checkpoint is complete, delete // the newly created redo log file. if (doCheckpoint) { checkpoint(true, 0, 0); // Only cleanup after successful checkpoint. for (File file : redoFiles) { file.delete(); } } // Delete lingering fragmented values after undo logs have been processed, // ensuring deletes were committed. emptyAllFragmentedTrash(true); recoveryComplete(recoveryStart); } } if (mBaseFile == null || openMode == OPEN_TEMP) { mTempFileManager = null; } else { mTempFileManager = new TempFileManager(mBaseFile, config.mFileFactory); } } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } } /** * Post construction, allow additional threads access to the database. */ private void finishInit(DatabaseConfig config) throws IOException { if (mRedoWriter == null && mTempFileManager == null) { // Nothing is durable and nothing to ever clean up return; } Checkpointer c = new Checkpointer(this, config); mCheckpointer = c; // Register objects to automatically shutdown. c.register(mRedoWriter); c.register(mTempFileManager); if (mRedoWriter instanceof ReplRedoWriter) { // Start replication and recovery. ReplRedoWriter writer = (ReplRedoWriter) mRedoWriter; try { // Pass the original listener, in case it has been specialized. writer.recover(config.mReplInitialTxnId, config.mEventListener); } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } checkpoint(); recoveryComplete(config.mReplRecoveryStartNanos); } c.start(); } private void recoveryComplete(long recoveryStart) { if (mRedoWriter != null && mEventListener != null) { double duration = (System.nanoTime() - recoveryStart) / 1000000000.0; mEventListener.notify(EventType.RECOVERY_COMPLETE, "Recovery completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } } private void deleteRedoLogFiles() throws IOException { if (mBaseFile != null) { deleteNumberedFiles(mBaseFile, REDO_FILE_SUFFIX); } } /* void trace() throws IOException { int[] inBuckets = new int[16]; int[] leafBuckets = new int[16]; java.util.BitSet pages = mPageDb.tracePages(); mRegistry.mRoot.tracePages(this, pages, inBuckets, leafBuckets); mRegistryKeyMap.mRoot.tracePages(this, pages, inBuckets, leafBuckets); Cursor all = indexRegistryByName().newCursor(null); for (all.first(); all.key() != null; all.next()) { Index ix = indexById(all.value()); System.out.println(ix.getNameString()); Cursor c = ix.newCursor(Transaction.BOGUS); c.first(); System.out.println("height: " + ((TreeCursor) c).height()); c.reset(); ((Tree) ix).mRoot.tracePages(this, pages, inBuckets, leafBuckets); System.out.println("unaccounted: " + pages.cardinality()); System.out.println("internal avail: " + Arrays.toString(inBuckets)); System.out.println("leaf avail: " + Arrays.toString(leafBuckets)); } all.reset(); System.out.println("unaccounted: " + pages.cardinality()); System.out.println(pages); } */ /** * Returns the given named index, returning null if not found. * * @return shared Index instance; null if not found */ public Index findIndex(byte[] name) throws IOException { return openIndex(name.clone(), false); } /** * Returns the given named index, returning null if not found. Name is UTF-8 * encoded. * * @return shared Index instance; null if not found */ public Index findIndex(String name) throws IOException { return openIndex(name.getBytes("UTF-8"), false); } /** * Returns the given named index, creating it if necessary. * * @return shared Index instance */ public Index openIndex(byte[] name) throws IOException { return openIndex(name.clone(), true); } /** * Returns the given named index, creating it if necessary. Name is UTF-8 * encoded. * * @return shared Index instance */ public Index openIndex(String name) throws IOException { return openIndex(name.getBytes("UTF-8"), true); } /** * Returns an index by its identifier, returning null if not found. * * @throws IllegalArgumentException if id is reserved */ public Index indexById(long id) throws IOException { if (Tree.isInternal(id)) { throw new IllegalArgumentException("Invalid id: " + id); } Index index; final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { if ((index = lookupIndexById(id)) != null) { return index; } byte[] idKey = new byte[9]; idKey[0] = KEY_TYPE_INDEX_ID; encodeLongBE(idKey, 1, id); byte[] name = mRegistryKeyMap.load(null, idKey); if (name == null) { return null; } index = openIndex(name, false); } catch (Throwable e) { if (e instanceof DatabaseException && ((DatabaseException) e).isRecoverable()) { throw (DatabaseException) e; } throw closeOnFailure(this, e); } finally { commitLock.unlock(); } if (index == null) { // Registry needs to be repaired to fix this. throw new DatabaseException("Unable to find index in registry"); } return index; } /** * @return null if index is not open */ private Tree lookupIndexById(long id) { mOpenTreesLatch.acquireShared(); try { LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(id); return entry == null ? null : entry.value.get(); } finally { mOpenTreesLatch.releaseShared(); } } /** * Returns an index by its identifier, returning null if not found. * * @param id big-endian encoded long integer * @throws IllegalArgumentException if id is malformed or reserved */ public Index indexById(byte[] id) throws IOException { if (id.length != 8) { throw new IllegalArgumentException("Expected an 8 byte identifier: " + id.length); } return indexById(decodeLongBE(id, 0)); } /** * Allows access to internal indexes which can use the redo log. */ Index anyIndexById(long id) throws IOException { if (id == Tree.REGISTRY_KEY_MAP_ID) { return mRegistryKeyMap; } else if (id == Tree.FRAGMENTED_TRASH_ID) { return fragmentedTrash().mTrash; } return indexById(id); } /** * Renames the given index to the one given. * * @param index non-null open index * @param newName new non-null name * @throws ClosedIndexException if index reference is closed * @throws IllegalStateException if name is already in use by another index * @throws IllegalArgumentException if index belongs to another database instance */ public void renameIndex(Index index, byte[] newName) throws IOException { renameIndex(index, newName.clone(), true); } /** * Renames the given index to the one given. Name is UTF-8 encoded. * * @param index non-null open index * @param newName new non-null name * @throws ClosedIndexException if index reference is closed * @throws IllegalStateException if name is already in use by another index * @throws IllegalArgumentException if index belongs to another database instance */ public void renameIndex(Index index, String newName) throws IOException { renameIndex(index, newName.getBytes("UTF-8"), true); } /** * @param newName not cloned */ void renameIndex(Index index, byte[] newName, boolean doRedo) throws IOException { // Design note: Rename is a Database method instead of an Index method because it // offers an extra degree of safety. It's too easy to call rename and pass a byte[] by // an accident when something like remove was desired instead. Requiring access to the // Database instance makes this operation a bit more of a hassle to use, which is // desirable. Rename is not expected to be a common operation. Tree tree; check: { try { if ((tree = ((Tree) index)).mDatabase == this) { break check; } } catch (ClassCastException e) { // Cast and catch an exception instead of calling instanceof to cause a // NullPointerException to be thrown if index is null. } throw new IllegalArgumentException("Index belongs to a different database"); } byte[] idKey; byte[] oldName, oldNameKey; byte[] newNameKey; Transaction txn; Node root = tree.mRoot; root.acquireExclusive(); try { if (root.mPage == EMPTY_BYTES) { throw new ClosedIndexException(); } if (Tree.isInternal(tree.mId)) { throw new IllegalStateException("Cannot rename an internal index"); } oldName = tree.mName; if (Arrays.equals(oldName, newName)) { return; } idKey = newKey(KEY_TYPE_INDEX_ID, tree.mIdBytes); oldNameKey = newKey(KEY_TYPE_INDEX_NAME, oldName); newNameKey = newKey(KEY_TYPE_INDEX_NAME, newName); txn = newNoRedoTransaction(); try { txn.lockExclusive(mRegistryKeyMap.mId, idKey); // Lock in a consistent order, avoiding deadlocks. if (compareKeys(oldNameKey, newNameKey) <= 0) { txn.lockExclusive(mRegistryKeyMap.mId, oldNameKey); txn.lockExclusive(mRegistryKeyMap.mId, newNameKey); } else { txn.lockExclusive(mRegistryKeyMap.mId, newNameKey); txn.lockExclusive(mRegistryKeyMap.mId, oldNameKey); } } catch (Throwable e) { txn.reset(); throw rethrow(e); } } finally { // Can release now that registry entries are locked. Those locks will prevent // concurrent renames of the same index. root.releaseExclusive(); } RedoWriter redo; long commitPos = 0; try { Cursor c = mRegistryKeyMap.newCursor(txn); try { c.autoload(false); c.find(newNameKey); if (c.value() != null) { throw new IllegalStateException("New name is used by another index"); } c.store(tree.mIdBytes); } finally { c.reset(); } if (!doRedo) { redo = null; } else if ((redo = mRedoWriter) != null) { commitPos = redo.renameIndex(tree.mId, newName, mDurabilityMode); } mRegistryKeyMap.delete(txn, oldNameKey); mRegistryKeyMap.store(txn, idKey, newName); mOpenTreesLatch.acquireExclusive(); try { txn.commit(); tree.mName = newName; mOpenTrees.put(newName, mOpenTrees.remove(oldName)); } finally { mOpenTreesLatch.releaseExclusive(); } } catch (IllegalStateException e) { throw e; } catch (Throwable e) { throw closeOnFailure(this, e); } finally { txn.reset(); } if (redo != null && commitPos != 0) { // Don't hold locks and latches during sync. redo.txnCommitSync(commitPos); } } /** * Returns an {@link UnmodifiableViewException unmodifiable} View which maps all available * index names to identifiers. Identifiers are long integers, {@link * org.cojen.tupl.io.Utils#decodeLongBE big-endian} encoded. */ public View indexRegistryByName() throws IOException { return mRegistryKeyMap.viewPrefix(new byte[] {KEY_TYPE_INDEX_NAME}, 1).viewUnmodifiable(); } /** * Returns an {@link UnmodifiableViewException unmodifiable} View which maps all available * index identifiers to names. Identifiers are long integers, {@link * org.cojen.tupl.io.Utils#decodeLongBE big-endian} encoded. */ public View indexRegistryById() throws IOException { return mRegistryKeyMap.viewPrefix(new byte[] {KEY_TYPE_INDEX_ID}, 1).viewUnmodifiable(); } /** * Returns a new Transaction with the {@link DatabaseConfig#durabilityMode default} * durability mode. */ public Transaction newTransaction() { return doNewTransaction(mDurabilityMode); } /** * Returns a new Transaction with the given durability mode. If null, the * {@link DatabaseConfig#durabilityMode default} is used. */ public Transaction newTransaction(DurabilityMode durabilityMode) { return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode); } private Transaction doNewTransaction(DurabilityMode durabilityMode) { return new Transaction (this, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); } /** * Convenience method which returns a transaction intended for locking. Caller can make * modifications, but they won't go to the redo log. */ Transaction newNoRedoTransaction() { return new Transaction(this, DurabilityMode.NO_REDO, LockMode.UPGRADABLE_READ, -1); } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. */ void register(UndoLog undo) { synchronized (mTxnIdLock) { UndoLog top = mTopUndoLog; if (top != null) { undo.mPrev = top; top.mNext = undo; } mTopUndoLog = undo; mUndoLogCount++; } } /** * Caller must hold commit lock. This ensures that highest transaction id * is persisted correctly by checkpoint. * * @return non-zero transaction id */ long nextTransactionId() throws IOException { RedoWriter redo = mRedoWriter; if (redo != null) { // Replicas cannot create loggable transactions. redo.opWriteCheck(); } long txnId; do { synchronized (mTxnIdLock) { txnId = ++mTxnId; } } while (txnId == 0); return txnId; } /** * Called only by UndoLog. */ void unregister(UndoLog log) { synchronized (mTxnIdLock) { UndoLog prev = log.mPrev; UndoLog next = log.mNext; if (prev != null) { prev.mNext = next; log.mPrev = null; } if (next != null) { next.mPrev = prev; log.mNext = null; } else if (log == mTopUndoLog) { mTopUndoLog = prev; } mUndoLogCount--; } } /** * Preallocates pages for immediate use. The actual amount allocated * varies, depending on the amount of free pages already available. * * @return actual amount allocated */ public long preallocate(long bytes) throws IOException { if (!mClosed && mPageDb instanceof DurablePageDb) { int pageSize = mPageSize; long pageCount = (bytes + pageSize - 1) / pageSize; if (pageCount > 0) { pageCount = mPageDb.allocatePages(pageCount); if (pageCount > 0) { try { checkpoint(true, 0, 0); } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } } return pageCount * pageSize; } } return 0; } /** * Support for capturing a snapshot (hot backup) of the database, while * still allowing concurrent modifications. The snapshot contains all data * up to the last checkpoint. Call the {@link #checkpoint checkpoint} * method immediately before to ensure that an up-to-date snapshot is * captured. * * <p>To restore from a snapshot, store it in the primary data file, which * is the base file with a ".db" extension. Make sure no redo log files * exist and then open the database. Alternatively, call {@link * #restoreFromSnapshot restoreFromSnapshot}, which also supports restoring * into separate data files. * * <p>During the snapshot, temporary files are created to hold pre-modified * copies of pages. If the snapshot destination stream blocks for too long, * these files keep growing. File growth rate increases too if the database * is being heavily modified. In the worst case, the temporary files can * become larger than the primary database files. * * @return a snapshot control object, which must be closed when no longer needed */ public Snapshot beginSnapshot() throws IOException { if (!(mPageDb instanceof DurablePageDb)) { throw new UnsupportedOperationException("Snapshot only allowed for durable databases"); } checkClosed(); DurablePageDb pageDb = (DurablePageDb) mPageDb; return pageDb.beginSnapshot(mTempFileManager); } /** * Restore from a {@link #beginSnapshot snapshot}, into the data files * defined by the given configuration. * * @param in snapshot source; does not require extra buffering; auto-closed */ public static Database restoreFromSnapshot(DatabaseConfig config, InputStream in) throws IOException { PageDb restored; File[] dataFiles = config.dataFiles(); if (dataFiles == null) { PageArray dataPageArray = config.mDataPageArray; if (dataPageArray == null) { throw new UnsupportedOperationException ("Restore only allowed for durable databases"); } // Delete old redo log files. deleteNumberedFiles(config.mBaseFile, REDO_FILE_SUFFIX); restored = DurablePageDb.restoreFromSnapshot(dataPageArray, config.mCrypto, in); } else { if (!config.mReadOnly) { for (File f : dataFiles) { // Delete old data file. f.delete(); if (config.mMkdirs) { f.getParentFile().mkdirs(); } } } FileFactory factory = config.mFileFactory; EnumSet<OpenOption> options = config.createOpenOptions(); // Delete old redo log files. deleteNumberedFiles(config.mBaseFile, REDO_FILE_SUFFIX); int pageSize = config.mPageSize; if (pageSize <= 0) { pageSize = DEFAULT_PAGE_SIZE; } restored = DurablePageDb.restoreFromSnapshot (pageSize, dataFiles, factory, options, config.mCrypto, in); } restored.close(); return Database.open(config); } /** * Returns an immutable copy of database statistics. */ public Stats stats() { Stats stats = new Stats(); stats.mPageSize = mPageSize; mSharedCommitLock.lock(); try { long cursorCount = 0; mOpenTreesLatch.acquireShared(); try { stats.mOpenIndexes = mOpenTrees.size(); for (TreeRef treeRef : mOpenTrees.values()) { Tree tree = treeRef.get(); if (tree != null) { cursorCount += tree.mRoot.countCursors(); } } } finally { mOpenTreesLatch.releaseShared(); } stats.mCursorCount = cursorCount; PageDb.Stats pstats = mPageDb.stats(); stats.mFreePages = pstats.freePages; stats.mTotalPages = pstats.totalPages; stats.mLockCount = mLockManager.numLocksHeld(); synchronized (mTxnIdLock) { stats.mTxnCount = mUndoLogCount; stats.mTxnsCreated = mTxnId; } } finally { mSharedCommitLock.unlock(); } return stats; } /** * Immutable copy of database {@link Database#stats statistics}. */ public static class Stats implements Serializable { private static final long serialVersionUID = 2L; int mPageSize; long mFreePages; long mTotalPages; int mOpenIndexes; long mLockCount; long mCursorCount; long mTxnCount; long mTxnsCreated; Stats() { } /** * Returns the allocation page size. */ public int pageSize() { return mPageSize; } /** * Returns the amount of unused pages in the database. */ public long freePages() { return mFreePages; } /** * Returns the total amount of pages in the database. */ public long totalPages() { return mTotalPages; } /** * Returns the amount of indexes currently open. */ public int openIndexes() { return mOpenIndexes; } /** * Returns the amount of locks currently allocated. Locks are created as transactions * access or modify records, and they are destroyed when transactions exit or reset. An * accumulation of locks can indicate that transactions are not being reset properly. */ public long lockCount() { return mLockCount; } /** * Returns the amount of cursors which are in a non-reset state. An accumulation of * cursors can indicate that they are not being reset properly. */ public long cursorCount() { return mCursorCount; } /** * Returns the amount of fully-established transactions which are in a non-reset * state. This value is unaffected by transactions which make no changes, and it is * also unaffected by auto-commit transactions. An accumulation of transactions can * indicate that they are not being reset properly. */ public long transactionCount() { return mTxnCount; } /** * Returns the total amount of fully-established transactions created over the life of * the database. This value is unaffected by transactions which make no changes, and it * is also unaffected by auto-commit transactions. A resurrected transaction can become * fully-established again, further increasing the total created value. */ public long transactionsCreated() { return mTxnsCreated; } @Override public int hashCode() { long hash = mFreePages; hash = hash * 31 + mTotalPages; hash = hash * 31 + mTxnsCreated; return (int) scramble(hash); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof Stats) { Stats other = (Stats) obj; return mPageSize == other.mPageSize && mFreePages == other.mFreePages && mTotalPages == other.mTotalPages && mOpenIndexes == other.mOpenIndexes && mLockCount == other.mLockCount && mCursorCount == other.mCursorCount && mTxnCount == other.mTxnCount && mTxnsCreated == other.mTxnsCreated; } return false; } @Override public String toString() { return "Database.Stats {pageSize=" + mPageSize + ", freePages=" + mFreePages + ", totalPages=" + mTotalPages + ", openIndexes=" + mOpenIndexes + ", lockCount=" + mLockCount + ", cursorCount=" + mCursorCount + ", transactionCount=" + mTxnCount + ", transactionsCreated=" + mTxnsCreated + '}'; } } /** * Flushes, but does not sync, all non-flushed transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} effectively * become {@link DurabilityMode#NO_SYNC no-sync} durable. */ public void flush() throws IOException { if (!mClosed && mRedoWriter != null) { mRedoWriter.flush(); } } /** * Persists all non-flushed and non-sync'd transactions. Transactions * committed with {@link DurabilityMode#NO_FLUSH no-flush} and {@link * DurabilityMode#NO_SYNC no-sync} effectively become {@link * DurabilityMode#SYNC sync} durable. */ public void sync() throws IOException { if (!mClosed && mRedoWriter != null) { mRedoWriter.sync(); } } /** * Durably sync and checkpoint all changes to the database. In addition to * ensuring that all transactions are durable, checkpointing ensures that * non-transactional modifications are durable. Checkpoints are performed * automatically by a background thread, at a {@link * DatabaseConfig#checkpointRate configurable} rate. */ public void checkpoint() throws IOException { if (!mClosed && mPageDb instanceof DurablePageDb) { try { checkpoint(false, 0, 0); } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } } } /** * Temporarily suspend automatic checkpoints without waiting for any in-progress checkpoint * to complete. Suspend may be invoked multiple times, but each must be paired with a * {@link #resumeCheckpoints resume} call to enable automatic checkpoints again. * * @throws IllegalStateException if suspended more than 2<sup>31</sup> times */ public void suspendCheckpoints() { Checkpointer c = mCheckpointer; if (c != null) { c.suspend(); } } /** * Resume automatic checkpoints after having been temporarily {@link #suspendCheckpoints * suspended}. * * @throws IllegalStateException if resumed more than suspended */ public void resumeCheckpoints() { Checkpointer c = mCheckpointer; if (c != null) { c.resume(); } } /** * Compacts the database by shrinking the database file. The compaction target is the * desired file utilization, and it controls how much compaction should be performed. A * target of 0.0 performs no compaction, and a value of 1.0 attempts to compact as much as * possible. * * <p>If the compaction target cannot be met, the entire operation aborts. If the database * is being concurrently modified, large compaction targets will likely never succeed. * Although compacting by smaller amounts is more likely to succeed, the entire database * must still be scanned. A minimum target of 0.5 is recommended for the compaction to be * worth the effort. * * <p>Compaction requires some amount of free space for page movement, and so some free * space might still linger following a massive compaction. More iterations are required to * fully complete such a compaction. The first iteration might actually cause the file to * grow slightly. This can be prevented by doing a less massive compaction first. * * @param observer optional observer; pass null for default * @param target database file compaction target [0.0, 1.0] * @return false if file compaction aborted * @throws IllegalArgumentException if compaction target is out of bounds * @throws IllegalStateException if compaction is already in progress */ public boolean compactFile(CompactionObserver observer, double target) throws IOException { if (target < 0 || target > 1) { throw new IllegalArgumentException("Illegal compaction target: " + target); } if (target == 0) { // No compaction to do at all, but not aborted. return true; } long targetPageCount; synchronized (mCheckpointLock) { PageDb.Stats stats = mPageDb.stats(); long usedPages = stats.totalPages - stats.freePages; targetPageCount = Math.max(usedPages, (long) (usedPages / target)); // Determine the maximum amount of space required to store the reserve list nodes // and ensure the target includes them. long reserve; { // Total pages freed. long freed = stats.totalPages - targetPageCount; // Scale by the maximum size for encoding page identifers, assuming no savings // from delta encoding. freed *= calcUnsignedVarLongLength(stats.totalPages << 1); // Divide by the node size, excluding the header (see PageQueue). reserve = freed / (mPageSize - (8 + 8)); // A minimum is required because the regular and free lists need to allocate // one extra node at checkpoint. Up to three checkpoints may be issued, so pad // by 2 * 3 = 6. reserve += 6; } targetPageCount += reserve; if (targetPageCount >= stats.totalPages) { return true; } if (!mPageDb.compactionStart(targetPageCount)) { return false; } } if (!mPageDb.compactionScanFreeList()) { synchronized (mCheckpointLock) { mPageDb.compactionEnd(); } return false; } // Issue a checkpoint to ensure all dirty nodes are flushed out. This ensures that // nodes can be moved out of the compaction zone by simply marking them dirty. If // already dirty, they'll not be in the compaction zone unless compaction aborted. checkpoint(); if (observer == null) { observer = new CompactionObserver(); } final long highestNodeId = targetPageCount - 1; final CompactionObserver fobserver = observer; boolean completed = scanAllIndexes(new ScanVisitor() { public boolean apply(Tree tree) throws IOException { return tree.compactTree(tree.observableView(), highestNodeId, fobserver); } }); checkpoint(true, 0, 0); if (completed && mPageDb.compactionScanFreeList()) { if (!mPageDb.compactionVerify() && mPageDb.compactionScanFreeList()) { checkpoint(true, 0, 0); } } synchronized (mCheckpointLock) { completed &= mPageDb.compactionEnd(); // If completed, then this allows file to shrink. Otherwise, it allows reclaimed // reserved pages to be immediately usable. checkpoint(true, 0, 0); if (completed) { // And now, attempt to actually shrink the file. return mPageDb.truncatePages(); } } return false; } /** * Verifies the integrity of the database and all indexes. * * @param observer optional observer; pass null for default * @return true if verification passed */ public boolean verify(VerificationObserver observer) throws IOException { // TODO: Verify free lists. if (observer == null) { observer = new VerificationObserver(); } final boolean[] passedRef = {true}; final VerificationObserver fobserver = observer; scanAllIndexes(new ScanVisitor() { public boolean apply(Tree tree) throws IOException { Index view = tree.observableView(); fobserver.failed = false; boolean keepGoing = tree.verifyTree(view, fobserver); passedRef[0] &= !fobserver.failed; if (keepGoing) { keepGoing = fobserver.indexComplete(view, !fobserver.failed, null); } return keepGoing; } }); return passedRef[0]; } static interface ScanVisitor { /** * @return false if should stop */ boolean apply(Tree tree) throws IOException; } /** * @return false if stopped */ private boolean scanAllIndexes(ScanVisitor visitor) throws IOException { if (!visitor.apply(mRegistry)) { return false; } if (!visitor.apply(mRegistryKeyMap)) { return false; } FragmentedTrash trash = mFragmentedTrash; if (trash != null) { if (!visitor.apply(trash.mTrash)) { return false; } } Cursor all = indexRegistryByName().newCursor(null); try { for (all.first(); all.key() != null; all.next()) { long id = decodeLongBE(all.value(), 0); Tree index = lookupIndexById(id); if (index != null) { if (!visitor.apply(index)) { return false; } } else { // Open the index. index = (Tree) indexById(id); boolean keepGoing = visitor.apply(index); try { index.close(); } catch (IllegalStateException e) { // Leave open if in use now. } if (!keepGoing) { return false; } } } } finally { all.reset(); } return true; } /** * Closes the database, ensuring durability of committed transactions. No * checkpoint is performed by this method, and so non-transactional * modifications can be lost. * * @see #shutdown */ @Override public void close() throws IOException { close(null, false); } /** * Closes the database after an unexpected failure. No checkpoint is performed by this * method, and so non-transactional modifications can be lost. * * @param cause if non-null, delivers a {@link EventType#PANIC_UNHANDLED_EXCEPTION panic} * event and future database accesses will rethrow the cause * @see #shutdown */ @Override public void close(Throwable cause) throws IOException { close(cause, false); } /** * Cleanly closes the database, ensuring durability of all modifications. A checkpoint is * issued first, and so a quick recovery is performed when the database is re-opened. As a * side effect of shutting down, all extraneous files are deleted. */ public void shutdown() throws IOException { close(null, mPageDb instanceof DurablePageDb); } private void close(Throwable cause, boolean shutdown) throws IOException { if (cause != null && !mClosed) { if (cClosedCauseUpdater.compareAndSet(this, null, cause) && mEventListener != null) { mEventListener.notify(EventType.PANIC_UNHANDLED_EXCEPTION, "Closing database due to unhandled exception: %1$s", rootCause(cause)); } } Checkpointer c = mCheckpointer; if (shutdown) { synchronized (mCheckpointLock) { checkpoint(true, 0, 0); mClosed = true; if (c != null) { c.close(); } } } else { mClosed = true; if (c != null) { c.close(); } // Synchronize to wait for any in-progress checkpoint to complete. synchronized (mCheckpointLock) { // Nothing really needs to be done in the synchronized block, but // do something just in case a "smart" compiler thinks an empty // synchronized block can be eliminated. mClosed = true; } } mCheckpointer = null; if (mOpenTrees != null) { mOpenTreesLatch.acquireExclusive(); try { mOpenTrees.clear(); mOpenTreesById.clear(0); } finally { mOpenTreesLatch.releaseExclusive(); } } Lock lock = mSharedCommitLock; if (lock != null) { lock.lock(); } try { closeNodeCache(); if (mAllocator != null) { mAllocator.clearDirtyNodes(); } IOException ex = null; ex = closeQuietly(ex, mRedoWriter, cause); ex = closeQuietly(ex, mPageDb, cause); ex = closeQuietly(ex, mTempFileManager, cause); if (shutdown && mBaseFile != null) { deleteRedoLogFiles(); new File(mBaseFile.getPath() + INFO_FILE_SUFFIX).delete(); ex = closeQuietly(ex, mLockFile, cause); new File(mBaseFile.getPath() + LOCK_FILE_SUFFIX).delete(); } else { ex = closeQuietly(ex, mLockFile, cause); } mLockManager.close(); if (ex != null) { throw ex; } } finally { if (lock != null) { lock.unlock(); } } } void checkClosed() throws DatabaseException { if (mClosed) { String message = "Closed"; Throwable cause = mClosedCause; if (cause != null) { message += "; " + rootCause(cause); } throw new DatabaseException(message, cause); } } void treeClosed(Tree tree) { mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.getValue(tree.mId); if (ref != null && ref.get() == tree) { ref.clear(); mOpenTrees.remove(tree.mName); mOpenTreesById.remove(tree.mId); } } finally { mOpenTreesLatch.releaseExclusive(); } } /** * @return new tree or null if given tree was not the currently open one */ Tree replaceClosedTree(Tree tree, Node newRoot) { mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.getValue(tree.mId); if (ref != null && ref.get() == tree) { ref.clear(); tree = new Tree(this, tree.mId, tree.mIdBytes, tree.mName, newRoot); ref = new TreeRef(tree, mOpenTreesRefQueue); mOpenTrees.put(tree.mName, ref); mOpenTreesById.insert(tree.mId).value = ref; return tree; } else { return null; } } finally { mOpenTreesLatch.releaseExclusive(); } } void dropClosedTree(Tree tree, long rootId, int cachedState) throws IOException { RedoWriter redo = mRedoWriter; byte[] idKey, nameKey; long commitPos; final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { Transaction txn; mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.getValue(tree.mId); if (ref == null || ref.get() != tree) { return; } idKey = newKey(KEY_TYPE_INDEX_ID, tree.mIdBytes); nameKey = newKey(KEY_TYPE_INDEX_NAME, tree.mName); txn = newNoRedoTransaction(); try { // Acquire locks to prevent tree from being re-opened. No deadlocks should // be possible with tree latch held exclusively, but order in a safe // fashion anyhow. A registry lookup can only follow a key map lookup. txn.lockExclusive(mRegistryKeyMap.mId, idKey); txn.lockExclusive(mRegistryKeyMap.mId, nameKey); txn.lockExclusive(mRegistry.mId, tree.mIdBytes); ref.clear(); mOpenTrees.remove(tree.mName); mOpenTreesById.remove(tree.mId); } catch (Throwable e) { txn.reset(); throw rethrow(e); } } finally { mOpenTreesLatch.releaseExclusive(); } // Complete the drop operation without preventing other indexes from being opened // or dropped concurrently. try { deletePage(rootId, cachedState); mRegistryKeyMap.remove(txn, idKey, tree.mName); mRegistryKeyMap.remove(txn, nameKey, tree.mIdBytes); mRegistry.delete(txn, tree.mIdBytes); commitPos = redo == null ? 0 : redo.dropIndex(tree.mId, mDurabilityMode.alwaysRedo()); txn.commit(); } catch (Throwable e) { throw closeOnFailure(this, e); } finally { txn.reset(); } } finally { commitLock.unlock(); } if (redo != null && commitPos != 0) { // Don't hold commit lock during sync. redo.txnCommitSync(commitPos); } } /** * @param rootId pass zero to create * @return unlatched and unevictable root node */ private Node loadTreeRoot(long rootId) throws IOException { Node rootNode = allocLatchedNode(false); try { if (rootId == 0) { rootNode.asEmptyRoot(); } else { try { rootNode.read(this, rootId); } catch (IOException e) { makeEvictableNow(rootNode); throw e; } } } finally { rootNode.releaseExclusive(); } return rootNode; } /** * Loads the root registry node, or creates one if store is new. Root node * is not eligible for eviction. */ private Node loadRegistryRoot(byte[] header, ReplicationManager rm) throws IOException { int version = decodeIntLE(header, I_ENCODING_VERSION); long rootId; if (version == 0) { rootId = 0; // No registry; clearly nothing has been checkpointed. mHasCheckpointed = false; } else { if (version != ENCODING_VERSION) { throw new CorruptDatabaseException("Unknown encoding version: " + version); } long replEncoding = decodeLongLE(header, I_REPL_ENCODING); if (rm == null) { if (replEncoding != 0) { throw new DatabaseException ("Database must be configured with a replication manager, " + "identified by: " + replEncoding); } } else { if (replEncoding == 0) { throw new DatabaseException ("Database was created initially without a replication manager"); } long expectedReplEncoding = rm.encoding(); if (replEncoding != expectedReplEncoding) { throw new DatabaseException ("Database was created initially with a different replication manager, " + "identified by: " + replEncoding); } } rootId = decodeLongLE(header, I_ROOT_PAGE_ID); } return loadTreeRoot(rootId); } private Tree openInternalTree(long treeId, boolean create) throws IOException { final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { byte[] treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, treeId); byte[] rootIdBytes = mRegistry.load(Transaction.BOGUS, treeIdBytes); long rootId; if (rootIdBytes != null) { rootId = decodeLongLE(rootIdBytes, 0); } else { if (!create) { return null; } rootId = 0; } return new Tree(this, treeId, treeIdBytes, null, loadTreeRoot(rootId)); } finally { commitLock.unlock(); } } private Index openIndex(byte[] name, boolean create) throws IOException { checkClosed(); Tree tree = quickFindIndex(null, name); if (tree != null) { return tree; } final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { // Cleaup before opening more indexes. cleanupUnreferencedTrees(null); byte[] nameKey = newKey(KEY_TYPE_INDEX_NAME, name); byte[] treeIdBytes = mRegistryKeyMap.load(null, nameKey); long treeId; // Is non-null if index was created. byte[] idKey; if (treeIdBytes != null) { idKey = null; treeId = decodeLongBE(treeIdBytes, 0); } else if (!create) { return null; } else { mOpenTreesLatch.acquireExclusive(); try { treeIdBytes = mRegistryKeyMap.load(null, nameKey); if (treeIdBytes != null) { idKey = null; treeId = decodeLongBE(treeIdBytes, 0); } else { treeIdBytes = new byte[8]; // Non-transactional operations are critical, in that // any failure is treated as non-recoverable. boolean critical = true; try { do { critical = false; treeId = nextTreeId(); encodeLongBE(treeIdBytes, 0, treeId); critical = true; } while (!mRegistry.insert (Transaction.BOGUS, treeIdBytes, EMPTY_BYTES)); critical = false; if (!mRegistryKeyMap.insert(null, nameKey, treeIdBytes)) { critical = true; mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index name"); } idKey = newKey(KEY_TYPE_INDEX_ID, treeIdBytes); critical = false; if (!mRegistryKeyMap.insert(null, idKey, name)) { mRegistryKeyMap.delete(null, nameKey); critical = true; mRegistry.delete(Transaction.BOGUS, treeIdBytes); throw new DatabaseException("Unable to insert index id"); } } catch (Throwable e) { if (!critical && e instanceof DatabaseException && ((DatabaseException) e).isRecoverable()) { throw (DatabaseException) e; } throw closeOnFailure(this, e); } } } finally { mOpenTreesLatch.releaseExclusive(); } } // Use a transaction to ensure that only one thread loads the // requested index. Nothing is written into it. Transaction txn = newNoRedoTransaction(); try { // Pass the transaction to acquire the lock. byte[] rootIdBytes = mRegistry.load(txn, treeIdBytes); tree = quickFindIndex(txn, name); if (tree != null) { // Another thread got the lock first and loaded the index. return tree; } long rootId = (rootIdBytes == null || rootIdBytes.length == 0) ? 0 : decodeLongLE(rootIdBytes, 0); tree = new Tree(this, treeId, treeIdBytes, name, loadTreeRoot(rootId)); TreeRef treeRef = new TreeRef(tree, mOpenTreesRefQueue); mOpenTreesLatch.acquireExclusive(); try { mOpenTrees.put(name, treeRef); mOpenTreesById.insert(treeId).value = treeRef; } finally { mOpenTreesLatch.releaseExclusive(); } return tree; } catch (Throwable e) { if (idKey != null) { // Rollback create of new index. try { mRegistryKeyMap.delete(null, idKey); mRegistryKeyMap.delete(null, nameKey); mRegistry.delete(Transaction.BOGUS, treeIdBytes); } catch (Throwable e2) { // Ignore. } } throw rethrow(e); } finally { txn.reset(); } } finally { commitLock.unlock(); } } private long nextTreeId() throws IOException { // By generating identifiers from a 64-bit sequence, it's effectively // impossible for them to get re-used after trees are deleted. Transaction txn = newTransaction(mDurabilityMode.alwaysRedo()); try { // Tree id mask, to make the identifiers less predictable and // non-compatible with other database instances. long treeIdMask; { byte[] key = {KEY_TYPE_TREE_ID_MASK}; byte[] treeIdMaskBytes = mRegistryKeyMap.load(txn, key); if (treeIdMaskBytes == null) { treeIdMaskBytes = new byte[8]; random().nextBytes(treeIdMaskBytes); mRegistryKeyMap.store(txn, key, treeIdMaskBytes); } treeIdMask = decodeLongLE(treeIdMaskBytes, 0); } byte[] key = {KEY_TYPE_NEXT_TREE_ID}; byte[] nextTreeIdBytes = mRegistryKeyMap.load(txn, key); if (nextTreeIdBytes == null) { nextTreeIdBytes = new byte[8]; } long nextTreeId = decodeLongLE(nextTreeIdBytes, 0); long treeId; do { treeId = scramble((nextTreeId++) ^ treeIdMask); } while (Tree.isInternal(treeId)); encodeLongLE(nextTreeIdBytes, 0, nextTreeId); mRegistryKeyMap.store(txn, key, nextTreeIdBytes); txn.commit(); return treeId; } finally { txn.reset(); } } /** * @return null if not found */ private Tree quickFindIndex(Transaction txn, byte[] name) throws IOException { TreeRef treeRef; mOpenTreesLatch.acquireShared(); try { treeRef = mOpenTrees.get(name); if (treeRef == null) { return null; } Tree tree = treeRef.get(); if (tree != null) { return tree; } } finally { mOpenTreesLatch.releaseShared(); } // Ensure that all nodes of cleared tree reference are evicted before // potentially replacing them. Weak references are cleared before they // are enqueued, and so polling the queue does not guarantee node // eviction. Process the tree directly. cleanupUnreferencedTree(txn, treeRef); return null; } /** * Tree instances retain a reference to an unevictable root node. If tree is no longer in * use, evict everything, including the root node. Method cannot be called while a * checkpoint is in progress. */ private void cleanupUnreferencedTrees(Transaction txn) throws IOException { final ReferenceQueue<Tree> queue = mOpenTreesRefQueue; if (queue == null) { return; } try { while (true) { Reference<? extends Tree> ref = queue.poll(); if (ref == null) { break; } if (ref instanceof TreeRef) { cleanupUnreferencedTree(txn, (TreeRef) ref); } } } catch (Exception e) { if (!mClosed) { throw rethrow(e); } } } private void cleanupUnreferencedTree(Transaction txn, TreeRef ref) throws IOException { // Acquire lock to prevent tree from being reloaded too soon. byte[] treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, ref.mId); if (txn == null) { txn = newNoRedoTransaction(); } else { txn.enter(); } try { // Pass the transaction to acquire the lock. mRegistry.load(txn, treeIdBytes); mOpenTreesLatch.acquireShared(); try { LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(ref.mId); if (entry == null || entry.value != ref) { return; } } finally { mOpenTreesLatch.releaseShared(); } Node root = ref.mRoot; root.acquireExclusive(); root.forceEvictTree(mPageDb); root.releaseExclusive(); mOpenTreesLatch.acquireExclusive(); try { mOpenTreesById.remove(ref.mId); mOpenTrees.remove(ref.mName); } finally { mOpenTreesLatch.releaseExclusive(); } } finally { txn.exit(); } // Move root node into usage list, allowing it to be re-used. makeEvictableNow(ref.mRoot); } private static byte[] newKey(byte type, byte[] payload) { byte[] key = new byte[1 + payload.length]; key[0] = type; arraycopy(payload, 0, key, 1, payload.length); return key; } /** * Returns the fixed size of all pages in the store, in bytes. */ int pageSize() { return mPageSize; } /** * Access the shared commit lock, which prevents commits while held. */ Lock sharedCommitLock() { return mSharedCommitLock; } /** * Acquires the excluisve commit lock, which prevents any database modifications. */ Lock acquireExclusiveCommitLock() throws InterruptedIOException { // If the commit lock cannot be immediately obtained, it's due to a shared lock being // held for a long time. While waiting for the exclusive lock, all other shared // requests are queued. By waiting a timed amount and giving up, the exclusive lock // request is effectively de-prioritized. For each retry, the timeout is doubled, to // ensure that the checkpoint request is not starved. Lock commitLock = mPageDb.exclusiveCommitLock(); try { long timeoutMillis = 1; while (!commitLock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS)) { timeoutMillis <<= 1; } return commitLock; } catch (InterruptedException e) { throw new InterruptedIOException(); } } /** * Returns a new or recycled Node instance, latched exclusively, with an id * of zero and a clean state. */ Node allocLatchedNode() throws IOException { return allocLatchedNode(true); } /** * Returns a new or recycled Node instance, latched exclusively, with an id * of zero and a clean state. * * @param evictable true if allocated node can be automatically evicted */ Node allocLatchedNode(boolean evictable) throws IOException { final Latch usageLatch = mUsageLatch; for (int trial = 1; trial <= 3; trial++) { usageLatch.acquireExclusive(); alloc: { int max = mMaxNodeCount; if (max == 0) { break alloc; } if (mNodeCount < max) { try { checkClosed(); Node node = new Node(mPageSize); node.acquireExclusive(); mNodeCount++; if (evictable) { if ((node.mLessUsed = mMostRecentlyUsed) == null) { mLeastRecentlyUsed = node; } else { mMostRecentlyUsed.mMoreUsed = node; } mMostRecentlyUsed = node; } // Return with node latch still held. return node; } finally { usageLatch.releaseExclusive(); } } if (!evictable && mLeastRecentlyUsed.mMoreUsed == mMostRecentlyUsed) { // Cannot allow list to shrink to less than two elements. break alloc; } do { Node node = mLeastRecentlyUsed; (mLeastRecentlyUsed = node.mMoreUsed).mLessUsed = null; node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; if (!node.tryAcquireExclusive()) { continue; } if (trial == 1) { // For first attempt, release the usage latch early to prevent blocking // other allocations while node is evicted. Subsequent attempts retain // the latch, preventing potential allocation starvation. usageLatch.releaseExclusive(); if ((node = Node.evict(node, mPageDb)) != null) { if (!evictable) { makeUnevictable(node); } // Return with node latch still held. return node; } usageLatch.acquireExclusive(); if (mMaxNodeCount == 0) { break alloc; } } else { try { if ((node = Node.evict(node, mPageDb)) != null) { if (!evictable) { // Detach from linked list. (mMostRecentlyUsed = node.mLessUsed).mMoreUsed = null; node.mLessUsed = null; } usageLatch.releaseExclusive(); // Return with node latch still held. return node; } } catch (Throwable e) { usageLatch.releaseExclusive(); throw rethrow(e); } } } while (--max > 0); } usageLatch.releaseExclusive(); checkClosed(); final Lock commitLock = sharedCommitLock(); commitLock.lock(); try { // Try to free up nodes from unreferenced trees. cleanupUnreferencedTrees(null); } finally { commitLock.unlock(); } } throw new CacheExhaustedException(); } /** * Unlinks all nodes from each other in usage list, and prevents new nodes * from being allocated. */ private void closeNodeCache() { final Latch usageLatch = mUsageLatch; usageLatch.acquireExclusive(); try { // Prevent new allocations. mMaxNodeCount = 0; Node node = mLeastRecentlyUsed; mLeastRecentlyUsed = null; mMostRecentlyUsed = null; while (node != null) { Node next = node.mMoreUsed; node.mLessUsed = null; node.mMoreUsed = null; // Make node appear to be evicted. node.mId = 0; // Attempt to unlink child nodes, making them appear to be evicted. if (node.tryAcquireExclusive()) { Node[] childNodes = node.mChildNodes; if (childNodes != null) { fill(childNodes, null); } node.releaseExclusive(); } node = next; } } finally { usageLatch.releaseExclusive(); } } /** * Returns a new or recycled Node instance, latched exclusively and marked * dirty. Caller must hold commit lock. */ Node allocDirtyNode() throws IOException { Node node = allocLatchedNode(true); try { dirty(node, mAllocator.allocPage(node)); return node; } catch (IOException e) { node.releaseExclusive(); throw e; } } /** * Returns a new or recycled Node instance, latched exclusively, marked * dirty and unevictable. Caller must hold commit lock. */ Node allocUnevictableNode() throws IOException { Node node = allocLatchedNode(false); try { dirty(node, mAllocator.allocPage(node)); return node; } catch (IOException e) { makeEvictableNow(node); node.releaseExclusive(); throw e; } } /** * Allow a Node which was allocated as unevictable to be evictable, * starting off as the most recently used. */ void makeEvictable(Node node) { final Latch usageLatch = mUsageLatch; usageLatch.acquireExclusive(); try { if (mMaxNodeCount == 0) { // Closed. return; } if (node.mMoreUsed != null || node.mLessUsed != null) { throw new IllegalStateException(); } (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; } finally { usageLatch.releaseExclusive(); } } /** * Allow a Node which was allocated as unevictable to be evictable, as the * least recently used. */ void makeEvictableNow(Node node) { final Latch usageLatch = mUsageLatch; usageLatch.acquireExclusive(); try { if (mMaxNodeCount == 0) { // Closed. return; } if (node.mMoreUsed != null || node.mLessUsed != null) { throw new IllegalStateException(); } (node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node; mLeastRecentlyUsed = node; } finally { usageLatch.releaseExclusive(); } } /** * Allow a Node which was allocated as evictable to be unevictable. */ void makeUnevictable(final Node node) { final Latch usageLatch = mUsageLatch; usageLatch.acquireExclusive(); try { if (mMaxNodeCount == 0) { // Closed. return; } final Node lessUsed = node.mLessUsed; final Node moreUsed = node.mMoreUsed; if (lessUsed == null) { (mLeastRecentlyUsed = moreUsed).mLessUsed = null; } else if (moreUsed == null) { (mMostRecentlyUsed = lessUsed).mMoreUsed = null; } else { lessUsed.mMoreUsed = moreUsed; moreUsed.mLessUsed = lessUsed; } node.mMoreUsed = null; node.mLessUsed = null; } finally { usageLatch.releaseExclusive(); } } /** * Caller must hold commit lock and any latch on node. */ boolean shouldMarkDirty(Node node) { return node.mCachedState != mCommitState && node.mId != Node.STUB_ID; } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markDirty(Tree tree, Node node) throws IOException { if (node.mCachedState == mCommitState || node.mId == Node.STUB_ID) { return false; } else { doMarkDirty(tree, node); return true; } } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markFragmentDirty(Node node) throws IOException { if (node.mCachedState == mCommitState) { return false; } else { long oldId = node.mId; long newId = mAllocator.allocPage(node); if (oldId != 0) { mPageDb.deletePage(oldId); } if (node.mCachedState != CACHED_CLEAN) { node.write(mPageDb); } dirty(node, newId); return true; } } /** * Caller must hold commit lock and exclusive latch on node. Method does * nothing if node is already dirty. Latch is never released by this method, * even if an exception is thrown. */ void markUndoLogDirty(Node node) throws IOException { if (node.mCachedState != mCommitState) { long oldId = node.mId; long newId = mAllocator.allocPage(node); mPageDb.deletePage(oldId); node.write(mPageDb); dirty(node, newId); } } /** * Caller must hold commit lock and exclusive latch on node. Method must * not be called if node is already dirty. Latch is never released by this * method, even if an exception is thrown. */ void doMarkDirty(Tree tree, Node node) throws IOException { long oldId = node.mId; long newId = mAllocator.allocPage(node); if (oldId != 0) { mPageDb.deletePage(oldId); } if (node.mCachedState != CACHED_CLEAN) { node.write(mPageDb); } if (node == tree.mRoot && tree.mIdBytes != null) { byte[] newEncodedId = new byte[8]; encodeLongLE(newEncodedId, 0, newId); mRegistry.store(Transaction.BOGUS, tree.mIdBytes, newEncodedId); } dirty(node, newId); } /** * Caller must hold commit lock and exclusive latch on node. */ private void dirty(Node node, long newId) { node.mId = newId; node.mCachedState = mCommitState; } /** * Caller must hold commit lock and exclusive latch on node. This method * should only be called for nodes whose existing data is not needed. */ void redirty(Node node) { node.mCachedState = mCommitState; mAllocator.dirty(node); } /** * Caller must hold commit lock and exclusive latch on node. This method should only be * called for nodes whose existing data is not needed and it is known that node is already * in the allocator's dirty list. */ void redirtyQ(Node node) { node.mCachedState = mCommitState; } /** * Similar to markDirty method except no new page is reserved, and old page * is not immediately deleted. Caller must hold commit lock and exclusive * latch on node. Latch is never released by this method, unless an * exception is thrown. */ void prepareToDelete(Node node) throws IOException { // Hello. My name is Inigo Montoya. You killed my father. Prepare to die. if (node.mCachedState == mCheckpointFlushState) { // Node must be committed with the current checkpoint, and so // it must be written out before it can be deleted. try { node.write(mPageDb); } catch (Throwable e) { node.releaseExclusive(); throw rethrow(e); } } } /** * Caller must hold commit lock and exclusive latch on node. The * prepareToDelete method must have been called first. Latch is always * released by this method, even if an exception is thrown. */ void deleteNode(Node node) throws IOException { deleteNode(node, true); } /** * @param canRecycle true if node's page can be immediately re-used */ void deleteNode(Node node, boolean canRecycle) throws IOException { try { long id = node.mId; if (canRecycle) { deletePage(id, node.mCachedState); } else if (id != 0) { mPageDb.deletePage(id); } node.mId = 0; // TODO: child node array should be recycled node.mChildNodes = null; // When node is re-allocated, it will be evicted. Ensure that eviction // doesn't write anything. node.mCachedState = CACHED_CLEAN; } finally { node.releaseExclusive(); } // Indicate that node is least recently used, allowing it to be // re-allocated immediately without evicting another node. Node must be // unlatched at this point, to prevent it from being immediately // promoted to most recently used by allocLatchedNode. final Latch usageLatch = mUsageLatch; usageLatch.acquireExclusive(); try { if (mMaxNodeCount == 0) { // Closed. return; } Node lessUsed = node.mLessUsed; if (lessUsed == null) { // Node might already be least... if (node.mMoreUsed != null) { // ...confirmed. return; } // ...Node isn't in the usage list at all. } else { Node moreUsed = node.mMoreUsed; if ((lessUsed.mMoreUsed = moreUsed) == null) { mMostRecentlyUsed = lessUsed; } else { moreUsed.mLessUsed = lessUsed; } node.mLessUsed = null; } (node.mMoreUsed = mLeastRecentlyUsed).mLessUsed = node; mLeastRecentlyUsed = node; } finally { usageLatch.releaseExclusive(); } } /** * Caller must hold commit lock. */ void deletePage(long id, int cachedState) throws IOException { if (id != 0) { if (cachedState == mCommitState) { // Newly reserved page was never used, so recycle it. mAllocator.recyclePage(id); } else { // Old data must survive until after checkpoint. mPageDb.deletePage(id); } } } /** * Deletes a page without the possibility of recycling it. Caller must hold commit lock. * * @param id must be greater than one */ void forceDeletePage(long id) throws IOException { mPageDb.deletePage(id); } /** * Indicate that a non-root node is most recently used. Root node is not * managed in usage list and cannot be evicted. Caller must hold any latch * on node. Latch is never released by this method, even if an exception is * thrown. */ void used(Node node) { // Because this method can be a bottleneck, don't wait for exclusive // latch. If node is popular, it will get more chances to be identified // as most recently used. This strategy works well enough because cache // eviction is always a best-guess approach. final Latch usageLatch = mUsageLatch; if (usageLatch.tryAcquireExclusive()) { Node moreUsed = node.mMoreUsed; if (moreUsed != null) { Node lessUsed = node.mLessUsed; if ((moreUsed.mLessUsed = lessUsed) == null) { mLeastRecentlyUsed = moreUsed; } else { lessUsed.mMoreUsed = moreUsed; } node.mMoreUsed = null; (node.mLessUsed = mMostRecentlyUsed).mMoreUsed = node; mMostRecentlyUsed = node; } usageLatch.releaseExclusive(); } } /** * Breakup a large value into separate pages, returning a new value which * encodes the page references. Caller must hold commit lock. * * Returned value begins with a one byte header: * * 0b0000_ffip * * The leading 4 bits define the encoding type, which must be 0. The 'f' bits define the * full value length field size: 2, 4, 6, or 8 bytes. The 'i' bit defines the inline * content length field size: 0 or 2 bytes. The 'p' bit is clear if direct pointers are * used, and set for indirect pointers. Pointers are always 6 bytes. * * @param caller optional tree node which is latched and calling this method * @param value can be null if value is all zeros * @param max maximum allowed size for returned byte array; must not be * less than 11 (can be 9 if full value length is < 65536) * @return null if max is too small */ byte[] fragment(Node caller, final byte[] value, final long vlength, int max) throws IOException { int pageSize = mPageSize; long pageCount = vlength / pageSize; int remainder = (int) (vlength % pageSize); if (vlength >= 65536) { // Subtract header size, full length field size, and size of one pointer. max -= (1 + 4 + 6); } else if (pageCount == 0 && remainder <= (max - (1 + 2 + 2))) { // Entire value fits inline. It didn't really need to be // encoded this way, but do as we're told. byte[] newValue = new byte[(1 + 2 + 2) + (int) vlength]; newValue[0] = 0x02; // ff=0, i=1, p=0 encodeShortLE(newValue, 1, (int) vlength); // full length encodeShortLE(newValue, 1 + 2, (int) vlength); // inline length arrayCopyOrFill(value, 0, newValue, (1 + 2 + 2), (int) vlength); return newValue; } else { // Subtract header size, full length field size, and size of one pointer. max -= (1 + 2 + 6); } if (max < 0) { return null; } long pointerSpace = pageCount * 6; byte[] newValue; if (remainder <= max && remainder < 65536 && (pointerSpace <= (max + (6 - 2) - remainder))) { // Remainder fits inline, minimizing internal fragmentation. All // extra pages will be full. All pointers fit too; encode direct. // Conveniently, 2 is the header bit and the inline length field size. int inline = remainder == 0 ? 0 : 2; byte header = (byte) inline; int offset; if (vlength < (1L << (2 * 8))) { // (2 byte length field) offset = 1 + 2; } else if (vlength < (1L << (4 * 8))) { header |= 0x04; // ff = 1 (4 byte length field) offset = 1 + 4; } else if (vlength < (1L << (6 * 8))) { header |= 0x08; // ff = 2 (6 byte length field) offset = 1 + 6; } else { header |= 0x0c; // ff = 3 (8 byte length field) offset = 1 + 8; } int poffset = offset + inline + remainder; newValue = new byte[poffset + (int) pointerSpace]; if (pageCount > 0) { if (value == null) { // Value is sparse, so just fill with null pointers. fill(newValue, poffset, poffset + ((int) pageCount) * 6, (byte) 0); } else { int voffset = remainder; while (true) { Node node = allocDirtyNode(); try { mFragmentCache.put(caller, node); encodeInt48LE(newValue, poffset, node.mId); arraycopy(value, voffset, node.mPage, 0, pageSize); if (pageCount == 1) { break; } } finally { node.releaseExclusive(); } pageCount--; poffset += 6; voffset += pageSize; } } } newValue[0] = header; if (remainder != 0) { encodeShortLE(newValue, offset, remainder); // inline length arrayCopyOrFill(value, 0, newValue, offset + 2, remainder); } } else { // Remainder doesn't fit inline, so don't encode any inline // content. Last extra page will not be full. pageCount++; pointerSpace += 6; byte header; int offset; if (vlength < (1L << (2 * 8))) { header = 0x00; // ff = 0, i=0 offset = 1 + 2; } else if (vlength < (1L << (4 * 8))) { header = 0x04; // ff = 1, i=0 offset = 1 + 4; } else if (vlength < (1L << (6 * 8))) { header = 0x08; // ff = 2, i=0 offset = 1 + 6; } else { header = 0x0c; // ff = 3, i=0 offset = 1 + 8; } if (pointerSpace <= (max + 6)) { // All pointers fit, so encode as direct. newValue = new byte[offset + (int) pointerSpace]; if (pageCount > 0) { if (value == null) { // Value is sparse, so just fill with null pointers. fill(newValue, offset, offset + ((int) pageCount) * 6, (byte) 0); } else { int voffset = 0; while (true) { Node node = allocDirtyNode(); try { mFragmentCache.put(caller, node); encodeInt48LE(newValue, offset, node.mId); byte[] page = node.mPage; if (pageCount > 1) { arraycopy(value, voffset, page, 0, pageSize); } else { arraycopy(value, voffset, page, 0, remainder); // Zero fill the rest, making it easier to extend later. fill(page, remainder, page.length, (byte) 0); break; } } finally { node.releaseExclusive(); } pageCount--; offset += 6; voffset += pageSize; } } } } else { // Use indirect pointers. header |= 0x01; newValue = new byte[offset + 6]; if (value == null) { // Value is sparse, so just store a null pointer. encodeInt48LE(newValue, offset, 0); } else { Node inode = allocDirtyNode(); encodeInt48LE(newValue, offset, inode.mId); int levels = calculateInodeLevels(vlength, pageSize); writeMultilevelFragments(caller, levels, inode, value, 0, vlength); } } newValue[0] = header; } // Encode full length field. if (vlength < (1L << (2 * 8))) { encodeShortLE(newValue, 1, (int) vlength); } else if (vlength < (1L << (4 * 8))) { encodeIntLE(newValue, 1, (int) vlength); } else if (vlength < (1L << (6 * 8))) { encodeInt48LE(newValue, 1, vlength); } else { encodeLongLE(newValue, 1, vlength); } return newValue; } static int calculateInodeLevels(long vlength, int pageSize) { int levels = 0; if (vlength >= 0 && vlength < (Long.MAX_VALUE / 2)) { long len = (vlength + (pageSize - 1)) / pageSize; if (len > 1) { int ptrCount = pageSize / 6; do { levels++; } while ((len = (len + (ptrCount - 1)) / ptrCount) > 1); } } else { BigInteger bPageSize = BigInteger.valueOf(pageSize); BigInteger bLen = (valueOfUnsigned(vlength) .add(bPageSize.subtract(BigInteger.ONE))).divide(bPageSize); if (bLen.compareTo(BigInteger.ONE) > 0) { BigInteger bPtrCount = bPageSize.divide(BigInteger.valueOf(6)); BigInteger bPtrCountM1 = bPtrCount.subtract(BigInteger.ONE); do { levels++; } while ((bLen = (bLen.add(bPtrCountM1)).divide(bPtrCount)) .compareTo(BigInteger.ONE) > 0); } } return levels; } /** * @param level inode level; at least 1 * @param inode exclusive latched parent inode; always released by this method * @param value slice of complete value being fragmented */ private void writeMultilevelFragments(Node caller, int level, Node inode, byte[] value, int voffset, long vlength) throws IOException { long levelCap; long[] childNodeIds; Node[] childNodes; try { byte[] page = inode.mPage; level--; levelCap = levelCap(level); // Pre-allocate and reference the required child nodes in order for // parent node latch to be released early. FragmentCache can then // safely evict the parent node if necessary. int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap); childNodeIds = new long[childNodeCount]; childNodes = new Node[childNodeCount]; try { int poffset = 0; for (int i=0; i<childNodeCount; poffset += 6, i++) { Node childNode = allocDirtyNode(); encodeInt48LE(page, poffset, childNodeIds[i] = childNode.mId); childNodes[i] = childNode; // Allow node to be evicted, but don't write anything yet. childNode.mCachedState = CACHED_CLEAN; childNode.releaseExclusive(); } // Zero fill the rest, making it easier to extend later. fill(page, poffset, page.length, (byte) 0); } catch (Throwable e) { // Panic. close(e); throw rethrow(e); } mFragmentCache.put(caller, inode); } finally { inode.releaseExclusive(); } for (int i=0; i<childNodeIds.length; i++) { long childNodeId = childNodeIds[i]; Node childNode = childNodes[i]; latchChild: { if (childNodeId == childNode.mId) { childNode.acquireExclusive(); if (childNodeId == childNode.mId) { // Since commit lock is held, only need to switch the state. Calling // redirty is unnecessary and it would screw up the dirty list order // for no good reason. Use the quick variant. redirtyQ(childNode); break latchChild; } childNode.releaseExclusive(); } // Child node was evicted, although it was clean. childNode = allocLatchedNode(); childNode.mId = childNodeId; redirty(childNode); } int len = (int) Math.min(levelCap, vlength); if (level <= 0) { byte[] childPage = childNode.mPage; arraycopy(value, voffset, childPage, 0, len); // Zero fill the rest, making it easier to extend later. fill(childPage, len, childPage.length, (byte) 0); mFragmentCache.put(caller, childNode); childNode.releaseExclusive(); } else { writeMultilevelFragments(caller, level, childNode, value, voffset, len); } vlength -= len; voffset += len; } } /** * Reconstruct a fragmented value. * * @param caller optional tree node which is latched and calling this method */ byte[] reconstruct(Node caller, byte[] fragmented, int off, int len) throws IOException { int header = fragmented[off++]; len--; int vLen; switch ((header >> 2) & 0x03) { default: vLen = decodeUnsignedShortLE(fragmented, off); break; case 1: vLen = decodeIntLE(fragmented, off); if (vLen < 0) { throw new LargeValueException(vLen & 0xffffffffL); } break; case 2: long vLenL = decodeUnsignedInt48LE(fragmented, off); if (vLenL > Integer.MAX_VALUE) { throw new LargeValueException(vLenL); } vLen = (int) vLenL; break; case 3: vLenL = decodeLongLE(fragmented, off); if (vLenL < 0 || vLenL > Integer.MAX_VALUE) { throw new LargeValueException(vLenL); } vLen = (int) vLenL; break; } { int vLenFieldSize = 2 + ((header >> 1) & 0x06); off += vLenFieldSize; len -= vLenFieldSize; } byte[] value; try { value = new byte[vLen]; } catch (OutOfMemoryError e) { throw new LargeValueException(vLen, e); } int vOff = 0; if ((header & 0x02) != 0) { // Inline content. int inLen = decodeUnsignedShortLE(fragmented, off); off += 2; len -= 2; arraycopy(fragmented, off, value, vOff, inLen); off += inLen; len -= inLen; vOff += inLen; vLen -= inLen; } if ((header & 0x01) == 0) { // Direct pointers. while (len >= 6) { long nodeId = decodeUnsignedInt48LE(fragmented, off); off += 6; len -= 6; int pLen; if (nodeId == 0) { // Reconstructing a sparse value. Array is already zero-filled. pLen = Math.min(vLen, mPageSize); } else { Node node = mFragmentCache.get(caller, nodeId); try { byte[] page = node.mPage; pLen = Math.min(vLen, page.length); arraycopy(page, 0, value, vOff, pLen); } finally { node.releaseShared(); } } vOff += pLen; vLen -= pLen; } } else { // Indirect pointers. long inodeId = decodeUnsignedInt48LE(fragmented, off); if (inodeId != 0) { Node inode = mFragmentCache.get(caller, inodeId); int levels = calculateInodeLevels(vLen, mPageSize); readMultilevelFragments(caller, levels, inode, value, 0, vLen); } } return value; } /** * @param level inode level; at least 1 * @param inode shared latched parent inode; always released by this method * @param value slice of complete value being reconstructed; initially filled with zeros */ private void readMultilevelFragments(Node caller, int level, Node inode, byte[] value, int voffset, int vlength) throws IOException { byte[] page = inode.mPage; level--; long levelCap = levelCap(level); // Copy all child node ids and release parent latch early. // FragmentCache can then safely evict the parent node if necessary. int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap); long[] childNodeIds = new long[childNodeCount]; for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) { childNodeIds[i] = decodeUnsignedInt48LE(page, poffset); } inode.releaseShared(); for (long childNodeId : childNodeIds) { int len = (int) Math.min(levelCap, vlength); if (childNodeId != 0) { Node childNode = mFragmentCache.get(caller, childNodeId); if (level <= 0) { arraycopy(childNode.mPage, 0, value, voffset, len); childNode.releaseShared(); } else { readMultilevelFragments(caller, level, childNode, value, voffset, len); } } vlength -= len; voffset += len; } } /** * Delete the extra pages of a fragmented value. Caller must hold commit lock. * * @param caller optional tree node which is latched and calling this method */ void deleteFragments(Node caller, byte[] fragmented, int off, int len) throws IOException { int header = fragmented[off++]; len--; long vLen; if ((header & 0x01) == 0) { // Don't need to read the value length when deleting direct pointers. vLen = 0; } else { switch ((header >> 2) & 0x03) { default: vLen = decodeUnsignedShortLE(fragmented, off); break; case 1: vLen = decodeIntLE(fragmented, off) & 0xffffffffL; break; case 2: vLen = decodeUnsignedInt48LE(fragmented, off); break; case 3: vLen = decodeLongLE(fragmented, off); break; } } { int vLenFieldSize = 2 + ((header >> 1) & 0x06); off += vLenFieldSize; len -= vLenFieldSize; } if ((header & 0x02) != 0) { // Skip inline content. int inLen = 2 + decodeUnsignedShortLE(fragmented, off); off += inLen; len -= inLen; } if ((header & 0x01) == 0) { // Direct pointers. while (len >= 6) { long nodeId = decodeUnsignedInt48LE(fragmented, off); off += 6; len -= 6; deleteFragment(caller, nodeId); } } else { // Indirect pointers. long inodeId = decodeUnsignedInt48LE(fragmented, off); if (inodeId != 0) { Node inode = removeInode(caller, inodeId); int levels = calculateInodeLevels(vLen, mPageSize); deleteMultilevelFragments(caller, levels, inode, vLen); } } } /** * @param level inode level; at least 1 * @param inode exclusive latched parent inode; always released by this method */ private void deleteMultilevelFragments(Node caller, int level, Node inode, long vlength) throws IOException { byte[] page = inode.mPage; level--; long levelCap = levelCap(level); // Copy all child node ids and release parent latch early. int childNodeCount = (int) ((vlength + (levelCap - 1)) / levelCap); long[] childNodeIds = new long[childNodeCount]; for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) { childNodeIds[i] = decodeUnsignedInt48LE(page, poffset); } deleteNode(inode); if (level <= 0) for (long childNodeId : childNodeIds) { deleteFragment(caller, childNodeId); } else for (long childNodeId : childNodeIds) { long len = Math.min(levelCap, vlength); if (childNodeId != 0) { Node childNode = removeInode(caller, childNodeId); deleteMultilevelFragments(caller, level, childNode, len); } vlength -= len; } } /** * @param nodeId must not be zero * @return non-null Node with exclusive latch held */ private Node removeInode(Node caller, long nodeId) throws IOException { Node node = mFragmentCache.remove(caller, nodeId); if (node == null) { node = allocLatchedNode(false); node.mId = nodeId; node.mType = TYPE_FRAGMENT; node.mCachedState = readNodePage(nodeId, node.mPage); } return node; } /** * @param nodeId can be zero */ private void deleteFragment(Node caller, long nodeId) throws IOException { if (nodeId != 0) { Node node = mFragmentCache.remove(caller, nodeId); if (node != null) { deleteNode(node); } else if (!mHasCheckpointed) { // Page was never used if nothing has ever been checkpointed. mAllocator.recyclePage(nodeId); } else { // Page is clean if not in a Node, and so it must survive until // after the next checkpoint. mPageDb.deletePage(nodeId); } } } private static long[] calculateInodeLevelCaps(int pageSize) { long[] caps = new long[10]; long cap = pageSize; long scalar = pageSize / 6; // 6-byte pointers int i = 0; while (i < caps.length) { caps[i++] = cap; long next = cap * scalar; if (next / scalar != cap) { caps[i++] = Long.MAX_VALUE; break; } cap = next; } if (i < caps.length) { long[] newCaps = new long[i]; arraycopy(caps, 0, newCaps, 0, i); caps = newCaps; } return caps; } long levelCap(int level) { return mFragmentInodeLevelCaps[level]; } /** * If fragmented trash exists, non-transactionally delete all fragmented values. Expected * to be called only during recovery or replication leader switch. */ void emptyAllFragmentedTrash(boolean checkpoint) throws IOException { FragmentedTrash trash = mFragmentedTrash; if (trash != null) { if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_DELETE_FRAGMENTS, "Deleting unused large fragments"); } if (trash.emptyAllTrash() && checkpoint) { checkpoint(false, 0, 0); } } } /** * Obtain the trash for transactionally deleting fragmented values. */ FragmentedTrash fragmentedTrash() throws IOException { FragmentedTrash trash = mFragmentedTrash; if (trash != null) { return trash; } mOpenTreesLatch.acquireExclusive(); try { if ((trash = mFragmentedTrash) != null) { return trash; } Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, true); return mFragmentedTrash = new FragmentedTrash(tree); } finally { mOpenTreesLatch.releaseExclusive(); } } byte[] removeSpareBuffer() { return mSpareBufferPool.remove(); } void addSpareBuffer(byte[] buffer) { mSpareBufferPool.add(buffer); } /** * @return initial cached state for node */ byte readNodePage(long id, byte[] page) throws IOException { mPageDb.readPage(id, page); if (!mHasCheckpointed) { // Read is reloading an evicted node which is known to be dirty. mSharedCommitLock.lock(); try { return mCommitState; } finally { mSharedCommitLock.unlock(); } } // TODO: Keep some sort of cache of ids known to be dirty. If reloaded // before commit, then they're still dirty. Without this optimization, // too many pages are allocated when: evictions are high, write rate is // high, and commits are bogged down. A Bloom filter is not // appropriate, because of false positives. A random evicting cache // works well -- it has no collision chains. Evict whatever else was // there in the slot. An array of longs should suffice. return CACHED_CLEAN; } void checkpoint(boolean force, long sizeThreshold, long delayThresholdNanos) throws IOException { // Checkpoint lock ensures consistent state between page store and logs. synchronized (mCheckpointLock) { if (mClosed) { return; } // Now's a good time to clean things up. cleanupUnreferencedTrees(null); final Node root = mRegistry.mRoot; long nowNanos = System.nanoTime(); if (!force) { check: { if (delayThresholdNanos == 0) { break check; } if (delayThresholdNanos > 0 && ((nowNanos - mLastCheckpointNanos) >= delayThresholdNanos)) { break check; } if (mRedoWriter == null || mRedoWriter.shouldCheckpoint(sizeThreshold)) { break check; } // Thresholds not met for a full checkpoint, but sync the // redo log for durability. mRedoWriter.sync(); return; } root.acquireShared(); try { if (root.mCachedState == CACHED_CLEAN) { // Root is clean, so nothing to do. return; } } finally { root.releaseShared(); } } mLastCheckpointNanos = nowNanos; final RedoWriter redo = mRedoWriter; if (redo != null) { // File-based redo log should create a new file, but not write to it yet. redo.checkpointPrepare(); } while (true) { Lock commitLock = acquireExclusiveCommitLock(); // Registry root is infrequently modified, and so shared latch // is usually available. If not, cause might be a deadlock. To // be safe, always release commit lock and start over. if (root.tryAcquireShared()) { break; } commitLock.unlock(); } final long redoNum, redoPos, redoTxnId; if (redo == null) { redoNum = 0; redoPos = 0; redoTxnId = 0; } else { // Switch and capture state while commit lock is held. redo.checkpointSwitch(); redoNum = redo.checkpointNumber(); redoPos = redo.checkpointPosition(); redoTxnId = redo.checkpointTransactionId(); } if (mEventListener != null) { mEventListener.notify(EventType.CHECKPOINT_BEGIN, "Checkpoint begin: %1$d, %2$d", redoNum, redoPos); } mCheckpointFlushState = CHECKPOINT_FLUSH_PREPARE; UndoLog masterUndoLog; try { // TODO: I don't like all this activity with exclusive commit // lock held. UndoLog can be refactored to store into a special // Tree, but this requires more features to be added to Tree // first. Specifically, large values and appending to them. final long masterUndoLogId; synchronized (mTxnIdLock) { int count = mUndoLogCount; if (count == 0) { masterUndoLog = null; masterUndoLogId = 0; } else { masterUndoLog = new UndoLog(this, 0); byte[] workspace = null; for (UndoLog log = mTopUndoLog; log != null; log = log.mPrev) { workspace = log.writeToMaster(masterUndoLog, workspace); } masterUndoLogId = masterUndoLog.topNodeId(); if (masterUndoLogId == 0) { // Nothing was actually written to the log. masterUndoLog = null; } } } mPageDb.commit(new PageDb.CommitCallback() { @Override public byte[] prepare() throws IOException { return flush(redoNum, redoPos, redoTxnId, masterUndoLogId); } }); } catch (IOException e) { if (mCheckpointFlushState == CHECKPOINT_FLUSH_PREPARE) { // Exception was thrown with locks still held. mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; root.releaseShared(); mPageDb.exclusiveCommitLock().unlock(); } throw e; } if (masterUndoLog != null) { // Delete the master undo log, which won't take effect until // the next checkpoint. masterUndoLog.truncate(false); } // Note: This step is intended to discard old redo data, but it can // get skipped if process exits at this point. Data is discarded // again when database is re-opened. if (mRedoWriter != null) { mRedoWriter.checkpointFinished(); } if (mEventListener != null) { double duration = (System.nanoTime() - mLastCheckpointNanos) / 1000000000.0; mEventListener.notify(EventType.CHECKPOINT_BEGIN, "Checkpoint completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } } } /** * Method is invoked with exclusive commit lock and shared root node latch * held. Both are released by this method. */ private byte[] flush(final long redoNum, final long redoPos, final long redoTxnId, final long masterUndoLogId) throws IOException { final long txnId; synchronized (mTxnIdLock) { txnId = mTxnId; } final Node root = mRegistry.mRoot; final long rootId = root.mId; final int stateToFlush = mCommitState; mHasCheckpointed = true; // Must be set before switching commit state. mCheckpointFlushState = stateToFlush; mCommitState = (byte) (stateToFlush ^ 1); root.releaseShared(); mPageDb.exclusiveCommitLock().unlock(); if (mRedoWriter != null) { mRedoWriter.checkpointStarted(); } if (mEventListener != null) { mEventListener.notify(EventType.CHECKPOINT_FLUSH, "Flushing all dirty nodes"); } try { mAllocator.flushDirtyNodes(stateToFlush); } finally { mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; } byte[] header = new byte[HEADER_SIZE]; encodeIntLE(header, I_ENCODING_VERSION, ENCODING_VERSION); encodeLongLE(header, I_ROOT_PAGE_ID, rootId); encodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID, masterUndoLogId); encodeLongLE(header, I_TRANSACTION_ID, txnId); encodeLongLE(header, I_CHECKPOINT_NUMBER, redoNum); encodeLongLE(header, I_REDO_TXN_ID, redoTxnId); encodeLongLE(header, I_REDO_POSITION, redoPos); encodeLongLE(header, I_REPL_ENCODING, mRedoWriter == null ? 0 : mRedoWriter.encoding()); return header; } // Called by DurablePageDb with header latch held. static long readRedoPosition(byte[] header, int offset) { return decodeLongLE(header, offset + I_REDO_POSITION); } }
true
true
private Database(DatabaseConfig config, int openMode) throws IOException { config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener); mBaseFile = config.mBaseFile; final File[] dataFiles = config.dataFiles(); int pageSize = config.mPageSize; boolean explicitPageSize = true; if (pageSize <= 0) { config.pageSize(pageSize = DEFAULT_PAGE_SIZE); explicitPageSize = false; } else if (pageSize < MINIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE); } else if (pageSize > MAXIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE); } else if ((pageSize & 1) != 0) { throw new IllegalArgumentException ("Page size must be even: " + pageSize); } int minCache, maxCache; cacheSize: { long minCachedBytes = Math.max(0, config.mMinCachedBytes); long maxCachedBytes = Math.max(0, config.mMaxCachedBytes); if (maxCachedBytes == 0) { maxCachedBytes = minCachedBytes; if (maxCachedBytes == 0) { minCache = maxCache = DEFAULT_CACHED_NODES; break cacheSize; } } if (minCachedBytes > maxCachedBytes) { throw new IllegalArgumentException ("Minimum cache size exceeds maximum: " + minCachedBytes + " > " + maxCachedBytes); } minCache = nodeCountFromBytes(minCachedBytes, pageSize); maxCache = nodeCountFromBytes(maxCachedBytes, pageSize); minCache = Math.max(MIN_CACHED_NODES, minCache); maxCache = Math.max(MIN_CACHED_NODES, maxCache); } // Update config such that info file is correct. config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize); config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize); mUsageLatch = new Latch(); mMaxNodeCount = maxCache; mDurabilityMode = config.mDurabilityMode; mDefaultLockTimeoutNanos = config.mLockTimeoutNanos; mLockManager = new LockManager(config.mLockUpgradeRule, mDefaultLockTimeoutNanos); if (mBaseFile != null && !config.mReadOnly && config.mMkdirs) { FileFactory factory = config.mFileFactory; File baseDir = mBaseFile.getParentFile(); if (factory == null) { baseDir.mkdirs(); } else { factory.createDirectories(baseDir); } if (dataFiles != null) { for (File f : dataFiles) { File dataDir = f.getParentFile(); if (factory == null) { dataDir.mkdirs(); } else { factory.createDirectories(dataDir); } } } } try { // Create lock file, preventing database from being opened multiple times. if (mBaseFile == null || openMode == OPEN_TEMP) { mLockFile = null; } else { File lockFile = new File(mBaseFile.getPath() + LOCK_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null && !config.mReadOnly) { factory.createFile(lockFile); } mLockFile = new LockedFile(lockFile, config.mReadOnly); } if (openMode == OPEN_DESTROY) { deleteRedoLogFiles(); } if (dataFiles == null) { PageArray dataPageArray = config.mDataPageArray; if (dataPageArray == null) { mPageDb = new NonPageDb(pageSize); } else { mPageDb = DurablePageDb.open (dataPageArray, config.mCrypto, openMode == OPEN_DESTROY); } } else { EnumSet<OpenOption> options = config.createOpenOptions(); mPageDb = DurablePageDb.open (explicitPageSize, pageSize, dataFiles, config.mFileFactory, options, config.mCrypto, openMode == OPEN_DESTROY); } // Actual page size might differ from configured size. config.pageSize(mPageSize = mPageDb.pageSize()); // Write info file of properties, after database has been opened and after page // size is truly known. if (mBaseFile != null && openMode != OPEN_TEMP && !config.mReadOnly) { File infoFile = new File(mBaseFile.getPath() + INFO_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null) { factory.createFile(infoFile); } Writer w = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8")); try { config.writeInfo(w); } finally { w.close(); } } mSharedCommitLock = mPageDb.sharedCommitLock(); // Pre-allocate nodes. They are automatically added to the usage // list, and so nothing special needs to be done to allow them to // get used. Since the initial state is clean, evicting these // nodes does nothing. long cacheInitStart = 0; if (mEventListener != null) { mEventListener.notify(EventType.CACHE_INIT_BEGIN, "Initializing %1$d cached nodes", minCache); cacheInitStart = System.nanoTime(); } try { for (int i=minCache; --i>=0; ) { allocLatchedNode(true).releaseExclusive(); } } catch (OutOfMemoryError e) { mMostRecentlyUsed = null; mLeastRecentlyUsed = null; throw new OutOfMemoryError ("Unable to allocate the minimum required number of cached nodes: " + minCache + " (" + (minCache * (pageSize + NODE_OVERHEAD)) + " bytes)"); } if (mEventListener != null) { double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0; mEventListener.notify(EventType.CACHE_INIT_COMPLETE, "Cache initialization completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } int spareBufferCount = Runtime.getRuntime().availableProcessors(); mSpareBufferPool = new BufferPool(mPageSize, spareBufferCount); mSharedCommitLock.lock(); try { mCommitState = CACHED_DIRTY_0; } finally { mSharedCommitLock.unlock(); } byte[] header = new byte[HEADER_SIZE]; mPageDb.readExtraCommitData(header); // Also verifies the database and replication encodings. Node rootNode = loadRegistryRoot(header, config.mReplManager); mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, rootNode); mOpenTreesLatch = new Latch(); if (openMode == OPEN_TEMP) { mOpenTrees = Collections.emptyMap(); mOpenTreesById = new LHashTable.Obj<TreeRef>(0); mOpenTreesRefQueue = null; } else { mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE); mOpenTreesById = new LHashTable.Obj<TreeRef>(16); mOpenTreesRefQueue = new ReferenceQueue<Tree>(); } synchronized (mTxnIdLock) { mTxnId = decodeLongLE(header, I_TRANSACTION_ID); } long redoNum = decodeLongLE(header, I_CHECKPOINT_NUMBER); long redoPos = decodeLongLE(header, I_REDO_POSITION); long redoTxnId = decodeLongLE(header, I_REDO_TXN_ID); if (openMode == OPEN_TEMP) { mRegistryKeyMap = null; } else { mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true); } mAllocator = new PageAllocator(mPageDb); if (mBaseFile == null) { // Non-durable database never evicts anything. mFragmentCache = new FragmentMap(); } else { // Regular database evicts automatically. mFragmentCache = new FragmentCache(this, mMaxNodeCount); } if (openMode != OPEN_TEMP) { Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false); if (tree != null) { mFragmentedTrash = new FragmentedTrash(tree); } } // Limit maximum fragmented entry size to guarantee that 2 entries // fit. Each also requires 2 bytes for pointer and up to 3 bytes // for value length field. mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1; mFragmentInodeLevelCaps = calculateInodeLevelCaps(mPageSize); long recoveryStart = 0; if (mBaseFile == null || openMode == OPEN_TEMP) { mRedoWriter = null; } else { // Perform recovery by examining redo and undo logs. if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin"); recoveryStart = System.nanoTime(); } LHashTable.Obj<Transaction> txns = new LHashTable.Obj<Transaction>(16); { long masterNodeId = decodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID); if (masterNodeId != 0) { if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs"); } UndoLog.recoverMasterUndoLog(this, masterNodeId) .recoverTransactions(txns, LockMode.UPGRADABLE_READ, 0L); } } ReplicationManager rm = config.mReplManager; if (rm != null) { rm.start(redoPos); ReplRedoEngine engine = new ReplRedoEngine (rm, config.mMaxReplicaThreads, this, txns); mRedoWriter = engine.initWriter(redoNum); // Cannot start recovery until constructor is finished and final field // values are visible to other threads. Pass the state to the caller // through the config object. config.mReplRecoveryStartNanos = recoveryStart; config.mReplInitialTxnId = redoTxnId; } else { long logId = redoNum; // Make sure old redo logs are deleted. Process might have exited // before last checkpoint could delete them. for (int i=1; i<=2; i++) { RedoLog.deleteOldFile(config.mBaseFile, logId - i); } RedoLogApplier applier = new RedoLogApplier(this, txns); RedoLog replayLog = new RedoLog(config, logId, redoPos); // As a side-effect, log id is set one higher than last file scanned. Set<File> redoFiles = replayLog.replay (applier, mEventListener, EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d"); boolean doCheckpoint = !redoFiles.isEmpty(); // Avoid re-using transaction ids used by recovery. redoTxnId = applier.mHighestTxnId; if (redoTxnId != 0) { synchronized (mTxnIdLock) { // Subtract for modulo comparison. if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) { mTxnId = redoTxnId; } } } if (txns.size() > 0) { // Rollback or truncate all remaining transactions. They were never // explicitly rolled back, or they were committed but not cleaned up. if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_PROCESS_REMAINING, "Processing remaining transactions"); } txns.traverse(new LHashTable.Visitor <LHashTable.ObjEntry<Transaction>, IOException>() { public boolean visit(LHashTable.ObjEntry<Transaction> entry) throws IOException { entry.value.recoveryCleanup(); return false; } }); doCheckpoint = true; } // New redo logs begin with identifiers one higher than last scanned. mRedoWriter = new RedoLog(config, replayLog); // FIXME: If any exception is thrown before checkpoint is complete, delete // the newly created redo log file. if (doCheckpoint) { checkpoint(true, 0, 0); // Only cleanup after successful checkpoint. for (File file : redoFiles) { file.delete(); } } // Delete lingering fragmented values after undo logs have been processed, // ensuring deletes were committed. emptyAllFragmentedTrash(true); recoveryComplete(recoveryStart); } } if (mBaseFile == null || openMode == OPEN_TEMP) { mTempFileManager = null; } else { mTempFileManager = new TempFileManager(mBaseFile, config.mFileFactory); } } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } }
private Database(DatabaseConfig config, int openMode) throws IOException { config.mEventListener = mEventListener = SafeEventListener.makeSafe(config.mEventListener); mBaseFile = config.mBaseFile; final File[] dataFiles = config.dataFiles(); int pageSize = config.mPageSize; boolean explicitPageSize = true; if (pageSize <= 0) { config.pageSize(pageSize = DEFAULT_PAGE_SIZE); explicitPageSize = false; } else if (pageSize < MINIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE); } else if (pageSize > MAXIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE); } else if ((pageSize & 1) != 0) { throw new IllegalArgumentException ("Page size must be even: " + pageSize); } int minCache, maxCache; cacheSize: { long minCachedBytes = Math.max(0, config.mMinCachedBytes); long maxCachedBytes = Math.max(0, config.mMaxCachedBytes); if (maxCachedBytes == 0) { maxCachedBytes = minCachedBytes; if (maxCachedBytes == 0) { minCache = maxCache = DEFAULT_CACHED_NODES; break cacheSize; } } if (minCachedBytes > maxCachedBytes) { throw new IllegalArgumentException ("Minimum cache size exceeds maximum: " + minCachedBytes + " > " + maxCachedBytes); } minCache = nodeCountFromBytes(minCachedBytes, pageSize); maxCache = nodeCountFromBytes(maxCachedBytes, pageSize); minCache = Math.max(MIN_CACHED_NODES, minCache); maxCache = Math.max(MIN_CACHED_NODES, maxCache); } // Update config such that info file is correct. config.mMinCachedBytes = byteCountFromNodes(minCache, pageSize); config.mMaxCachedBytes = byteCountFromNodes(maxCache, pageSize); mUsageLatch = new Latch(); mMaxNodeCount = maxCache; mDurabilityMode = config.mDurabilityMode; mDefaultLockTimeoutNanos = config.mLockTimeoutNanos; mLockManager = new LockManager(config.mLockUpgradeRule, mDefaultLockTimeoutNanos); if (mBaseFile != null && !config.mReadOnly && config.mMkdirs) { FileFactory factory = config.mFileFactory; File baseDir = mBaseFile.getParentFile(); if (factory == null) { baseDir.mkdirs(); } else { factory.createDirectories(baseDir); } if (dataFiles != null) { for (File f : dataFiles) { File dataDir = f.getParentFile(); if (factory == null) { dataDir.mkdirs(); } else { factory.createDirectories(dataDir); } } } } try { // Create lock file, preventing database from being opened multiple times. if (mBaseFile == null || openMode == OPEN_TEMP) { mLockFile = null; } else { File lockFile = new File(mBaseFile.getPath() + LOCK_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null && !config.mReadOnly) { factory.createFile(lockFile); } mLockFile = new LockedFile(lockFile, config.mReadOnly); } if (openMode == OPEN_DESTROY) { deleteRedoLogFiles(); } if (dataFiles == null) { PageArray dataPageArray = config.mDataPageArray; if (dataPageArray == null) { mPageDb = new NonPageDb(pageSize); } else { mPageDb = DurablePageDb.open (dataPageArray, config.mCrypto, openMode == OPEN_DESTROY); } } else { EnumSet<OpenOption> options = config.createOpenOptions(); mPageDb = DurablePageDb.open (explicitPageSize, pageSize, dataFiles, config.mFileFactory, options, config.mCrypto, openMode == OPEN_DESTROY); } // Actual page size might differ from configured size. config.pageSize(mPageSize = mPageDb.pageSize()); // Write info file of properties, after database has been opened and after page // size is truly known. if (mBaseFile != null && openMode != OPEN_TEMP && !config.mReadOnly) { File infoFile = new File(mBaseFile.getPath() + INFO_FILE_SUFFIX); FileFactory factory = config.mFileFactory; if (factory != null) { factory.createFile(infoFile); } Writer w = new BufferedWriter (new OutputStreamWriter(new FileOutputStream(infoFile), "UTF-8")); try { config.writeInfo(w); } finally { w.close(); } } mSharedCommitLock = mPageDb.sharedCommitLock(); // Pre-allocate nodes. They are automatically added to the usage // list, and so nothing special needs to be done to allow them to // get used. Since the initial state is clean, evicting these // nodes does nothing. long cacheInitStart = 0; if (mEventListener != null) { mEventListener.notify(EventType.CACHE_INIT_BEGIN, "Initializing %1$d cached nodes", minCache); cacheInitStart = System.nanoTime(); } try { for (int i=minCache; --i>=0; ) { allocLatchedNode(true).releaseExclusive(); } } catch (OutOfMemoryError e) { mMostRecentlyUsed = null; mLeastRecentlyUsed = null; throw new OutOfMemoryError ("Unable to allocate the minimum required number of cached nodes: " + minCache + " (" + (minCache * (long) (pageSize + NODE_OVERHEAD)) + " bytes)"); } if (mEventListener != null) { double duration = (System.nanoTime() - cacheInitStart) / 1000000000.0; mEventListener.notify(EventType.CACHE_INIT_COMPLETE, "Cache initialization completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } int spareBufferCount = Runtime.getRuntime().availableProcessors(); mSpareBufferPool = new BufferPool(mPageSize, spareBufferCount); mSharedCommitLock.lock(); try { mCommitState = CACHED_DIRTY_0; } finally { mSharedCommitLock.unlock(); } byte[] header = new byte[HEADER_SIZE]; mPageDb.readExtraCommitData(header); // Also verifies the database and replication encodings. Node rootNode = loadRegistryRoot(header, config.mReplManager); mRegistry = new Tree(this, Tree.REGISTRY_ID, null, null, rootNode); mOpenTreesLatch = new Latch(); if (openMode == OPEN_TEMP) { mOpenTrees = Collections.emptyMap(); mOpenTreesById = new LHashTable.Obj<TreeRef>(0); mOpenTreesRefQueue = null; } else { mOpenTrees = new TreeMap<byte[], TreeRef>(KeyComparator.THE); mOpenTreesById = new LHashTable.Obj<TreeRef>(16); mOpenTreesRefQueue = new ReferenceQueue<Tree>(); } synchronized (mTxnIdLock) { mTxnId = decodeLongLE(header, I_TRANSACTION_ID); } long redoNum = decodeLongLE(header, I_CHECKPOINT_NUMBER); long redoPos = decodeLongLE(header, I_REDO_POSITION); long redoTxnId = decodeLongLE(header, I_REDO_TXN_ID); if (openMode == OPEN_TEMP) { mRegistryKeyMap = null; } else { mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, true); } mAllocator = new PageAllocator(mPageDb); if (mBaseFile == null) { // Non-durable database never evicts anything. mFragmentCache = new FragmentMap(); } else { // Regular database evicts automatically. mFragmentCache = new FragmentCache(this, mMaxNodeCount); } if (openMode != OPEN_TEMP) { Tree tree = openInternalTree(Tree.FRAGMENTED_TRASH_ID, false); if (tree != null) { mFragmentedTrash = new FragmentedTrash(tree); } } // Limit maximum fragmented entry size to guarantee that 2 entries // fit. Each also requires 2 bytes for pointer and up to 3 bytes // for value length field. mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1; mFragmentInodeLevelCaps = calculateInodeLevelCaps(mPageSize); long recoveryStart = 0; if (mBaseFile == null || openMode == OPEN_TEMP) { mRedoWriter = null; } else { // Perform recovery by examining redo and undo logs. if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin"); recoveryStart = System.nanoTime(); } LHashTable.Obj<Transaction> txns = new LHashTable.Obj<Transaction>(16); { long masterNodeId = decodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID); if (masterNodeId != 0) { if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs"); } UndoLog.recoverMasterUndoLog(this, masterNodeId) .recoverTransactions(txns, LockMode.UPGRADABLE_READ, 0L); } } ReplicationManager rm = config.mReplManager; if (rm != null) { rm.start(redoPos); ReplRedoEngine engine = new ReplRedoEngine (rm, config.mMaxReplicaThreads, this, txns); mRedoWriter = engine.initWriter(redoNum); // Cannot start recovery until constructor is finished and final field // values are visible to other threads. Pass the state to the caller // through the config object. config.mReplRecoveryStartNanos = recoveryStart; config.mReplInitialTxnId = redoTxnId; } else { long logId = redoNum; // Make sure old redo logs are deleted. Process might have exited // before last checkpoint could delete them. for (int i=1; i<=2; i++) { RedoLog.deleteOldFile(config.mBaseFile, logId - i); } RedoLogApplier applier = new RedoLogApplier(this, txns); RedoLog replayLog = new RedoLog(config, logId, redoPos); // As a side-effect, log id is set one higher than last file scanned. Set<File> redoFiles = replayLog.replay (applier, mEventListener, EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d"); boolean doCheckpoint = !redoFiles.isEmpty(); // Avoid re-using transaction ids used by recovery. redoTxnId = applier.mHighestTxnId; if (redoTxnId != 0) { synchronized (mTxnIdLock) { // Subtract for modulo comparison. if (mTxnId == 0 || (redoTxnId - mTxnId) > 0) { mTxnId = redoTxnId; } } } if (txns.size() > 0) { // Rollback or truncate all remaining transactions. They were never // explicitly rolled back, or they were committed but not cleaned up. if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_PROCESS_REMAINING, "Processing remaining transactions"); } txns.traverse(new LHashTable.Visitor <LHashTable.ObjEntry<Transaction>, IOException>() { public boolean visit(LHashTable.ObjEntry<Transaction> entry) throws IOException { entry.value.recoveryCleanup(); return false; } }); doCheckpoint = true; } // New redo logs begin with identifiers one higher than last scanned. mRedoWriter = new RedoLog(config, replayLog); // FIXME: If any exception is thrown before checkpoint is complete, delete // the newly created redo log file. if (doCheckpoint) { checkpoint(true, 0, 0); // Only cleanup after successful checkpoint. for (File file : redoFiles) { file.delete(); } } // Delete lingering fragmented values after undo logs have been processed, // ensuring deletes were committed. emptyAllFragmentedTrash(true); recoveryComplete(recoveryStart); } } if (mBaseFile == null || openMode == OPEN_TEMP) { mTempFileManager = null; } else { mTempFileManager = new TempFileManager(mBaseFile, config.mFileFactory); } } catch (Throwable e) { closeQuietly(null, this, e); throw rethrow(e); } }
diff --git a/src/xtuaok/sharegyazo/HttpMultipartPostRequest.java b/src/xtuaok/sharegyazo/HttpMultipartPostRequest.java index 113cf6d..5ed9627 100644 --- a/src/xtuaok/sharegyazo/HttpMultipartPostRequest.java +++ b/src/xtuaok/sharegyazo/HttpMultipartPostRequest.java @@ -1,116 +1,116 @@ /* * Copyright (C) 2012 xtuaok (http://twitter.com/xtuaok) * * 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 xtuaok.sharegyazo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import org.apache.http.NameValuePair; import android.util.Log; public class HttpMultipartPostRequest { private static final String LOG_TAG = HttpMultipartPostRequest.class.toString(); private static final String BOUNDARY = "----BOUNDARYBOUNDARY----"; private String mCgi; private List<NameValuePair> mPostData; private byte[] mByteData; public HttpMultipartPostRequest(String cgi, List<NameValuePair> postData, byte[] byteData) { mCgi = cgi; mPostData = postData; mByteData = byteData; } public String send() { URLConnection conn = null; String res = null; try { conn = new URL(mCgi).openConnection(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); ((HttpURLConnection)conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStream os = conn.getOutputStream(); os.write(createBoundaryMessage("imagedata").getBytes()); os.write(mByteData); String endBoundary = "\r\n--" + BOUNDARY + "--\r\n"; os.write(endBoundary.getBytes()); os.close(); InputStream is = conn.getInputStream(); res = convertToString(is); } catch (Exception e) { - Log.d(LOG_TAG, e.getMessage()); + Log.d(LOG_TAG, e.getMessage() + ""); } finally { if (conn != null) { ((HttpURLConnection)conn).disconnect(); } } return res; } private String createBoundaryMessage(String fileName) { StringBuffer res = new StringBuffer("--").append(BOUNDARY).append("\r\n"); for (NameValuePair nv : mPostData) { res.append("Content-Disposition: form-data; name=\"").append(nv.getName()).append("\"\r\n") .append("\r\n").append(nv.getValue()).append("\r\n") .append("--").append(BOUNDARY).append("\r\n"); } res.append("Content-Disposition: form-data; name=\"") .append(fileName).append("\"; filename=\"").append(fileName).append("\"\r\n\r\n"); return res.toString(); } private String convertToString(InputStream stream) { InputStreamReader streamReader = null; BufferedReader bufferReader = null; try { streamReader = new InputStreamReader(stream, "UTF-8"); bufferReader = new BufferedReader(streamReader); StringBuilder builder = new StringBuilder(); for (String line = null; (line = bufferReader.readLine()) != null;) { builder.append(line).append("\n"); } return builder.toString(); } catch (UnsupportedEncodingException e) { Log.e(LOG_TAG, e.getMessage()); } catch (IOException e) { Log.e(LOG_TAG, e.toString()); } finally { try { stream.close(); if (bufferReader != null) { bufferReader.close(); } } catch (IOException e) { // IOError Log.e(LOG_TAG, e.toString()); } } return null; } }
true
true
public String send() { URLConnection conn = null; String res = null; try { conn = new URL(mCgi).openConnection(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); ((HttpURLConnection)conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStream os = conn.getOutputStream(); os.write(createBoundaryMessage("imagedata").getBytes()); os.write(mByteData); String endBoundary = "\r\n--" + BOUNDARY + "--\r\n"; os.write(endBoundary.getBytes()); os.close(); InputStream is = conn.getInputStream(); res = convertToString(is); } catch (Exception e) { Log.d(LOG_TAG, e.getMessage()); } finally { if (conn != null) { ((HttpURLConnection)conn).disconnect(); } } return res; }
public String send() { URLConnection conn = null; String res = null; try { conn = new URL(mCgi).openConnection(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); ((HttpURLConnection)conn).setRequestMethod("POST"); conn.setDoOutput(true); conn.connect(); OutputStream os = conn.getOutputStream(); os.write(createBoundaryMessage("imagedata").getBytes()); os.write(mByteData); String endBoundary = "\r\n--" + BOUNDARY + "--\r\n"; os.write(endBoundary.getBytes()); os.close(); InputStream is = conn.getInputStream(); res = convertToString(is); } catch (Exception e) { Log.d(LOG_TAG, e.getMessage() + ""); } finally { if (conn != null) { ((HttpURLConnection)conn).disconnect(); } } return res; }
diff --git a/java/src/steamcondenser/steam/community/css/CSSStats.java b/java/src/steamcondenser/steam/community/css/CSSStats.java index 4b20118..941c6c3 100644 --- a/java/src/steamcondenser/steam/community/css/CSSStats.java +++ b/java/src/steamcondenser/steam/community/css/CSSStats.java @@ -1,149 +1,149 @@ /** * This code is free software; you can redistribute it and/or modify it under * the terms of the new BSD License. * * Copyright (c) 2010, Sebastian Staudt */ package steamcondenser.steam.community.css; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Element; import steamcondenser.SteamCondenserException; import steamcondenser.steam.community.GameStats; /** * The CSSStats class represents the game statistics for a single user in * Counter-Strike: Source */ public class CSSStats extends GameStats { private static final String[] MAPS = { "cs_assault", "cs_compound", "cs_havana", "cs_italy", "cs_militia", "cs_office", "de_aztec", "de_cbble", "de_chateau", "de_dust", "de_dust2", "de_inferno", "de_nuke", "de_piranesi", "de_port", "de_prodigy", "de_tides", "de_train" } ; private static final String[] WEAPONS = { "deagle", "usp", "glock", "p228", "elite", "fiveseven", "awp", "ak47", "m4a1", "aug", "sg552", "sg550", "galil", "famas", "scout", "g3sg1", "p90", "mp5navy", "tmp", "mac10", "ump45", "m3", "xm1014", "m249", "knife", "grenade" }; private Map<String, Object> lastMatchStats; private Map<String, CSSMap> mapStats; private Map<String, Object> totalStats; private Map<String, CSSWeapon> weaponStats; /** * Creates a CSSStats object by calling the super constructor with the game * name "cs:s" * @param steamId The custom URL or the 64bit Steam ID of the user * @throws SteamCondenserException If an error occurs */ public CSSStats(Object steamId) throws SteamCondenserException { super(steamId, "cs:s"); if(this.isPublic()); { Element lastMatchStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lastmatch").item(0); Element lifetimeStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lifetime").item(0); Element summaryStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("summary").item(0); this.lastMatchStats = new HashMap<String, Object>(); this.totalStats = new HashMap<String, Object>(); this.lastMatchStats.put("costPerKill", Float.parseFloat(lastMatchStats.getElementsByTagName("costkill").item(0).getTextContent())); this.lastMatchStats.put("ctWins", Integer.parseInt(lastMatchStats.getElementsByTagName("ct_wins").item(0).getTextContent())); this.lastMatchStats.put("damage", Integer.parseInt(lastMatchStats.getElementsByTagName("dmg").item(0).getTextContent())); this.lastMatchStats.put("deaths", Integer.parseInt(lastMatchStats.getElementsByTagName("deaths").item(0).getTextContent())); this.lastMatchStats.put("dominations", Integer.parseInt(lastMatchStats.getElementsByTagName("dominations").item(0).getTextContent())); - this.lastMatchStats.put("favoriteWeapon", lastMatchStats.getElementsByTagName("favwpn").item(0).getTextContent()); + this.lastMatchStats.put("favoriteWeaponId", Integer.parseInt(lastMatchStats.getElementsByTagName("favwpnid").item(0).getTextContent())); this.lastMatchStats.put("kills", Integer.parseInt(lastMatchStats.getElementsByTagName("kills").item(0).getTextContent())); this.lastMatchStats.put("maxPlayers", Integer.parseInt(lastMatchStats.getElementsByTagName("max_players").item(0).getTextContent())); this.lastMatchStats.put("money", Integer.parseInt(lastMatchStats.getElementsByTagName("money").item(0).getTextContent())); this.lastMatchStats.put("revenges", Integer.parseInt(lastMatchStats.getElementsByTagName("revenges").item(0).getTextContent())); this.lastMatchStats.put("stars", Integer.parseInt(lastMatchStats.getElementsByTagName("stars").item(0).getTextContent())); this.lastMatchStats.put("tWins", Integer.parseInt(lastMatchStats.getElementsByTagName("t_wins").item(0).getTextContent())); this.lastMatchStats.put("wins", Integer.parseInt(lastMatchStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("blindKills", Integer.parseInt(lifetimeStats.getElementsByTagName("blindkills").item(0).getTextContent())); this.totalStats.put("bombsDefused", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsdefused").item(0).getTextContent())); this.totalStats.put("bombsPlanted", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsplanted").item(0).getTextContent())); this.totalStats.put("damage", Integer.parseInt(lifetimeStats.getElementsByTagName("dmg").item(0).getTextContent())); this.totalStats.put("deaths", Integer.parseInt(summaryStats.getElementsByTagName("deaths").item(0).getTextContent())); this.totalStats.put("dominationOverkills", Integer.parseInt(lifetimeStats.getElementsByTagName("dominationoverkills").item(0).getTextContent())); this.totalStats.put("dominations", Integer.parseInt(lifetimeStats.getElementsByTagName("dominations").item(0).getTextContent())); this.totalStats.put("earnedMoney", Integer.parseInt(lifetimeStats.getElementsByTagName("money").item(0).getTextContent())); this.totalStats.put("enemyWeaponKills", Integer.parseInt(lifetimeStats.getElementsByTagName("enemywpnkills").item(0).getTextContent())); this.totalStats.put("headshots", Integer.parseInt(lifetimeStats.getElementsByTagName("headshots").item(0).getTextContent())); this.totalStats.put("hits", Integer.parseInt(summaryStats.getElementsByTagName("shotshit").item(0).getTextContent())); this.totalStats.put("hostagesRescued", Integer.parseInt(lifetimeStats.getElementsByTagName("hostagesrescued").item(0).getTextContent())); this.totalStats.put("kills", Integer.parseInt(summaryStats.getElementsByTagName("kills").item(0).getTextContent())); this.totalStats.put("knifeKills", Integer.parseInt(lifetimeStats.getElementsByTagName("knifekills").item(0).getTextContent())); this.totalStats.put("logosSprayed", Integer.parseInt(lifetimeStats.getElementsByTagName("decals").item(0).getTextContent())); this.totalStats.put("nightvisionDamage", Integer.parseInt(lifetimeStats.getElementsByTagName("nvgdmg").item(0).getTextContent())); this.totalStats.put("pistolRoundsWon", Integer.parseInt(lifetimeStats.getElementsByTagName("pistolrounds").item(0).getTextContent())); this.totalStats.put("revenges", Integer.parseInt(lifetimeStats.getElementsByTagName("revenges").item(0).getTextContent())); this.totalStats.put("roundsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("rounds").item(0).getTextContent())); this.totalStats.put("roundsWon", Integer.parseInt(summaryStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("secondsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("timeplayed").item(0).getTextContent())); this.totalStats.put("shots", Integer.parseInt(summaryStats.getElementsByTagName("shots").item(0).getTextContent())); this.totalStats.put("stars", Integer.parseInt(summaryStats.getElementsByTagName("stars").item(0).getTextContent())); this.totalStats.put("weaponsDonated", Integer.parseInt(lifetimeStats.getElementsByTagName("wpndonated").item(0).getTextContent())); this.totalStats.put("windowsBroken", Integer.parseInt(lifetimeStats.getElementsByTagName("winbroken").item(0).getTextContent())); this.totalStats.put("zoomedSniperKills", Integer.parseInt(lifetimeStats.getElementsByTagName("zsniperkills").item(0).getTextContent())); this.lastMatchStats.put("kdratio", (Integer) this.lastMatchStats.get("kills") / (Integer) this.lastMatchStats.get("deaths")); this.totalStats.put("accuracy", (Integer) this.totalStats.get("hits") / (Integer) this.totalStats.get("shots")); this.totalStats.put("kdratio", (Integer) this.totalStats.get("kills") / (Integer) this.totalStats.get("deaths")); this.totalStats.put("roundsLost", (Integer) this.totalStats.get("roundsPlayed") - (Integer) this.totalStats.get("roundsWon")); } } public Map<String, Object> getLastMatchStats() { return this.lastMatchStats; } public Map<String, CSSMap> getMapStats() { if(!this.isPublic()) { return null; } if(this.mapStats == null) { this.mapStats = new HashMap<String, CSSMap>(); Element mapsData = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("maps").item(0); for(String mapName : MAPS) { this.mapStats.put(mapName, new CSSMap(mapName, mapsData)); } } return this.mapStats; } public Map<String, Object> getTotalStats() { return this.totalStats; } public Map<String, CSSWeapon> getWeaponStats() { if(!this.isPublic()) { return null; } if(this.weaponStats == null) { this.weaponStats = new HashMap<String, CSSWeapon>(); Element weaponData = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("weapons").item(0); for(String weaponName : WEAPONS) { this.weaponStats.put(weaponName, new CSSWeapon(weaponName, weaponData)); } } return this.weaponStats; } }
true
true
public CSSStats(Object steamId) throws SteamCondenserException { super(steamId, "cs:s"); if(this.isPublic()); { Element lastMatchStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lastmatch").item(0); Element lifetimeStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lifetime").item(0); Element summaryStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("summary").item(0); this.lastMatchStats = new HashMap<String, Object>(); this.totalStats = new HashMap<String, Object>(); this.lastMatchStats.put("costPerKill", Float.parseFloat(lastMatchStats.getElementsByTagName("costkill").item(0).getTextContent())); this.lastMatchStats.put("ctWins", Integer.parseInt(lastMatchStats.getElementsByTagName("ct_wins").item(0).getTextContent())); this.lastMatchStats.put("damage", Integer.parseInt(lastMatchStats.getElementsByTagName("dmg").item(0).getTextContent())); this.lastMatchStats.put("deaths", Integer.parseInt(lastMatchStats.getElementsByTagName("deaths").item(0).getTextContent())); this.lastMatchStats.put("dominations", Integer.parseInt(lastMatchStats.getElementsByTagName("dominations").item(0).getTextContent())); this.lastMatchStats.put("favoriteWeapon", lastMatchStats.getElementsByTagName("favwpn").item(0).getTextContent()); this.lastMatchStats.put("kills", Integer.parseInt(lastMatchStats.getElementsByTagName("kills").item(0).getTextContent())); this.lastMatchStats.put("maxPlayers", Integer.parseInt(lastMatchStats.getElementsByTagName("max_players").item(0).getTextContent())); this.lastMatchStats.put("money", Integer.parseInt(lastMatchStats.getElementsByTagName("money").item(0).getTextContent())); this.lastMatchStats.put("revenges", Integer.parseInt(lastMatchStats.getElementsByTagName("revenges").item(0).getTextContent())); this.lastMatchStats.put("stars", Integer.parseInt(lastMatchStats.getElementsByTagName("stars").item(0).getTextContent())); this.lastMatchStats.put("tWins", Integer.parseInt(lastMatchStats.getElementsByTagName("t_wins").item(0).getTextContent())); this.lastMatchStats.put("wins", Integer.parseInt(lastMatchStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("blindKills", Integer.parseInt(lifetimeStats.getElementsByTagName("blindkills").item(0).getTextContent())); this.totalStats.put("bombsDefused", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsdefused").item(0).getTextContent())); this.totalStats.put("bombsPlanted", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsplanted").item(0).getTextContent())); this.totalStats.put("damage", Integer.parseInt(lifetimeStats.getElementsByTagName("dmg").item(0).getTextContent())); this.totalStats.put("deaths", Integer.parseInt(summaryStats.getElementsByTagName("deaths").item(0).getTextContent())); this.totalStats.put("dominationOverkills", Integer.parseInt(lifetimeStats.getElementsByTagName("dominationoverkills").item(0).getTextContent())); this.totalStats.put("dominations", Integer.parseInt(lifetimeStats.getElementsByTagName("dominations").item(0).getTextContent())); this.totalStats.put("earnedMoney", Integer.parseInt(lifetimeStats.getElementsByTagName("money").item(0).getTextContent())); this.totalStats.put("enemyWeaponKills", Integer.parseInt(lifetimeStats.getElementsByTagName("enemywpnkills").item(0).getTextContent())); this.totalStats.put("headshots", Integer.parseInt(lifetimeStats.getElementsByTagName("headshots").item(0).getTextContent())); this.totalStats.put("hits", Integer.parseInt(summaryStats.getElementsByTagName("shotshit").item(0).getTextContent())); this.totalStats.put("hostagesRescued", Integer.parseInt(lifetimeStats.getElementsByTagName("hostagesrescued").item(0).getTextContent())); this.totalStats.put("kills", Integer.parseInt(summaryStats.getElementsByTagName("kills").item(0).getTextContent())); this.totalStats.put("knifeKills", Integer.parseInt(lifetimeStats.getElementsByTagName("knifekills").item(0).getTextContent())); this.totalStats.put("logosSprayed", Integer.parseInt(lifetimeStats.getElementsByTagName("decals").item(0).getTextContent())); this.totalStats.put("nightvisionDamage", Integer.parseInt(lifetimeStats.getElementsByTagName("nvgdmg").item(0).getTextContent())); this.totalStats.put("pistolRoundsWon", Integer.parseInt(lifetimeStats.getElementsByTagName("pistolrounds").item(0).getTextContent())); this.totalStats.put("revenges", Integer.parseInt(lifetimeStats.getElementsByTagName("revenges").item(0).getTextContent())); this.totalStats.put("roundsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("rounds").item(0).getTextContent())); this.totalStats.put("roundsWon", Integer.parseInt(summaryStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("secondsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("timeplayed").item(0).getTextContent())); this.totalStats.put("shots", Integer.parseInt(summaryStats.getElementsByTagName("shots").item(0).getTextContent())); this.totalStats.put("stars", Integer.parseInt(summaryStats.getElementsByTagName("stars").item(0).getTextContent())); this.totalStats.put("weaponsDonated", Integer.parseInt(lifetimeStats.getElementsByTagName("wpndonated").item(0).getTextContent())); this.totalStats.put("windowsBroken", Integer.parseInt(lifetimeStats.getElementsByTagName("winbroken").item(0).getTextContent())); this.totalStats.put("zoomedSniperKills", Integer.parseInt(lifetimeStats.getElementsByTagName("zsniperkills").item(0).getTextContent())); this.lastMatchStats.put("kdratio", (Integer) this.lastMatchStats.get("kills") / (Integer) this.lastMatchStats.get("deaths")); this.totalStats.put("accuracy", (Integer) this.totalStats.get("hits") / (Integer) this.totalStats.get("shots")); this.totalStats.put("kdratio", (Integer) this.totalStats.get("kills") / (Integer) this.totalStats.get("deaths")); this.totalStats.put("roundsLost", (Integer) this.totalStats.get("roundsPlayed") - (Integer) this.totalStats.get("roundsWon")); } }
public CSSStats(Object steamId) throws SteamCondenserException { super(steamId, "cs:s"); if(this.isPublic()); { Element lastMatchStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lastmatch").item(0); Element lifetimeStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("lifetime").item(0); Element summaryStats = (Element) ((Element) this.xmlData.getElementsByTagName("stats").item(0)).getElementsByTagName("summary").item(0); this.lastMatchStats = new HashMap<String, Object>(); this.totalStats = new HashMap<String, Object>(); this.lastMatchStats.put("costPerKill", Float.parseFloat(lastMatchStats.getElementsByTagName("costkill").item(0).getTextContent())); this.lastMatchStats.put("ctWins", Integer.parseInt(lastMatchStats.getElementsByTagName("ct_wins").item(0).getTextContent())); this.lastMatchStats.put("damage", Integer.parseInt(lastMatchStats.getElementsByTagName("dmg").item(0).getTextContent())); this.lastMatchStats.put("deaths", Integer.parseInt(lastMatchStats.getElementsByTagName("deaths").item(0).getTextContent())); this.lastMatchStats.put("dominations", Integer.parseInt(lastMatchStats.getElementsByTagName("dominations").item(0).getTextContent())); this.lastMatchStats.put("favoriteWeaponId", Integer.parseInt(lastMatchStats.getElementsByTagName("favwpnid").item(0).getTextContent())); this.lastMatchStats.put("kills", Integer.parseInt(lastMatchStats.getElementsByTagName("kills").item(0).getTextContent())); this.lastMatchStats.put("maxPlayers", Integer.parseInt(lastMatchStats.getElementsByTagName("max_players").item(0).getTextContent())); this.lastMatchStats.put("money", Integer.parseInt(lastMatchStats.getElementsByTagName("money").item(0).getTextContent())); this.lastMatchStats.put("revenges", Integer.parseInt(lastMatchStats.getElementsByTagName("revenges").item(0).getTextContent())); this.lastMatchStats.put("stars", Integer.parseInt(lastMatchStats.getElementsByTagName("stars").item(0).getTextContent())); this.lastMatchStats.put("tWins", Integer.parseInt(lastMatchStats.getElementsByTagName("t_wins").item(0).getTextContent())); this.lastMatchStats.put("wins", Integer.parseInt(lastMatchStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("blindKills", Integer.parseInt(lifetimeStats.getElementsByTagName("blindkills").item(0).getTextContent())); this.totalStats.put("bombsDefused", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsdefused").item(0).getTextContent())); this.totalStats.put("bombsPlanted", Integer.parseInt(lifetimeStats.getElementsByTagName("bombsplanted").item(0).getTextContent())); this.totalStats.put("damage", Integer.parseInt(lifetimeStats.getElementsByTagName("dmg").item(0).getTextContent())); this.totalStats.put("deaths", Integer.parseInt(summaryStats.getElementsByTagName("deaths").item(0).getTextContent())); this.totalStats.put("dominationOverkills", Integer.parseInt(lifetimeStats.getElementsByTagName("dominationoverkills").item(0).getTextContent())); this.totalStats.put("dominations", Integer.parseInt(lifetimeStats.getElementsByTagName("dominations").item(0).getTextContent())); this.totalStats.put("earnedMoney", Integer.parseInt(lifetimeStats.getElementsByTagName("money").item(0).getTextContent())); this.totalStats.put("enemyWeaponKills", Integer.parseInt(lifetimeStats.getElementsByTagName("enemywpnkills").item(0).getTextContent())); this.totalStats.put("headshots", Integer.parseInt(lifetimeStats.getElementsByTagName("headshots").item(0).getTextContent())); this.totalStats.put("hits", Integer.parseInt(summaryStats.getElementsByTagName("shotshit").item(0).getTextContent())); this.totalStats.put("hostagesRescued", Integer.parseInt(lifetimeStats.getElementsByTagName("hostagesrescued").item(0).getTextContent())); this.totalStats.put("kills", Integer.parseInt(summaryStats.getElementsByTagName("kills").item(0).getTextContent())); this.totalStats.put("knifeKills", Integer.parseInt(lifetimeStats.getElementsByTagName("knifekills").item(0).getTextContent())); this.totalStats.put("logosSprayed", Integer.parseInt(lifetimeStats.getElementsByTagName("decals").item(0).getTextContent())); this.totalStats.put("nightvisionDamage", Integer.parseInt(lifetimeStats.getElementsByTagName("nvgdmg").item(0).getTextContent())); this.totalStats.put("pistolRoundsWon", Integer.parseInt(lifetimeStats.getElementsByTagName("pistolrounds").item(0).getTextContent())); this.totalStats.put("revenges", Integer.parseInt(lifetimeStats.getElementsByTagName("revenges").item(0).getTextContent())); this.totalStats.put("roundsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("rounds").item(0).getTextContent())); this.totalStats.put("roundsWon", Integer.parseInt(summaryStats.getElementsByTagName("wins").item(0).getTextContent())); this.totalStats.put("secondsPlayed", Integer.parseInt(summaryStats.getElementsByTagName("timeplayed").item(0).getTextContent())); this.totalStats.put("shots", Integer.parseInt(summaryStats.getElementsByTagName("shots").item(0).getTextContent())); this.totalStats.put("stars", Integer.parseInt(summaryStats.getElementsByTagName("stars").item(0).getTextContent())); this.totalStats.put("weaponsDonated", Integer.parseInt(lifetimeStats.getElementsByTagName("wpndonated").item(0).getTextContent())); this.totalStats.put("windowsBroken", Integer.parseInt(lifetimeStats.getElementsByTagName("winbroken").item(0).getTextContent())); this.totalStats.put("zoomedSniperKills", Integer.parseInt(lifetimeStats.getElementsByTagName("zsniperkills").item(0).getTextContent())); this.lastMatchStats.put("kdratio", (Integer) this.lastMatchStats.get("kills") / (Integer) this.lastMatchStats.get("deaths")); this.totalStats.put("accuracy", (Integer) this.totalStats.get("hits") / (Integer) this.totalStats.get("shots")); this.totalStats.put("kdratio", (Integer) this.totalStats.get("kills") / (Integer) this.totalStats.get("deaths")); this.totalStats.put("roundsLost", (Integer) this.totalStats.get("roundsPlayed") - (Integer) this.totalStats.get("roundsWon")); } }
diff --git a/src/org/bodytrack/client/InfoPublisher.java b/src/org/bodytrack/client/InfoPublisher.java index f9b4038..f476520 100644 --- a/src/org/bodytrack/client/InfoPublisher.java +++ b/src/org/bodytrack/client/InfoPublisher.java @@ -1,152 +1,152 @@ package org.bodytrack.client; /** * Publishes information to the page outside of the Grapher * widget. This information is available outside of GWT and * offers a consistent interface to the rest of the page, * regardless of how GWT compiles this widget. * * <p>This class contains several methods for publishing * information to the rest of the page. They would be * static, except that some initialization must be done * for the first call into this interface. As such, this * class does not rely on static methods, but is * instance-controlled. There is never more than one instance * of this class available at any time.</p> * * <p>Note that race conditions are possible, since this modifies the * global state, but race conditions are not a problem with a single * thread. Since JavaScript is single-threaded (notwithstanding the * very limited threading model provided by Web Workers), there is * no harm in guarantees that only hold for a single-threaded * program.</p> * * <p>This class deals with the public API between the GWT application * and the rest of the webpage. This is through the * window.grapherState dictionary, which contains several predefined * keys for the interface. See the {@link #initialize()} method to * see the dictionary keys that are available for the rest of the * page.</p> * * <p>There are several informative parts of the API, and one part by * which the rest of the page can request to be notified on changes. * The window.grapherState[&quot;change_listeners&quot;] part of the * API is meant to be an array of no-argument functions. Outside * JavScript may modify this array at will. Whenever a change is made * to the informative part of the API, and actually when any non-static * method of this class is called from GWT, all these functions are * called in JavaScript. Thus, these functions may be called when the * actual information does not change, so they are responsible for * checking the pertinent information in the window.grapherState * variable.</p> */ public final class InfoPublisher { private static final InfoPublisher INSTANCE = new InfoPublisher(); // Don't make constructors for this class available to the // rest of the widget private InfoPublisher() { initialize(); } /** * Used by the constructor to initialize the * window.grapherState global variable. */ private native void initialize() /*-{ $wnd.grapherState = {}; $wnd.grapherState['change_listeners'] = []; $wnd.grapherState['x_axis'] = {}; $wnd.grapherState['y_axis'] = {}; $wnd.grapherState['channel_colors'] = {}; }-*/; /** * Returns an InfoPublisher instance. * * @return * an InfoPublisher to be used by this widget */ public static InfoPublisher getInstance() { return INSTANCE; } /** * Publishes the min/max values for the X-axis. * * @param min * the current min value for the X-axis * @param max * the current max value for the X-axis */ public native void publishXAxisBounds(double min, double max) /*-{ $wnd.grapherState['x_axis']['min'] = min; $wnd.grapherState['x_axis']['max'] = max; var len = $wnd.grapherState['change_listeners'].length; for (var i = 0; i < len; i++) { $wnd.grapherState['change_listeners'][i](); } }-*/; /** * Publishes the min/max values for the Y-axis. * * @param channelName * the name of the channel with which this Y-axis is paired * @param min * the current min value for the Y-axis * @param max * the current max value for the Y-axis */ public native void publishYAxisBounds(String channelName, double min, double max) /*-{ - if (! channelName in $wnd.grapherState['y_axis']) + if (! (channelName in $wnd.grapherState['y_axis'])) $wnd.grapherState['y_axis'][channelName] = {}; $wnd.grapherState['y_axis'][channelName]['min'] = min; $wnd.grapherState['y_axis'][channelName]['max'] = max; var len = $wnd.grapherState['change_listeners'].length; for (var i = 0; i < len; i++) { $wnd.grapherState['change_listeners'][i](); } }-*/; /* * TODO: Add this, or something similar * * Manipulate a $wnd.grapherState['plot_type'] dictionary, perhaps * * Could even use an InfoPublisher.PlotType enum, giving nice * properties in Java, with only a little glue code needed to * convert to JavaScript values and publish to the page * * Perhaps expect that Zeo plots are published with the special * color &quot;ZEO&quot;, which will alert any outside scripts to * the type of channel. * * Now, though, Zeo plots are published with the color * Grapher2.ZEO_COLOR_STRING, which is the empty string public native void publishPlotType(String channelName, int plotType); */ /** * Publishes the color for a channel. * * @param channelName * the name of the channel * @param color * the color of the data plot with the specified channel name */ public native void publishChannelColor(String channelName, String color) /*-{ $wnd.grapherState['channel_colors'][channelName] = color; var len = $wnd.grapherState['change_listeners'].length; for (var i = 0; i < len; i++) { $wnd.grapherState['change_listeners'][i](); } }-*/; }
true
true
public native void publishYAxisBounds(String channelName, double min, double max) /*-{ if (! channelName in $wnd.grapherState['y_axis']) $wnd.grapherState['y_axis'][channelName] = {}; $wnd.grapherState['y_axis'][channelName]['min'] = min; $wnd.grapherState['y_axis'][channelName]['max'] = max; var len = $wnd.grapherState['change_listeners'].length; for (var i = 0; i < len; i++) { $wnd.grapherState['change_listeners'][i](); } }-*/;
public native void publishYAxisBounds(String channelName, double min, double max) /*-{ if (! (channelName in $wnd.grapherState['y_axis'])) $wnd.grapherState['y_axis'][channelName] = {}; $wnd.grapherState['y_axis'][channelName]['min'] = min; $wnd.grapherState['y_axis'][channelName]['max'] = max; var len = $wnd.grapherState['change_listeners'].length; for (var i = 0; i < len; i++) { $wnd.grapherState['change_listeners'][i](); } }-*/;
diff --git a/BigSemanticsCore/src/ecologylab/bigsemantics/metadata/builtins/DocumentClosure.java b/BigSemanticsCore/src/ecologylab/bigsemantics/metadata/builtins/DocumentClosure.java index 93e3c309..964d5087 100644 --- a/BigSemanticsCore/src/ecologylab/bigsemantics/metadata/builtins/DocumentClosure.java +++ b/BigSemanticsCore/src/ecologylab/bigsemantics/metadata/builtins/DocumentClosure.java @@ -1,933 +1,935 @@ /** * */ package ecologylab.bigsemantics.metadata.builtins; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ecologylab.bigsemantics.actions.SemanticAction; import ecologylab.bigsemantics.actions.SemanticActionHandler; import ecologylab.bigsemantics.actions.SemanticActionsKeyWords; import ecologylab.bigsemantics.collecting.DocumentDownloadedEventHandler; import ecologylab.bigsemantics.collecting.DownloadStatus; import ecologylab.bigsemantics.collecting.SemanticsDownloadMonitors; import ecologylab.bigsemantics.collecting.SemanticsGlobalScope; import ecologylab.bigsemantics.collecting.SemanticsSite; import ecologylab.bigsemantics.documentcache.PersistenceMetadata; import ecologylab.bigsemantics.documentcache.PersistentDocumentCache; import ecologylab.bigsemantics.documentparsers.DocumentParser; import ecologylab.bigsemantics.downloadcontrollers.DownloadController; import ecologylab.bigsemantics.html.documentstructure.SemanticInLinks; import ecologylab.bigsemantics.metadata.output.DocumentLogRecord; import ecologylab.bigsemantics.metametadata.MetaMetadata; import ecologylab.bigsemantics.metametadata.MetaMetadataRepository; import ecologylab.bigsemantics.model.text.ITermVector; import ecologylab.bigsemantics.model.text.TermVectorFeature; import ecologylab.bigsemantics.seeding.SearchResult; import ecologylab.bigsemantics.seeding.Seed; import ecologylab.bigsemantics.seeding.SeedDistributor; import ecologylab.collections.SetElement; import ecologylab.concurrent.Downloadable; import ecologylab.concurrent.DownloadableLogRecord; import ecologylab.generic.Continuation; import ecologylab.io.DownloadProcessor; import ecologylab.net.ParsedURL; import ecologylab.serialization.SIMPLTranslationException; import ecologylab.serialization.SimplTypesScope; import ecologylab.serialization.formatenums.StringFormat; import ecologylab.serialization.library.geom.PointInt; /** * New Container object. Mostly just a closure around Document. Used as a candidate and wrapper for * downloading. * * @author andruid */ @SuppressWarnings( { "rawtypes", "unchecked" }) public class DocumentClosure extends SetElement implements TermVectorFeature, Downloadable, SemanticActionsKeyWords, Continuation<DocumentClosure> { static Logger logger; static { logger = LoggerFactory.getLogger(DocumentClosure.class); } private SemanticsGlobalScope semanticsScope; /** * This is tracked mainly for debugging, so we can see what pURL was fed into the meta-metadata * address resolver machine. */ private ParsedURL initialPURL; private Document document; private final Object DOCUMENT_LOCK = new Object(); private DownloadStatus downloadStatus = DownloadStatus.UNPROCESSED; private final Object DOWNLOAD_STATUS_LOCK = new Object(); private DocumentParser documentParser; private SemanticInLinks semanticInlinks; private List<Continuation<DocumentClosure>> continuations; /** * Keeps state about the search process, if this is encapsulates a search result; */ private SearchResult searchResult; private DocumentLogRecord logRecord; private PointInt dndPoint; /** * If true (the normal case), then any MediaElements encountered will be added to the candidates * collection, for possible inclusion in the visual information space. */ private boolean collectMedia = true; /** * If true (the normal case), then hyperlinks encounted will be fed to the web crawler, providing * that they are traversable() and of the right mime types. */ private boolean crawlLinks = true; private final Object DOWNLOAD_LOCK = new Object(); /** * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ private DocumentClosure(Document document, SemanticsGlobalScope semanticsSessionScope, SemanticInLinks semanticInlinks) { super(); this.semanticsScope = semanticsSessionScope; this.initialPURL = document.getLocation(); this.document = document; this.semanticInlinks = semanticInlinks; this.continuations = new ArrayList<Continuation<DocumentClosure>>(); } /** * Should only be called by Document.getOrCreateClosure(). * * @param document * @param semanticInlinks */ DocumentClosure(Document document, SemanticInLinks semanticInlinks) { this(document, document.getSemanticsScope(), semanticInlinks); } /** * @return the infoCollector */ public SemanticsGlobalScope getSemanticsScope() { return semanticsScope; } public ParsedURL getInitialPURL() { return initialPURL; } /** * @return the document */ public Document getDocument() { synchronized (DOCUMENT_LOCK) { return document; } } public DocumentParser getDocumentParser() { return documentParser; } /** * @param presetDocumentParser * the presetDocumentParser to set */ public void setDocumentParser(DocumentParser presetDocumentParser) { this.documentParser = presetDocumentParser; } @Override public SemanticsSite getSite() { Document document = this.document; return (document == null) ? null : document.getSite(); } @Override public SemanticsSite getDownloadSite() { Document document = this.document; if (document != null) { if (document.getDownloadLocation().isFile()) return null; } return (document == null) ? null : document.getSite(); } public boolean isFromSite(SemanticsSite site) { return site != null && site == getSite(); } @Override public ParsedURL location() { Document document = this.document; return (document == null) ? null : document.getLocation(); } @Override public ParsedURL getDownloadLocation() { Document document = this.document; return (document == null) ? null : document.getDownloadLocation(); } /** * @return the semanticInlinks */ public SemanticInLinks getSemanticInlinks() { return semanticInlinks; } /** * Keeps state about the search process, if this Container is a search result; */ public SearchResult searchResult() { return searchResult; } /** * * @param resultDistributer * @param searchNum * Index into the total number of (seeding) searches specified and being aggregated. * @param resultNum * Result number among those returned by google. */ public void setSearchResult(SeedDistributor resultDistributer, int resultNum) { searchResult = new SearchResult(resultDistributer, resultNum); } public SeedDistributor resultDistributer() { return (searchResult == null) ? null : searchResult.resultDistributer(); } @Override public DownloadableLogRecord getLogRecord() { return logRecord; } public void setLogRecord(DocumentLogRecord logRecord) { this.logRecord = logRecord; } @Override public boolean isImage() { return document.isImage(); } public boolean isSeed() { return (document != null) && document.isSeed(); } public Seed getSeed() { return document != null ? document.getSeed() : null; } public boolean isDnd() { return dndPoint != null; } public PointInt getDndPoint() { return dndPoint; } public void setDndPoint(PointInt dndPoint) { this.dndPoint = dndPoint; } /** * This method is called before we actually hit the website. Thus, it uses the initial URL to test * if we need to hit the website. If it returns true, we definitely don't need to hit the website; * if it returns false, we need to hit the website, but the actual document might have been cached * using another URL. */ @Override public boolean isCached() { return false; } /** * @return the downloadStatus */ public DownloadStatus getDownloadStatus() { synchronized (DOWNLOAD_STATUS_LOCK) { return downloadStatus; } } public boolean isUnprocessed() { return getDownloadStatus() == DownloadStatus.UNPROCESSED; } /** * Test state variable inside of QUEUE_DOWNLOAD_LOCK. * * @return true if result has already been queued, connected to, downloaded, ... so it should not * be operated on further. */ public boolean downloadHasBeenQueued() { return getDownloadStatus() != DownloadStatus.UNPROCESSED; } /** * Test and set state variable inside of QUEUE_DOWNLOAD_LOCK. * * @return true if this really queues the download, and false if it had already been queued. */ private boolean testAndSetQueueDownload() { synchronized (DOWNLOAD_STATUS_LOCK) { if (downloadStatus != DownloadStatus.UNPROCESSED) return false; setDownloadStatusInternal(DownloadStatus.QUEUED); return true; } } private void setDownloadStatus(DownloadStatus newStatus) { synchronized (DOWNLOAD_STATUS_LOCK) { setDownloadStatusInternal(newStatus); } } /** * (this method does not lock DOWNLOAD_STATUS_LOCK!) * * @param newStatus */ private void setDownloadStatusInternal(DownloadStatus newStatus) { this.downloadStatus = newStatus; if (this.document != null) document.setDownloadStatus(newStatus); } public DownloadProcessor<DocumentClosure> downloadMonitor() { SemanticsDownloadMonitors downloadMonitors = semanticsScope.getDownloadMonitors(); return downloadMonitors.downloadProcessor(document.isImage(), isDnd(), isSeed(), document.isGui()); } /** * Download if necessary, using the {@link ecologylab.concurrent.DownloadMonitor DownloadMonitor} * if USE_DOWNLOAD_MONITOR is set (it seems it always is), or in a new thread. Control will be * passed to {@link #downloadAndParse() downloadAndParse()}. Does nothing if this has been * previously queued, if it has been recycled, or if it isMuted(). * * @return true if this is actually queued for download. false if it was previously, if its been * recycled, or if it is muted. */ public boolean queueDownload() { if (recycled()) { debugA("ERROR: cant queue download cause already recycled."); return false; } if (this.getDownloadLocation() == null) return false; final boolean result = !filteredOut(); // for dashboard type on the fly filtering if (result) { if (!testAndSetQueueDownload()) return false; delete(); // remove from candidate pools! (invokes deleteHook as well) downloadMonitor().download(this, continuations == null ? null : this); } return result; } /** * Connect to the information resource. Figure out the appropriate MetaMetadata and DocumentType. * Download the information resource and parse it. Do cleanup afterwards. * * This method is typically called by DownloadMonitor. * * @throws IOException */ @Override public void performDownload() throws IOException { if (recycled() || document.isRecycled()) { logger.error("Recycled document closure in performDownload(): " + document); return; } synchronized (DOWNLOAD_STATUS_LOCK) { if (!(downloadStatus == DownloadStatus.QUEUED || downloadStatus == DownloadStatus.UNPROCESSED)) { return; } setDownloadStatusInternal(DownloadStatus.CONNECTING); } ParsedURL location = location(); MetaMetadata metaMetadata = (MetaMetadata) document.getMetaMetadata(); boolean noCache = metaMetadata.isNoCache(); PersistentDocumentCache pCache = semanticsScope.getPersistentDocumentCache(); // Check the persistent cache first Document cachedDoc = null; if (pCache != null && !noCache) { cachedDoc = retrieveFromPersistentCache(pCache, location); } // If not in the persistent cache, download the raw page and parse if (cachedDoc == null) { DownloadController downloadController = downloadRawPage(location); if (downloadController.isGood()) { handleRedirections(downloadController, location); metaMetadata = changeMetaMetadataIfNeeded(downloadController.getMimeType()); findParser(metaMetadata, downloadController); if (documentParser != null) { doParse(metaMetadata); if (pCache != null && !noCache) { doPersist(pCache, downloadController); } - document.downloadAndParseDone(documentParser); - setDownloadStatus(DownloadStatus.DOWNLOAD_DONE); - // Successfully finished. - return; } } else { logger.error("Network connection error: " + document); + recycle(); + return; } } + else + { + changeDocument(cachedDoc); + } - // Error happened. - recycle(); + document.downloadAndParseDone(documentParser); + setDownloadStatus(DownloadStatus.DOWNLOAD_DONE); } private Document retrieveFromPersistentCache(PersistentDocumentCache pCache, ParsedURL location) { Document cachedDoc = null; long t0 = System.currentTimeMillis(); PersistenceMetadata pMetadata = pCache.getMetadata(location); String repoHash = semanticsScope.getMetaMetadataRepositoryHash(); if (pMetadata != null && repoHash.equals(pMetadata.getRepositoryHash())) { cachedDoc = pCache.retrieve(location); } if (logRecord != null) { logRecord.setMsMetadataCacheLookup(System.currentTimeMillis() - t0); if (cachedDoc != null) { logRecord.setPersisentDocumentCacheHit(true); } } return cachedDoc; } private DownloadController downloadRawPage(ParsedURL location) throws IOException { String userAgent = document.getMetaMetadata().getUserAgentString(); DownloadController downloadController = semanticsScope.createDownloadController(this); downloadController.setUserAgent(userAgent); long t0download = System.currentTimeMillis(); downloadController.accessAndDownload(location); if (logRecord != null) { logRecord.setMsHtmlDownload(System.currentTimeMillis() - t0download); } return downloadController; } private void handleRedirections(DownloadController downloadController, ParsedURL location) { // handle redirections: List<ParsedURL> redirectedLocations = downloadController.getRedirectedLocations(); if (redirectedLocations != null) { for (ParsedURL redirectedLocation : redirectedLocations) { if (redirectedLocation != null) { document.addAdditionalLocation(redirectedLocation); Document newDocument = semanticsScope.getOrConstructDocument(redirectedLocation); newDocument.addAdditionalLocation(location); changeDocument(newDocument); } } } } private MetaMetadata changeMetaMetadataIfNeeded(String mimeType) { MetaMetadata metaMetadata = (MetaMetadata) document.getMetaMetadata(); // check for more specific meta-metadata if (metaMetadata.isGenericMetadata()) { // see if we can find more specifc meta-metadata using mimeType MetaMetadataRepository repository = semanticsScope.getMetaMetadataRepository(); MetaMetadata mimeMmd = repository.getMMByMime(mimeType); if (mimeMmd != null && !mimeMmd.equals(metaMetadata)) { // new meta-metadata! if (!mimeMmd.getMetadataClass().isAssignableFrom(document.getClass())) { // more specific so we need new metadata! Document document = (Document) mimeMmd.constructMetadata(); // set temporary on stack changeDocument(document); } metaMetadata = mimeMmd; document.setMetaMetadata(mimeMmd); } } return metaMetadata; } private void findParser(MetaMetadata metaMetadata, DownloadController downloadController) { if (documentParser == null) { boolean noParser = false; // // First check if registered no parser // boolean noParser = DocumentParser.isRegisteredNoParser(document.getLocation()); // List<MetadataParsedURL> additionalLocations = document.getAdditionalLocations(); // if (additionalLocations != null) // { // for (int i = 0; i < additionalLocations.size() && !noParser; ++i) // { // noParser |= DocumentParser.isRegisteredNoParser(additionalLocations.get(i).getValue()); // } // } if (noParser) { logger.warn("Registered no parser: " + document); } else { // If not registered no parser, try to find one documentParser = DocumentParser.getByMmd(metaMetadata, semanticsScope, this, downloadController); if (documentParser == null) { logger.warn("No parser found: " + metaMetadata); } } } } private void doParse(MetaMetadata metaMetadata) throws IOException { // container or not (it could turn out to be an image or some other mime type), parse the baby! setDownloadStatus(DownloadStatus.PARSING); takeSemanticActions(metaMetadata, metaMetadata.getBeforeSemanticActions()); long t0extraction = System.currentTimeMillis(); documentParser.parse(); if (logRecord != null) { logRecord.setMsExtraction(System.currentTimeMillis() - t0extraction); } takeSemanticActions(metaMetadata, metaMetadata.getAfterSemanticActions()); addDocGraphCallbacksIfNeeded(); } private void takeSemanticActions(MetaMetadata metaMetadata, ArrayList<SemanticAction> actions) { if (metaMetadata != null && actions != null) { SemanticActionHandler handler = new SemanticActionHandler(semanticsScope, documentParser); handler.takeSemanticActions(metaMetadata, document, actions); } } private void addDocGraphCallbacksIfNeeded() { if (this.getSemanticsScope().ifAutoUpdateDocRefs()) { // add callbacks so that when this document is downloaded and parsed, references to it will // be updated automatically. Set<DocumentDownloadedEventHandler> listeners = semanticsScope.getDocumentDownloadingMonitor().getListenersForDocument(document); if (listeners != null && listeners.size() > 0) { addContinuations(listeners); } } } private void doPersist(PersistentDocumentCache pCache, DownloadController downloadController) throws IOException { long t0persist = System.currentTimeMillis(); PersistenceMetadata pMetadata = new PersistenceMetadata(); pMetadata.setMimeType(downloadController.getMimeType()); String rawDoc = downloadController.getContent(); pCache.store(document, rawDoc, pMetadata); if (logRecord != null) { logRecord.setMsMetadataCaching(System.currentTimeMillis() - t0persist); } } /** * In use cases such as the service, we want to be able to call performDownload() synchronously, * and in the same time make sure that the same closure will be downloaded by one thread at a * time. This method uses a lock to implement this. * * @throws IOException */ public void performDownloadSynchronously() throws IOException { synchronized (DOWNLOAD_LOCK) { performDownload(); } } /** * Dispatch all of our registered callbacks. */ @Override public void callback(DocumentClosure o) { if (continuations == null) return; List<Continuation<DocumentClosure>> currentContinuations; synchronized (continuations) { currentContinuations = new ArrayList<Continuation<DocumentClosure>>(continuations); } if (currentContinuations != null) { for (Continuation<DocumentClosure> continuation : currentContinuations) { try { continuation.callback(o); } catch (Exception e) { logger.error("Error calling back: " + o + ": " + continuation, e); } } } // wait to recycle continuations until after they have been called. if (isRecycled()) { continuations.clear(); continuations = null; } } public List<Continuation<DocumentClosure>> getContinuations() { return continuations; } private List<Continuation<DocumentClosure>> continuations() { return continuations; } public void addContinuation(Continuation<DocumentClosure> continuation) { synchronized (continuations) { continuations().add(continuation); } } public void addContinuations(Collection<? extends Continuation<DocumentClosure>> incomingContinuations) { synchronized (continuations) { List<Continuation<DocumentClosure>> continuations = continuations(); for (Continuation<DocumentClosure> continuation : incomingContinuations) continuations.add(continuation); } } public void addContinuationBefore(Continuation<DocumentClosure> continuation) { synchronized (continuations) { continuations().add(0, continuation); } } /** * Add a continuation to this closure before it is downloaded (i.e. before its performDownload() * method finishes). * * This gives the client the possibility of making sure the continuation will be called when the * closure finishes downloading. * * @param continuation * @return true if the continuation is added before the closure finishes downloading; false if the * closure is already downloaded. */ public boolean addContinuationBeforeDownloadDone(Continuation<DocumentClosure> continuation) { if (downloadStatus != DownloadStatus.DOWNLOAD_DONE && downloadStatus != DownloadStatus.IOERROR && downloadStatus != DownloadStatus.RECYCLED) { synchronized (DOWNLOAD_STATUS_LOCK) { if (downloadStatus != DownloadStatus.DOWNLOAD_DONE && downloadStatus != DownloadStatus.IOERROR && downloadStatus != DownloadStatus.RECYCLED) { addContinuation(continuation); return true; } } } return false; } /** * Document metadata object must change, because we learned something new about its type. * * @param newDocument */ public void changeDocument(Document newDocument) { synchronized (DOCUMENT_LOCK) { Document oldDocument = document; document = newDocument; SemanticsSite oldSite = oldDocument.site(); SemanticsSite newSite = newDocument.site(); if (oldSite != null && oldSite != newSite) { // calling changeDocument() because of redirecting? if (oldSite.isDownloading()) oldSite.endDownload(oldDocument.getDownloadLocation()); } newDocument.inheritValues(oldDocument); semanticInlinks = newDocument.getSemanticInlinks(); // probably not needed, but just in case. oldDocument.recycle(); } } /** * Close the current connection. Re-open a connection to the same location. Use the same Document * object; don't process re-directs, or anything like that. Re-connect simply. * * @return PURLConnection for the new connection. * @throws IOException */ public DownloadController reConnect() throws IOException { DownloadController downloadController = semanticsScope.createDownloadController(this); downloadController.accessAndDownload(document.getLocation()); return downloadController; } @Override public void recycle() { recycle(false); } @Override public synchronized void recycle(boolean recycleDocument) { synchronized (DOWNLOAD_STATUS_LOCK) { if (downloadStatus == DownloadStatus.RECYCLED) return; setDownloadStatusInternal(DownloadStatus.RECYCLED); } if (documentParser != null) documentParser.recycle(); semanticInlinks = null; initialPURL = null; // ??? should we recycle Document here -- under what circumstances??? if (recycleDocument) document.recycle(); } @Override public boolean recycled() { Document document = this.document; return document == null || document.isRecycled(); } @Override public boolean isRecycled() { return document == null || document.isRecycled(); } /** * Resets this closure as if it is newly created. */ public void reset() { setDownloadStatus(DownloadStatus.UNPROCESSED); if (document != null) { document.resetRecycleStatus(); } } @Override public String toString() { return super.toString() + "[" + document.getLocation() + "]"; } @Override public int hashCode() { return (document == null) ? -1 : document.hashCode(); } @Override public ITermVector termVector() { return (document == null) ? null : document.termVector(); } /** * Called by DownloadMonitor in case a timeout happens. */ @Override public void handleIoError(Throwable e) { setDownloadStatus(DownloadStatus.IOERROR); if (documentParser != null) { documentParser.handleIoError(e); } recycle(); } @Override public String message() { return document == null ? "recycled" : document.getLocation().toString(); } public void serialize(OutputStream stream) { serialize(stream, StringFormat.XML); } public void serialize(OutputStream stream, StringFormat format) { Document document = getDocument(); try { SimplTypesScope.serialize(document, System.out, format); System.out.println("\n"); } catch (SIMPLTranslationException e) { error("Could not serialize " + document); e.printStackTrace(); } } public void serialize(StringBuilder buffy) { Document document = getDocument(); try { SimplTypesScope.serialize(document, buffy, StringFormat.XML); System.out.println("\n"); } catch (SIMPLTranslationException e) { error("Could not serialize " + document); e.printStackTrace(); } } }
false
true
public void performDownload() throws IOException { if (recycled() || document.isRecycled()) { logger.error("Recycled document closure in performDownload(): " + document); return; } synchronized (DOWNLOAD_STATUS_LOCK) { if (!(downloadStatus == DownloadStatus.QUEUED || downloadStatus == DownloadStatus.UNPROCESSED)) { return; } setDownloadStatusInternal(DownloadStatus.CONNECTING); } ParsedURL location = location(); MetaMetadata metaMetadata = (MetaMetadata) document.getMetaMetadata(); boolean noCache = metaMetadata.isNoCache(); PersistentDocumentCache pCache = semanticsScope.getPersistentDocumentCache(); // Check the persistent cache first Document cachedDoc = null; if (pCache != null && !noCache) { cachedDoc = retrieveFromPersistentCache(pCache, location); } // If not in the persistent cache, download the raw page and parse if (cachedDoc == null) { DownloadController downloadController = downloadRawPage(location); if (downloadController.isGood()) { handleRedirections(downloadController, location); metaMetadata = changeMetaMetadataIfNeeded(downloadController.getMimeType()); findParser(metaMetadata, downloadController); if (documentParser != null) { doParse(metaMetadata); if (pCache != null && !noCache) { doPersist(pCache, downloadController); } document.downloadAndParseDone(documentParser); setDownloadStatus(DownloadStatus.DOWNLOAD_DONE); // Successfully finished. return; } } else { logger.error("Network connection error: " + document); } } // Error happened. recycle(); }
public void performDownload() throws IOException { if (recycled() || document.isRecycled()) { logger.error("Recycled document closure in performDownload(): " + document); return; } synchronized (DOWNLOAD_STATUS_LOCK) { if (!(downloadStatus == DownloadStatus.QUEUED || downloadStatus == DownloadStatus.UNPROCESSED)) { return; } setDownloadStatusInternal(DownloadStatus.CONNECTING); } ParsedURL location = location(); MetaMetadata metaMetadata = (MetaMetadata) document.getMetaMetadata(); boolean noCache = metaMetadata.isNoCache(); PersistentDocumentCache pCache = semanticsScope.getPersistentDocumentCache(); // Check the persistent cache first Document cachedDoc = null; if (pCache != null && !noCache) { cachedDoc = retrieveFromPersistentCache(pCache, location); } // If not in the persistent cache, download the raw page and parse if (cachedDoc == null) { DownloadController downloadController = downloadRawPage(location); if (downloadController.isGood()) { handleRedirections(downloadController, location); metaMetadata = changeMetaMetadataIfNeeded(downloadController.getMimeType()); findParser(metaMetadata, downloadController); if (documentParser != null) { doParse(metaMetadata); if (pCache != null && !noCache) { doPersist(pCache, downloadController); } } } else { logger.error("Network connection error: " + document); recycle(); return; } } else { changeDocument(cachedDoc); } document.downloadAndParseDone(documentParser); setDownloadStatus(DownloadStatus.DOWNLOAD_DONE); }
diff --git a/src/org/fbreader/formats/fb2/FB2Reader.java b/src/org/fbreader/formats/fb2/FB2Reader.java index 0d6103ba..18803600 100644 --- a/src/org/fbreader/formats/fb2/FB2Reader.java +++ b/src/org/fbreader/formats/fb2/FB2Reader.java @@ -1,378 +1,379 @@ package org.fbreader.formats.fb2; import org.fbreader.bookmodel.BookModel; import org.fbreader.bookmodel.BookReader; import org.fbreader.bookmodel.FBTextKind; import org.zlibrary.core.xml.*; import org.zlibrary.core.util.ZLArrayUtils; import org.zlibrary.text.model.ZLTextParagraph; public final class FB2Reader extends BookReader implements ZLXMLReader { private boolean myInsidePoem = false; private boolean myInsideTitle = false; private int myBodyCounter = 0; private boolean myReadMainText = false; private int mySectionDepth = 0; private boolean mySectionStarted = false; private byte myHyperlinkType; private Base64EncodedImage myCurrentImage; private boolean myInsideCoverpage = false; private String myCoverImageReference; private int myParagraphsBeforeBodyNumber = Integer.MAX_VALUE; private final char[] SPACE = { ' ' }; private String myHrefAttribute = ":href"; private byte[] myTagStack = new byte[10]; private int myTagStackSize = 0; public FB2Reader(BookModel model) { super(model); } public boolean read() { final ZLXMLProcessor processor = ZLXMLProcessorFactory.getInstance().createXMLProcessor(); return processor.read(this, getModel().getFileName()); } //strange boolean readBook(String fileName) { final ZLXMLProcessor processor = ZLXMLProcessorFactory.getInstance().createXMLProcessor(); return processor.read(this, fileName); //return readDocument(fileName); } public void startDocumentHandler() { } public void endDocumentHandler() { } public boolean dontCacheAttributeValues() { return true; } public void characterDataHandler(char[] ch, int start, int length) { if (length == 0) { return; } final Base64EncodedImage image = myCurrentImage; if (image != null) { image.addData(ch, start, length); } else { addData(ch, start, length); } } public void characterDataHandlerFinal(char[] ch, int start, int length) { if (length == 0) { return; } final Base64EncodedImage image = myCurrentImage; if (image != null) { image.addData(ch, start, length); } else { addDataFinal(ch, start, length); } } public void endElementHandler(String tagName) { final byte tag = myTagStack[--myTagStackSize]; switch (tag) { case FB2Tag.P: endParagraph(); break; case FB2Tag.SUB: addControl(FBTextKind.SUB, false); break; case FB2Tag.SUP: addControl(FBTextKind.SUP, false); break; case FB2Tag.CODE: addControl(FBTextKind.CODE, false); break; case FB2Tag.EMPHASIS: addControl(FBTextKind.EMPHASIS, false); break; case FB2Tag.STRONG: addControl(FBTextKind.STRONG, false); break; case FB2Tag.STRIKETHROUGH: addControl(FBTextKind.STRIKETHROUGH, false); break; case FB2Tag.V: case FB2Tag.SUBTITLE: case FB2Tag.TEXT_AUTHOR: case FB2Tag.DATE: popKind(); endParagraph(); break; case FB2Tag.CITE: case FB2Tag.EPIGRAPH: popKind(); break; case FB2Tag.POEM: myInsidePoem = false; break; case FB2Tag.STANZA: beginParagraph(ZLTextParagraph.Kind.AFTER_SKIP_PARAGRAPH); endParagraph(); popKind(); break; case FB2Tag.SECTION: if (myReadMainText) { endContentsParagraph(); --mySectionDepth; mySectionStarted = false; } else { unsetCurrentTextModel(); } break; case FB2Tag.ANNOTATION: popKind(); if (myBodyCounter == 0) { insertEndOfSectionParagraph(); unsetCurrentTextModel(); } break; case FB2Tag.TITLE: popKind(); exitTitle(); myInsideTitle = false; break; case FB2Tag.BODY: popKind(); myReadMainText = false; unsetCurrentTextModel(); break; case FB2Tag.A: addControl(myHyperlinkType, false); break; case FB2Tag.COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = false; insertEndOfSectionParagraph(); unsetCurrentTextModel(); } break; case FB2Tag.BINARY: if (myCurrentImage != null) { myCurrentImage.trimToSize(); myCurrentImage = null; } break; default: break; } } public void startElementHandler(String tagName, ZLStringMap attributes) { String id = attributes.getValue("id"); if (id != null) { if (!myReadMainText) { setFootnoteTextModel(id); } addHyperlinkLabel(id); } final byte tag = FB2Tag.getTagByName(tagName); byte[] tagStack = myTagStack; if (tagStack.length == myTagStackSize) { tagStack = ZLArrayUtils.createCopy(tagStack, myTagStackSize, myTagStackSize * 2); myTagStack = tagStack; } tagStack[myTagStackSize++] = tag; switch (tag) { case FB2Tag.FICTIONBOOK: { final int attibutesNumber = attributes.getSize(); for (int i = 0; i < attibutesNumber; ++i) { final String key = attributes.getKey(i); if (key.startsWith("xmlns:")) { final String value = attributes.getValue(key); if (value.endsWith("/xlink")) { myHrefAttribute = (key.substring(6) + ":href").intern(); break; } } } break; } case FB2Tag.P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { addContentsData(SPACE); } beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUB: addControl(FBTextKind.SUB, true); break; case FB2Tag.SUP: addControl(FBTextKind.SUP, true); break; case FB2Tag.CODE: addControl(FBTextKind.CODE, true); break; case FB2Tag.EMPHASIS: addControl(FBTextKind.EMPHASIS, true); break; case FB2Tag.STRONG: addControl(FBTextKind.STRONG, true); break; case FB2Tag.STRIKETHROUGH: addControl(FBTextKind.STRIKETHROUGH, true); break; case FB2Tag.V: pushKind(FBTextKind.VERSE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.TEXT_AUTHOR: pushKind(FBTextKind.AUTHOR); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUBTITLE: pushKind(FBTextKind.SUBTITLE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.DATE: pushKind(FBTextKind.DATE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.EMPTY_LINE: beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); endParagraph(); break; case FB2Tag.CITE: pushKind(FBTextKind.CITE); break; case FB2Tag.EPIGRAPH: pushKind(FBTextKind.EPIGRAPH); break; case FB2Tag.POEM: myInsidePoem = true; break; case FB2Tag.STANZA: pushKind(FBTextKind.STANZA); beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); endParagraph(); break; case FB2Tag.SECTION: if (myReadMainText) { insertEndOfSectionParagraph(); ++mySectionDepth; beginContentsParagraph(); mySectionStarted = true; } break; case FB2Tag.ANNOTATION: if (myBodyCounter == 0) { setMainTextModel(); } pushKind(FBTextKind.ANNOTATION); break; case FB2Tag.TITLE: if (myInsidePoem) { pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { insertEndOfSectionParagraph(); pushKind(FBTextKind.TITLE); } else { pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; enterTitle(); } break; case FB2Tag.BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = getModel().getBookTextModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.getValue("name") == null)) { setMainTextModel(); myReadMainText = true; } pushKind(FBTextKind.REGULAR); break; case FB2Tag.A: String ref = attributes.getValue(myHrefAttribute); + String type = attributes.getValue("type"); if ((ref != null) && (ref.length() != 0)) { if (ref.charAt(0) == '#') { - myHyperlinkType = FBTextKind.FOOTNOTE; + myHyperlinkType = "note".equals(type) ? FBTextKind.FOOTNOTE : FBTextKind.INTERNAL_HYPERLINK; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; addControl(myHyperlinkType, true); } break; case FB2Tag.COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; setMainTextModel(); } break; case FB2Tag.IMAGE: String imgRef = attributes.getValue(myHrefAttribute); if ((imgRef != null) && (imgRef.length() != 0) && (imgRef.charAt(0) == '#')) { String vOffset = attributes.getValue("voffset"); short offset = 0; try { offset = Short.parseShort(vOffset); } catch (NumberFormatException e) { } imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != getModel().getBookTextModel().getParagraphsNumber()) { addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case FB2Tag.BINARY: String contentType = attributes.getValue("content-type"); String imgId = attributes.getValue("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); addImage(imgId, myCurrentImage); } break; default: break; } } }
false
true
public void startElementHandler(String tagName, ZLStringMap attributes) { String id = attributes.getValue("id"); if (id != null) { if (!myReadMainText) { setFootnoteTextModel(id); } addHyperlinkLabel(id); } final byte tag = FB2Tag.getTagByName(tagName); byte[] tagStack = myTagStack; if (tagStack.length == myTagStackSize) { tagStack = ZLArrayUtils.createCopy(tagStack, myTagStackSize, myTagStackSize * 2); myTagStack = tagStack; } tagStack[myTagStackSize++] = tag; switch (tag) { case FB2Tag.FICTIONBOOK: { final int attibutesNumber = attributes.getSize(); for (int i = 0; i < attibutesNumber; ++i) { final String key = attributes.getKey(i); if (key.startsWith("xmlns:")) { final String value = attributes.getValue(key); if (value.endsWith("/xlink")) { myHrefAttribute = (key.substring(6) + ":href").intern(); break; } } } break; } case FB2Tag.P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { addContentsData(SPACE); } beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUB: addControl(FBTextKind.SUB, true); break; case FB2Tag.SUP: addControl(FBTextKind.SUP, true); break; case FB2Tag.CODE: addControl(FBTextKind.CODE, true); break; case FB2Tag.EMPHASIS: addControl(FBTextKind.EMPHASIS, true); break; case FB2Tag.STRONG: addControl(FBTextKind.STRONG, true); break; case FB2Tag.STRIKETHROUGH: addControl(FBTextKind.STRIKETHROUGH, true); break; case FB2Tag.V: pushKind(FBTextKind.VERSE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.TEXT_AUTHOR: pushKind(FBTextKind.AUTHOR); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUBTITLE: pushKind(FBTextKind.SUBTITLE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.DATE: pushKind(FBTextKind.DATE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.EMPTY_LINE: beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); endParagraph(); break; case FB2Tag.CITE: pushKind(FBTextKind.CITE); break; case FB2Tag.EPIGRAPH: pushKind(FBTextKind.EPIGRAPH); break; case FB2Tag.POEM: myInsidePoem = true; break; case FB2Tag.STANZA: pushKind(FBTextKind.STANZA); beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); endParagraph(); break; case FB2Tag.SECTION: if (myReadMainText) { insertEndOfSectionParagraph(); ++mySectionDepth; beginContentsParagraph(); mySectionStarted = true; } break; case FB2Tag.ANNOTATION: if (myBodyCounter == 0) { setMainTextModel(); } pushKind(FBTextKind.ANNOTATION); break; case FB2Tag.TITLE: if (myInsidePoem) { pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { insertEndOfSectionParagraph(); pushKind(FBTextKind.TITLE); } else { pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; enterTitle(); } break; case FB2Tag.BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = getModel().getBookTextModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.getValue("name") == null)) { setMainTextModel(); myReadMainText = true; } pushKind(FBTextKind.REGULAR); break; case FB2Tag.A: String ref = attributes.getValue(myHrefAttribute); if ((ref != null) && (ref.length() != 0)) { if (ref.charAt(0) == '#') { myHyperlinkType = FBTextKind.FOOTNOTE; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; addControl(myHyperlinkType, true); } break; case FB2Tag.COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; setMainTextModel(); } break; case FB2Tag.IMAGE: String imgRef = attributes.getValue(myHrefAttribute); if ((imgRef != null) && (imgRef.length() != 0) && (imgRef.charAt(0) == '#')) { String vOffset = attributes.getValue("voffset"); short offset = 0; try { offset = Short.parseShort(vOffset); } catch (NumberFormatException e) { } imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != getModel().getBookTextModel().getParagraphsNumber()) { addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case FB2Tag.BINARY: String contentType = attributes.getValue("content-type"); String imgId = attributes.getValue("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); addImage(imgId, myCurrentImage); } break; default: break; } }
public void startElementHandler(String tagName, ZLStringMap attributes) { String id = attributes.getValue("id"); if (id != null) { if (!myReadMainText) { setFootnoteTextModel(id); } addHyperlinkLabel(id); } final byte tag = FB2Tag.getTagByName(tagName); byte[] tagStack = myTagStack; if (tagStack.length == myTagStackSize) { tagStack = ZLArrayUtils.createCopy(tagStack, myTagStackSize, myTagStackSize * 2); myTagStack = tagStack; } tagStack[myTagStackSize++] = tag; switch (tag) { case FB2Tag.FICTIONBOOK: { final int attibutesNumber = attributes.getSize(); for (int i = 0; i < attibutesNumber; ++i) { final String key = attributes.getKey(i); if (key.startsWith("xmlns:")) { final String value = attributes.getValue(key); if (value.endsWith("/xlink")) { myHrefAttribute = (key.substring(6) + ":href").intern(); break; } } } break; } case FB2Tag.P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { addContentsData(SPACE); } beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUB: addControl(FBTextKind.SUB, true); break; case FB2Tag.SUP: addControl(FBTextKind.SUP, true); break; case FB2Tag.CODE: addControl(FBTextKind.CODE, true); break; case FB2Tag.EMPHASIS: addControl(FBTextKind.EMPHASIS, true); break; case FB2Tag.STRONG: addControl(FBTextKind.STRONG, true); break; case FB2Tag.STRIKETHROUGH: addControl(FBTextKind.STRIKETHROUGH, true); break; case FB2Tag.V: pushKind(FBTextKind.VERSE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.TEXT_AUTHOR: pushKind(FBTextKind.AUTHOR); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.SUBTITLE: pushKind(FBTextKind.SUBTITLE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.DATE: pushKind(FBTextKind.DATE); beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case FB2Tag.EMPTY_LINE: beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); endParagraph(); break; case FB2Tag.CITE: pushKind(FBTextKind.CITE); break; case FB2Tag.EPIGRAPH: pushKind(FBTextKind.EPIGRAPH); break; case FB2Tag.POEM: myInsidePoem = true; break; case FB2Tag.STANZA: pushKind(FBTextKind.STANZA); beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); endParagraph(); break; case FB2Tag.SECTION: if (myReadMainText) { insertEndOfSectionParagraph(); ++mySectionDepth; beginContentsParagraph(); mySectionStarted = true; } break; case FB2Tag.ANNOTATION: if (myBodyCounter == 0) { setMainTextModel(); } pushKind(FBTextKind.ANNOTATION); break; case FB2Tag.TITLE: if (myInsidePoem) { pushKind(FBTextKind.POEM_TITLE); } else if (mySectionDepth == 0) { insertEndOfSectionParagraph(); pushKind(FBTextKind.TITLE); } else { pushKind(FBTextKind.SECTION_TITLE); myInsideTitle = true; enterTitle(); } break; case FB2Tag.BODY: ++myBodyCounter; myParagraphsBeforeBodyNumber = getModel().getBookTextModel().getParagraphsNumber(); if ((myBodyCounter == 1) || (attributes.getValue("name") == null)) { setMainTextModel(); myReadMainText = true; } pushKind(FBTextKind.REGULAR); break; case FB2Tag.A: String ref = attributes.getValue(myHrefAttribute); String type = attributes.getValue("type"); if ((ref != null) && (ref.length() != 0)) { if (ref.charAt(0) == '#') { myHyperlinkType = "note".equals(type) ? FBTextKind.FOOTNOTE : FBTextKind.INTERNAL_HYPERLINK; ref = ref.substring(1); } else { myHyperlinkType = FBTextKind.EXTERNAL_HYPERLINK; } addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = FBTextKind.FOOTNOTE; addControl(myHyperlinkType, true); } break; case FB2Tag.COVERPAGE: if (myBodyCounter == 0) { myInsideCoverpage = true; setMainTextModel(); } break; case FB2Tag.IMAGE: String imgRef = attributes.getValue(myHrefAttribute); if ((imgRef != null) && (imgRef.length() != 0) && (imgRef.charAt(0) == '#')) { String vOffset = attributes.getValue("voffset"); short offset = 0; try { offset = Short.parseShort(vOffset); } catch (NumberFormatException e) { } imgRef = imgRef.substring(1); if (!imgRef.equals(myCoverImageReference) || myParagraphsBeforeBodyNumber != getModel().getBookTextModel().getParagraphsNumber()) { addImageReference(imgRef, offset); } if (myInsideCoverpage) { myCoverImageReference = imgRef; } } break; case FB2Tag.BINARY: String contentType = attributes.getValue("content-type"); String imgId = attributes.getValue("id"); if ((contentType != null) && (id != null)) { myCurrentImage = new Base64EncodedImage(contentType); addImage(imgId, myCurrentImage); } break; default: break; } }
diff --git a/project-set/core/core-lib/src/main/java/com/rackspace/papi/service/context/ContainerServiceContext.java b/project-set/core/core-lib/src/main/java/com/rackspace/papi/service/context/ContainerServiceContext.java index a55b1575dc..c96c8bf431 100644 --- a/project-set/core/core-lib/src/main/java/com/rackspace/papi/service/context/ContainerServiceContext.java +++ b/project-set/core/core-lib/src/main/java/com/rackspace/papi/service/context/ContainerServiceContext.java @@ -1,105 +1,105 @@ package com.rackspace.papi.service.context; import com.rackspace.papi.commons.config.manager.UpdateListener; import com.rackspace.papi.container.config.ContainerConfiguration; import com.rackspace.papi.container.config.DeploymentConfiguration; import com.rackspace.papi.service.ServiceContext; import com.rackspace.papi.service.config.ConfigurationService; import com.rackspace.papi.service.context.container.ContainerConfigurationService; import com.rackspace.papi.service.context.container.ContainerConfigurationServiceImpl; import com.rackspace.papi.service.context.jndi.ServletContextHelper; import com.rackspace.papi.servlet.InitParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; public class ContainerServiceContext implements ServiceContext<ContainerConfigurationService> { private static final Logger LOG = LoggerFactory.getLogger(ContainerServiceContext.class); public static final String SERVICE_NAME = "powerapi:/services/container"; private final ContainerConfigurationListener configurationListener; private ContainerConfigurationService containerConfigurationService; private ConfigurationService configurationManager; private ServletContext servletContext; public ContainerServiceContext() { this.containerConfigurationService = new ContainerConfigurationServiceImpl(); this.configurationListener = new ContainerConfigurationListener(); } @Override public String getServiceName() { return SERVICE_NAME; } @Override public ContainerConfigurationService getService() { return containerConfigurationService; } /** * Listens for updates to the container.cfg.xml file which holds the location of the log properties * file. */ private class ContainerConfigurationListener implements UpdateListener<ContainerConfiguration> { private int determinePort(DeploymentConfiguration deployConfig) { int port = -1; if (deployConfig != null && deployConfig.getPort() != null) { port = deployConfig.getPort(); } else { LOG.error("Service port not specified in container.cfg.xml"); } return port; } @Override public void configurationUpdated(ContainerConfiguration configurationObject) { DeploymentConfiguration deployConfig = configurationObject.getDeploymentConfig(); int currentPort = ServletContextHelper.getServerPort(servletContext); int port = determinePort(deployConfig); if (currentPort == -1) { // No port has been set into the servlet context if (port > 0) { containerConfigurationService = new ContainerConfigurationServiceImpl(port); servletContext.setAttribute(InitParameter.PORT.getParameterName(), port); LOG.info("Setting " + InitParameter.PORT.getParameterName() + " to " + port); } else { // current port and port specified in container.cfg.xml are -1 (not set) - LOG.equals("Cannot determine " + InitParameter.PORT.getParameterName() + ". Port must be specified in container.cfg.xml or on the command line."); + LOG.error("Cannot determine " + InitParameter.PORT.getParameterName() + ". Port must be specified in container.cfg.xml or on the command line."); } } else { if (port > 0 && currentPort != port) { // Port changed and is different from port already available in servlet context. LOG.warn("****** " + InitParameter.PORT.getParameterName() + " changed from " + currentPort + " --> " + port + ". Restart is required for this change."); } } } } @Override public void contextInitialized(ServletContextEvent servletContextEvent) { servletContext = servletContextEvent.getServletContext(); configurationManager = ServletContextHelper.getPowerApiContext(servletContext).configurationService(); configurationManager.subscribeTo("container.cfg.xml", configurationListener, ContainerConfiguration.class); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { if (configurationManager != null) { configurationManager.unsubscribeFrom("container.cfg.xml", configurationListener); } } }
true
true
public void configurationUpdated(ContainerConfiguration configurationObject) { DeploymentConfiguration deployConfig = configurationObject.getDeploymentConfig(); int currentPort = ServletContextHelper.getServerPort(servletContext); int port = determinePort(deployConfig); if (currentPort == -1) { // No port has been set into the servlet context if (port > 0) { containerConfigurationService = new ContainerConfigurationServiceImpl(port); servletContext.setAttribute(InitParameter.PORT.getParameterName(), port); LOG.info("Setting " + InitParameter.PORT.getParameterName() + " to " + port); } else { // current port and port specified in container.cfg.xml are -1 (not set) LOG.equals("Cannot determine " + InitParameter.PORT.getParameterName() + ". Port must be specified in container.cfg.xml or on the command line."); } } else { if (port > 0 && currentPort != port) { // Port changed and is different from port already available in servlet context. LOG.warn("****** " + InitParameter.PORT.getParameterName() + " changed from " + currentPort + " --> " + port + ". Restart is required for this change."); } } }
public void configurationUpdated(ContainerConfiguration configurationObject) { DeploymentConfiguration deployConfig = configurationObject.getDeploymentConfig(); int currentPort = ServletContextHelper.getServerPort(servletContext); int port = determinePort(deployConfig); if (currentPort == -1) { // No port has been set into the servlet context if (port > 0) { containerConfigurationService = new ContainerConfigurationServiceImpl(port); servletContext.setAttribute(InitParameter.PORT.getParameterName(), port); LOG.info("Setting " + InitParameter.PORT.getParameterName() + " to " + port); } else { // current port and port specified in container.cfg.xml are -1 (not set) LOG.error("Cannot determine " + InitParameter.PORT.getParameterName() + ". Port must be specified in container.cfg.xml or on the command line."); } } else { if (port > 0 && currentPort != port) { // Port changed and is different from port already available in servlet context. LOG.warn("****** " + InitParameter.PORT.getParameterName() + " changed from " + currentPort + " --> " + port + ". Restart is required for this change."); } } }
diff --git a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java index efdfadef7..f13fc3bbb 100644 --- a/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java +++ b/dspace-jspui/dspace-jspui-api/src/main/java/org/dspace/app/webui/servlet/AbstractBrowserServlet.java @@ -1,364 +1,364 @@ package org.dspace.app.webui.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dspace.app.webui.util.UIUtil; import org.dspace.authorize.AuthorizeException; import org.dspace.browse.BrowseEngine; import org.dspace.browse.BrowseException; import org.dspace.browse.BrowseIndex; import org.dspace.browse.BrowseInfo; import org.dspace.browse.BrowserScope; import org.dspace.sort.SortOption; import org.dspace.sort.SortException; import org.dspace.content.Collection; import org.dspace.content.Community; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.LogManager; /** * Servlet for browsing through indices, as they are defined in * the configuration. This class can take a wide variety of inputs from * the user interface: * * - type: the type of browse (index name) being performed * - order: (ASC | DESC) the direction for result sorting * - value: A specific value to find items around. For example the author name or subject * - month: integer specification of the month of a date browse * - year: integer specification of the year of a date browse * - starts_with: string value at which to start browsing * - vfocus: start browsing with a value of this string * - focus: integer id of the item at which to start browsing * - rpp: integer number of results per page to display * - sort_by: integer specification of the field to search on * - etal: integer number to limit multiple value items specified in config to * * @author Richard Jones * @version $Revision: $ */ public abstract class AbstractBrowserServlet extends DSpaceServlet { /** log4j category */ private static Logger log = Logger.getLogger(AbstractBrowserServlet.class); public AbstractBrowserServlet() { super(); } /** * Create a BrowserScope from the current request * * @param context The database context * @param request The servlet request * @param response The servlet response * @return A BrowserScope for the current parameters * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // first, lift all the stuff out of the request that we might need String type = request.getParameter("type"); String order = request.getParameter("order"); String value = request.getParameter("value"); String valueLang = request.getParameter("value_lang"); String month = request.getParameter("month"); String year = request.getParameter("year"); String startsWith = request.getParameter("starts_with"); String valueFocus = request.getParameter("vfocus"); String valueFocusLang = request.getParameter("vfocus_lang"); int focus = UIUtil.getIntParameter(request, "focus"); int resultsperpage = UIUtil.getIntParameter(request, "rpp"); int sortBy = UIUtil.getIntParameter(request, "sort_by"); int etAl = UIUtil.getIntParameter(request, "etal"); // get the community or collection location for the browse request // Note that we are only interested in getting the "smallest" container, // so if we find a collection, we don't bother looking up the community Collection collection = null; Community community = null; collection = UIUtil.getCollectionLocation(request); if (collection == null) { community = UIUtil.getCommunityLocation(request); } // process the input, performing some inline validation BrowseIndex bi = null; if (type != null && !"".equals(type)) { bi = BrowseIndex.getBrowseIndex(type); } if (bi == null) { if (sortBy > 0) bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy)); else bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption()); } // If we don't have a sort column if (bi != null && sortBy == -1) { // Get the default one SortOption so = bi.getSortOption(); if (so != null) { sortBy = so.getNumber(); } } else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex()) { // If a default sort option is specified by the index, but it isn't // the same as sort option requested, attempt to find an index that // is configured to use that sort by default // This is so that we can then highlight the correct option in the navigation SortOption bso = bi.getSortOption(); SortOption so = SortOption.getSortOption(sortBy); if ( bso != null && bso != so) { BrowseIndex newBi = BrowseIndex.getBrowseIndex(so); if (newBi != null) { bi = newBi; type = bi.getName(); } } } if (order == null && bi != null) { order = bi.getDefaultOrder(); } // if no resultsperpage set, default to 20 if (resultsperpage == -1) { resultsperpage = 20; } // if year and perhaps month have been selected, we translate these into "startsWith" // if startsWith has already been defined then it is overwritten if (year != null && !"".equals(year) && !"-1".equals(year)) { startsWith = year; if ((month != null) && !"-1".equals(month) && !"".equals(month)) { // subtract 1 from the month, so the match works appropriately if ("ASC".equals(order)) { month = Integer.toString((Integer.parseInt(month) - 1)); } // They've selected a month as well if (month.length() == 1) { // Ensure double-digit month number month = "0" + month; } startsWith = year + "-" + month; } } // determine which level of the browse we are at: 0 for top, 1 for second int level = 0; if (value != null) { level = 1; } // if sortBy is still not set, set it to 0, which is default to use the primary index value if (sortBy == -1) { sortBy = 0; } // figure out the setting for author list truncation if (etAl == -1) // there is no limit, or the UI says to use the default { int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit"); if (limitLine != 0) { etAl = limitLine; } } else // if the user has set a limit { if (etAl == 0) // 0 is the user setting for unlimited { etAl = -1; // but -1 is the application setting for unlimited } } // log the request String comHandle = "n/a"; if (community != null) { comHandle = community.getHandle(); } String colHandle = "n/a"; if (collection != null) { colHandle = collection.getHandle(); } String arguments = "type=" + type + ",order=" + order + ",value=" + value + ",month=" + month + ",year=" + year + ",starts_with=" + startsWith + ",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage + ",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle + ",level=" + level + ",etal=" + etAl; log.info(LogManager.getHeader(context, "browse", arguments)); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(context); scope.setBrowseIndex(bi); scope.setOrder(order); scope.setFilterValue(value); scope.setFilterValueLang(valueLang); scope.setJumpToItem(focus); scope.setJumpToValue(valueFocus); scope.setJumpToValueLang(valueFocusLang); scope.setStartsWith(startsWith); scope.setResultsPerPage(resultsperpage); scope.setSortBy(sortBy); scope.setBrowseLevel(level); scope.setEtAl(etAl); // assign the scope of either Community or Collection if necessary if (community != null) { scope.setBrowseContainer(community); } else if (collection != null) { scope.setBrowseContainer(collection); } // For second level browses on metadata indexes, we need to adjust the default sorting - if (bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0) + if (bi != null && bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0) { scope.setSortBy(1); } return scope; } catch (SortException se) { log.error("caught exception: ", se); throw new ServletException(se); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Do the usual DSpace GET method. You will notice that browse does not currently * respond to POST requests. */ protected void processBrowse(Context context, BrowserScope scope, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { BrowseIndex bi = scope.getBrowseIndex(); // now start up a browse engine and get it to do the work for us BrowseEngine be = new BrowseEngine(context); BrowseInfo binfo = be.browse(scope); request.setAttribute("browse.info", binfo); if (binfo.hasResults()) { if (bi.isMetadataIndex() && !scope.isSecondLevel()) { showSinglePage(context, request, response); } else { showFullPage(context, request, response); } } else { showNoResultsPage(context, request, response); } } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } } /** * Display the error page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showError(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; /** * Display the No Results page * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showNoResultsPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; /** * Display the single page. This is the page which lists just the single values of a * metadata browse, not individual items. Single values are links through to all the items * that match that metadata value * * @param context * @param request * @param response * @throws ServletException * @throws IOException * @throws SQLException * @throws AuthorizeException */ protected abstract void showSinglePage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; protected abstract void showFullPage(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException; }
true
true
protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // first, lift all the stuff out of the request that we might need String type = request.getParameter("type"); String order = request.getParameter("order"); String value = request.getParameter("value"); String valueLang = request.getParameter("value_lang"); String month = request.getParameter("month"); String year = request.getParameter("year"); String startsWith = request.getParameter("starts_with"); String valueFocus = request.getParameter("vfocus"); String valueFocusLang = request.getParameter("vfocus_lang"); int focus = UIUtil.getIntParameter(request, "focus"); int resultsperpage = UIUtil.getIntParameter(request, "rpp"); int sortBy = UIUtil.getIntParameter(request, "sort_by"); int etAl = UIUtil.getIntParameter(request, "etal"); // get the community or collection location for the browse request // Note that we are only interested in getting the "smallest" container, // so if we find a collection, we don't bother looking up the community Collection collection = null; Community community = null; collection = UIUtil.getCollectionLocation(request); if (collection == null) { community = UIUtil.getCommunityLocation(request); } // process the input, performing some inline validation BrowseIndex bi = null; if (type != null && !"".equals(type)) { bi = BrowseIndex.getBrowseIndex(type); } if (bi == null) { if (sortBy > 0) bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy)); else bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption()); } // If we don't have a sort column if (bi != null && sortBy == -1) { // Get the default one SortOption so = bi.getSortOption(); if (so != null) { sortBy = so.getNumber(); } } else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex()) { // If a default sort option is specified by the index, but it isn't // the same as sort option requested, attempt to find an index that // is configured to use that sort by default // This is so that we can then highlight the correct option in the navigation SortOption bso = bi.getSortOption(); SortOption so = SortOption.getSortOption(sortBy); if ( bso != null && bso != so) { BrowseIndex newBi = BrowseIndex.getBrowseIndex(so); if (newBi != null) { bi = newBi; type = bi.getName(); } } } if (order == null && bi != null) { order = bi.getDefaultOrder(); } // if no resultsperpage set, default to 20 if (resultsperpage == -1) { resultsperpage = 20; } // if year and perhaps month have been selected, we translate these into "startsWith" // if startsWith has already been defined then it is overwritten if (year != null && !"".equals(year) && !"-1".equals(year)) { startsWith = year; if ((month != null) && !"-1".equals(month) && !"".equals(month)) { // subtract 1 from the month, so the match works appropriately if ("ASC".equals(order)) { month = Integer.toString((Integer.parseInt(month) - 1)); } // They've selected a month as well if (month.length() == 1) { // Ensure double-digit month number month = "0" + month; } startsWith = year + "-" + month; } } // determine which level of the browse we are at: 0 for top, 1 for second int level = 0; if (value != null) { level = 1; } // if sortBy is still not set, set it to 0, which is default to use the primary index value if (sortBy == -1) { sortBy = 0; } // figure out the setting for author list truncation if (etAl == -1) // there is no limit, or the UI says to use the default { int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit"); if (limitLine != 0) { etAl = limitLine; } } else // if the user has set a limit { if (etAl == 0) // 0 is the user setting for unlimited { etAl = -1; // but -1 is the application setting for unlimited } } // log the request String comHandle = "n/a"; if (community != null) { comHandle = community.getHandle(); } String colHandle = "n/a"; if (collection != null) { colHandle = collection.getHandle(); } String arguments = "type=" + type + ",order=" + order + ",value=" + value + ",month=" + month + ",year=" + year + ",starts_with=" + startsWith + ",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage + ",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle + ",level=" + level + ",etal=" + etAl; log.info(LogManager.getHeader(context, "browse", arguments)); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(context); scope.setBrowseIndex(bi); scope.setOrder(order); scope.setFilterValue(value); scope.setFilterValueLang(valueLang); scope.setJumpToItem(focus); scope.setJumpToValue(valueFocus); scope.setJumpToValueLang(valueFocusLang); scope.setStartsWith(startsWith); scope.setResultsPerPage(resultsperpage); scope.setSortBy(sortBy); scope.setBrowseLevel(level); scope.setEtAl(etAl); // assign the scope of either Community or Collection if necessary if (community != null) { scope.setBrowseContainer(community); } else if (collection != null) { scope.setBrowseContainer(collection); } // For second level browses on metadata indexes, we need to adjust the default sorting if (bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0) { scope.setSortBy(1); } return scope; } catch (SortException se) { log.error("caught exception: ", se); throw new ServletException(se); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } }
protected BrowserScope getBrowserScopeForRequest(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { try { // first, lift all the stuff out of the request that we might need String type = request.getParameter("type"); String order = request.getParameter("order"); String value = request.getParameter("value"); String valueLang = request.getParameter("value_lang"); String month = request.getParameter("month"); String year = request.getParameter("year"); String startsWith = request.getParameter("starts_with"); String valueFocus = request.getParameter("vfocus"); String valueFocusLang = request.getParameter("vfocus_lang"); int focus = UIUtil.getIntParameter(request, "focus"); int resultsperpage = UIUtil.getIntParameter(request, "rpp"); int sortBy = UIUtil.getIntParameter(request, "sort_by"); int etAl = UIUtil.getIntParameter(request, "etal"); // get the community or collection location for the browse request // Note that we are only interested in getting the "smallest" container, // so if we find a collection, we don't bother looking up the community Collection collection = null; Community community = null; collection = UIUtil.getCollectionLocation(request); if (collection == null) { community = UIUtil.getCommunityLocation(request); } // process the input, performing some inline validation BrowseIndex bi = null; if (type != null && !"".equals(type)) { bi = BrowseIndex.getBrowseIndex(type); } if (bi == null) { if (sortBy > 0) bi = BrowseIndex.getBrowseIndex(SortOption.getSortOption(sortBy)); else bi = BrowseIndex.getBrowseIndex(SortOption.getDefaultSortOption()); } // If we don't have a sort column if (bi != null && sortBy == -1) { // Get the default one SortOption so = bi.getSortOption(); if (so != null) { sortBy = so.getNumber(); } } else if (bi != null && bi.isItemIndex() && !bi.isInternalIndex()) { // If a default sort option is specified by the index, but it isn't // the same as sort option requested, attempt to find an index that // is configured to use that sort by default // This is so that we can then highlight the correct option in the navigation SortOption bso = bi.getSortOption(); SortOption so = SortOption.getSortOption(sortBy); if ( bso != null && bso != so) { BrowseIndex newBi = BrowseIndex.getBrowseIndex(so); if (newBi != null) { bi = newBi; type = bi.getName(); } } } if (order == null && bi != null) { order = bi.getDefaultOrder(); } // if no resultsperpage set, default to 20 if (resultsperpage == -1) { resultsperpage = 20; } // if year and perhaps month have been selected, we translate these into "startsWith" // if startsWith has already been defined then it is overwritten if (year != null && !"".equals(year) && !"-1".equals(year)) { startsWith = year; if ((month != null) && !"-1".equals(month) && !"".equals(month)) { // subtract 1 from the month, so the match works appropriately if ("ASC".equals(order)) { month = Integer.toString((Integer.parseInt(month) - 1)); } // They've selected a month as well if (month.length() == 1) { // Ensure double-digit month number month = "0" + month; } startsWith = year + "-" + month; } } // determine which level of the browse we are at: 0 for top, 1 for second int level = 0; if (value != null) { level = 1; } // if sortBy is still not set, set it to 0, which is default to use the primary index value if (sortBy == -1) { sortBy = 0; } // figure out the setting for author list truncation if (etAl == -1) // there is no limit, or the UI says to use the default { int limitLine = ConfigurationManager.getIntProperty("webui.browse.author-limit"); if (limitLine != 0) { etAl = limitLine; } } else // if the user has set a limit { if (etAl == 0) // 0 is the user setting for unlimited { etAl = -1; // but -1 is the application setting for unlimited } } // log the request String comHandle = "n/a"; if (community != null) { comHandle = community.getHandle(); } String colHandle = "n/a"; if (collection != null) { colHandle = collection.getHandle(); } String arguments = "type=" + type + ",order=" + order + ",value=" + value + ",month=" + month + ",year=" + year + ",starts_with=" + startsWith + ",vfocus=" + valueFocus + ",focus=" + focus + ",rpp=" + resultsperpage + ",sort_by=" + sortBy + ",community=" + comHandle + ",collection=" + colHandle + ",level=" + level + ",etal=" + etAl; log.info(LogManager.getHeader(context, "browse", arguments)); // set up a BrowseScope and start loading the values into it BrowserScope scope = new BrowserScope(context); scope.setBrowseIndex(bi); scope.setOrder(order); scope.setFilterValue(value); scope.setFilterValueLang(valueLang); scope.setJumpToItem(focus); scope.setJumpToValue(valueFocus); scope.setJumpToValueLang(valueFocusLang); scope.setStartsWith(startsWith); scope.setResultsPerPage(resultsperpage); scope.setSortBy(sortBy); scope.setBrowseLevel(level); scope.setEtAl(etAl); // assign the scope of either Community or Collection if necessary if (community != null) { scope.setBrowseContainer(community); } else if (collection != null) { scope.setBrowseContainer(collection); } // For second level browses on metadata indexes, we need to adjust the default sorting if (bi != null && bi.isMetadataIndex() && scope.isSecondLevel() && scope.getSortBy() <= 0) { scope.setSortBy(1); } return scope; } catch (SortException se) { log.error("caught exception: ", se); throw new ServletException(se); } catch (BrowseException e) { log.error("caught exception: ", e); throw new ServletException(e); } }
diff --git a/src/java/uk/org/ponder/darwin/rsf/producers/SearchResultsProducer.java b/src/java/uk/org/ponder/darwin/rsf/producers/SearchResultsProducer.java index c5eaec3..70de0b1 100644 --- a/src/java/uk/org/ponder/darwin/rsf/producers/SearchResultsProducer.java +++ b/src/java/uk/org/ponder/darwin/rsf/producers/SearchResultsProducer.java @@ -1,305 +1,305 @@ /* * Created on 07-May-2006 */ package uk.org.ponder.darwin.rsf.producers; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.lucene.document.Document; import org.apache.lucene.index.Term; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.springframework.util.StringUtils; import uk.org.ponder.darwin.item.ItemCollection; import uk.org.ponder.darwin.lucene.DarwinHighlighter; import uk.org.ponder.darwin.lucene.IndexItemSearcher; import uk.org.ponder.darwin.lucene.QueryBuilder; import uk.org.ponder.darwin.rsf.params.AdvancedSearchParams; import uk.org.ponder.darwin.rsf.params.NavParams; import uk.org.ponder.darwin.rsf.params.RecordParams; import uk.org.ponder.darwin.rsf.params.SearchResultsParams; import uk.org.ponder.darwin.rsf.util.DarwinUtil; import uk.org.ponder.darwin.search.DocFields; import uk.org.ponder.darwin.search.DocTypeInterpreter; import uk.org.ponder.darwin.search.SearchParams; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.request.EarlyRequestParser; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; import uk.org.ponder.stringutil.CharWrap; import uk.org.ponder.util.Logger; import uk.org.ponder.util.UniversalRuntimeException; public class SearchResultsProducer implements ViewComponentProducer, ViewParamsReporter { public static final String VIEWID = "search-results"; private IndexItemSearcher itemsearcher; private QueryBuilder querybuilder; private ItemCollection itemcollection; private DocTypeInterpreter doctypeinterpreter; public String getViewID() { return VIEWID; } public ViewParameters getViewParameters() { return new SearchResultsParams(); } public void setIndexItemSearcher(IndexItemSearcher itemsearcher) { this.itemsearcher = itemsearcher; } public void setQueryBuilder(QueryBuilder querybuilder) { this.querybuilder = querybuilder; } public void setItemCollection(ItemCollection itemcollection) { this.itemcollection = itemcollection; } public void setDocTypeInterpreter(DocTypeInterpreter doctypeinterpreter) { this.doctypeinterpreter = doctypeinterpreter; } private String rewriteQuery(Query unrwquery) { try { CharWrap togo = new CharWrap(); Query query = unrwquery.rewrite(itemsearcher.getIndexSearcher().getIndexReader()); Set terms = new HashSet(); query.extractTerms(terms); boolean first = true; for (Iterator it = terms.iterator(); it.hasNext();) { Term term = (Term) it.next(); if (!term.field().equals("text")) continue; String text = term.text(); if (!first) { togo.append(" "); } first = false; togo.append(text); } return togo.toString(); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e, "Error rewriting query " + unrwquery); } } public void fillComponents(UIContainer tofill, ViewParameters viewparamso, ComponentChecker checker) { SearchResultsParams viewparams = (SearchResultsParams) viewparamso; if (viewparams.pageno == 0) { viewparams.pageno = 1; } SearchParams params = viewparams.params; UIForm repage = UIForm.make(tofill, "repage-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(repage, "pagesize", SearchResultsParams.pagesizes, SearchResultsParams.pagesizes, Integer.toString(viewparams.pagesize)); UIForm resort = UIForm.make(tofill, "resort-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(resort, "sort", SearchParams.SORT_OPTIONS, SearchParams.SORT_OPTIONS_NAMES, params.sort); UIForm research = UIForm.make(tofill, "research-form", new SearchResultsParams()); UIInput.make(research, "freetext", null, ""); UIInternalLink.make(tofill, "search-again", new AdvancedSearchParams()); boolean issingleitemquery = StringUtils.hasText(params.identifier); boolean isfreetext = StringUtils.hasText(params.freetext); int pagesize = viewparams.pagesize; int thispage = viewparams.pageno; if (thispage < 1) thispage = 1; if (pagesize < 5) pagesize = 5; int start = (thispage - 1) * pagesize; int limit = start + pagesize; if (thispage != 1) { SearchResultsParams prevparams = (SearchResultsParams) viewparams .copyBase(); prevparams.pageno = thispage - 1; UIInternalLink.make(tofill, "previous-page-text", prevparams); } else { UIOutput.make(tofill, "no-previous-text"); } UIForm gotoform = UIForm.make(tofill, "goto-form", EarlyRequestParser.RENDER_REQUEST); UIInput.make(gotoform, "pageno", null, ""); try { Query query = querybuilder.convertQuery(params); UIOutput.make(tofill, "search-string", query.toString()); Sort sort = QueryBuilder.convertSort(params); IndexSearcher searcher = itemsearcher.getIndexSearcher(); Hits hits = null; try { hits = searcher.search(query, sort); } catch (Exception e) { Logger.log.warn("Error performing search", e); } if (hits == null || hits.length() == 0) { UIOutput.make(tofill, "no-results"); } else { if (limit > hits.length()) limit = hits.length(); if (start >= limit) start = limit - pagesize; if (start < 0) start = 0; // 101 / 10 = 11, 100/10 = 10, 99/10 -> 10 int maxpage = (hits.length() + (pagesize - 1)) / pagesize; UIOutput.make(tofill, "this-page", Integer.toString(thispage)); UIOutput.make(tofill, "page-max", Integer.toString(maxpage)); if (thispage < maxpage) { SearchResultsParams nextparams = (SearchResultsParams) viewparams .copyBase(); nextparams.pageno = thispage + 1; UIInternalLink.make(tofill, "next-page-text", nextparams); } else { UIOutput.make(tofill, "no-next-text"); } UIOutput.make(tofill, "this-page-hits", (start + 1) + "-" + limit); UIOutput.make(tofill, "totalhits", Integer.toString(hits.length())); for (int i = start; i < limit; ++i) { Document hit = hits.doc(i); String keywords = rewriteQuery(query); ViewParameters navparams = findLink(hit, keywords); UIBranchContainer hitrow = UIBranchContainer.make(tofill, "hit-item:", Integer.toString(i)); String doctype = hit.get("documenttype"); String name = hit.get("name"); UIOutput.make(hitrow, "document-type", doctype); UIOutput.make(hitrow, "identifier", hit.get("identifier")); if (doctypeinterpreter.isConciseType(doctype)) { String concise = hit.get("reference"); if (navparams != null) { UIInternalLink.make(hitrow, "concise-link", concise, navparams); } else { UIOutput.make(hitrow, "concise", concise); } } else { String datestring = hit.get("displaydate"); UIOutput.make(hitrow, "date", datestring); UIOutput.make(hitrow, "name", name); String description = hit.get("description"); if (description != null) { - UIOutput.make(hitrow, "description"); + UIOutput.make(hitrow, "description", description); } if (!doctypeinterpreter.isType(doctype, DocTypeInterpreter.CORRESPONDENCE)) { String attribtitle = hit.get("attributedtitle"); if (navparams != null) { UIInternalLink.make(hitrow, "attrib-title-link", attribtitle, navparams); } else { UIOutput.make(hitrow, "attrib-title", attribtitle); } } else { String place = hit.get("place"); if (place != null) { UIOutput.make(hitrow, "place-created", place); } if (navparams != null) { UIInternalLink.make(hitrow, "name-link", name, navparams); } else { UIOutput.make(hitrow, "name", name); } } } if (isfreetext) { float score = hits.score(i); String relperc = (int) (score * 100) + "%"; UIOutput.make(hitrow, "hit-weight", relperc); String pagetext = hit.get(DocFields.FLAT_TEXT); String rendered = DarwinHighlighter.getHighlightedHit(query, pagetext, searcher.getIndexReader()); UIVerbatim.make(hitrow, "rendered-hit", rendered); } else { UIOutput.make(hitrow, "hit-weight", (1 + i) + ". "); } } } } catch (Exception e) { Logger.log.warn("Error performing query: ", e); } } private ViewParameters findLink(Document hit, String freetext) { // We could presumably use DocFields.TYPE_ITEM here String pageno = hit.get(DocFields.PAGESEQ_START); if (pageno != null) { NavParams togo = new NavParams(); togo.itemID = hit.get("identifier"); if (togo.itemID == null) { Logger.log.warn("Warning: identifier not found for " + hit); togo.itemID = hit.get("itemID"); } togo.pageseq = Integer.parseInt(pageno); DarwinUtil.chooseBestView(togo, itemcollection); togo.viewID = FramesetProducer.VIEWID; togo.keywords = freetext; return togo; } else { RecordParams togo = new RecordParams(hit.get("identifier")); return togo; } } }
true
true
public void fillComponents(UIContainer tofill, ViewParameters viewparamso, ComponentChecker checker) { SearchResultsParams viewparams = (SearchResultsParams) viewparamso; if (viewparams.pageno == 0) { viewparams.pageno = 1; } SearchParams params = viewparams.params; UIForm repage = UIForm.make(tofill, "repage-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(repage, "pagesize", SearchResultsParams.pagesizes, SearchResultsParams.pagesizes, Integer.toString(viewparams.pagesize)); UIForm resort = UIForm.make(tofill, "resort-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(resort, "sort", SearchParams.SORT_OPTIONS, SearchParams.SORT_OPTIONS_NAMES, params.sort); UIForm research = UIForm.make(tofill, "research-form", new SearchResultsParams()); UIInput.make(research, "freetext", null, ""); UIInternalLink.make(tofill, "search-again", new AdvancedSearchParams()); boolean issingleitemquery = StringUtils.hasText(params.identifier); boolean isfreetext = StringUtils.hasText(params.freetext); int pagesize = viewparams.pagesize; int thispage = viewparams.pageno; if (thispage < 1) thispage = 1; if (pagesize < 5) pagesize = 5; int start = (thispage - 1) * pagesize; int limit = start + pagesize; if (thispage != 1) { SearchResultsParams prevparams = (SearchResultsParams) viewparams .copyBase(); prevparams.pageno = thispage - 1; UIInternalLink.make(tofill, "previous-page-text", prevparams); } else { UIOutput.make(tofill, "no-previous-text"); } UIForm gotoform = UIForm.make(tofill, "goto-form", EarlyRequestParser.RENDER_REQUEST); UIInput.make(gotoform, "pageno", null, ""); try { Query query = querybuilder.convertQuery(params); UIOutput.make(tofill, "search-string", query.toString()); Sort sort = QueryBuilder.convertSort(params); IndexSearcher searcher = itemsearcher.getIndexSearcher(); Hits hits = null; try { hits = searcher.search(query, sort); } catch (Exception e) { Logger.log.warn("Error performing search", e); } if (hits == null || hits.length() == 0) { UIOutput.make(tofill, "no-results"); } else { if (limit > hits.length()) limit = hits.length(); if (start >= limit) start = limit - pagesize; if (start < 0) start = 0; // 101 / 10 = 11, 100/10 = 10, 99/10 -> 10 int maxpage = (hits.length() + (pagesize - 1)) / pagesize; UIOutput.make(tofill, "this-page", Integer.toString(thispage)); UIOutput.make(tofill, "page-max", Integer.toString(maxpage)); if (thispage < maxpage) { SearchResultsParams nextparams = (SearchResultsParams) viewparams .copyBase(); nextparams.pageno = thispage + 1; UIInternalLink.make(tofill, "next-page-text", nextparams); } else { UIOutput.make(tofill, "no-next-text"); } UIOutput.make(tofill, "this-page-hits", (start + 1) + "-" + limit); UIOutput.make(tofill, "totalhits", Integer.toString(hits.length())); for (int i = start; i < limit; ++i) { Document hit = hits.doc(i); String keywords = rewriteQuery(query); ViewParameters navparams = findLink(hit, keywords); UIBranchContainer hitrow = UIBranchContainer.make(tofill, "hit-item:", Integer.toString(i)); String doctype = hit.get("documenttype"); String name = hit.get("name"); UIOutput.make(hitrow, "document-type", doctype); UIOutput.make(hitrow, "identifier", hit.get("identifier")); if (doctypeinterpreter.isConciseType(doctype)) { String concise = hit.get("reference"); if (navparams != null) { UIInternalLink.make(hitrow, "concise-link", concise, navparams); } else { UIOutput.make(hitrow, "concise", concise); } } else { String datestring = hit.get("displaydate"); UIOutput.make(hitrow, "date", datestring); UIOutput.make(hitrow, "name", name); String description = hit.get("description"); if (description != null) { UIOutput.make(hitrow, "description"); } if (!doctypeinterpreter.isType(doctype, DocTypeInterpreter.CORRESPONDENCE)) { String attribtitle = hit.get("attributedtitle"); if (navparams != null) { UIInternalLink.make(hitrow, "attrib-title-link", attribtitle, navparams); } else { UIOutput.make(hitrow, "attrib-title", attribtitle); } } else { String place = hit.get("place"); if (place != null) { UIOutput.make(hitrow, "place-created", place); } if (navparams != null) { UIInternalLink.make(hitrow, "name-link", name, navparams); } else { UIOutput.make(hitrow, "name", name); } } } if (isfreetext) { float score = hits.score(i); String relperc = (int) (score * 100) + "%"; UIOutput.make(hitrow, "hit-weight", relperc); String pagetext = hit.get(DocFields.FLAT_TEXT); String rendered = DarwinHighlighter.getHighlightedHit(query, pagetext, searcher.getIndexReader()); UIVerbatim.make(hitrow, "rendered-hit", rendered); } else { UIOutput.make(hitrow, "hit-weight", (1 + i) + ". "); } } } } catch (Exception e) { Logger.log.warn("Error performing query: ", e); } }
public void fillComponents(UIContainer tofill, ViewParameters viewparamso, ComponentChecker checker) { SearchResultsParams viewparams = (SearchResultsParams) viewparamso; if (viewparams.pageno == 0) { viewparams.pageno = 1; } SearchParams params = viewparams.params; UIForm repage = UIForm.make(tofill, "repage-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(repage, "pagesize", SearchResultsParams.pagesizes, SearchResultsParams.pagesizes, Integer.toString(viewparams.pagesize)); UIForm resort = UIForm.make(tofill, "resort-form", EarlyRequestParser.RENDER_REQUEST); UISelect.make(resort, "sort", SearchParams.SORT_OPTIONS, SearchParams.SORT_OPTIONS_NAMES, params.sort); UIForm research = UIForm.make(tofill, "research-form", new SearchResultsParams()); UIInput.make(research, "freetext", null, ""); UIInternalLink.make(tofill, "search-again", new AdvancedSearchParams()); boolean issingleitemquery = StringUtils.hasText(params.identifier); boolean isfreetext = StringUtils.hasText(params.freetext); int pagesize = viewparams.pagesize; int thispage = viewparams.pageno; if (thispage < 1) thispage = 1; if (pagesize < 5) pagesize = 5; int start = (thispage - 1) * pagesize; int limit = start + pagesize; if (thispage != 1) { SearchResultsParams prevparams = (SearchResultsParams) viewparams .copyBase(); prevparams.pageno = thispage - 1; UIInternalLink.make(tofill, "previous-page-text", prevparams); } else { UIOutput.make(tofill, "no-previous-text"); } UIForm gotoform = UIForm.make(tofill, "goto-form", EarlyRequestParser.RENDER_REQUEST); UIInput.make(gotoform, "pageno", null, ""); try { Query query = querybuilder.convertQuery(params); UIOutput.make(tofill, "search-string", query.toString()); Sort sort = QueryBuilder.convertSort(params); IndexSearcher searcher = itemsearcher.getIndexSearcher(); Hits hits = null; try { hits = searcher.search(query, sort); } catch (Exception e) { Logger.log.warn("Error performing search", e); } if (hits == null || hits.length() == 0) { UIOutput.make(tofill, "no-results"); } else { if (limit > hits.length()) limit = hits.length(); if (start >= limit) start = limit - pagesize; if (start < 0) start = 0; // 101 / 10 = 11, 100/10 = 10, 99/10 -> 10 int maxpage = (hits.length() + (pagesize - 1)) / pagesize; UIOutput.make(tofill, "this-page", Integer.toString(thispage)); UIOutput.make(tofill, "page-max", Integer.toString(maxpage)); if (thispage < maxpage) { SearchResultsParams nextparams = (SearchResultsParams) viewparams .copyBase(); nextparams.pageno = thispage + 1; UIInternalLink.make(tofill, "next-page-text", nextparams); } else { UIOutput.make(tofill, "no-next-text"); } UIOutput.make(tofill, "this-page-hits", (start + 1) + "-" + limit); UIOutput.make(tofill, "totalhits", Integer.toString(hits.length())); for (int i = start; i < limit; ++i) { Document hit = hits.doc(i); String keywords = rewriteQuery(query); ViewParameters navparams = findLink(hit, keywords); UIBranchContainer hitrow = UIBranchContainer.make(tofill, "hit-item:", Integer.toString(i)); String doctype = hit.get("documenttype"); String name = hit.get("name"); UIOutput.make(hitrow, "document-type", doctype); UIOutput.make(hitrow, "identifier", hit.get("identifier")); if (doctypeinterpreter.isConciseType(doctype)) { String concise = hit.get("reference"); if (navparams != null) { UIInternalLink.make(hitrow, "concise-link", concise, navparams); } else { UIOutput.make(hitrow, "concise", concise); } } else { String datestring = hit.get("displaydate"); UIOutput.make(hitrow, "date", datestring); UIOutput.make(hitrow, "name", name); String description = hit.get("description"); if (description != null) { UIOutput.make(hitrow, "description", description); } if (!doctypeinterpreter.isType(doctype, DocTypeInterpreter.CORRESPONDENCE)) { String attribtitle = hit.get("attributedtitle"); if (navparams != null) { UIInternalLink.make(hitrow, "attrib-title-link", attribtitle, navparams); } else { UIOutput.make(hitrow, "attrib-title", attribtitle); } } else { String place = hit.get("place"); if (place != null) { UIOutput.make(hitrow, "place-created", place); } if (navparams != null) { UIInternalLink.make(hitrow, "name-link", name, navparams); } else { UIOutput.make(hitrow, "name", name); } } } if (isfreetext) { float score = hits.score(i); String relperc = (int) (score * 100) + "%"; UIOutput.make(hitrow, "hit-weight", relperc); String pagetext = hit.get(DocFields.FLAT_TEXT); String rendered = DarwinHighlighter.getHighlightedHit(query, pagetext, searcher.getIndexReader()); UIVerbatim.make(hitrow, "rendered-hit", rendered); } else { UIOutput.make(hitrow, "hit-weight", (1 + i) + ". "); } } } } catch (Exception e) { Logger.log.warn("Error performing query: ", e); } }
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java index e9db431e..5c3e43fb 100644 --- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java +++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/study/SetUpDataExplorationPage.java @@ -1,2603 +1,2599 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.harvard.iq.dvn.core.web.study; import com.icesoft.faces.component.ext.HtmlCommandButton; import edu.harvard.iq.dvn.core.study.DataTable; import com.icesoft.faces.component.ext.HtmlDataTable; import com.icesoft.faces.component.ext.HtmlInputText; import com.icesoft.faces.component.ext.HtmlCommandLink; import com.icesoft.faces.component.ext.HtmlSelectBooleanCheckbox; import com.icesoft.faces.component.ext.HtmlSelectOneMenu; import com.icesoft.faces.context.effects.JavascriptContext; import edu.harvard.iq.dvn.core.study.DataVariable; import edu.harvard.iq.dvn.core.study.EditStudyFilesService; import edu.harvard.iq.dvn.core.study.Metadata; import edu.harvard.iq.dvn.core.study.Study; import edu.harvard.iq.dvn.core.study.StudyFile; import edu.harvard.iq.dvn.core.study.StudyVersion; import edu.harvard.iq.dvn.core.study.VariableServiceLocal; import edu.harvard.iq.dvn.core.visualization.DataVariableMapping; import edu.harvard.iq.dvn.core.visualization.VarGroup; import edu.harvard.iq.dvn.core.visualization.VarGroupType; import edu.harvard.iq.dvn.core.visualization.VarGrouping; import edu.harvard.iq.dvn.core.visualization.VarGrouping.GroupingType; import edu.harvard.iq.dvn.core.visualization.VisualizationServiceLocal; import edu.harvard.iq.dvn.core.web.DataVariableUI; import edu.harvard.iq.dvn.core.web.VarGroupTypeUI; import edu.harvard.iq.dvn.core.web.VarGroupUI; import edu.harvard.iq.dvn.core.web.VarGroupingUI; import edu.harvard.iq.dvn.core.web.common.VDCBaseBean; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.PhaseId; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; /** * * @author skraffmiller */ @EJB(name="visualizationService", beanInterface=edu.harvard.iq.dvn.core.visualization.VisualizationServiceBean.class) public class SetUpDataExplorationPage extends VDCBaseBean implements java.io.Serializable { @EJB VisualizationServiceLocal visualizationService; @EJB VariableServiceLocal varService; private EditStudyFilesService editStudyFilesService; private List <VarGrouping> varGroupings = new ArrayList();; private List <DataVariable> dvList = new ArrayList(); private List <DataVariable> dvFilteredList = new ArrayList(); private List <DataVariableUI> dvGenericListUI = new ArrayList(); private List <DataVariableUI> dvDateListUI = new ArrayList(); private List <DataVariableUI> dvNumericListUI = new ArrayList(); private List <DataVariableUI> dvGenericFilteredListUI = new ArrayList(); // private List <VarGroupType> measureGroupTypes = new ArrayList(); private VarGroupingUI measureGrouping = new VarGroupingUI(); private List <VarGroupingUI> filterGroupings = new ArrayList(); private List <SelectItem> studyFileIdSelectItems = new ArrayList(); private DataVariable xAxisVariable = new DataVariable(); private Long xAxisVariableId = new Long(0); private StudyVersion studyVersion; private Study study; private StudyUI studyUI; private Long studyFileId = new Long(0); private Long studyId ; private Metadata metadata; private String currentTitle; private String xAxisUnits = ""; DataTable dataTable; private boolean showCommands = false; private boolean showMeasureVariables = false; private boolean editXAxis = false; private boolean editMeasure = false; private boolean editFilterGroup = false; private boolean editMeasureGrouping = false; private boolean addMeasureType = false; private boolean addFilterType = false; private boolean addMeasureGroup = false; private boolean addFilterGroup = false; private boolean addFilterGrouping = false; private boolean manageMeasureTypes = false; private boolean manageFilterTypes = false; private boolean editMeasureType = false; private boolean editFilterType = false; private boolean editFilterGrouping = false; private String studyFileName = ""; private boolean xAxisSet = false; private boolean hasMeasureGroups = false; private boolean hasFilterGroupings = false; private boolean hasFilterGroups = false; private VarGroupUI editFragmentVarGroup = new VarGroupUI(); private VarGroupUI editFilterVarGroup = new VarGroupUI(); private VarGroupUI editMeasureVarGroup = new VarGroupUI(); private VarGroupingUI editFilterVarGrouping = new VarGroupingUI(); private boolean showFilterVariables = false; private boolean selectFile = true; public SetUpDataExplorationPage(){ } public void init() { super.init(); studyId = new Long( getVDCRequestBean().getRequestParam("studyId")); try { Context ctx = new InitialContext(); editStudyFilesService = (EditStudyFilesService) ctx.lookup("java:comp/env/editStudyFiles"); } catch (NamingException e) { e.printStackTrace(); FacesContext context = FacesContext.getCurrentInstance(); FacesMessage errMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), null); context.addMessage(null, errMessage); } if (getStudyId() != null) { editStudyFilesService.setStudyVersion(studyId); study = editStudyFilesService.getStudyVersion().getStudy(); studyVersion = study.getEditVersion(); metadata = editStudyFilesService.getStudyVersion().getMetadata(); currentTitle = metadata.getTitle(); setFiles(editStudyFilesService.getCurrentFiles()); } else { FacesContext context = FacesContext.getCurrentInstance(); FacesMessage errMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "The Study ID is null", null); context.addMessage(null, errMessage); //Should not get here. //Must always be in a study to get to this page. } studyUI = new StudyUI(studyVersion, null); studyFileIdSelectItems = loadStudyFileSelectItems(); } public void resetStudyFileId(){ Object value= this.selectStudyFile.getValue(); studyFileName = this.selectStudyFile.getLabel(); Iterator iterator = study.getStudyFiles().iterator(); while (iterator.hasNext() ){ StudyFile studyFile = (StudyFile) iterator.next(); if (studyFile.getId().equals((Long) value)){ studyFileName = studyFile.getFileName(); } } studyFileId = (Long) value; if (!studyFileId.equals(new Long(0))) { loadDataTable(); showCommands = true; selectFile = false; } } private void loadDataTable(){ dataTable = new DataTable(); visualizationService.setDataTableFromStudyFileId(studyFileId); dataTable = visualizationService.getDataTable(); varGroupings = dataTable.getVarGroupings(); study = visualizationService.getStudyFromStudyFileId(studyFileId); dvList = dataTable.getDataVariables(); loadSelectMeasureGroupTypes(); loadMeasureGroupUIs(); dvNumericListUI = loadDvListUIs(false); dvDateListUI = loadDvListUIs(true); xAxisVariable = visualizationService.getXAxisVariable(dataTable.getId()); xAxisVariableId = xAxisVariable.getId(); if (xAxisVariableId.intValue() > 0){ xAxisSet = true; } else { xAxisSet = false; editXAxisAction(); } if (xAxisSet){ for (DataVariableMapping mapping : xAxisVariable.getDataVariableMappings()){ if (mapping.isX_axis())xAxisUnits = mapping.getLabel(); } } if (measureGrouping.getVarGrouping() == null){ addMeasureGrouping(); } else { if (!measureGrouping.getVarGroupUI().isEmpty()){ hasMeasureGroups = true; } } loadFilterGroupings(); if (!filterGroupings.isEmpty()){ hasFilterGroupings = true; } } public List<VarGrouping> getVarGroupings() { return varGroupings; } public void setVarGroupings(List<VarGrouping> varGroupings) { this.varGroupings = varGroupings; } public List<VarGroupType> loadSelectMeasureGroupTypes() { for (VarGrouping varGrouping: varGroupings ){ if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)){ measureGrouping.setVarGrouping(varGrouping); measureGrouping.setVarGroupTypesUI(new ArrayList()); for (VarGroupType varGroupType: varGrouping.getVarGroupTypes()){ VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(varGroupType); varGroupTypeUI.setEditMode(false); measureGrouping.getVarGroupTypesUI().add(varGroupTypeUI); } return (List<VarGroupType>) varGrouping.getVarGroupTypes(); } } return null; } private void loadFilterGroupings() { filterGroupings.clear(); for (VarGrouping varGrouping: varGroupings ){ if (varGrouping.getGroupingType().equals(GroupingType.FILTER)){ VarGroupingUI varGroupingUI = new VarGroupingUI(); varGroupingUI.setVarGrouping(varGrouping); varGroupingUI.setVarGroupTypesUI(varGroupingUI); setVarGroupUI(varGroupingUI); filterGroupings.add(varGroupingUI); } } } public void setMeasureGroups(){ } public void setMeasureGroupTypes(){ } public List<VarGroupTypeUI> getMeasureGroupTypes() { if (measureGrouping == null) return null; return (List) measureGrouping.getVarGroupTypesUI(); } public List <DataVariableUI> loadDvListUIs(boolean isDate){ List <DataVariableUI> dvListUILocG = new ArrayList(); for (DataVariable dataVariable : dvList){ if ((isDate && "date".equals(dataVariable.getFormatCategory())) || (!isDate && dataVariable.getVariableFormatType().getName().equals("numeric"))) { DataVariableUI dataVariableUI = new DataVariableUI(); dataVariableUI.setDataVariable(dataVariable); dataVariableUI.setSelected(false); dataVariableUI.setDisplay(true); dvListUILocG.add(dataVariableUI); } } return dvListUILocG; } public void loadMeasureGroupUIs (){ List <VarGroupUI> returnList = new ArrayList(); for (VarGrouping varGrouping: varGroupings ){ if (varGrouping.getGroupingType().equals(GroupingType.MEASURE)){ List <VarGroup> localMeasureGroups = (List<VarGroup>) varGrouping.getVarGroups(); for(VarGroup varGroup: localMeasureGroups) { VarGroupUI varGroupUI = new VarGroupUI(); varGroupUI.setVarGroup(varGroup); varGroupUI.setVarGroupTypes(new ArrayList()); varGroupUI.setVarGroupTypesSelectItems(new ArrayList()); varGroupUI.setDataVariablesSelected(new ArrayList()); List <VarGroupType> varGroupTypes = new ArrayList(); varGroupTypes = (List<VarGroupType>) varGroupUI.getVarGroup().getGroupTypes(); if (varGroupTypes !=null ) { String groupTypesSelectedString = ""; for(VarGroupType varGroupType: varGroupTypes){ VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(varGroupType); varGroupTypeUI.setEnabled(true); varGroupTypeUI.setSelected(true); varGroupTypeUI.getVarGroupType().getName(); varGroupType.getName(); varGroupUI.getVarGroupTypes().add(varGroupTypeUI); varGroupUI.getVarGroupTypesSelectItems().add(varGroupTypeUI); if (groupTypesSelectedString.isEmpty()){ groupTypesSelectedString+=varGroupTypeUI.getVarGroupType().getName(); } else { groupTypesSelectedString = groupTypesSelectedString + ", " + varGroupTypeUI.getVarGroupType().getName(); } } varGroupUI.setGroupTypesSelectedString(groupTypesSelectedString); } List <DataVariable> dataVariables = new ArrayList(); dataVariables = (List<DataVariable>) visualizationService.getDataVariableMappingsFromDataTableGroup(dataTable, varGroup); int selectedVariables = 0; if (dataVariables !=null ) { for(DataVariable dataVariable: dataVariables){ varGroupUI.getDataVariablesSelected().add(new Long(dataVariable.getId())); selectedVariables++; } } varGroupUI.setNumberOfVariablesSelected(new Long(selectedVariables)); returnList.add(varGroupUI); } measureGrouping.setVarGroupUI(returnList); } } } private void setVarGroupUI(VarGroupingUI varGroupingUI) { List<VarGroupUI> varGroupUIList = new ArrayList(); VarGrouping varGroupingIn = varGroupingUI.getVarGrouping(); varGroupingIn.getVarGroupTypes(); List <VarGroup> varGroups = new ArrayList(); varGroups = (List<VarGroup>) varGroupingIn.getVarGroups(); if (varGroups !=null ) { for(VarGroup varGroup: varGroups){ VarGroupUI varGroupUILoc = new VarGroupUI(); varGroupUILoc.setVarGroup(varGroup); varGroupUILoc.getVarGroup().getName(); varGroupUILoc.setVarGroupTypes(new ArrayList()); varGroupUILoc.setVarGroupTypesSelectItems(new ArrayList()); varGroupUILoc.setDataVariablesSelected(new ArrayList()); List <VarGroupType> varGroupTypes = new ArrayList(); List <DataVariable> dataVariables = new ArrayList(); dataVariables = (List<DataVariable>) visualizationService.getDataVariableMappingsFromDataTableGroup(dataTable, varGroup); int selectedVariables = 0; if (dataVariables !=null ) { for(DataVariable dataVariable: dataVariables){ varGroupUILoc.getDataVariablesSelected().add(new Long(dataVariable.getId())); selectedVariables++; } } varGroupUILoc.setNumberOfVariablesSelected(new Long(selectedVariables)); varGroupTypes = (List<VarGroupType>) varGroupUILoc.getVarGroup().getGroupTypes(); String groupTypesSelectedString = ""; if (varGroupTypes !=null ) { for(VarGroupType varGroupType: varGroupTypes){ VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(varGroupType); varGroupTypeUI.getVarGroupType().getName(); varGroupType.getName(); varGroupUILoc.getVarGroupTypesSelectItems().add(varGroupTypeUI); if (groupTypesSelectedString.isEmpty()){ groupTypesSelectedString+=varGroupTypeUI.getVarGroupType().getName(); } else { groupTypesSelectedString = groupTypesSelectedString + ", " + varGroupTypeUI.getVarGroupType().getName(); } } varGroupUILoc.setGroupTypesSelectedString(groupTypesSelectedString); } hasFilterGroups = true; varGroupUIList.add(varGroupUILoc); } } varGroupingUI.setVarGroupUI(varGroupUIList) ; } public List<VarGroupUI> getMeasureGroups() { return (List) measureGrouping.getVarGroupUI(); } public VarGroupingUI getMeasureGrouping() { return measureGrouping; } private boolean hasAssignedGroups(VarGroupType varGroupTypeIn){ if (varGroupTypeIn.getId() == null){ return false; } List varGroup = visualizationService.getGroupsFromGroupTypeId(varGroupTypeIn.getId()); varGroup = (List) varGroupTypeIn.getGroups(); if (!varGroup.isEmpty()){ FacesMessage message = new FacesMessage("You may not delete a type that is assigned to a measure or filter."); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return true; } return false; } public void deleteGroupType(ActionEvent ae){ boolean measure = false; boolean filter = false; UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable dataTable2 = (HtmlDataTable) uiComponent; if (uiComponent.equals(dataTableManageMeasureGroupType)){ measure = true; } if (uiComponent.equals(dataTableMeasureGroupType)){ measure = true; } if (uiComponent.equals(dataTableManageFilterGroupType)){ filter = true; } if (uiComponent.equals(dataTableFilterGroupType)){ filter = true; } if (dataTable2.getRowCount()>0) { VarGroupTypeUI varGroupTypeUI2 = (VarGroupTypeUI) dataTable2.getRowData(); VarGroupType varGroupType = varGroupTypeUI2.getVarGroupType(); List varGroupTypeList = (List) dataTable2.getValue(); if (hasAssignedGroups(varGroupType)){ return; } Iterator iterator = varGroupTypeList.iterator(); List deleteList = new ArrayList(); while (iterator.hasNext() ){ VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) iterator.next(); VarGroupType data = varGroupTypeUI.getVarGroupType(); deleteList.add(data); } visualizationService.removeCollectionElement(deleteList,dataTable2.getRowIndex()); for(VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping() == (varGroupType.getVarGrouping())){ varGroupingUI.getVarGroupTypesUI().remove(varGroupTypeUI2); varGroupingUI.getVarGrouping().getVarGroupTypes().remove(varGroupType); dataTableManageFilterGroupType.setValue(varGroupingUI.getVarGroupTypesUI()); dataTable2.setValue(varGroupingUI.getVarGroupTypesUI()); } } if (filter) { for(VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping() == (varGroupType.getVarGrouping())){ varGroupingUI.getVarGroupTypesUI().remove(varGroupTypeUI2); varGroupingUI.getVarGrouping().getVarGroupTypes().remove(varGroupType); dataTableManageFilterGroupType.setValue(varGroupingUI.getVarGroupTypesUI()); dataTable2.setValue(varGroupingUI.getVarGroupTypesUI()); } } if (editFilterVarGroup !=null && editFilterVarGroup.getVarGroup() != null){ removeTypeFromGroupUI(editFilterVarGroup, varGroupTypeUI2 ); } } if (measure) { measureGrouping.getVarGroupTypesUI().remove(varGroupTypeUI2); measureGrouping.getVarGrouping().getVarGroupTypes().remove(varGroupType); if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null){ removeTypeFromGroupUI(editMeasureVarGroup, varGroupTypeUI2 ); } } } } public void editMeasureGroup (ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupUI varGroupUI = (VarGroupUI) tempTable.getRowData(); dvGenericFilteredListUI.clear(); dvGenericListUI = dvNumericListUI; for (DataVariableUI dataVariableUI: dvGenericListUI){ dataVariableUI.setSelected(false); if (varGroupUI.getDataVariablesSelected() != null){ for (Object dv : varGroupUI.getDataVariablesSelected() ){ Long testId = (Long) dv; if (testId.equals(dataVariableUI.getDataVariable().getId())){ dataVariableUI.setSelected(true); } } } dvGenericFilteredListUI.add(dataVariableUI); } varGroupUI.setVarGroupTypes(new ArrayList()); List <VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) measureGrouping.getVarGroupTypesUI(); for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) { varGroupTypeUI.setSelected(false); List <VarGroupType> varGroupTypes = new ArrayList(); varGroupTypes = (List<VarGroupType>) varGroupUI.getVarGroup().getGroupTypes(); if (varGroupTypes !=null ) { for(VarGroupType varGroupType: varGroupTypes){ if (varGroupType == varGroupTypeUI.getVarGroupType()){ varGroupTypeUI.setSelected(true); } } } varGroupUI.getVarGroupTypes().add(varGroupTypeUI); } editMeasureVarGroup = varGroupUI; cancelAddEdit(); getInputMeasureName().setValue(editMeasureVarGroup.getVarGroup().getName()); getInputMeasureUnits().setValue(editMeasureVarGroup.getVarGroup().getUnits()); editMeasure = true; } public void editMeasureTypeAction(ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData(); getEditMeasureGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName()); getEditManageMeasureGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName()); varGroupTypeUI.setEditMode(true); editMeasureType = true; } public void editFilterType(ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData(); varGroupTypeUI.setEditMode(true); getEditFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName()); getEditManageFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName()); editFilterType = true; } public void editManageFilterType(ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData(); varGroupTypeUI.setEditMode(true); getEditManageFilterGroupTypeName().setValue(varGroupTypeUI.getVarGroupType().getName()); editFilterType = true; } public void saveFilterType(ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData(); String getName = ""; if (tempTable.equals(dataTableManageFilterGroupType)) { getName = (String) getEditManageFilterGroupTypeName().getValue(); } else { getName = (String) getEditFilterGroupTypeName().getValue(); } if (checkForDuplicateEntries(varGroupTypeUI.getVarGroupType().getVarGrouping(), getName, false, varGroupTypeUI.getVarGroupType() )){ return; } varGroupTypeUI.getVarGroupType().setName(getName); loadFilterGroupings(); dataTableFilterGrouping.getChildren().clear(); varGroupTypeUI.setEditMode(false); } public void saveMeasureType(ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupTypeUI varGroupTypeUI = (VarGroupTypeUI) tempTable.getRowData(); String getName = ""; if (tempTable.equals(dataTableManageMeasureGroupType)) { getName = (String) getEditManageMeasureGroupTypeName().getValue(); } else { getName = (String) ((String) getEditMeasureGroupTypeName().getValue()); } if (checkForDuplicateEntries(varGroupTypeUI.getVarGroupType().getVarGrouping(), getName, false, varGroupTypeUI.getVarGroupType() )){ return; } varGroupTypeUI.getVarGroupType().setName(getName); varGroupTypeUI.setEditMode(false); } public void editFilterGroup (ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupUI varGroupUI = (VarGroupUI) tempTable.getRowData(); varGroupUI.getVarGroup().getName(); dvGenericFilteredListUI.clear(); dvGenericListUI = dvNumericListUI; for (DataVariableUI dataVariableUI: dvGenericListUI){ dataVariableUI.setSelected(false); if (varGroupUI.getDataVariablesSelected() != null){ for (Object dv : varGroupUI.getDataVariablesSelected() ){ Long testId = (Long) dv; if (testId.equals(dataVariableUI.getDataVariable().getId())){ dataVariableUI.setSelected(true); } } } dvGenericFilteredListUI.add(dataVariableUI); } varGroupUI.setVarGroupTypes(new ArrayList()); for (VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping() == (varGroupUI.getVarGroup().getGroupAssociation())){ List <VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) varGroupingUI.getVarGroupTypesUI(); for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) { varGroupTypeUI.setSelected(false); List <VarGroupType> varGroupTypes = new ArrayList(); varGroupTypes = (List<VarGroupType>) varGroupUI.getVarGroup().getGroupTypes(); if (varGroupTypes !=null ) { for(VarGroupType varGroupType: varGroupTypes){ if (varGroupType == varGroupTypeUI.getVarGroupType()){ varGroupTypeUI.setSelected(true); } } } varGroupUI.getVarGroupTypes().add(varGroupTypeUI); } } } editFilterVarGroup = varGroupUI; cancelAddEdit(); getInputFilterGroupName().setValue(editFilterVarGroup.getVarGroup().getName()); editFilterGroup = true; } public void editFilterGroupingAction (ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupingUI varGroupingUI = (VarGroupingUI) tempTable.getRowData(); editFilterVarGrouping = varGroupingUI; cancelAddEdit(); getInputFilterGroupingName().setValue(editFilterVarGrouping.getVarGrouping().getName()); editFilterGrouping = true; } public void manageFilterGroupTypeAction (ActionEvent ae){ UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } HtmlDataTable tempTable = (HtmlDataTable) uiComponent; VarGroupingUI varGroupingUI = (VarGroupingUI) tempTable.getRowData(); editFilterVarGrouping = varGroupingUI; cancelAddEdit(); manageFilterTypes = true; } public void manageMeasureGroupTypeAction (){ cancelAddEdit(); manageMeasureTypes = true; } public void editMeasureGroupingAction (){ cancelAddEdit(); editMeasureGrouping = true; getInputMeasureGroupingName().setValue(measureGrouping.getVarGrouping().getName()); } public void editXAxisAction (){ dvGenericListUI = dvDateListUI; Iterator iterator = dvGenericListUI.iterator(); dvGenericFilteredListUI.clear(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); dataVariableUI.setSelected(false); if (dataVariableUI.getDataVariable().getId().equals(xAxisVariableId)){ dataVariableUI.setSelected(true); } dvGenericFilteredListUI.add(dataVariableUI); } cancelAddEdit(); getInputXAxisUnits().setValue(xAxisUnits); editXAxis = true; } public void removeXAxisAction (){ xAxisVariable = new DataVariable(); xAxisVariableId = new Long(0); xAxisSet = false; xAxisUnits = ""; resetDVMappingsXAxis(); cancelAddEdit(); } public void cancelFragment(){ cancelAddEdit(); } public void saveXAxis(){ xAxisUnits = (String) getInputXAxisUnits().getValue(); Long SelectedId = new Long(0); for(DataVariableUI dataVariableUI:dvGenericListUI){ for(DataVariableUI dvTest: dvGenericFilteredListUI){ if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())){ dataVariableUI.setSelected(dvTest.isSelected()); } } } int countSelected = 0; for (DataVariableUI dataVariableUI: dvGenericListUI){ if (dataVariableUI.isSelected()){ SelectedId = dataVariableUI.getDataVariable().getId(); countSelected++; } } if (countSelected > 1) { FacesMessage message = new FacesMessage("You may not select more than one variable"); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); } if (countSelected == 1){ xAxisVariableId = SelectedId; xAxisVariable = varService.getDataVariable(SelectedId); resetDVMappingsXAxis(); xAxisSet = true; } if (countSelected == 0){ xAxisVariableId = SelectedId; xAxisVariable = new DataVariable(); resetDVMappingsXAxis(); xAxisSet = false; } cancelAddEdit(); } public void saveMeasureFragment(){ String chkGroupName = (String) getInputMeasureName().getValue(); if (chkGroupName.isEmpty() || chkGroupName.trim().equals("") ) { FacesMessage message = new FacesMessage("Please Enter a Measure Name"); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return; } if(addMeasureGroup){ if (checkForDuplicateEntries(editMeasureVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, null )){ return; } editMeasureVarGroup.getVarGroup().setName(chkGroupName); editMeasureVarGroup.getVarGroup().setUnits((String) getInputMeasureUnits().getValue()); addMeasureGroupSave(); } else { if (checkForDuplicateEntries(editMeasureVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, editMeasureVarGroup.getVarGroup() )){ return; } editMeasureVarGroup.getVarGroup().setName(chkGroupName); editMeasureVarGroup.getVarGroup().setUnits((String) getInputMeasureUnits().getValue()); } updateVariableByGroup(editMeasureVarGroup); resetDVMappingsByGroup(editMeasureVarGroup); editMeasureVarGroup = null; cancelAddEdit(); } public void saveMeasureGrouping(){ String chkGroupName = (String) getInputMeasureGroupingName().getValue(); if (chkGroupName.isEmpty() || chkGroupName.trim().equals("") ) { FacesMessage message = new FacesMessage("Please Enter a Measure Label"); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return; } if (!getInputMeasureGroupingName().getValue().equals("")){ measureGrouping.getVarGrouping().setName((String) getInputMeasureGroupingName().getValue()); } cancelAddEdit(); } public void cancelMeasureGrouping(){ cancelAddEdit(); } public void saveFilterFragment(ActionEvent ae){ String chkGroupName = (String) getInputFilterGroupName().getValue(); if (chkGroupName.isEmpty()) { FacesMessage message = new FacesMessage("Please Enter a Filter Name"); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return; } if(addFilterGroup){ if (checkForDuplicateEntries(editFilterVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, null )){ return; } addFilterGroupSave(); } else { if (checkForDuplicateEntries(editFilterVarGroup.getVarGroup().getGroupAssociation(), chkGroupName, true, editFilterVarGroup.getVarGroup() )){ return; } } editFilterVarGroup.getVarGroup().setName(chkGroupName); updateVariableByGroup(editFilterVarGroup); resetDVMappingsByGroup(editFilterVarGroup); loadFilterGroupings(); editFilterVarGroup = null; getInputFilterGroupName().setValue(""); dataTableFilterGrouping.getChildren().clear(); cancelAddEdit(); } private void updateVariableByGroup(VarGroupUI varGroupUIin){ if (varGroupUIin.getDataVariablesSelected() != null){ varGroupUIin.getDataVariablesSelected().clear(); } else { varGroupUIin.setDataVariablesSelected(new ArrayList()); } for(DataVariableUI dataVariableUI:dvGenericListUI){ for(DataVariableUI dvTest: dvGenericFilteredListUI){ if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())){ dataVariableUI.setSelected(dvTest.isSelected()); } } } int countSelected = 0; for (DataVariableUI dataVariableUI: dvGenericListUI){ if (dataVariableUI.isSelected()){ varGroupUIin.getDataVariablesSelected().add(dataVariableUI.getDataVariable().getId()); countSelected++; } } if (varGroupUIin.getVarGroupTypesSelectItems() != null) { varGroupUIin.getVarGroupTypesSelectItems().clear(); } else { varGroupUIin.setVarGroupTypesSelectItems(new ArrayList()); } for (VarGroupTypeUI varGroupTypeUI: varGroupUIin.getVarGroupTypes()){ if (varGroupTypeUI.isSelected()){ varGroupUIin.getVarGroupTypesSelectItems().add(varGroupTypeUI); } } varGroupUIin.setNumberOfVariablesSelected(new Long(countSelected)); VarGroup varGroup = varGroupUIin.getVarGroup(); varGroup.getGroupTypes().clear(); String groupTypesSelectedString = ""; for (VarGroupTypeUI vgtUI: varGroupUIin.getVarGroupTypesSelectItems()){ varGroup.getGroupTypes().add(vgtUI.getVarGroupType()); if (groupTypesSelectedString.isEmpty()){ groupTypesSelectedString+=vgtUI.getVarGroupType().getName(); } else { groupTypesSelectedString = groupTypesSelectedString + ", " + vgtUI.getVarGroupType().getName(); } } varGroupUIin.setGroupTypesSelectedString(groupTypesSelectedString); } public void saveFilterGrouping(){ String testString = (String) getInputFilterGroupingName().getValue(); boolean duplicates = false; if (!testString.isEmpty()){ List filterVarGroupings = new ArrayList(); for (VarGroupingUI varGroupingUI : filterGroupings){ filterVarGroupings.add(varGroupingUI.getVarGrouping()); } if (addFilterGrouping){ duplicates = visualizationService.checkForDuplicateGroupings(filterVarGroupings, testString, null ); } else { duplicates = visualizationService.checkForDuplicateGroupings(filterVarGroupings, testString, editFilterVarGrouping.getVarGrouping()); } if (duplicates) { FacesContext fc = FacesContext.getCurrentInstance(); String fullErrorMessage = "This name already exists. Please enter another. <br>" ; FacesMessage message = new FacesMessage(fullErrorMessage); fc.addMessage(validateButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); return; } if (addFilterGrouping) { addFilterGroupingSave(); cancelAddEdit(); } else { if (!getInputFilterGroupingName().getValue().equals("")) { editFilterVarGrouping.getVarGrouping().setName(testString); } cancelAddEdit(); } } else { FacesMessage message = new FacesMessage("Please Enter a Filter Group Name"); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return; } } public void addMeasureGroup() { VarGroupUI newElem = new VarGroupUI(); newElem.setVarGroup(new VarGroup()); newElem.getVarGroup().setGroupAssociation(measureGrouping.getVarGrouping()); newElem.getVarGroup().setGroupTypes(new ArrayList()); newElem.setVarGroupTypes(new ArrayList()); List <VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) measureGrouping.getVarGroupTypesUI(); for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) { varGroupTypeUI.setSelected(false); newElem.getVarGroupTypes().add(varGroupTypeUI); } dvGenericListUI = dvNumericListUI; loadEmptyVariableList(); editMeasureVarGroup = newElem; cancelAddEdit(); editMeasure = true; addMeasureGroup = true; } private void addMeasureGroupSave() { int i = measureGrouping.getVarGrouping().getVarGroups().size(); measureGrouping.getVarGrouping().getVarGroups().add(i, editMeasureVarGroup.getVarGroup()); measureGrouping.getVarGroupUI().add(editMeasureVarGroup); cancelAddEdit(); editMeasure = false; addMeasureGroup = false; } private void loadEmptyVariableList(){ Iterator iterator = dvGenericListUI.iterator(); dvGenericFilteredListUI.clear(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); dataVariableUI.setSelected(false); dvGenericFilteredListUI.add(dataVariableUI); } } private void addFilterGroupSave() { for(VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping().equals(editFilterVarGroup.getVarGroup().getGroupAssociation())){ varGroupingUI.getVarGroupUI().add(editFilterVarGroup); varGroupingUI.getVarGrouping().getVarGroups().add( editFilterVarGroup.getVarGroup()); } } //dataTableFilterGrouping.setValue(filterGroupings); dataTableFilterGrouping.getChildren().clear(); cancelAddEdit(); } public void addFilterGroupAction(ActionEvent ae) { UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } VarGroupingUI varGroupingUI = (VarGroupingUI) dataTableFilterGrouping.getRowData(); VarGroupUI newElem = new VarGroupUI(); newElem.setVarGroup(new VarGroup()); newElem.getVarGroup().setGroupTypes(new ArrayList()); newElem.getVarGroup().setGroupAssociation(varGroupingUI.getVarGrouping()); loadEmptyVariableList(); newElem.setVarGroupTypes(new ArrayList()); List <VarGroupTypeUI> allVarGroupTypes = (List<VarGroupTypeUI>) varGroupingUI.getVarGroupTypesUI(); for (VarGroupTypeUI varGroupTypeUI : allVarGroupTypes) { varGroupTypeUI.setSelected(false); newElem.getVarGroupTypes().add(varGroupTypeUI); } editFilterVarGroup = newElem; dvGenericListUI = dvNumericListUI; loadEmptyVariableList(); cancelAddEdit(); editFilterGroup = true; addFilterGroup = true; } public void addMeasureTypeButton(){ addMeasureType = true; } public void addFilterTypeButton(){ addFilterType = true; } public void saveMeasureTypeButton(){ boolean groupEdit = false; VarGroupType newElem = new VarGroupType(); if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null ) { groupEdit = true; } newElem.setVarGrouping(measureGrouping.getVarGrouping()); newElem.setName((String)getInputMeasureGroupTypeName().getValue()); if (newElem.getName().isEmpty()){ newElem.setName((String)getInputManageMeasureGroupTypeName().getValue()); } VarGrouping varGroupingTest = new VarGrouping(); if (editMeasureVarGroup != null && editMeasureVarGroup.getVarGroup() != null ) { newElem.setVarGrouping(editMeasureVarGroup.getVarGroup().getGroupAssociation()); varGroupingTest = editMeasureVarGroup.getVarGroup().getGroupAssociation(); groupEdit = true; } else { newElem.setVarGrouping(measureGrouping.getVarGrouping()); varGroupingTest = measureGrouping.getVarGrouping(); } if (checkForDuplicateEntries(varGroupingTest, newElem.getName(), false, null )){ return; } measureGrouping.getVarGrouping().getVarGroupTypes().add(newElem); VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(newElem); if (measureGrouping.getVarGroupTypesUI() == null){ measureGrouping.setVarGroupTypesUI(new ArrayList()); } measureGrouping.getVarGroupTypesUI().add(varGroupTypeUI); if (groupEdit){ addNewTypeToGroupUI(editMeasureVarGroup, varGroupTypeUI); } addMeasureType = false; } private boolean checkForDuplicateEntries(VarGrouping varGrouping, String name, boolean group, Object testObject){ boolean duplicates = visualizationService.checkForDuplicateEntries(varGrouping, name, group, testObject); if (duplicates) { FacesContext fc = FacesContext.getCurrentInstance(); String fullErrorMessage = "This name already exists. Please enter another. <br>" ; FacesMessage message = new FacesMessage(fullErrorMessage); fc.addMessage(validateButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } return duplicates; } public void saveFilterTypeButton(){ boolean groupEdit = false; VarGroupType newElem = new VarGroupType(); VarGrouping varGroupingTest = new VarGrouping(); if (editFilterVarGroup != null && editFilterVarGroup.getVarGroup() != null ) { newElem.setVarGrouping(editFilterVarGroup.getVarGroup().getGroupAssociation()); varGroupingTest = editFilterVarGroup.getVarGroup().getGroupAssociation(); groupEdit = true; } else { newElem.setVarGrouping(editFilterVarGrouping.getVarGrouping()); varGroupingTest = editFilterVarGrouping.getVarGrouping(); } newElem.setName((String)getInputFilterGroupTypeName().getValue()); if (newElem.getName().isEmpty()){ newElem.setName((String)getInputManageFilterGroupTypeName().getValue()); } if (checkForDuplicateEntries(varGroupingTest, newElem.getName(), false, null )){ return; } for(VarGrouping varGrouping: varGroupings){ if (varGrouping == newElem.getVarGrouping()){ varGrouping.getVarGroupTypes().add(newElem); } } VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(newElem); for(VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping() == newElem.getVarGrouping()){ varGroupingUI.getVarGroupTypesUI().add(varGroupTypeUI); dataTableManageFilterGroupType.setValue(varGroupingUI.getVarGroupTypesUI()); } } if (groupEdit){ addNewTypeToGroupUI(editFilterVarGroup, varGroupTypeUI); dataTableFilterGroupType.setValue(editFilterVarGroup.getVarGroupTypes()); } loadFilterGroupings(); dataTableFilterGrouping.getChildren().clear(); addFilterType = false; } private void addNewTypeToGroupUI(VarGroupUI varGroupUI, VarGroupTypeUI varGroupTypeUI ){ varGroupUI.getVarGroupTypes().add(varGroupTypeUI); } private void removeTypeFromGroupUI(VarGroupUI varGroupUI, VarGroupTypeUI varGroupTypeUI ){ varGroupUI.getVarGroupTypes().remove(varGroupTypeUI); } public void cancelMeasureTypeButton(){ addMeasureType = false; manageMeasureTypes = true; } public void cancelFilterTypeButton(){ addFilterType = false; manageFilterTypes = true; } public void addMeasureGroupType() { cancelAddEdit(); VarGroupType newElem = new VarGroupType(); newElem.setVarGrouping(measureGrouping.getVarGrouping()); measureGrouping.getVarGrouping().getVarGroupTypes().add(newElem); VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(newElem); varGroupTypeUI.setEditMode(true); if (measureGrouping.getVarGroupTypesUI() == null){ measureGrouping.setVarGroupTypesUI(new ArrayList()); } measureGrouping.getVarGroupTypesUI().add(varGroupTypeUI); } public void addFilterGroupType(ActionEvent ae) { VarGroupType newElem = new VarGroupType(); UIComponent uiComponent = ae.getComponent().getParent(); while (!(uiComponent instanceof HtmlDataTable)){ uiComponent = uiComponent.getParent(); } VarGroupingUI varGroupingUI = (VarGroupingUI) dataTableFilterGrouping.getRowData(); for(VarGrouping varGrouping: varGroupings){ if (varGrouping == varGroupingUI.getVarGrouping()){ newElem.setVarGrouping(varGrouping); varGrouping.getVarGroupTypes().add(newElem); } } for(VarGroupingUI varGroupingUIList: filterGroupings){ if (varGroupingUIList.getVarGrouping() == newElem.getVarGrouping()){ VarGroupTypeUI varGroupTypeUI = new VarGroupTypeUI(); varGroupTypeUI.setVarGroupType(newElem); varGroupTypeUI.setEditMode(true); varGroupingUI.getVarGroupTypesUI().add(varGroupTypeUI); varGroupingUI.setVarGroupTypesUI(varGroupingUI); } } } private void addMeasureGrouping() { VarGrouping varGrouping = new VarGrouping(); varGrouping.setGroupingType(GroupingType.MEASURE); varGrouping.setDataTable(dataTable); varGrouping.setDataVariableMappings(new ArrayList()); varGrouping.setGroups(new ArrayList()); varGrouping.setVarGroupTypes(new ArrayList()); measureGrouping.setVarGrouping(varGrouping); measureGrouping.setSelectedGroupId(new Long(0)); measureGrouping.setVarGroupTypesUI(new ArrayList()); measureGrouping.setVarGroupUI(new ArrayList()); loadSelectMeasureGroupTypes(); dataTable.getVarGroupings().add(varGrouping); measureGrouping.setVarGrouping(varGrouping); } public void addFilterGroupingAction() { cancelAddEdit(); VarGrouping newElem = new VarGrouping(); newElem.setDataTable(dataTable); addFilterGrouping = true; editFilterGrouping = true; } private void addFilterGroupingSave(){ VarGrouping varGrouping = new VarGrouping(); varGrouping.setGroupingType(GroupingType.FILTER); varGrouping.setDataTable(dataTable); varGrouping.setDataVariableMappings(new ArrayList()); varGrouping.setGroups(new ArrayList()); varGrouping.setVarGroupTypes(new ArrayList()); dataTable.getVarGroupings().add(varGrouping); loadFilterGroupings(); VarGroupingUI varGroupingUI = new VarGroupingUI(); varGroupingUI.setVarGrouping(varGrouping); editFilterVarGrouping = varGroupingUI; editFilterVarGrouping.getVarGrouping().setName((String) getInputFilterGroupingName().getValue()); } public void deleteFilterGroup(ActionEvent ae){ HtmlDataTable dataTable2 = dataTableFilterGroup; if (dataTable2.getRowCount()>0) { VarGroupUI varGroupUI2 = (VarGroupUI) dataTable2.getRowData(); VarGroup varGroup = varGroupUI2.getVarGroup(); deleteVariablesFromGroup(varGroupUI2); List varGroupList = (List) dataTable2.getValue(); Iterator iterator = varGroupList.iterator(); List deleteList = new ArrayList(); while (iterator.hasNext() ){ VarGroupUI varGroupUI = (VarGroupUI) iterator.next(); VarGroup data = varGroupUI.getVarGroup(); deleteList.add(data); } visualizationService.removeCollectionElement(deleteList,dataTable2.getRowIndex()); for(VarGroupingUI varGroupingUI: filterGroupings){ if (varGroupingUI.getVarGrouping() == (varGroup.getGroupAssociation())){ varGroupingUI.getVarGroupUI().remove(varGroupUI2); varGroupingUI.getVarGrouping().getVarGroups().remove(varGroup); setVarGroupUI(varGroupingUI); dataTableFilterGroup.setValue(varGroupingUI.getVarGroupUI()); } } } loadFilterGroupings(); forceRender(); } public void deleteMeasureGroup(){ HtmlDataTable dataTable2 = dataTableVarGroup; if (dataTable2.getRowCount()>0) { VarGroupUI varGroupUI2 = (VarGroupUI) dataTable2.getRowData(); deleteVariablesFromGroup(varGroupUI2); VarGroup varGroup = varGroupUI2.getVarGroup(); List varGroupList = (List) dataTable2.getValue(); Iterator iterator = varGroupList.iterator(); List deleteList = new ArrayList(); while (iterator.hasNext() ){ VarGroupUI varGroupUI = (VarGroupUI) iterator.next(); VarGroup data = varGroupUI.getVarGroup(); deleteList.add(data); } visualizationService.removeCollectionElement(deleteList,dataTable2.getRowIndex()); measureGrouping.getVarGroupUI().remove(varGroupUI2); measureGrouping.getVarGrouping().getVarGroups().remove(varGroup); } } public void deleteFilterGrouping(ActionEvent ae){ HtmlDataTable dataTable2 = dataTableFilterGrouping; VarGroupingUI varGroupingUI2 = (VarGroupingUI) dataTable2.getRowData(); if (dataTable2.getRowCount()>0) { filterGroupings.remove(varGroupingUI2); varGroupings.remove(varGroupingUI2.getVarGrouping()); } visualizationService.removeCollectionElement(varGroupings,varGroupingUI2.getVarGrouping()); loadFilterGroupings(); for(VarGroupingUI varGroupingUI: filterGroupings){ dataTableFilterGroup.setValue(varGroupingUI.getVarGroupUI()); } } public String cancel(){ visualizationService.cancel(); getVDCRequestBean().setStudyId(study.getId()); if ( studyVersion.getId() == null ) { getVDCRequestBean().setStudyVersionNumber(study.getReleasedVersion().getVersionNumber()); } else { getVDCRequestBean().setStudyVersionNumber(studyVersion.getVersionNumber()); } getVDCRequestBean().setSelectedTab("files"); return "viewStudy"; } private void cancelAddEdit(){ getInputFilterGroupName().setValue(""); getInputFilterGroupTypeName().setValue(""); getInputFilterGroupingName().setValue(""); getInputMeasureGroupTypeName().setValue(""); getInputMeasureName().setValue(""); getInputMeasureGroupingName().setValue(""); getInputMeasureUnits().setValue(""); getInputVariableFilter().setValue(""); getInputVariableMeasure().setValue(""); getInputVariableGeneric().setValue(""); getMeasureCheckBox().setValue(false); getFilterCheckBox().setValue(false); editXAxis = false; editMeasure = false; editFilterGroup = false; editMeasureGrouping = false; addMeasureType = false; addFilterType = false; addMeasureGroup = false; addFilterGroup = false; addFilterGrouping = false; editMeasureType = false; editFilterType = false; editFilterGrouping = false; manageFilterTypes = false; manageMeasureTypes = false; } public boolean validateForRelease(boolean messages){ boolean valid = true; List <String> errorMessages = new ArrayList(); List fullListOfErrors = new ArrayList(); List returnListOfErrors = new ArrayList(); List duplicateVariables = new ArrayList(); String fullErrorMessage = ""; if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) { if (messages){ - fullErrorMessage += ("You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br>"); + fullErrorMessage += "You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br>"; } valid = false; } if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = "\r" + dataVariable.getName() + " requires at least one filter.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); - errorMessages.add("validateAtLeastOneFilterMapping."); } valid = false; } if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a filter but not to any measure.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); - errorMessages.add("validateOneMeasureMapping"); } valid = false; } if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) { if (messages){ - FacesMessage message = new FacesMessage("The Data Visualization must include at least one Measure.<br>"); - FacesContext fc = FacesContext.getCurrentInstance(); - errorMessages.add("validateAtLeastOneMeasureMapping"); - //fc.addMessage(validateButton.getClientId(fc), message); + String errorMessage = "The Data Visualization must include at least one Measure.<br>"; + fullErrorMessage += errorMessage; } valid = false; } duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors); if (duplicateVariables.size() > 0) { if (messages){ if (!duplicateVariables.isEmpty()){ int i = 0; for(Object dataVariableIn: duplicateVariables){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a non-unique measure and filter combination."; errorMessage += "(" + returnListOfErrors.get(i).toString() + ") <br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; i++; } } fullErrorMessage+= " Found non-unique groups for variables."; } returnListOfErrors.clear(); valid=false; } if (valid && messages){ FacesMessage message = new FacesMessage("The Data Visualization is valid for release."); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(releaseButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } if (!valid&& messages) { // add rounded corners to the validation message box FacesContext fc = FacesContext.getCurrentInstance(); fullErrorMessage = "This visualization is not valid for release. <br>" + fullErrorMessage; FacesMessage message = new FacesMessage(fullErrorMessage); fc.addMessage(validateButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } return valid; } public String validate(){ validateForRelease(true); return ""; } public String release(){ if (validateForRelease(true)) { dataTable.setVisualizationEnabled(true); saveAndExit(); return "viewStudy"; } return ""; } public String unRelease(){ dataTable.setVisualizationEnabled(false); saveAndExit(); return "viewStudy"; } public String saveAndExit(){ if (dataTable.isVisualizationEnabled()){ if (!validateForRelease(false)) { FacesMessage message = new FacesMessage("Your current changes are invalid. Correct these issues or unrelease your visualization before saving.<br>Click Validate button to get a full list of validation issues."); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(validateButton.getClientId(fc), message); return ""; } } save(); getVDCRequestBean().setStudyId(study.getId()); if ( studyVersion.getId() == null ) { getVDCRequestBean().setStudyVersionNumber(study.getReleasedVersion().getVersionNumber()); } else { getVDCRequestBean().setStudyVersionNumber(studyVersion.getVersionNumber()); } getVDCRequestBean().setSelectedTab("files"); return "viewStudy"; } private void resetDVMappingsByGroup(VarGroupUI varGroupUI){ deleteVariablesFromGroup(varGroupUI); List dataVariableIds = varGroupUI.getDataVariablesSelected(); if (!dataVariableIds.isEmpty()){ for(Object dataVariableId: dataVariableIds){ String id = dataVariableId.toString(); for(DataVariable dataVariable: dvList){ if (dataVariable.getId() !=null && dataVariable.getId().equals(new Long(id))){ DataVariableMapping dataVariableMapping = new DataVariableMapping(); dataVariableMapping.setDataTable(dataTable); dataVariableMapping.setDataVariable(dataVariable); dataVariableMapping.setGroup(varGroupUI.getVarGroup()); dataVariableMapping.setVarGrouping(varGroupUI.getVarGroup().getGroupAssociation()); dataVariableMapping.setX_axis(false); dataVariable.getDataVariableMappings().add(dataVariableMapping); for(VarGrouping varGrouping : varGroupings){ if (varGrouping.equals(varGroupUI.getVarGroup().getGroupAssociation())){ varGrouping.getDataVariableMappings().add(dataVariableMapping); } } } } } } } private void deleteVariablesFromGroup(VarGroupUI varGroupUI){ List <DataVariableMapping> removeList = new ArrayList(); List <DataVariable> tempList = new ArrayList(dvList); List <DataVariableMapping> groupingRemoveList = new ArrayList(); for(DataVariable dataVariable: tempList){ List <DataVariableMapping> deleteList = (List <DataVariableMapping>) dataVariable.getDataVariableMappings(); for (DataVariableMapping dataVariableMapping : deleteList ){ if (dataVariableMapping.getGroup() != null && dataVariableMapping.getGroup() == (varGroupUI.getVarGroup())) removeList.add(dataVariableMapping); } for (DataVariableMapping dataVariableMapping : deleteList ){ if (dataVariableMapping.getGroup() != null && dataVariableMapping.getGroup() == (varGroupUI.getVarGroup())) groupingRemoveList.add(dataVariableMapping); } } for(DataVariableMapping dataVarMappingRemove : removeList){ visualizationService.removeCollectionElement(dataVarMappingRemove.getDataVariable().getDataVariableMappings(),dataVarMappingRemove); } for(DataVariableMapping dataVarMappingRemove : groupingRemoveList){ visualizationService.removeCollectionElement(dataVarMappingRemove.getVarGrouping().getDataVariableMappings(),dataVarMappingRemove); } } private void resetDVMappingsXAxis(){ List <DataVariableMapping> removeList = new ArrayList(); List <DataVariable> tempList = new ArrayList(dvList); for(DataVariable dataVariable: tempList){ List <DataVariableMapping> deleteList = (List <DataVariableMapping>) dataVariable.getDataVariableMappings(); for (DataVariableMapping dataVariableMapping : deleteList ){ if (dataVariableMapping.getGroup() == null ) removeList.add(dataVariableMapping); } } for(DataVariableMapping dataVarMappingRemove : removeList){ visualizationService.removeCollectionElement(dataVarMappingRemove.getDataVariable().getDataVariableMappings(),dataVarMappingRemove); } if(xAxisVariableId != null && !xAxisVariableId.equals(new Long(0))){ for(DataVariable dataVariable: dvList){ if (dataVariable.getId() !=null && dataVariable.getId().equals(xAxisVariableId)){ DataVariableMapping dataVariableMapping = new DataVariableMapping(); dataVariableMapping.setDataTable(dataTable); dataVariableMapping.setDataVariable(dataVariable); dataVariableMapping.setGroup(null); dataVariableMapping.setVarGrouping(null); dataVariableMapping.setX_axis(true); dataVariableMapping.setLabel(xAxisUnits); dataVariable.getDataVariableMappings().add(dataVariableMapping); } } } } public String save() { visualizationService.saveAll(); return ""; } private HtmlInputText inputXAxisUnits; public HtmlInputText getInputXAxisUnits() { return this.inputXAxisUnits; } public void setInputXAxisUnits(HtmlInputText inputXAxisUnits) { this.inputXAxisUnits = inputXAxisUnits; } private HtmlInputText inputVariableGeneric; public HtmlInputText getInputVariableGeneric() { return this.inputVariableGeneric; } public void setInputVariableGeneric(HtmlInputText inputVariableGeneric) { this.inputVariableGeneric = inputVariableGeneric; } private HtmlInputText inputVariableFilter; public HtmlInputText getInputVariableFilter() { return this.inputVariableFilter; } public void setInputVariableFilter(HtmlInputText inputVariableFilter) { this.inputVariableFilter = inputVariableFilter; } private HtmlInputText inputVariableMeasure; public HtmlInputText getInputVariableMeasure() { return this.inputVariableMeasure; } public void setInputVariableMeasure(HtmlInputText inputVariableMeasure) { this.inputVariableMeasure = inputVariableMeasure; } private HtmlInputText inputMeasureName; public HtmlInputText getInputMeasureName() { return this.inputMeasureName; } public void setInputMeasureName(HtmlInputText inputMeasureName) { this.inputMeasureName = inputMeasureName; } private HtmlInputText inputMeasureUnits; public HtmlInputText getInputMeasureUnits() { return this.inputMeasureUnits; } public void setInputMeasureUnits(HtmlInputText inputMeasureUnits) { this.inputMeasureUnits = inputMeasureUnits; } private HtmlInputText inputGroupTypeName; public HtmlInputText getInputGroupTypeName() { return this.inputGroupTypeName; } public void setInputGroupTypeName(HtmlInputText inputGroupTypeName) { this.inputGroupTypeName = inputGroupTypeName; } private HtmlInputText inputFilterGroupTypeName; public HtmlInputText getInputFilterGroupTypeName() { return this.inputFilterGroupTypeName; } public void setInputFilterGroupTypeName(HtmlInputText inputFilterGroupTypeName) { this.inputFilterGroupTypeName = inputFilterGroupTypeName; } private HtmlInputText inputMeasureGroupTypeName; public HtmlInputText getInputMeasureGroupTypeName() { return this.inputMeasureGroupTypeName; } public void setInputMeasureGroupTypeName(HtmlInputText inputMeasureGroupTypeName) { this.inputMeasureGroupTypeName = inputMeasureGroupTypeName; } private HtmlInputText inputManageMeasureGroupTypeName; public HtmlInputText getInputManageMeasureGroupTypeName() { return this.inputManageMeasureGroupTypeName; } public void setInputManageMeasureGroupTypeName(HtmlInputText inputMeasureGroupTypeName) { this.inputManageMeasureGroupTypeName = inputMeasureGroupTypeName; } private HtmlInputText inputManageFilterGroupTypeName; public HtmlInputText getInputManageFilterGroupTypeName() { return this.inputManageFilterGroupTypeName; } public void setInputManageFilterGroupTypeName(HtmlInputText inputFilterGroupTypeName) { this.inputManageFilterGroupTypeName = inputFilterGroupTypeName; } private HtmlInputText inputMeasureGroupingName; public HtmlInputText getInputMeasureGroupingName() { return this.inputMeasureGroupingName; } public void setInputMeasureGroupingName(HtmlInputText inputMeasureGroupingName) { this.inputMeasureGroupingName = inputMeasureGroupingName; } private HtmlInputText editGroupTypeName; public HtmlInputText getEditGroupTypeName() { return this.editGroupTypeName; } public void setEditGroupTypeName(HtmlInputText editGroupTypeName) { this.editGroupTypeName = editGroupTypeName; } private HtmlInputText editFilterGroupTypeName; public HtmlInputText getEditFilterGroupTypeName() { return this.editFilterGroupTypeName; } public void setEditFilterGroupTypeName(HtmlInputText editFilterGroupTypeName) { this.editFilterGroupTypeName = editFilterGroupTypeName; } private HtmlInputText editMeasureGroupTypeName; public HtmlInputText getEditMeasureGroupTypeName() { return this.editMeasureGroupTypeName; } public void setEditMeasureGroupTypeName(HtmlInputText editMeasureGroupTypeName) { this.editMeasureGroupTypeName = editMeasureGroupTypeName; } private HtmlInputText editManageFilterGroupTypeName; public HtmlInputText getEditManageFilterGroupTypeName() { return this.editManageFilterGroupTypeName; } public void setEditManageFilterGroupTypeName(HtmlInputText editManageFilterGroupTypeName) { this.editManageFilterGroupTypeName = editManageFilterGroupTypeName; } private HtmlInputText editManageMeasureGroupTypeName; public HtmlInputText getEditManageMeasureGroupTypeName() { return this.editManageMeasureGroupTypeName; } public void setEditManageMeasureGroupTypeName(HtmlInputText editManageMeasureGroupTypeName) { this.editManageMeasureGroupTypeName = editManageMeasureGroupTypeName; } public List<SelectItem> loadStudyFileSelectItems(){ List selectItems = new ArrayList<SelectItem>(); selectItems.add(new SelectItem(0, "Select a File")); Iterator iterator = study.getStudyFiles().iterator(); while (iterator.hasNext() ){ StudyFile studyFile = (StudyFile) iterator.next(); if (studyFile.isSubsettable()){ selectItems.add(new SelectItem(studyFile.getId(), studyFile.getFileName())); } } return selectItems; } public void updateGenericGroupVariableList (String checkString){ for(DataVariableUI dataVariableUI:dvGenericListUI){ for(DataVariableUI dvTest: dvGenericFilteredListUI){ if (dvTest.getDataVariable().equals(dataVariableUI.getDataVariable())){ dataVariableUI.setSelected(dvTest.isSelected()); } } } dvGenericFilteredListUI.clear(); for(DataVariableUI dataVariableUI:dvGenericListUI){ dataVariableUI.setDisplay(false); if (dataVariableUI.getDataVariable().getName().contains(checkString)) { dataVariableUI.setDisplay(true); DataVariableUI dvAdd = new DataVariableUI(); dvAdd.setDataVariable(dataVariableUI.getDataVariable()); dvAdd.setSelected(dataVariableUI.isSelected()); dvAdd.setDisplay(true); dvGenericFilteredListUI.add(dvAdd); } } } public String updateMeasureList(){ String checkString = (String) getInputVariableMeasure().getValue(); updateGenericGroupVariableList(checkString); selectOneMeasureVariableClick(); return ""; } public String updateFilterList(){ String checkString = (String) getInputVariableFilter().getValue(); updateGenericGroupVariableList(checkString); selectOneFilterVariableClick(); return ""; } public String updateXAxisList(){ String checkString = (String) getInputVariableGeneric().getValue(); updateGenericGroupVariableList(checkString); return ""; } public void selectAllMeasureVariables(ValueChangeEvent ce){ selectAllVariablesPrivate((Boolean)measureCheckBox.getValue()); forceRender(ce); } public void selectAllFilterVariables(ValueChangeEvent ce){ selectAllVariablesPrivate((Boolean)filterCheckBox.getValue()); forceRender(ce); } public void selectAllFilterVariablesClick(){ boolean value = (Boolean)filterCheckBox.getValue(); selectAllVariablesPrivate(value); } public void selectAllMeasureVariablesClick(){ boolean value = (Boolean)measureCheckBox.getValue(); selectAllVariablesPrivate(value); } public void selectOneFilterVariableClick(){ boolean setSelected = checkSelectAllVariablesPrivate(); filterCheckBox.setSelected(setSelected) ; } public void selectOneMeasureVariableClick(){ boolean setSelected = checkSelectAllVariablesPrivate(); measureCheckBox.setSelected(setSelected) ; } private void selectAllVariablesPrivate(boolean check){ Iterator iterator = dvGenericFilteredListUI.iterator(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); if (dataVariableUI.isDisplay()){ dataVariableUI.setSelected(check); } } } public void checkSelectAllFilterVariables(ValueChangeEvent ce){ boolean setSelected = checkSelectAllVariablesPrivate(); filterCheckBox.setSelected(setSelected) ; forceRender(ce); } private boolean checkSelectAllVariablesPrivate(){ boolean allSelected = true; Iterator iterator = dvGenericFilteredListUI.iterator(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); if (!dataVariableUI.isSelected()){ allSelected = false; } } return allSelected; } private void forceRender(ValueChangeEvent ce){ PhaseId phase = ce.getPhaseId(); if (phase.equals(PhaseId.INVOKE_APPLICATION)) { FacesContext.getCurrentInstance().renderResponse(); } else { ce.setPhaseId(PhaseId.INVOKE_APPLICATION); ce.queue(); } } private void forceRender(){ FacesContext.getCurrentInstance().renderResponse(); } public void selectAllMeasureButton(){ Iterator iterator = dvGenericFilteredListUI.iterator(); boolean selectMeasureVariables = (Boolean)measureCheckBox.getValue(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); dataVariableUI.setSelected(selectMeasureVariables); } } private HtmlDataTable dataTableVarGroup; public HtmlDataTable getDataTableVarGroup() { return this.dataTableVarGroup; } public void setDataTableVarGroup(HtmlDataTable dataTableVarGroup) { this.dataTableVarGroup = dataTableVarGroup; } private HtmlDataTable dataTableXAxis; public HtmlDataTable getDataTableXAxis() { return this.dataTableXAxis; } public void setDataTableXAxis(HtmlDataTable dataTableXAxis) { this.dataTableXAxis = dataTableXAxis; } private HtmlDataTable dataTableFilterGroup; public HtmlDataTable getDataTableFilterGroup() { return this.dataTableFilterGroup; } public void setDataTableFilterGroup(HtmlDataTable dataTableFilterGroup) { this.dataTableFilterGroup = dataTableFilterGroup; } private HtmlDataTable dataTableFilterGrouping; public HtmlDataTable getDataTableFilterGrouping() { return this.dataTableFilterGrouping; } public void setDataTableFilterGrouping(HtmlDataTable dataTableFilterGrouping) { this.dataTableFilterGrouping = dataTableFilterGrouping; } /** * Holds value of property dataTableVarGroup. */ private HtmlDataTable dataTableVarGroupType; /** * Getter for property dataTableVarGroup. * @return Value of property dataTableVarGroup. */ public HtmlDataTable getDataTableVarGroupType() { return this.dataTableVarGroupType; } public void setDataTableVarGroupType(HtmlDataTable dataTableVarGroupType) { this.dataTableVarGroupType = dataTableVarGroupType; } private HtmlDataTable dataTableFilterGroupType; public HtmlDataTable getDataTableFilterGroupType() { return this.dataTableFilterGroupType; } public void setDataTableFilterGroupType(HtmlDataTable dataTableFilterGroupType) { this.dataTableFilterGroupType = dataTableFilterGroupType; } private HtmlDataTable dataTableManageFilterGroupType; public HtmlDataTable getDataTableManageFilterGroupType() { return this.dataTableManageFilterGroupType; } public void setDataTableManageFilterGroupType(HtmlDataTable dataTableManageFilterGroupType) { this.dataTableManageFilterGroupType = dataTableManageFilterGroupType; } private HtmlDataTable dataTableManageMeasureGroupType; public HtmlDataTable getDataTableManageMeasureGroupType() { return this.dataTableManageMeasureGroupType; } public void setDataTableManageMeasureGroupType(HtmlDataTable dataTableManageMeasureGroupType) { this.dataTableManageMeasureGroupType = dataTableManageMeasureGroupType; } private HtmlDataTable dataTableMeasureGroupType; public HtmlDataTable getDataTableMeasureGroupType() { return this.dataTableMeasureGroupType; } public void setDataTableMeasureGroupType(HtmlDataTable dataTableMeasureGroupType) { this.dataTableMeasureGroupType = dataTableMeasureGroupType; } public List<VarGroupingUI> getFilterGroupings() { return filterGroupings; } public void setFilterGroupings(List<VarGroupingUI> filterGroupings) { this.filterGroupings = filterGroupings; } private HtmlInputText inputFilterGroupingName; public HtmlInputText getInputFilterGroupingName() { return this.inputFilterGroupingName; } public void setInputFilterGroupingName(HtmlInputText inputFilterGroupingName) { this.inputFilterGroupingName = inputFilterGroupingName; } private HtmlDataTable dataTableFilterGroups; public HtmlDataTable getDataTableFilterGroups() { return dataTableFilterGroups; } public void setDataTableFilterGroups(HtmlDataTable dataTableFilterGroups) { this.dataTableFilterGroups = dataTableFilterGroups; } private HtmlInputText inputFilterGroupName; public HtmlInputText getInputFilterGroupName() { return this.inputFilterGroupName; } public void setInputFilterGroupName(HtmlInputText inputFilterGroupName) { this.inputFilterGroupName = inputFilterGroupName; } private HtmlCommandLink addFilterGroupLink; public HtmlCommandLink getAddFilterGroupLink() { return this.addFilterGroupLink; } public void setAddFilterGroupLink(HtmlCommandLink addFilterGroupLink) { this.addFilterGroupLink = addFilterGroupLink; } private HtmlCommandLink addFilterGroupTypeLink; public HtmlCommandLink getAddFilterGroupTypeLink() { return this.addFilterGroupTypeLink; } public void setAddFilterGroupTypeLink(HtmlCommandLink addFilterGroupTypeLink) { this.addFilterGroupTypeLink = addFilterGroupTypeLink; } private HtmlCommandLink addSecondFilterGroupTypeLink; public HtmlCommandLink getAddSecondFilterGroupTypeLink() { return this.addSecondFilterGroupTypeLink; } public void setAddSecondFilterGroupTypeLink(HtmlCommandLink addFilterGroupTypeLink) { this.addSecondFilterGroupTypeLink = addFilterGroupTypeLink; } private HtmlCommandLink deleteFilterGroupLink; public HtmlCommandLink getDeleteFilterGroupLink() { return this.deleteFilterGroupLink; } public void setDeleteFilterGroupLink(HtmlCommandLink deleteFilterGroupLink) { this.deleteFilterGroupLink = deleteFilterGroupLink; } public DataVariable getxAxisVariable() { return xAxisVariable; } public void setxAxisVariable(DataVariable xAxisVariable) { this.xAxisVariable = xAxisVariable; } public Study getStudy() { return study; } public void setStudy(Study study) { this.study = study; } public Long getStudyFileId() { return studyFileId; } public void setStudyFileId(Long studyFileId) { this.studyFileId = studyFileId; } private List files; public List getFiles() { return files; } public void setFiles(List files) { this.files = files; } public List<SelectItem> getStudyFileIdSelectItems() { return studyFileIdSelectItems; } public void setStudyFileIdSelectItems(List<SelectItem> studyFileIdSelectItems) { this.studyFileIdSelectItems = studyFileIdSelectItems; } public Long getStudyId() { return studyId; } public void setStudyId(Long studyId) { this.studyId = studyId; } public Long getxAxisVariableId() { return xAxisVariableId; } public void setxAxisVariableId(Long xAxisVariableId) { this.xAxisVariableId = xAxisVariableId; } HtmlSelectOneMenu selectStudyFile; public HtmlSelectOneMenu getSelectStudyFile() { return selectStudyFile; } public void setSelectStudyFile(HtmlSelectOneMenu selectStudyFile) { this.selectStudyFile = selectStudyFile; } public DataTable getDataTable() { return dataTable; } public void setDataTable(DataTable dataTable) { this.dataTable = dataTable; } private HtmlCommandButton validateButton = new HtmlCommandButton(); private HtmlCommandButton releaseButton = new HtmlCommandButton(); public HtmlCommandButton getValidateButton() { return validateButton; } public void setValidateButton(HtmlCommandButton hit) { this.validateButton = hit; } public HtmlCommandButton getReleaseButton() { return releaseButton; } public void setReleaseButton(HtmlCommandButton releaseButton) { this.releaseButton = releaseButton; } public boolean isShowCommands() { return showCommands; } public void setShowCommands(boolean showCommands) { this.showCommands = showCommands; } public boolean isSelectFile() { return selectFile; } public void setSelectFile(boolean selectFile) { this.selectFile = selectFile; } public List<DataVariable> getDvList() { return dvList; } public void setDvList(List<DataVariable> dvList) { this.dvList = dvList; } public String getxAxisUnits() { return xAxisUnits; } public void setxAxisUnits(String xAxisUnits) { this.xAxisUnits = xAxisUnits; } public List<DataVariable> getDvFilteredList() { if (getInputVariableFilter() == null) return dvList; if (getInputVariableFilter().getValue() == null) return dvList; if (getInputVariableFilter().getValue().equals("")) return dvList; return dvFilteredList; } public void setDvFilteredList(List<DataVariable> dvFilteredList) { this.dvFilteredList = dvFilteredList; } public List<DataVariableUI> getDvGenericListUI() { return dvGenericListUI; } public boolean isShowFilterVariables() { return showFilterVariables; } public void setShowFilterVariables(boolean showFilterVariables) { this.showFilterVariables = showFilterVariables; } public boolean isShowMeasureVariables() { return showMeasureVariables; } public void setShowMeasureVariables(boolean showMeasureVariables) { this.showMeasureVariables = showMeasureVariables; } public boolean isEditXAxis() { return editXAxis; } public void setEditXAxis(boolean editXAxis) { this.editXAxis = editXAxis; } public void setDvGenericFilteredListUI(List<DataVariableUI> dvGenericFilteredListUI) { this.dvGenericFilteredListUI = dvGenericFilteredListUI; } public List<DataVariableUI> getDvGenericFilteredListUI() { List <DataVariableUI> returnList = new ArrayList(); Iterator iterator = dvGenericListUI.iterator(); iterator = dvGenericListUI.iterator(); while (iterator.hasNext() ){ DataVariableUI dataVariableUI = (DataVariableUI) iterator.next(); if (dataVariableUI.isDisplay()){ DataVariableUI dvAdd = new DataVariableUI(); dvAdd.setDataVariable(dataVariableUI.getDataVariable()); dvAdd.setSelected(dataVariableUI.isSelected()); dvAdd.setDisplay(true); returnList.add(dvAdd); } } return dvGenericFilteredListUI; //return returnList; } public VarGroupUI getEditFragmentVarGroup() { return editFragmentVarGroup; } public void setEditFragmentVarGroup(VarGroupUI editFragmentVarGroup) { this.editFragmentVarGroup = editFragmentVarGroup; } public boolean isEditFilterGroup() { return editFilterGroup; } public void setEditFilter(boolean editFilterGroup) { this.editFilterGroup = editFilterGroup; } public boolean isEditMeasure() { return editMeasure; } public void setEditMeasure(boolean editMeasure) { this.editMeasure = editMeasure; } public VarGroupUI getEditFilterVarGroup() { return editFilterVarGroup; } public void setEditFilterVarGroup(VarGroupUI editFilterVarGroup) { this.editFilterVarGroup = editFilterVarGroup; } public VarGroupUI getEditMeasureVarGroup() { return editMeasureVarGroup; } public void setEditMeasureVarGroup(VarGroupUI editMeasureVarGroup) { this.editMeasureVarGroup = editMeasureVarGroup; } public boolean isxAxisSet() { return xAxisSet; } public boolean isAddFilterType() { return addFilterType; } public void setAddFilterType(boolean addFilterType) { this.addFilterType = addFilterType; } public boolean isAddMeasureType() { return addMeasureType; } public void setAddMeasureType(boolean addMeasureType) { this.addMeasureType = addMeasureType; } public boolean isHasFilterGroupings() { return hasFilterGroupings; } public void setHasFilterGroupings(boolean hasFilterGroupings) { this.hasFilterGroupings = hasFilterGroupings; } public boolean isHasFilterGroups() { return hasFilterGroups; } public void setHasFilterGroups(boolean hasFilterGroups) { this.hasFilterGroups = hasFilterGroups; } public boolean isHasMeasureGroups() { return hasMeasureGroups; } public void setHasMeasureGroups(boolean hasMeasureGroups) { this.hasMeasureGroups = hasMeasureGroups; } public boolean isEditMeasureType() { return editMeasureType; } public void setEditMeasureType(boolean editMeasureType) { this.editMeasureType = editMeasureType; } public boolean isEditFilterType() { return editFilterType; } public void setEditFilterType(boolean editFilterType) { this.editFilterType = editFilterType; } public boolean isEditFilterGrouping() { return editFilterGrouping; } public void setEditFilterGrouping(boolean editFilterGrouping) { this.editFilterGrouping = editFilterGrouping; } public VarGroupingUI getEditFilterVarGrouping() { return editFilterVarGrouping; } public void setEditFilterVarGrouping(VarGroupingUI editFilterVarGrouping) { this.editFilterVarGrouping = editFilterVarGrouping; } public String getStudyFileName() { return studyFileName; } public void setStudyFileName(String studyFileName) { this.studyFileName = studyFileName; } public boolean isEditMeasureGrouping() { return editMeasureGrouping; } public boolean isManageMeasureTypes() { return manageMeasureTypes; } public boolean isAddFilterGroup() { return addFilterGroup; } public boolean isAddMeasureGroup() { return addMeasureGroup; } public boolean isAddFilterGrouping() { return addFilterGrouping; } public boolean isManageFilterTypes() { return manageFilterTypes; } private HtmlSelectBooleanCheckbox measureCheckBox; /** * @return the archiveCheckBox */ public HtmlSelectBooleanCheckbox getMeasureCheckBox() { return measureCheckBox; } /** * @param archiveCheckBox the archiveCheckBox to set */ public void setMeasureCheckBox(HtmlSelectBooleanCheckbox measureCheckBox) { this.measureCheckBox = measureCheckBox; } private HtmlSelectBooleanCheckbox filterCheckBox; /** * @return the archiveCheckBox */ public HtmlSelectBooleanCheckbox getFilterCheckBox() { return filterCheckBox; } /** * @param archiveCheckBox the archiveCheckBox to set */ public void setFilterCheckBox(HtmlSelectBooleanCheckbox filterCheckBox) { this.filterCheckBox = filterCheckBox; } public boolean isDisplayValidationFailure() { FacesContext fc = FacesContext.getCurrentInstance(); return fc.getMessages(validateButton.getClientId(fc)).hasNext(); } public boolean isDisplayValidationSuccess() { FacesContext fc = FacesContext.getCurrentInstance(); return fc.getMessages(releaseButton.getClientId(fc)).hasNext(); } public StudyUI getStudyUI() { return studyUI; } public void setStudyUI(StudyUI studyUI) { this.studyUI = studyUI; } }
false
true
public boolean validateForRelease(boolean messages){ boolean valid = true; List <String> errorMessages = new ArrayList(); List fullListOfErrors = new ArrayList(); List returnListOfErrors = new ArrayList(); List duplicateVariables = new ArrayList(); String fullErrorMessage = ""; if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) { if (messages){ fullErrorMessage += ("You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br>"); } valid = false; } if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = "\r" + dataVariable.getName() + " requires at least one filter.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); errorMessages.add("validateAtLeastOneFilterMapping."); } valid = false; } if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a filter but not to any measure.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); errorMessages.add("validateOneMeasureMapping"); } valid = false; } if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) { if (messages){ FacesMessage message = new FacesMessage("The Data Visualization must include at least one Measure.<br>"); FacesContext fc = FacesContext.getCurrentInstance(); errorMessages.add("validateAtLeastOneMeasureMapping"); //fc.addMessage(validateButton.getClientId(fc), message); } valid = false; } duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors); if (duplicateVariables.size() > 0) { if (messages){ if (!duplicateVariables.isEmpty()){ int i = 0; for(Object dataVariableIn: duplicateVariables){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a non-unique measure and filter combination."; errorMessage += "(" + returnListOfErrors.get(i).toString() + ") <br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; i++; } } fullErrorMessage+= " Found non-unique groups for variables."; } returnListOfErrors.clear(); valid=false; } if (valid && messages){ FacesMessage message = new FacesMessage("The Data Visualization is valid for release."); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(releaseButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } if (!valid&& messages) { // add rounded corners to the validation message box FacesContext fc = FacesContext.getCurrentInstance(); fullErrorMessage = "This visualization is not valid for release. <br>" + fullErrorMessage; FacesMessage message = new FacesMessage(fullErrorMessage); fc.addMessage(validateButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } return valid; }
public boolean validateForRelease(boolean messages){ boolean valid = true; List <String> errorMessages = new ArrayList(); List fullListOfErrors = new ArrayList(); List returnListOfErrors = new ArrayList(); List duplicateVariables = new ArrayList(); String fullErrorMessage = ""; if (!xAxisSet || !visualizationService.validateXAxisMapping(dataTable, xAxisVariableId)) { if (messages){ fullErrorMessage += "You must select one X-axis variable and it cannot be mapped to any Measure or Filter.<br>"; } valid = false; } if (!visualizationService.validateAtLeastOneFilterMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = "\r" + dataVariable.getName() + " requires at least one filter.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); } valid = false; } if (!visualizationService.validateMoreThanZeroMeasureMapping(dataTable, returnListOfErrors)) { if (messages){ if (!returnListOfErrors.isEmpty()){ for(Object dataVariableIn: returnListOfErrors){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a filter but not to any measure.<br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; } } returnListOfErrors.clear(); } valid = false; } if (!visualizationService.validateAtLeastOneMeasureMapping(dataTable)) { if (messages){ String errorMessage = "The Data Visualization must include at least one Measure.<br>"; fullErrorMessage += errorMessage; } valid = false; } duplicateVariables = visualizationService.getDuplicateMappings(dataTable, returnListOfErrors); if (duplicateVariables.size() > 0) { if (messages){ if (!duplicateVariables.isEmpty()){ int i = 0; for(Object dataVariableIn: duplicateVariables){ DataVariable dataVariable = (DataVariable) dataVariableIn; String errorMessage = dataVariable.getName() + " is mapped to a non-unique measure and filter combination."; errorMessage += "(" + returnListOfErrors.get(i).toString() + ") <br>"; fullListOfErrors.add(errorMessage); fullErrorMessage += errorMessage; i++; } } fullErrorMessage+= " Found non-unique groups for variables."; } returnListOfErrors.clear(); valid=false; } if (valid && messages){ FacesMessage message = new FacesMessage("The Data Visualization is valid for release."); FacesContext fc = FacesContext.getCurrentInstance(); fc.addMessage(releaseButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } if (!valid&& messages) { // add rounded corners to the validation message box FacesContext fc = FacesContext.getCurrentInstance(); fullErrorMessage = "This visualization is not valid for release. <br>" + fullErrorMessage; FacesMessage message = new FacesMessage(fullErrorMessage); fc.addMessage(validateButton.getClientId(fc), message); JavascriptContext.addJavascriptCall(fc, "jQuery(\"div.dvnMsgBlockRound\").corner(\"10px\");" ); } return valid; }
diff --git a/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/XBeanMojo.java b/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/XBeanMojo.java index 70f7a667..70472425 100644 --- a/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/XBeanMojo.java +++ b/maven-xbean-plugin/src/main/java/org/apache/xbean/maven/XBeanMojo.java @@ -1,199 +1,199 @@ /** * * Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable. * * 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.xbean.maven; import java.beans.PropertyEditorManager; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.tools.ant.BuildException; import org.apache.xbean.spring.generator.DocumentationGenerator; import org.apache.xbean.spring.generator.GeneratorPlugin; import org.apache.xbean.spring.generator.LogFacade; import org.apache.xbean.spring.generator.MappingLoader; import org.apache.xbean.spring.generator.NamespaceMapping; import org.apache.xbean.spring.generator.QdoxMappingLoader; import org.apache.xbean.spring.generator.WikiDocumentationGenerator; import org.apache.xbean.spring.generator.XmlMetadataGenerator; import org.apache.xbean.spring.generator.XsdGenerator; /** * @author <a href="[email protected]">Guillaume Nodet</a> * @version $Id: GenerateApplicationXmlMojo.java 314956 2005-10-12 16:27:15Z brett $ * @goal mapping * @description Creates xbean mapping file * @phase generate-sources */ public class XBeanMojo extends AbstractMojo implements LogFacade { /** * @parameter expression="${project}" * @required */ private MavenProject project; /** * Maven ProjectHelper * * @component */ protected MavenProjectHelper projectHelper; /** * @parameter * @required */ private String namespace; /** * @parameter expression="${basedir}/src/main/java" * @required */ private File srcDir; /** * @parameter */ private String excludedClasses; /** * @parameter expression="${basedir}/target/xbean/" * @required */ private File outputDir; /** * @parameter */ private File schema; /** * @parameter expression="org.apache.xbean.spring.context.impl" */ private String propertyEditorPaths; /** * @parameter schemaAsArtifact */ private boolean schemaAsArtifact = true; /** * A list of additional GeneratorPlugins that should get used executed * when generating output. * * @parameter */ private List generatorPlugins = Collections.EMPTY_LIST; public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug( " ======= XBeanMojo settings =======" ); getLog().debug( "namespace[" + namespace + "]" ); getLog().debug( "srcDir[" + srcDir + "]" ); getLog().debug( "schema[" + schema + "]" ); - getLog().debug( "excludedClasses" + excludedClasses ); + getLog().debug( "excludedClasses[" + excludedClasses + "]"); getLog().debug( "outputDir[" + outputDir + "]" ); getLog().debug( "propertyEditorPaths[" + propertyEditorPaths + "]" ); getLog().debug( "schemaAsArtifact[" + schemaAsArtifact + "]"); if (schema == null) { schema = new File(outputDir, project.getArtifactId() + ".xsd"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); editorSearchPath.addAll(Collections.list(paths)); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { schema.getParentFile().mkdirs(); String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } MappingLoader mappingLoader = new QdoxMappingLoader(namespace, new File[] { srcDir }, excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(outputDir.getAbsolutePath(), schema), new DocumentationGenerator(schema), new XsdGenerator(schema), new WikiDocumentationGenerator(schema), }; // load the mappings Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.setLog(this); plugin.generate(namespaceMapping); } for (Iterator iter = generatorPlugins.iterator(); iter.hasNext();) { GeneratorPlugin plugin = (GeneratorPlugin) iter.next(); plugin.setLog(this); plugin.generate(namespaceMapping); } } // Attach them as artifacts if (schemaAsArtifact) { projectHelper.attachArtifact(project, "xsd", null, schema); projectHelper.attachArtifact(project, "html", "schema", new File(schema.getAbsolutePath() + ".html")); } Resource res = new Resource(); res.setDirectory(outputDir.toString()); project.addResource(res); log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } public void log(String message) { getLog().info(message); } public void log(String message, int level) { getLog().info(message); } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug( " ======= XBeanMojo settings =======" ); getLog().debug( "namespace[" + namespace + "]" ); getLog().debug( "srcDir[" + srcDir + "]" ); getLog().debug( "schema[" + schema + "]" ); getLog().debug( "excludedClasses" + excludedClasses ); getLog().debug( "outputDir[" + outputDir + "]" ); getLog().debug( "propertyEditorPaths[" + propertyEditorPaths + "]" ); getLog().debug( "schemaAsArtifact[" + schemaAsArtifact + "]"); if (schema == null) { schema = new File(outputDir, project.getArtifactId() + ".xsd"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); editorSearchPath.addAll(Collections.list(paths)); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { schema.getParentFile().mkdirs(); String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } MappingLoader mappingLoader = new QdoxMappingLoader(namespace, new File[] { srcDir }, excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(outputDir.getAbsolutePath(), schema), new DocumentationGenerator(schema), new XsdGenerator(schema), new WikiDocumentationGenerator(schema), }; // load the mappings Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.setLog(this); plugin.generate(namespaceMapping); } for (Iterator iter = generatorPlugins.iterator(); iter.hasNext();) { GeneratorPlugin plugin = (GeneratorPlugin) iter.next(); plugin.setLog(this); plugin.generate(namespaceMapping); } } // Attach them as artifacts if (schemaAsArtifact) { projectHelper.attachArtifact(project, "xsd", null, schema); projectHelper.attachArtifact(project, "html", "schema", new File(schema.getAbsolutePath() + ".html")); } Resource res = new Resource(); res.setDirectory(outputDir.toString()); project.addResource(res); log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } }
public void execute() throws MojoExecutionException, MojoFailureException { getLog().debug( " ======= XBeanMojo settings =======" ); getLog().debug( "namespace[" + namespace + "]" ); getLog().debug( "srcDir[" + srcDir + "]" ); getLog().debug( "schema[" + schema + "]" ); getLog().debug( "excludedClasses[" + excludedClasses + "]"); getLog().debug( "outputDir[" + outputDir + "]" ); getLog().debug( "propertyEditorPaths[" + propertyEditorPaths + "]" ); getLog().debug( "schemaAsArtifact[" + schemaAsArtifact + "]"); if (schema == null) { schema = new File(outputDir, project.getArtifactId() + ".xsd"); } if (propertyEditorPaths != null) { List editorSearchPath = new LinkedList(Arrays.asList(PropertyEditorManager.getEditorSearchPath())); StringTokenizer paths = new StringTokenizer(propertyEditorPaths, " ,"); editorSearchPath.addAll(Collections.list(paths)); PropertyEditorManager.setEditorSearchPath((String[]) editorSearchPath.toArray(new String[editorSearchPath.size()])); } ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { schema.getParentFile().mkdirs(); String[] excludedClasses = null; if (this.excludedClasses != null) { excludedClasses = this.excludedClasses.split(" *, *"); } MappingLoader mappingLoader = new QdoxMappingLoader(namespace, new File[] { srcDir }, excludedClasses); GeneratorPlugin[] plugins = new GeneratorPlugin[]{ new XmlMetadataGenerator(outputDir.getAbsolutePath(), schema), new DocumentationGenerator(schema), new XsdGenerator(schema), new WikiDocumentationGenerator(schema), }; // load the mappings Set namespaces = mappingLoader.loadNamespaces(); if (namespaces.isEmpty()) { System.out.println("Warning: no namespaces found!"); } // generate the files for (Iterator iterator = namespaces.iterator(); iterator.hasNext();) { NamespaceMapping namespaceMapping = (NamespaceMapping) iterator.next(); for (int i = 0; i < plugins.length; i++) { GeneratorPlugin plugin = plugins[i]; plugin.setLog(this); plugin.generate(namespaceMapping); } for (Iterator iter = generatorPlugins.iterator(); iter.hasNext();) { GeneratorPlugin plugin = (GeneratorPlugin) iter.next(); plugin.setLog(this); plugin.generate(namespaceMapping); } } // Attach them as artifacts if (schemaAsArtifact) { projectHelper.attachArtifact(project, "xsd", null, schema); projectHelper.attachArtifact(project, "html", "schema", new File(schema.getAbsolutePath() + ".html")); } Resource res = new Resource(); res.setDirectory(outputDir.toString()); project.addResource(res); log("...done."); } catch (Exception e) { throw new BuildException(e); } finally { Thread.currentThread().setContextClassLoader(oldCL); } }
diff --git a/src/java-server-framework/org/xins/server/XSLTCallingConvention.java b/src/java-server-framework/org/xins/server/XSLTCallingConvention.java index c060df1bb..33078d962 100644 --- a/src/java-server-framework/org/xins/server/XSLTCallingConvention.java +++ b/src/java-server-framework/org/xins/server/XSLTCallingConvention.java @@ -1,347 +1,350 @@ /* * $Id$ * * Copyright 2003-2007 Orange Nederland Breedband B.V. * See the COPYRIGHT file for redistribution and use restrictions. */ package org.xins.server; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.xins.common.Utils; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.MissingRequiredPropertyException; import org.xins.common.collections.PropertyReader; import org.xins.common.manageable.InitializationException; import org.xins.common.text.TextUtils; import org.xins.logdoc.ExceptionUtils; /** * XSLT calling convention. * The XSLT calling convention input is the same as for the standard calling * convention. The XSLT calling convention output is the result of the XML * normally returned by the standard calling convention and the specified * XSLT. * The Mime type of the return data can be specified in the XSLT using the * media-type or method attribute of the XSL output element. * More information about the XSLT calling convention can be found in the * <a href="http://www.xins.org/docs/index.html">user guide</a>. * * @version $Revision$ $Date$ * @author <a href="mailto:[email protected]">Anthony Goubard</a> * @author <a href="mailto:[email protected]">Ernst de Haan</a> */ public class XSLTCallingConvention extends StandardCallingConvention { /** * The name of the runtime property that defines if the templates should be * cached. Should be either <code>"true"</code> or <code>"false"</code>. * By default the cache is enabled. */ protected static final String TEMPLATES_CACHE_PROPERTY = "templates.cache"; /** * The name of the runtime property that defines the prefix for the _template * parameter. * If this runtime property is not set or the value is empty, * the _template parameter is not allowed. */ protected static final String TEMPLATES_PARAMETER_PREFIX = "templates.parameter.prefix"; /** * The name of the input parameter that specifies the location of the XSLT * template to use. */ protected static final String TEMPLATE_PARAMETER = "_template"; /** * The name of the input parameter used to clear the template cache. */ protected static final String CLEAR_TEMPLATE_CACHE_PARAMETER = "_cleartemplatecache"; /** * The XSLT transformer. Never <code>null</code>. */ private final TransformerFactory _factory; /** * Flag that indicates whether the templates should be cached. This field * is set during initialization. */ private boolean _cacheTemplates; /** * The prefix to use for the _template parameter. * This field is set during initialization. * If the value is <code>null</code> the _template parameter is not allowed. */ private String _templatesPrefix; /** * Location of the XSLT templates. This field is initially * <code>null</code> and set during initialization. */ private String _location; /** * Cache for the XSLT templates. Never <code>null</code>. */ private Map _templateCache; /** * Constructs a new <code>XSLTCallingConvention</code> object. */ public XSLTCallingConvention() { // Create the transformer factory _factory = TransformerFactory.newInstance(); // Initialize the template cache _templateCache = new HashMap(89); } protected void initImpl(PropertyReader runtimeProperties) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { // Determine if the template cache should be enabled String cacheEnabled = runtimeProperties.get(TEMPLATES_CACHE_PROPERTY); initCacheEnabled(cacheEnabled); // Get the base directory of the style sheets. initXSLTLocation(runtimeProperties); // Determine whether template location can be passed as parameter String templatesPrefix = runtimeProperties.get(TEMPLATES_PARAMETER_PREFIX); if (TextUtils.isEmpty(templatesPrefix) || templatesPrefix.trim().equals("")) { _templatesPrefix = null; } else { _templatesPrefix = templatesPrefix; } } /** * Determines if the template cache should be enabled. If no value is * passed, then by default the cache is enabled. An invalid value, however, * will trigger an {@link InvalidPropertyValueException}. * * @param cacheEnabled * the value of the runtime property that specifies whether the cache * should be enabled, can be <code>null</code>. * * @throws InvalidPropertyValueException * if the value is incorrect. */ private void initCacheEnabled(String cacheEnabled) throws InvalidPropertyValueException { // By default, the template cache is enabled if (TextUtils.isEmpty(cacheEnabled)) { _cacheTemplates = true; // Trim before comparing with 'true' and 'false' } else { cacheEnabled = cacheEnabled.trim(); if ("true".equals(cacheEnabled)) { _cacheTemplates = true; } else if ("false".equals(cacheEnabled)) { _cacheTemplates = false; } else { throw new InvalidPropertyValueException(TEMPLATES_CACHE_PROPERTY, cacheEnabled, "Expected either \"true\" or \"false\"."); } } // Log whether the cache is enabled or not if (_cacheTemplates) { Log.log_3440(); } else { Log.log_3441(); } } /** * Initializes the location for the XSLT templates. Examples include: * * The name of the runtime property that defines the location of the XSLT * templates should indicate a directory, either locally or remotely. * Local locations will be interpreted as relative to the user home * directory. The value should be a URL or a relative directory. * * <p>Examples of valid locations include: * * <ul> * <li><code>projects/dubey/xslt/</code></li> * <li><code>file:///home/john.doe/projects/dubey/xslt/</code></li> * <li><code>http://johndoe.com/projects/dubey/xslt/</code></li> * <li><code>https://xslt.johndoe.com/</code></li> * <li><code>http://xslt.mycompany.com/myapi/</code></li> * <li><code>file:///c:/home/</code></li> * </ul> * * <p>XSLT template files must match the names of the corresponding * functions. * * @param runtimeProperties * the runtime properties, cannot be <code>null</code>. */ private void initXSLTLocation(PropertyReader runtimeProperties) { // Get the value of the property String templatesProperty = "templates." + getAPI().getName() + ".xins-xslt.source"; _location = runtimeProperties.get(templatesProperty); // If the value is not a URL, it's considered as a relative path. // Relative URLs use the user directory as base dir. if (TextUtils.isEmpty(_location) || _location.indexOf("://") == -1) { // Trim the location and make sure it's never null _location = TextUtils.trim(_location, ""); // Attempt to convert the home directory to a URL String home = System.getProperty("user.dir"); String homeURL = ""; try { homeURL = new File(home).toURL().toString(); // If the conversion to a URL failed, then just use the original } catch (IOException exception) { Utils.logIgnoredException( XSLTCallingConvention.class.getName(), "initImpl", "java.io.File", "toURL()", exception); } // Prepend the home directory URL _location = homeURL + _location; } // Log the base directory for XSLT templates Log.log_3442(_location); } protected void convertResultImpl(FunctionResult xinsResult, HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException { // If the request is to clear the cache, just clear the cache. if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) { _templateCache.clear(); PrintWriter out = httpResponse.getWriter(); out.write("Done."); out.close(); return; } // Get the XML output similar to the standard calling convention. StringWriter xmlOutput = new StringWriter(1024); CallResultOutputter.output(xmlOutput, xinsResult); xmlOutput.close(); // Get the location of the XSLT file. String xsltLocation = null; if (_templatesPrefix != null) { String templatesSuffix = httpRequest.getParameter(TEMPLATE_PARAMETER); - if (templatesSuffix.indexOf("..") != -1) { + if (templatesSuffix != null && templatesSuffix.indexOf("..") != -1) { throw new IOException("Incorrect _template parameter: " + templatesSuffix); } - xsltLocation = _templatesPrefix + templatesSuffix; + if (templatesSuffix != null ) { + xsltLocation = _templatesPrefix + templatesSuffix; + } } if (xsltLocation == null) { xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt"; } try { // Load the template or get it from the cache. Templates templates = null; if (_cacheTemplates && _templateCache.containsKey(xsltLocation)) { templates = (Templates) _templateCache.get(xsltLocation); } else { + Log.log_3443(xsltLocation); templates = _factory.newTemplates(new StreamSource(xsltLocation)); if (_cacheTemplates) { _templateCache.put(xsltLocation, templates); } } // Proceed to the transformation. Transformer xformer = templates.newTransformer(); Source source = new StreamSource(new StringReader(xmlOutput.toString())); Writer buffer = new StringWriter(4096); Result result = new StreamResult(buffer); xformer.transform(source, result); // Determine the MIME type for the output. String mimeType = getContentType(templates.getOutputProperties()); if (mimeType != null) { httpResponse.setContentType(mimeType); } httpResponse.setStatus(HttpServletResponse.SC_OK); PrintWriter out = httpResponse.getWriter(); out.print(buffer.toString()); out.close(); } catch (Exception exception) { if (exception instanceof IOException) { throw (IOException) exception; } else { String message = "Cannot transform the result with the XSLT " + "located at \"" + xsltLocation + "\"."; IOException ioe = new IOException(message); ExceptionUtils.setCause(ioe, exception); throw ioe; } } } /** * Gets the MIME type and the character encoding to return for the HTTP response. * * @param outputProperties * the output properties defined in the XSLT, never <code>null</code>. * * @return * the content type, never <code>null</code>. */ private String getContentType(Properties outputProperties) { String mimeType = outputProperties.getProperty("media-type"); if (mimeType == null) { String method = outputProperties.getProperty("method"); if ("xml".equals(method)) { mimeType = "text/xml"; } else if ("html".equals(method)) { mimeType = "text/html"; } else if ("text".equals(method)) { mimeType = "text/plain"; } } String encoding = outputProperties.getProperty("encoding"); if (mimeType != null && encoding != null) { mimeType += ";charset=" + encoding; } return mimeType; } }
false
true
protected void convertResultImpl(FunctionResult xinsResult, HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException { // If the request is to clear the cache, just clear the cache. if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) { _templateCache.clear(); PrintWriter out = httpResponse.getWriter(); out.write("Done."); out.close(); return; } // Get the XML output similar to the standard calling convention. StringWriter xmlOutput = new StringWriter(1024); CallResultOutputter.output(xmlOutput, xinsResult); xmlOutput.close(); // Get the location of the XSLT file. String xsltLocation = null; if (_templatesPrefix != null) { String templatesSuffix = httpRequest.getParameter(TEMPLATE_PARAMETER); if (templatesSuffix.indexOf("..") != -1) { throw new IOException("Incorrect _template parameter: " + templatesSuffix); } xsltLocation = _templatesPrefix + templatesSuffix; } if (xsltLocation == null) { xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt"; } try { // Load the template or get it from the cache. Templates templates = null; if (_cacheTemplates && _templateCache.containsKey(xsltLocation)) { templates = (Templates) _templateCache.get(xsltLocation); } else { templates = _factory.newTemplates(new StreamSource(xsltLocation)); if (_cacheTemplates) { _templateCache.put(xsltLocation, templates); } } // Proceed to the transformation. Transformer xformer = templates.newTransformer(); Source source = new StreamSource(new StringReader(xmlOutput.toString())); Writer buffer = new StringWriter(4096); Result result = new StreamResult(buffer); xformer.transform(source, result); // Determine the MIME type for the output. String mimeType = getContentType(templates.getOutputProperties()); if (mimeType != null) { httpResponse.setContentType(mimeType); } httpResponse.setStatus(HttpServletResponse.SC_OK); PrintWriter out = httpResponse.getWriter(); out.print(buffer.toString()); out.close(); } catch (Exception exception) { if (exception instanceof IOException) { throw (IOException) exception; } else { String message = "Cannot transform the result with the XSLT " + "located at \"" + xsltLocation + "\"."; IOException ioe = new IOException(message); ExceptionUtils.setCause(ioe, exception); throw ioe; } } }
protected void convertResultImpl(FunctionResult xinsResult, HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException { // If the request is to clear the cache, just clear the cache. if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) { _templateCache.clear(); PrintWriter out = httpResponse.getWriter(); out.write("Done."); out.close(); return; } // Get the XML output similar to the standard calling convention. StringWriter xmlOutput = new StringWriter(1024); CallResultOutputter.output(xmlOutput, xinsResult); xmlOutput.close(); // Get the location of the XSLT file. String xsltLocation = null; if (_templatesPrefix != null) { String templatesSuffix = httpRequest.getParameter(TEMPLATE_PARAMETER); if (templatesSuffix != null && templatesSuffix.indexOf("..") != -1) { throw new IOException("Incorrect _template parameter: " + templatesSuffix); } if (templatesSuffix != null ) { xsltLocation = _templatesPrefix + templatesSuffix; } } if (xsltLocation == null) { xsltLocation = _location + httpRequest.getParameter("_function") + ".xslt"; } try { // Load the template or get it from the cache. Templates templates = null; if (_cacheTemplates && _templateCache.containsKey(xsltLocation)) { templates = (Templates) _templateCache.get(xsltLocation); } else { Log.log_3443(xsltLocation); templates = _factory.newTemplates(new StreamSource(xsltLocation)); if (_cacheTemplates) { _templateCache.put(xsltLocation, templates); } } // Proceed to the transformation. Transformer xformer = templates.newTransformer(); Source source = new StreamSource(new StringReader(xmlOutput.toString())); Writer buffer = new StringWriter(4096); Result result = new StreamResult(buffer); xformer.transform(source, result); // Determine the MIME type for the output. String mimeType = getContentType(templates.getOutputProperties()); if (mimeType != null) { httpResponse.setContentType(mimeType); } httpResponse.setStatus(HttpServletResponse.SC_OK); PrintWriter out = httpResponse.getWriter(); out.print(buffer.toString()); out.close(); } catch (Exception exception) { if (exception instanceof IOException) { throw (IOException) exception; } else { String message = "Cannot transform the result with the XSLT " + "located at \"" + xsltLocation + "\"."; IOException ioe = new IOException(message); ExceptionUtils.setCause(ioe, exception); throw ioe; } } }
diff --git a/jboss-jsfunit-core/src/main/java/org/jboss/jsfunit/config/AbstractFacesConfigTestCase.java b/jboss-jsfunit-core/src/main/java/org/jboss/jsfunit/config/AbstractFacesConfigTestCase.java index 767c466..216c51b 100644 --- a/jboss-jsfunit-core/src/main/java/org/jboss/jsfunit/config/AbstractFacesConfigTestCase.java +++ b/jboss-jsfunit-core/src/main/java/org/jboss/jsfunit/config/AbstractFacesConfigTestCase.java @@ -1,199 +1,199 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2007, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jsfunit.config; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.faces.application.ApplicationFactory; import javax.faces.application.NavigationHandler; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.component.UIComponent; import javax.faces.context.FacesContextFactory; import javax.faces.convert.Converter; import javax.faces.el.PropertyResolver; import javax.faces.el.VariableResolver; import javax.faces.event.ActionListener; import javax.faces.event.PhaseListener; import javax.faces.lifecycle.LifecycleFactory; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.faces.render.Renderer; import javax.faces.validator.Validator; import javax.xml.parsers.SAXParserFactory; import junit.framework.TestCase; public abstract class AbstractFacesConfigTestCase extends TestCase { protected Set<String> facesConfigPaths = new HashSet<String>(); private final static Map<String, Class[]> CLASS_CONSTRAINTS = new HashMap<String, Class[]>(){{ put("action-listener", new Class[]{ActionListener.class}); put("navigation-handler", new Class[]{NavigationHandler.class}); put("variable-resolver", new Class[]{VariableResolver.class}); put("property-resolver", new Class[]{PropertyResolver.class}); put("view-handler", new Class[]{ViewHandler.class}); put("state-manager", new Class[] {StateManager.class}); put("faces-context-factory", new Class[]{FacesContextFactory.class}); put("application-factory", new Class[]{ApplicationFactory.class}); put("lifecycle-factory", new Class[]{LifecycleFactory.class}); put("render-kit-factory", new Class[]{RenderKitFactory.class}); put("component-class", new Class[]{UIComponent.class}); put("converter-class", new Class[]{Converter.class}); put("validator-class", new Class[]{Validator.class}); put("managed-bean-class", new Class[]{}); put("key-class", new Class[]{}); put("value-class", new Class[]{}); put("render-kit-class", new Class[]{RenderKit.class}); put("renderer-class", new Class[]{Renderer.class}); put("phase-listener", new Class[]{PhaseListener.class}); put("converter-for-class", new Class[]{}); }}; private final static Map<String, List<String>> VALUE_CONSTRAINTS = new HashMap<String, List<String>>(){{ put("managed-bean-scope", new ArrayList<String>(){{ add("none"); add("request"); add("session"); add("application"); }}); }}; // create this once, as it holds state across > 1 conf source private final FacesConfigHandler handler = new FacesConfigHandler(CLASS_CONSTRAINTS.keySet(), VALUE_CONSTRAINTS.keySet()); public AbstractFacesConfigTestCase(Set<String> facesConfigPaths) { this(facesConfigPaths, new ResourceUtils()); } AbstractFacesConfigTestCase(Set<String> facesConfigPaths, StreamProvider streamProvider) { if(streamProvider == null) throw new IllegalArgumentException("stream provider is null"); if(facesConfigPaths == null) throw new IllegalArgumentException("facesConfigPaths is null"); if(facesConfigPaths.isEmpty()) throw new IllegalArgumentException("facesConfigPaths is empty"); parseResources(facesConfigPaths, streamProvider); this.facesConfigPaths = facesConfigPaths; } private void parseResources(Set<String> facesConfigPaths, StreamProvider streamProvider) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(false); // TODO set to true factory.setNamespaceAware(false); // TODO set to true for(String resourcePath : facesConfigPaths) parseResource(streamProvider, factory, resourcePath); } private void parseResource(StreamProvider streamProvider, SAXParserFactory factory, String resourcePath) { String xml = getXml(streamProvider, resourcePath); try { factory.newSAXParser().parse(new ByteArrayInputStream(xml.getBytes()), handler); } catch (Exception e) { throw new RuntimeException("Could not parse XML:" + xml); } } private String getConstraintsList(Class[] constraints) { String msg = ""; for(int c = 0; c < constraints.length ; c++) { String append = c == constraints.length - 1 ? "" : " or "; msg += constraints[c].getName() + append; } return msg; } private boolean isAssignableFrom(Class[] constraints, Class clazz) { for(Class constraint : constraints) if(constraint.isAssignableFrom(clazz)) return true; return false; } private String getXml(StreamProvider streamProvider, String resourcePath) { InputStream stream = streamProvider.getInputStream(resourcePath); if(stream == null) throw new RuntimeException("Could not locate faces config file '" + resourcePath + "'" ); String xml = new ResourceUtils().getAsString(stream, resourcePath); // TODO find a better way to prevent SAX from going to the Internet int indexOf = xml.indexOf("<faces-config"); if(indexOf > 0) xml = xml.substring(indexOf, xml.length()); return xml; } public void testClassDefinitions() { for(String elementName : handler.getClassNamesByElement().keySet()) { List<String> classNames = handler.getClassNamesByElement().get(elementName); for(String className : classNames) { Class clazz = new ClassUtils().loadClass(className, elementName); Class[] constraints = CLASS_CONSTRAINTS.get(elementName); - if( ! isAssignableFrom(constraints, clazz) ) + if( constraints.length > 0 && ! isAssignableFrom(constraints, clazz) ) throw new RuntimeException(clazz.getName() + ", in element " + elementName + " should be a " + getConstraintsList(constraints)); } } } }
true
true
public void testClassDefinitions() { for(String elementName : handler.getClassNamesByElement().keySet()) { List<String> classNames = handler.getClassNamesByElement().get(elementName); for(String className : classNames) { Class clazz = new ClassUtils().loadClass(className, elementName); Class[] constraints = CLASS_CONSTRAINTS.get(elementName); if( ! isAssignableFrom(constraints, clazz) ) throw new RuntimeException(clazz.getName() + ", in element " + elementName + " should be a " + getConstraintsList(constraints)); } } }
public void testClassDefinitions() { for(String elementName : handler.getClassNamesByElement().keySet()) { List<String> classNames = handler.getClassNamesByElement().get(elementName); for(String className : classNames) { Class clazz = new ClassUtils().loadClass(className, elementName); Class[] constraints = CLASS_CONSTRAINTS.get(elementName); if( constraints.length > 0 && ! isAssignableFrom(constraints, clazz) ) throw new RuntimeException(clazz.getName() + ", in element " + elementName + " should be a " + getConstraintsList(constraints)); } } }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/DoBlockInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/DoBlockInfo.java index 9bf9b21b..47084304 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/DoBlockInfo.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/DoBlockInfo.java @@ -1,65 +1,65 @@ package jp.ac.osaka_u.ist.sel.metricstool.main.data.target; import java.util.SortedSet; /** * do �u���b�N��\���N���X * * @author higo * */ @SuppressWarnings("serial") public final class DoBlockInfo extends ConditionalBlockInfo { /** * �ʒu����^���� do �u���b�N�������� * * @param ownerClass ���L�N���X * @param outerSpace �O���̃u���b�N * @param fromLine �J�n�s * @param fromColumn �J�n�� * @param toLine �I���s * @param toColumn �I���� */ public DoBlockInfo(final TargetClassInfo ownerClass, final LocalSpaceInfo outerSpace, final int fromLine, final int fromColumn, final int toLine, final int toColumn) { super(ownerClass, outerSpace, fromLine, fromColumn, toLine, toColumn); } /** * ����Do���̃e�L�X�g�\���iString�^�j��ς��� * * @return ����Do���̃e�L�X�g�\���iString�^�j */ @Override public String getText() { final StringBuilder sb = new StringBuilder(); sb.append("do {"); sb.append(System.getProperty("line.separator")); final SortedSet<StatementInfo> statements = this.getStatements(); for (final StatementInfo statement : statements) { sb.append(statement.getText()); sb.append(System.getProperty("line.separator")); } sb.append("} while ("); final ConditionalClauseInfo conditionalClause = this.getConditionalClause(); sb.append(conditionalClause.getText()); - sb.append(")"); + sb.append(");"); return sb.toString(); } @Override public boolean isLoopStatement() { return true; } }
true
true
public String getText() { final StringBuilder sb = new StringBuilder(); sb.append("do {"); sb.append(System.getProperty("line.separator")); final SortedSet<StatementInfo> statements = this.getStatements(); for (final StatementInfo statement : statements) { sb.append(statement.getText()); sb.append(System.getProperty("line.separator")); } sb.append("} while ("); final ConditionalClauseInfo conditionalClause = this.getConditionalClause(); sb.append(conditionalClause.getText()); sb.append(")"); return sb.toString(); }
public String getText() { final StringBuilder sb = new StringBuilder(); sb.append("do {"); sb.append(System.getProperty("line.separator")); final SortedSet<StatementInfo> statements = this.getStatements(); for (final StatementInfo statement : statements) { sb.append(statement.getText()); sb.append(System.getProperty("line.separator")); } sb.append("} while ("); final ConditionalClauseInfo conditionalClause = this.getConditionalClause(); sb.append(conditionalClause.getText()); sb.append(");"); return sb.toString(); }
diff --git a/examples/units/org.eclipse.uomo.examples.units.console/src/main/java/org/eclipse/uomo/examples/units/console/HelloUnits.java b/examples/units/org.eclipse.uomo.examples.units.console/src/main/java/org/eclipse/uomo/examples/units/console/HelloUnits.java index d291358..f8f5f15 100644 --- a/examples/units/org.eclipse.uomo.examples.units.console/src/main/java/org/eclipse/uomo/examples/units/console/HelloUnits.java +++ b/examples/units/org.eclipse.uomo.examples.units.console/src/main/java/org/eclipse/uomo/examples/units/console/HelloUnits.java @@ -1,60 +1,60 @@ /** * Copyright (c) 2005, 2012, Werner Keil 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: * Werner Keil - initial API and implementation */ package org.eclipse.uomo.examples.units.console; import org.eclipse.uomo.units.IMeasure; import org.eclipse.uomo.units.SI; import org.eclipse.uomo.units.impl.quantity.AreaAmount; import org.eclipse.uomo.units.impl.quantity.LengthAmount; import org.eclipse.uomo.units.impl.quantity.TimeAmount; import org.eclipse.uomo.units.impl.system.USCustomary; import org.unitsofmeasurement.unit.Unit; import org.unitsofmeasurement.unit.UnitConverter; import org.unitsofmeasurement.quantity.Acceleration; import org.unitsofmeasurement.quantity.Area; import org.unitsofmeasurement.quantity.Length; import org.unitsofmeasurement.quantity.Time; public class HelloUnits { /** * @param args */ public static void main(String[] args) { LengthAmount length = new LengthAmount(10, SI.METRE); // LengthAmount length = new LengthAmount(10, SI.KILOGRAM); // this won't work ;-) System.out.println(length); Unit<Length> lenUnit = length.unit(); //System.out.println(lenUnit); System.out.print(length.doubleValue(USCustomary.FOOT)); System.out.println(" " + USCustomary.FOOT); // System.out.println(length.doubleValue(USCustomary.POUND)); // this won't work either. UnitConverter inchConverter = lenUnit.getConverterTo(USCustomary.INCH); - System.out.println(inchConverter.convert(length.getNumber().doubleValue())); - //System.out.println(" " + USCustomary.INCH); + System.out.print(inchConverter.convert(length.getNumber().doubleValue())); + System.out.println(" " + USCustomary.INCH); @SuppressWarnings("unchecked") AreaAmount area = new AreaAmount(length.getNumber().doubleValue() * length.getNumber().doubleValue(), (Unit<Area>) length.unit().multiply(SI.METRE)); System.out.println(area); // Equivalent to IMeasure<Length> meters = new LengthAmount(5, SI.METRE); IMeasure<Time> secs = new TimeAmount(2, SI.SECOND); @SuppressWarnings("unchecked") IMeasure<Acceleration> speed = (IMeasure<Acceleration>) meters.divide(secs); System.out.println(meters + "; " + secs + "; " + speed); } }
true
true
public static void main(String[] args) { LengthAmount length = new LengthAmount(10, SI.METRE); // LengthAmount length = new LengthAmount(10, SI.KILOGRAM); // this won't work ;-) System.out.println(length); Unit<Length> lenUnit = length.unit(); //System.out.println(lenUnit); System.out.print(length.doubleValue(USCustomary.FOOT)); System.out.println(" " + USCustomary.FOOT); // System.out.println(length.doubleValue(USCustomary.POUND)); // this won't work either. UnitConverter inchConverter = lenUnit.getConverterTo(USCustomary.INCH); System.out.println(inchConverter.convert(length.getNumber().doubleValue())); //System.out.println(" " + USCustomary.INCH); @SuppressWarnings("unchecked") AreaAmount area = new AreaAmount(length.getNumber().doubleValue() * length.getNumber().doubleValue(), (Unit<Area>) length.unit().multiply(SI.METRE)); System.out.println(area); // Equivalent to IMeasure<Length> meters = new LengthAmount(5, SI.METRE); IMeasure<Time> secs = new TimeAmount(2, SI.SECOND); @SuppressWarnings("unchecked") IMeasure<Acceleration> speed = (IMeasure<Acceleration>) meters.divide(secs); System.out.println(meters + "; " + secs + "; " + speed); }
public static void main(String[] args) { LengthAmount length = new LengthAmount(10, SI.METRE); // LengthAmount length = new LengthAmount(10, SI.KILOGRAM); // this won't work ;-) System.out.println(length); Unit<Length> lenUnit = length.unit(); //System.out.println(lenUnit); System.out.print(length.doubleValue(USCustomary.FOOT)); System.out.println(" " + USCustomary.FOOT); // System.out.println(length.doubleValue(USCustomary.POUND)); // this won't work either. UnitConverter inchConverter = lenUnit.getConverterTo(USCustomary.INCH); System.out.print(inchConverter.convert(length.getNumber().doubleValue())); System.out.println(" " + USCustomary.INCH); @SuppressWarnings("unchecked") AreaAmount area = new AreaAmount(length.getNumber().doubleValue() * length.getNumber().doubleValue(), (Unit<Area>) length.unit().multiply(SI.METRE)); System.out.println(area); // Equivalent to IMeasure<Length> meters = new LengthAmount(5, SI.METRE); IMeasure<Time> secs = new TimeAmount(2, SI.SECOND); @SuppressWarnings("unchecked") IMeasure<Acceleration> speed = (IMeasure<Acceleration>) meters.divide(secs); System.out.println(meters + "; " + secs + "; " + speed); }
diff --git a/modules/axiom-api/src/main/java/org/apache/axiom/om/impl/util/OMSerializerUtil.java b/modules/axiom-api/src/main/java/org/apache/axiom/om/impl/util/OMSerializerUtil.java index e1c6a5914..1802a3700 100644 --- a/modules/axiom-api/src/main/java/org/apache/axiom/om/impl/util/OMSerializerUtil.java +++ b/modules/axiom-api/src/main/java/org/apache/axiom/om/impl/util/OMSerializerUtil.java @@ -1,530 +1,534 @@ /* * 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.axiom.om.impl.util; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.impl.OMNodeEx; import org.apache.axiom.om.impl.serialize.StreamingOMSerializer; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import java.util.ArrayList; import java.util.Iterator; public class OMSerializerUtil { static long nsCounter = 0; /** * Method serializeEndpart. * * @param writer * @throws javax.xml.stream.XMLStreamException * */ public static void serializeEndpart(XMLStreamWriter writer) throws XMLStreamException { writer.writeEndElement(); } /** * Method serializeAttribute. * * @param attr * @param writer * @throws XMLStreamException * @deprecated use serializeStartpart instead */ public static void serializeAttribute(OMAttribute attr, XMLStreamWriter writer) throws XMLStreamException { // first check whether the attribute is associated with a namespace OMNamespace ns = attr.getNamespace(); String prefix = null; String namespaceName = null; if (ns != null) { // add the prefix if it's availble prefix = ns.getPrefix(); namespaceName = ns.getNamespaceURI(); if (prefix != null) { writer.writeAttribute(prefix, namespaceName, attr.getLocalName(), attr.getAttributeValue()); } else { writer.writeAttribute(namespaceName, attr.getLocalName(), attr.getAttributeValue()); } } else { String localName = attr.getLocalName(); String attributeValue = attr.getAttributeValue(); writer.writeAttribute(localName, attributeValue); } } /** * Method serializeNamespace. * * @param namespace * @param writer * @throws XMLStreamException * @deprecated Use serializeStartpart instead */ public static void serializeNamespace(OMNamespace namespace, XMLStreamWriter writer) throws XMLStreamException { if (namespace == null) { return; } String uri = namespace.getNamespaceURI(); String prefix = namespace.getPrefix(); if (uri != null && !"".equals(uri)) { String prefixFromWriter = writer.getPrefix(uri); // Handling Default Namespaces First // Case 1 : // here we are trying define a default namespace. But has this been defined in the current context. // yes, there can be a default namespace, but it may have a different URI. If its a different URI // then explicitly define the default namespace here. // Case 2 : // The passed in namespace is a default ns, but there is a non-default ns declared // in the current scope. if (("".equals(prefix) && "".equals(prefixFromWriter) && !uri.equals(writer.getNamespaceContext().getNamespaceURI(""))) || (prefix != null && "".equals(prefix) && (prefixFromWriter == null || !prefix.equals(prefixFromWriter)))) { // this has not been declared earlier writer.writeDefaultNamespace(uri); writer.setDefaultNamespace(uri); } else { prefix = prefix == null ? getNextNSPrefix(writer) : prefix; if (prefix != null && !prefix.equals(prefixFromWriter) && !checkForPrefixInTheCurrentContext(writer, uri, prefix)) { writer.writeNamespace(prefix, uri); writer.setPrefix(prefix, uri); } } } else { // now the nsURI passed is "" or null. Meaning we gonna work with defaultNS. // check whether there is a defaultNS already declared. If yes, is it the same as this ? String currentDefaultNSURI = writer.getNamespaceContext().getNamespaceURI(""); if( (currentDefaultNSURI != null && !currentDefaultNSURI.equals(uri)) || uri != null && !uri.equals(currentDefaultNSURI)){ // this has not been declared earlier writer.writeDefaultNamespace(uri); writer.setDefaultNamespace(uri); } } } /** * Unfortunately there is disagreement in the user community about the semantics of * setPrefix on the XMLStreamWriter. An example will explain the difference: * writer.startElement("a") * writer.setPrefix("pre", "urn://sample") * writer.startElement("b") * * Some user communities (woodstox) believe that the setPrefix is associate with the scope * for "a" and thus remains in scope until the end of a. The basis for this believe is * XMLStreamWriter javadoc (which some would argue is incomplete). * * Some user communities believe that the setPrefix is associated with the "b" element. * These communities reference an example in the specification and historical usage of SAX. * * This method will return true if the setPrefix is associated with the next writeStartElement. * * @param writer * @return true if setPrefix should be generated before startElement */ public static boolean isSetPrefixBeforeStartElement(XMLStreamWriter writer) { NamespaceContext nc = writer.getNamespaceContext(); return(nc ==null || nc.getClass().getName().indexOf("wstx") == -1); } /** * Method serializeStartpart. * Serialize the start tag of an element. * * @param element * @param writer * @throws XMLStreamException */ public static void serializeStartpart(OMElement element, XMLStreamWriter writer) throws XMLStreamException { serializeStartpart(element, element.getLocalName(), writer); } /** * Method serializeStartpart. * Serialize the start tag of an element. * * @param element * @param localName (in some cases, the caller wants to force a different localName) * @param writer * @throws XMLStreamException */ public static void serializeStartpart(OMElement element, String localName, XMLStreamWriter writer) throws XMLStreamException { // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification. // Please keep this code in sync with the code in StreamingOMSerializer.serializeElement // The algorithm is: // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated. // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes. // // ... generate writeStartElement (See NOTE_A) // // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing // ... generate writeAttribute for each attribute // NOTE_A: To confuse matters, some StAX vendors (including woodstox), believe that the setPrefix bindings // should occur after the writeStartElement. If this is the case, the writeStartElement is generated first. ArrayList writePrefixList = null; ArrayList writeNSList = null; // Get the namespace and prefix of the element OMNamespace eOMNamespace = element.getNamespace(); String ePrefix = null; String eNamespace = null; if (eOMNamespace != null) { ePrefix = eOMNamespace.getPrefix(); eNamespace = eOMNamespace.getNamespaceURI(); } ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix; eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace; // Write the startElement if required boolean setPrefixFirst = isSetPrefixBeforeStartElement(writer); if (!setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Generate setPrefix for the namespace declarations Iterator it = element.getAllDeclaredNamespaces(); while (it != null && it.hasNext()) { OMNamespace omNamespace = (OMNamespace) it.next(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; String newPrefix = generateSetPrefix(prefix, namespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Generate setPrefix for the element // Get the prefix and namespace of the element. "" and null are identical. String newPrefix = generateSetPrefix(ePrefix, eNamespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(eNamespace); } } // Now Generate setPrefix for each attribute Iterator attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; // Default prefix referencing is not allowed on an attribute if (prefix == null && namespace != null) { String writerPrefix = writer.getPrefix(namespace); writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix; prefix = (writerPrefix != null) ? writerPrefix : getNextNSPrefix(); } newPrefix = generateSetPrefix(prefix, namespace, writer, true); // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Write the startElement if required if (setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Now write out the list of namespace declarations in this list that we constructed // while doing the "set" processing. if (writePrefixList != null) { for (int i=0; i<writePrefixList.size(); i++) { String prefix = (String) writePrefixList.get(i); String namespace = (String) writeNSList.get(i); if (prefix != null) { - writer.writeNamespace(prefix, namespace); + if(namespace==null){ + writer.writeNamespace(prefix, ""); + } else{ + writer.writeNamespace(prefix, namespace); + } } else { writer.writeDefaultNamespace(namespace); } } } // Now write the attributes attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; if (prefix == null && namespace != null) { // Default namespaces are not allowed on an attribute reference. // Earlier in this code, a unique prefix was added for this case...now obtain and use it prefix = writer.getPrefix(namespace); } else if (namespace != null) { // Use the writer's prefix if it is different String writerPrefix = writer.getPrefix(namespace); if (!prefix.equals(writerPrefix)) { prefix = writerPrefix; } } if (namespace != null) { // Qualified attribute writer.writeAttribute(prefix, namespace, attr.getLocalName(), attr.getAttributeValue()); } else { // Unqualified attribute writer.writeAttribute(attr.getLocalName(), attr.getAttributeValue()); } } } private static boolean checkForPrefixInTheCurrentContext(XMLStreamWriter writer, String nameSpaceName, String prefix) throws XMLStreamException { Iterator prefixesIter = writer.getNamespaceContext().getPrefixes(nameSpaceName); while (prefixesIter.hasNext()) { String prefix_w = (String) prefixesIter.next(); if (prefix_w.equals(prefix)) { // if found do not declare the ns return true; } } return false; } /** * serializeNamespaces * * @param element * @param writer * @throws XMLStreamException * @deprecated Use serializeStartpart instead */ public static void serializeNamespaces (OMElement element, XMLStreamWriter writer) throws XMLStreamException { Iterator namespaces = element.getAllDeclaredNamespaces(); if (namespaces != null) { while (namespaces.hasNext()) { serializeNamespace((OMNamespace) namespaces.next(), writer); } } } /** * Serialize attributes * @param element * @param writer * @throws XMLStreamException * @deprecated Consider using serializeStartpart instead */ public static void serializeAttributes (OMElement element, XMLStreamWriter writer) throws XMLStreamException { Iterator attributes = element.getAllAttributes(); if (attributes != null && attributes.hasNext()) { while (attributes.hasNext()) { serializeAttribute((OMAttribute) attributes.next(), writer); } } } /** * Method serializeNormal. * * @param writer * @param cache * @throws XMLStreamException */ public static void serializeNormal (OMElement element, XMLStreamWriter writer, boolean cache) throws XMLStreamException { if (cache) { element.build(); } serializeStartpart(element, writer); OMNode firstChild = element.getFirstOMChild(); if (firstChild != null) { if (cache) { (firstChild).serialize(writer); } else { (firstChild).serializeAndConsume(writer); } } serializeEndpart(writer); } public static void serializeByPullStream (OMElement element, XMLStreamWriter writer) throws XMLStreamException { serializeByPullStream(element, writer, false); } public static void serializeByPullStream (OMElement element, XMLStreamWriter writer, boolean cache) throws XMLStreamException { StreamingOMSerializer streamingOMSerializer = new StreamingOMSerializer(); if (cache) { streamingOMSerializer.serialize(element.getXMLStreamReader(), writer); } else { XMLStreamReader xmlStreamReaderWithoutCaching = element.getXMLStreamReaderWithoutCaching(); streamingOMSerializer.serialize(xmlStreamReaderWithoutCaching, writer); } } public static String getNextNSPrefix() { return "axis2ns" + ++nsCounter % Long.MAX_VALUE; } public static String getNextNSPrefix(XMLStreamWriter writer) { String prefix = getNextNSPrefix(); while (writer.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = getNextNSPrefix(); } return prefix; } /** * Generate setPrefix/setDefaultNamespace if the prefix is not associated * @param prefix * @param namespace * @param writer * @param attr * @return prefix name if a setPrefix/setDefaultNamespace is performed */ public static String generateSetPrefix(String prefix, String namespace, XMLStreamWriter writer, boolean attr) throws XMLStreamException { // Generate setPrefix/setDefaultNamespace if the prefix is not associated. String newPrefix = null; if (namespace != null) { // Qualified Namespace // Get the namespace associated with this writer String writerNS = writer.getNamespaceContext().getNamespaceURI((prefix==null) ? "" : prefix); writerNS = (writerNS != null && writerNS.length() == 0) ? null : writerNS; if (writerNS == null || !writerNS.equals(namespace)) { // Writer has not associated this namespace with a prefix if (prefix == null) { writer.setDefaultNamespace(namespace); newPrefix = ""; } else { writer.setPrefix(prefix, namespace); newPrefix = prefix; } } else { // No Action needed..The writer already has associated this prefix to this namespace } } else { // Unqualified Namespace // Make sure the default namespace is either not used or disabled (set to "") String writerNS = writer.getNamespaceContext().getNamespaceURI(""); if (writerNS != null && writerNS.length() > 0 && !attr) { // Disable the default namespace writer.setDefaultNamespace(""); newPrefix = ""; } } return newPrefix; } }
true
true
public static void serializeStartpart(OMElement element, String localName, XMLStreamWriter writer) throws XMLStreamException { // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification. // Please keep this code in sync with the code in StreamingOMSerializer.serializeElement // The algorithm is: // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated. // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes. // // ... generate writeStartElement (See NOTE_A) // // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing // ... generate writeAttribute for each attribute // NOTE_A: To confuse matters, some StAX vendors (including woodstox), believe that the setPrefix bindings // should occur after the writeStartElement. If this is the case, the writeStartElement is generated first. ArrayList writePrefixList = null; ArrayList writeNSList = null; // Get the namespace and prefix of the element OMNamespace eOMNamespace = element.getNamespace(); String ePrefix = null; String eNamespace = null; if (eOMNamespace != null) { ePrefix = eOMNamespace.getPrefix(); eNamespace = eOMNamespace.getNamespaceURI(); } ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix; eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace; // Write the startElement if required boolean setPrefixFirst = isSetPrefixBeforeStartElement(writer); if (!setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Generate setPrefix for the namespace declarations Iterator it = element.getAllDeclaredNamespaces(); while (it != null && it.hasNext()) { OMNamespace omNamespace = (OMNamespace) it.next(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; String newPrefix = generateSetPrefix(prefix, namespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Generate setPrefix for the element // Get the prefix and namespace of the element. "" and null are identical. String newPrefix = generateSetPrefix(ePrefix, eNamespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(eNamespace); } } // Now Generate setPrefix for each attribute Iterator attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; // Default prefix referencing is not allowed on an attribute if (prefix == null && namespace != null) { String writerPrefix = writer.getPrefix(namespace); writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix; prefix = (writerPrefix != null) ? writerPrefix : getNextNSPrefix(); } newPrefix = generateSetPrefix(prefix, namespace, writer, true); // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Write the startElement if required if (setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Now write out the list of namespace declarations in this list that we constructed // while doing the "set" processing. if (writePrefixList != null) { for (int i=0; i<writePrefixList.size(); i++) { String prefix = (String) writePrefixList.get(i); String namespace = (String) writeNSList.get(i); if (prefix != null) { writer.writeNamespace(prefix, namespace); } else { writer.writeDefaultNamespace(namespace); } } } // Now write the attributes attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; if (prefix == null && namespace != null) { // Default namespaces are not allowed on an attribute reference. // Earlier in this code, a unique prefix was added for this case...now obtain and use it prefix = writer.getPrefix(namespace); } else if (namespace != null) { // Use the writer's prefix if it is different String writerPrefix = writer.getPrefix(namespace); if (!prefix.equals(writerPrefix)) { prefix = writerPrefix; } } if (namespace != null) { // Qualified attribute writer.writeAttribute(prefix, namespace, attr.getLocalName(), attr.getAttributeValue()); } else { // Unqualified attribute writer.writeAttribute(attr.getLocalName(), attr.getAttributeValue()); } } }
public static void serializeStartpart(OMElement element, String localName, XMLStreamWriter writer) throws XMLStreamException { // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification. // Please keep this code in sync with the code in StreamingOMSerializer.serializeElement // The algorithm is: // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated. // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes. // // ... generate writeStartElement (See NOTE_A) // // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing // ... generate writeAttribute for each attribute // NOTE_A: To confuse matters, some StAX vendors (including woodstox), believe that the setPrefix bindings // should occur after the writeStartElement. If this is the case, the writeStartElement is generated first. ArrayList writePrefixList = null; ArrayList writeNSList = null; // Get the namespace and prefix of the element OMNamespace eOMNamespace = element.getNamespace(); String ePrefix = null; String eNamespace = null; if (eOMNamespace != null) { ePrefix = eOMNamespace.getPrefix(); eNamespace = eOMNamespace.getNamespaceURI(); } ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix; eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace; // Write the startElement if required boolean setPrefixFirst = isSetPrefixBeforeStartElement(writer); if (!setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Generate setPrefix for the namespace declarations Iterator it = element.getAllDeclaredNamespaces(); while (it != null && it.hasNext()) { OMNamespace omNamespace = (OMNamespace) it.next(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; String newPrefix = generateSetPrefix(prefix, namespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Generate setPrefix for the element // Get the prefix and namespace of the element. "" and null are identical. String newPrefix = generateSetPrefix(ePrefix, eNamespace, writer, false); // If this is a new association, remember it so that it can written out later if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(eNamespace); } } // Now Generate setPrefix for each attribute Iterator attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; // Default prefix referencing is not allowed on an attribute if (prefix == null && namespace != null) { String writerPrefix = writer.getPrefix(namespace); writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix; prefix = (writerPrefix != null) ? writerPrefix : getNextNSPrefix(); } newPrefix = generateSetPrefix(prefix, namespace, writer, true); // If the prefix is not associated with a namespace yet, remember it so that we can // write out a namespace declaration if (newPrefix != null) { if (writePrefixList == null) { writePrefixList= new ArrayList(); writeNSList = new ArrayList(); } if (!writePrefixList.contains(newPrefix)) { writePrefixList.add(newPrefix); writeNSList.add(namespace); } } } // Write the startElement if required if (setPrefixFirst) { if (eNamespace != null) { if (ePrefix == null) { writer.writeStartElement("", localName, eNamespace); } else { writer.writeStartElement(ePrefix, localName, eNamespace); } } else { writer.writeStartElement(localName); } } // Now write out the list of namespace declarations in this list that we constructed // while doing the "set" processing. if (writePrefixList != null) { for (int i=0; i<writePrefixList.size(); i++) { String prefix = (String) writePrefixList.get(i); String namespace = (String) writeNSList.get(i); if (prefix != null) { if(namespace==null){ writer.writeNamespace(prefix, ""); } else{ writer.writeNamespace(prefix, namespace); } } else { writer.writeDefaultNamespace(namespace); } } } // Now write the attributes attrs = element.getAllAttributes(); while (attrs != null && attrs.hasNext()) { OMAttribute attr = (OMAttribute) attrs.next(); OMNamespace omNamespace = attr.getNamespace(); String prefix = null; String namespace = null; if (omNamespace != null) { prefix = omNamespace.getPrefix(); namespace = omNamespace.getNamespaceURI(); } prefix = (prefix != null && prefix.length() == 0) ? null : prefix; namespace = (namespace != null && namespace.length() == 0) ? null : namespace; if (prefix == null && namespace != null) { // Default namespaces are not allowed on an attribute reference. // Earlier in this code, a unique prefix was added for this case...now obtain and use it prefix = writer.getPrefix(namespace); } else if (namespace != null) { // Use the writer's prefix if it is different String writerPrefix = writer.getPrefix(namespace); if (!prefix.equals(writerPrefix)) { prefix = writerPrefix; } } if (namespace != null) { // Qualified attribute writer.writeAttribute(prefix, namespace, attr.getLocalName(), attr.getAttributeValue()); } else { // Unqualified attribute writer.writeAttribute(attr.getLocalName(), attr.getAttributeValue()); } } }
diff --git a/fuentes/ERUtil.java b/fuentes/ERUtil.java index a8b167c..a4362be 100644 --- a/fuentes/ERUtil.java +++ b/fuentes/ERUtil.java @@ -1,112 +1,112 @@ public class ERUtil { /** //fuente http://snipt.org/uffgc5 Calcula el dígito de control @param entidad Entidad bancaria. @param sucursal Código sucursal bancaria. @param n_cuenta Número de cuenta bancaria. @return Dígito de control. */ public static String calculaDC(String entidad, String sucursal, String n_cuenta) { String dc = ""; int calculo = 0; int calculo1 = 0; String dc1 = ""; String dc2 = ""; String enti = entidad; String sucur = sucursal; /*Primer dígito.*/ for (int i = 0; i < 4; i++) { if (i==0){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*4; }else if (i==1){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*8; }else if (i==2){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*5; }else { calculo1 = Integer.parseInt(enti.substring(i, i + 1))*10; } calculo = calculo + calculo1; } for (int j = 0; j < 4; j++) { if (j==0){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*9; }else if (j==1){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*7; }else if (j==2){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*3; }else { calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc1 = String.valueOf(1); } else if (calculo1 == 11) { dc1 = String.valueOf(0); } else { dc1 = String.valueOf(calculo1); } calculo=0; /*Segundo dígito.*/ for (int k=0; k<10; k++){ if (k==0){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*1; }else if (k==1){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*2; }else if (k==2){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*4; }else if (k==3){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*8; }else if (k==4){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*5; }else if (k==5){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*10; }else if (k==6){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*9; }else if (k==7){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*7; }else if (k==8){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*3; }else { calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc2 = String.valueOf(1); } else if (calculo1 == 11) { dc2 = String.valueOf(0); } else { dc2 = String.valueOf(calculo1); } calculo=0; - dc=String.valueOf(dc1)+String.valueOf(dc1); + dc=String.valueOf(dc1)+String.valueOf(dc2); return dc; } /** //fuente http://felinfo.blogspot.com.es/2010/12/calcular-la-letra-del-dni-con-java.html Calcula la letra del DNI @param dni Cadena numérica. @return Letra. */ public static char calculaLetraDNI(int dni) { String juegoCaracteres="TRWAGMYFPDXBNJZSQVHLCKET"; int modulo= dni % 23; char letra = juegoCaracteres.charAt(modulo); return letra; } }
true
true
public static String calculaDC(String entidad, String sucursal, String n_cuenta) { String dc = ""; int calculo = 0; int calculo1 = 0; String dc1 = ""; String dc2 = ""; String enti = entidad; String sucur = sucursal; /*Primer dígito.*/ for (int i = 0; i < 4; i++) { if (i==0){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*4; }else if (i==1){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*8; }else if (i==2){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*5; }else { calculo1 = Integer.parseInt(enti.substring(i, i + 1))*10; } calculo = calculo + calculo1; } for (int j = 0; j < 4; j++) { if (j==0){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*9; }else if (j==1){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*7; }else if (j==2){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*3; }else { calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc1 = String.valueOf(1); } else if (calculo1 == 11) { dc1 = String.valueOf(0); } else { dc1 = String.valueOf(calculo1); } calculo=0; /*Segundo dígito.*/ for (int k=0; k<10; k++){ if (k==0){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*1; }else if (k==1){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*2; }else if (k==2){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*4; }else if (k==3){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*8; }else if (k==4){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*5; }else if (k==5){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*10; }else if (k==6){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*9; }else if (k==7){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*7; }else if (k==8){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*3; }else { calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc2 = String.valueOf(1); } else if (calculo1 == 11) { dc2 = String.valueOf(0); } else { dc2 = String.valueOf(calculo1); } calculo=0; dc=String.valueOf(dc1)+String.valueOf(dc1); return dc; }
public static String calculaDC(String entidad, String sucursal, String n_cuenta) { String dc = ""; int calculo = 0; int calculo1 = 0; String dc1 = ""; String dc2 = ""; String enti = entidad; String sucur = sucursal; /*Primer dígito.*/ for (int i = 0; i < 4; i++) { if (i==0){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*4; }else if (i==1){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*8; }else if (i==2){ calculo1 = Integer.parseInt(enti.substring(i, i + 1))*5; }else { calculo1 = Integer.parseInt(enti.substring(i, i + 1))*10; } calculo = calculo + calculo1; } for (int j = 0; j < 4; j++) { if (j==0){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*9; }else if (j==1){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*7; }else if (j==2){ calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*3; }else { calculo1 = Integer.parseInt(sucur.substring(j, j + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc1 = String.valueOf(1); } else if (calculo1 == 11) { dc1 = String.valueOf(0); } else { dc1 = String.valueOf(calculo1); } calculo=0; /*Segundo dígito.*/ for (int k=0; k<10; k++){ if (k==0){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*1; }else if (k==1){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*2; }else if (k==2){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*4; }else if (k==3){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*8; }else if (k==4){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*5; }else if (k==5){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*10; }else if (k==6){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*9; }else if (k==7){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*7; }else if (k==8){ calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*3; }else { calculo1 = Integer.parseInt(n_cuenta.substring(k, k + 1))*6; } calculo = calculo + calculo1; } calculo1 = 11 - calculo % 11; if (calculo1 == 10) { dc2 = String.valueOf(1); } else if (calculo1 == 11) { dc2 = String.valueOf(0); } else { dc2 = String.valueOf(calculo1); } calculo=0; dc=String.valueOf(dc1)+String.valueOf(dc2); return dc; }
diff --git a/src/main/java/org/spout/vanilla/entity/living/creature/passive/Sheep.java b/src/main/java/org/spout/vanilla/entity/living/creature/passive/Sheep.java index e667d7e8..4fb0113b 100644 --- a/src/main/java/org/spout/vanilla/entity/living/creature/passive/Sheep.java +++ b/src/main/java/org/spout/vanilla/entity/living/creature/passive/Sheep.java @@ -1,143 +1,143 @@ /* * This file is part of Vanilla (http://www.spout.org/). * * Vanilla is licensed under the SpoutDev License Version 1. * * Vanilla 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. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Vanilla 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, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.vanilla.entity.living.creature.passive; import java.util.HashSet; import java.util.Set; import org.spout.api.inventory.ItemStack; import org.spout.api.material.MaterialData; import org.spout.api.protocol.EntityProtocol; import org.spout.api.protocol.EntityProtocolStore; import org.spout.vanilla.entity.Entity; import org.spout.vanilla.entity.living.Creature; import org.spout.vanilla.entity.living.creature.Passive; public class Sheep extends Creature implements Passive { private int countdown = 0; private int color; private org.spout.api.entity.Entity parent; private static EntityProtocolStore entityProtocolStore = new EntityProtocolStore(); public Sheep() { this(0x0); } public Sheep(WoolColor color) { this(color.getId()); } public Sheep(int color) { super(); this.color = color; } @Override public void onAttached() { super.onAttached(); parent = getParent(); parent.setData(Entity.KEY, Entity.Sheep.id); parent.setData("SheepSheared", false); parent.setData("SheepColor", color); } @Override public EntityProtocol getEntityProtocol(int protocolId) { return entityProtocolStore.getEntityProtocol(protocolId); } public static void setEntityProtocol(int protocolId, EntityProtocol protocol) { entityProtocolStore.setEntityProtocol(protocolId, protocol); } @Override public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); - getParent().translate(x, y, z); + //getParent().translate(x, y, z); } super.onTick(dt); } public boolean isSheared() { return parent.getData("SheepSheared").asBool(); } public void setSheared(boolean sheared) { parent.setData("SheepSheared", sheared); } public int getColor() { return parent.getData("SheepColor").asInt(); } public void setColor() { parent.setData("SheepColor", getRandom()); } public enum WoolColor { White(0), Orange(1), Magenta(2), LightBlue(3), Yellow(4), Lime(5), Pink(6), Gray(7), Silver(8), Cyan(9), Purple(10), Blue(11), Brown(12), Green(13), Red(14), Black(15); private final int id; private WoolColor(int color) { id = color; } public int getId() { return id; } } @Override public Set<ItemStack> getDeathDrops() { Set<ItemStack> drops = new HashSet<ItemStack>(); if (!isSheared()) { drops.add(new ItemStack(MaterialData.getMaterial((short) 35, (short) getColor()), 1)); } return drops; } }
true
true
public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); getParent().translate(x, y, z); } super.onTick(dt); }
public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); //getParent().translate(x, y, z); } super.onTick(dt); }
diff --git a/src/com/tutorial/appengine/GuestbookServlet.java b/src/com/tutorial/appengine/GuestbookServlet.java index 8024640..92d6784 100644 --- a/src/com/tutorial/appengine/GuestbookServlet.java +++ b/src/com/tutorial/appengine/GuestbookServlet.java @@ -1,37 +1,43 @@ package com.tutorial.appengine; import java.io.IOException; import javax.servlet.http.*; //import com.google.appengine.api.users.*; @SuppressWarnings("serial") public class GuestbookServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String userPath = req.getServletPath(); if(userPath.equals("/guestbook")){ try{ req.getRequestDispatcher("/jsp/guestbook.jsp").forward(req, resp); }catch(Exception ex){ ex.printStackTrace(); } + }else{ + try{ + req.getRequestDispatcher("/jsp" + userPath).forward(req, resp); + }catch(Exception ex){ + ex.printStackTrace(); + } } /*UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if(user != null){ resp.setContentType("text/plain"); resp.getWriter().println("Hello, " + user.getNickname()); } else{ resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); } */ //resp.setContentType("text/plain"); //resp.getWriter().println("Hello, this is guestbook!"); } }
true
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String userPath = req.getServletPath(); if(userPath.equals("/guestbook")){ try{ req.getRequestDispatcher("/jsp/guestbook.jsp").forward(req, resp); }catch(Exception ex){ ex.printStackTrace(); } } /*UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if(user != null){ resp.setContentType("text/plain"); resp.getWriter().println("Hello, " + user.getNickname()); } else{ resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); } */ //resp.setContentType("text/plain"); //resp.getWriter().println("Hello, this is guestbook!"); }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String userPath = req.getServletPath(); if(userPath.equals("/guestbook")){ try{ req.getRequestDispatcher("/jsp/guestbook.jsp").forward(req, resp); }catch(Exception ex){ ex.printStackTrace(); } }else{ try{ req.getRequestDispatcher("/jsp" + userPath).forward(req, resp); }catch(Exception ex){ ex.printStackTrace(); } } /*UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if(user != null){ resp.setContentType("text/plain"); resp.getWriter().println("Hello, " + user.getNickname()); } else{ resp.sendRedirect(userService.createLoginURL(req.getRequestURI())); } */ //resp.setContentType("text/plain"); //resp.getWriter().println("Hello, this is guestbook!"); }
diff --git a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/scannerinfo/RemoteIncludeDialog.java b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/scannerinfo/RemoteIncludeDialog.java index 42408e324..ce87d72b7 100644 --- a/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/scannerinfo/RemoteIncludeDialog.java +++ b/rdt/org.eclipse.ptp.rdt.ui/src/org/eclipse/ptp/internal/rdt/ui/scannerinfo/RemoteIncludeDialog.java @@ -1,260 +1,260 @@ /******************************************************************************* * Copyright (c) 2008, 2013 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.ptp.internal.rdt.ui.scannerinfo; import org.eclipse.cdt.core.settings.model.ICConfigurationDescription; import org.eclipse.cdt.ui.newui.AbstractCPropertyTab; import org.eclipse.remote.core.IRemoteConnection; import org.eclipse.remote.ui.IRemoteUIConnectionManager; import org.eclipse.remote.ui.IRemoteUIFileManager; import org.eclipse.remote.ui.RemoteUIServices; import org.eclipse.rse.core.filters.SystemFilterReference; import org.eclipse.rse.core.model.IHost; import org.eclipse.rse.files.ui.dialogs.SystemRemoteFolderDialog; import org.eclipse.rse.subsystems.files.core.subsystems.IRemoteFile; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Rectangle; 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.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; /** * Dialog box that allows the user to browse the remote system for include * directories. */ public class RemoteIncludeDialog extends Dialog { private Shell shell; // buttons private Button b_ok; private Button b_cancel; private Button b_browse; private Button b_vars; // check boxes private Button b_add2confs; private Button b_add2langs; // the text input area private Text text; // used to pre-fill the text area with some text private String pathText = null; // results private boolean result = false; private String directory = null; private boolean isAllLanguages = false; private boolean isAllConfigurations = false; private final ICConfigurationDescription config; private final boolean isEdit; // TODO: should remove IHost and only use IRemoteServices // and IRemoteConnection // fHost used for RSE connections private IHost fHost = null; // fRemoteServices and fRemoteConnection used for others private IRemoteConnection fRemoteConnection = null; public RemoteIncludeDialog(Shell parent, String title, boolean isEdit, ICConfigurationDescription config) { super(parent); setText(title); this.isEdit = isEdit; this.config = config; } public boolean open() { Shell parent = getParent(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE); shell.setText(getText()); createDialogArea(shell); shell.pack(); // center window Rectangle r1 = parent.getBounds(); Rectangle r2 = shell.getBounds(); int x = r1.x + (r1.width - r2.width) / 2; int y = r1.y + (r1.height - r2.height) / 2; shell.setBounds(x, y, r2.width, r2.height); shell.open(); Display display = parent.getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return result; } protected void createDialogArea(Composite parent) { parent.setLayout(new GridLayout(2, false)); GridData gd; Label l1 = new Label(parent, SWT.NONE); l1.setText(Messages.RemoteIncludeDialog_directory); l1.setLayoutData(gd = new GridData()); gd.horizontalSpan = 2; text = new Text(parent, SWT.SINGLE | SWT.BORDER); text.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL)); gd.widthHint = 300; text.setText(pathText == null ? "" : pathText); //$NON-NLS-1$ b_browse = new Button(parent, SWT.PUSH); b_browse.setText(Messages.RemoteIncludeDialog_browse); b_browse.addSelectionListener(listener); b_browse.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); new Label(parent, SWT.NONE); b_vars = new Button(parent, SWT.PUSH); b_vars.setText(Messages.RemoteIncludeDialog_vars); b_vars.addSelectionListener(listener); b_vars.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); b_add2confs = new Button(parent, SWT.CHECK); b_add2confs.setText(Messages.RemoteIncludeDialog_configurations); b_add2confs.setVisible(!isEdit); b_add2confs.setLayoutData(gd = new GridData()); gd.horizontalSpan = 2; b_add2langs = new Button(parent, SWT.CHECK); b_add2langs.setText(Messages.RemoteIncludeDialog_languages); b_add2langs.setVisible(!isEdit); b_add2langs.setLayoutData(gd = new GridData()); gd.horizontalSpan = 2; b_ok = new Button(parent, SWT.PUSH); b_ok.setText(Messages.RemoteIncludeDialog_ok); b_ok.addSelectionListener(listener); b_ok.setLayoutData(gd = new GridData()); gd.widthHint = 80; gd.horizontalAlignment = SWT.END; b_cancel = new Button(parent, SWT.PUSH); b_cancel.setText(Messages.RemoteIncludeDialog_cancel); b_cancel.addSelectionListener(listener); b_cancel.setLayoutData(gd = new GridData()); gd.widthHint = 80; } public void setPathText(String path) { this.pathText = path; } private final SelectionListener listener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { Widget pressed = e.widget; if (pressed.equals(b_ok)) { directory = text.getText(); isAllConfigurations = b_add2confs.getSelection(); isAllLanguages = b_add2langs.getSelection(); result = true; shell.dispose(); } else if (pressed.equals(b_cancel)) { result = false; shell.dispose(); } else if (pressed.equals(b_browse)) { if (fHost != null) { SystemRemoteFolderDialog folderDialog = new SystemRemoteFolderDialog(shell, Messages.RemoteIncludeDialog_select, fHost); folderDialog.setShowNewConnectionPrompt(false); folderDialog.open(); Object remoteObject = folderDialog.getSelectedObject(); if (folderDialog.wasCancelled()) { return; } if (remoteObject instanceof IRemoteFile) { IRemoteFile folder = (IRemoteFile) remoteObject; text.setText(folder.getCanonicalPath()); } else { // the default directory is the home directory which is a type of SystemFilterReference. String homeDir = ((SystemFilterReference) remoteObject).getSubSystem().getConnectorService().getHomeDirectory(); text.setText(homeDir); } } else { IRemoteUIConnectionManager connMgr = getUIConnectionManager(); if (connMgr != null) { connMgr.openConnectionWithProgress(shell, null, fRemoteConnection); - if (fRemoteConnection.isOpen()) { - IRemoteUIFileManager fileMgr = getUIFileManager(); - if (fileMgr != null) { - fileMgr.setConnection(fRemoteConnection); - String path = fileMgr.browseDirectory(shell, Messages.RemoteIncludeDialog_select, "", 0); //$NON-NLS-1$ - if (path != null) { - text.setText(path); - } + } + if (fRemoteConnection.isOpen()) { + IRemoteUIFileManager fileMgr = getUIFileManager(); + if (fileMgr != null) { + fileMgr.setConnection(fRemoteConnection); + String path = fileMgr.browseDirectory(shell, Messages.RemoteIncludeDialog_select, "", 0); //$NON-NLS-1$ + if (path != null) { + text.setText(path); } } } } } else if (pressed.equals(b_vars)) { String s = AbstractCPropertyTab.getVariableDialog(shell, config); if (s != null) text.insert(s); } } }; public String getDirectory() { return directory; } public boolean isAllLanguages() { return isAllLanguages; } public boolean isAllConfigurations() { return isAllConfigurations; } public void setHost(IHost host) { fHost = host; } /** * @since 2.0 */ public void setConnection(IRemoteConnection connection) { fRemoteConnection = connection; } private IRemoteUIFileManager getUIFileManager() { if (fRemoteConnection != null) { return RemoteUIServices.getRemoteUIServices(fRemoteConnection.getRemoteServices()).getUIFileManager(); } return null; } private IRemoteUIConnectionManager getUIConnectionManager() { if (fRemoteConnection != null) { return RemoteUIServices.getRemoteUIServices(fRemoteConnection.getRemoteServices()) .getUIConnectionManager(); } return null; } }
true
true
public void widgetSelected(SelectionEvent e) { Widget pressed = e.widget; if (pressed.equals(b_ok)) { directory = text.getText(); isAllConfigurations = b_add2confs.getSelection(); isAllLanguages = b_add2langs.getSelection(); result = true; shell.dispose(); } else if (pressed.equals(b_cancel)) { result = false; shell.dispose(); } else if (pressed.equals(b_browse)) { if (fHost != null) { SystemRemoteFolderDialog folderDialog = new SystemRemoteFolderDialog(shell, Messages.RemoteIncludeDialog_select, fHost); folderDialog.setShowNewConnectionPrompt(false); folderDialog.open(); Object remoteObject = folderDialog.getSelectedObject(); if (folderDialog.wasCancelled()) { return; } if (remoteObject instanceof IRemoteFile) { IRemoteFile folder = (IRemoteFile) remoteObject; text.setText(folder.getCanonicalPath()); } else { // the default directory is the home directory which is a type of SystemFilterReference. String homeDir = ((SystemFilterReference) remoteObject).getSubSystem().getConnectorService().getHomeDirectory(); text.setText(homeDir); } } else { IRemoteUIConnectionManager connMgr = getUIConnectionManager(); if (connMgr != null) { connMgr.openConnectionWithProgress(shell, null, fRemoteConnection); if (fRemoteConnection.isOpen()) { IRemoteUIFileManager fileMgr = getUIFileManager(); if (fileMgr != null) { fileMgr.setConnection(fRemoteConnection); String path = fileMgr.browseDirectory(shell, Messages.RemoteIncludeDialog_select, "", 0); //$NON-NLS-1$ if (path != null) { text.setText(path); } } } } } } else if (pressed.equals(b_vars)) { String s = AbstractCPropertyTab.getVariableDialog(shell, config); if (s != null) text.insert(s); } }
public void widgetSelected(SelectionEvent e) { Widget pressed = e.widget; if (pressed.equals(b_ok)) { directory = text.getText(); isAllConfigurations = b_add2confs.getSelection(); isAllLanguages = b_add2langs.getSelection(); result = true; shell.dispose(); } else if (pressed.equals(b_cancel)) { result = false; shell.dispose(); } else if (pressed.equals(b_browse)) { if (fHost != null) { SystemRemoteFolderDialog folderDialog = new SystemRemoteFolderDialog(shell, Messages.RemoteIncludeDialog_select, fHost); folderDialog.setShowNewConnectionPrompt(false); folderDialog.open(); Object remoteObject = folderDialog.getSelectedObject(); if (folderDialog.wasCancelled()) { return; } if (remoteObject instanceof IRemoteFile) { IRemoteFile folder = (IRemoteFile) remoteObject; text.setText(folder.getCanonicalPath()); } else { // the default directory is the home directory which is a type of SystemFilterReference. String homeDir = ((SystemFilterReference) remoteObject).getSubSystem().getConnectorService().getHomeDirectory(); text.setText(homeDir); } } else { IRemoteUIConnectionManager connMgr = getUIConnectionManager(); if (connMgr != null) { connMgr.openConnectionWithProgress(shell, null, fRemoteConnection); } if (fRemoteConnection.isOpen()) { IRemoteUIFileManager fileMgr = getUIFileManager(); if (fileMgr != null) { fileMgr.setConnection(fRemoteConnection); String path = fileMgr.browseDirectory(shell, Messages.RemoteIncludeDialog_select, "", 0); //$NON-NLS-1$ if (path != null) { text.setText(path); } } } } } else if (pressed.equals(b_vars)) { String s = AbstractCPropertyTab.getVariableDialog(shell, config); if (s != null) text.insert(s); } }
diff --git a/extensions/bundles/queuemanager/src/main/java/org/opennaas/extensions/queuemanager/shell/RemoveCommand.java b/extensions/bundles/queuemanager/src/main/java/org/opennaas/extensions/queuemanager/shell/RemoveCommand.java index fa1233591..bccbd5299 100644 --- a/extensions/bundles/queuemanager/src/main/java/org/opennaas/extensions/queuemanager/shell/RemoveCommand.java +++ b/extensions/bundles/queuemanager/src/main/java/org/opennaas/extensions/queuemanager/shell/RemoveCommand.java @@ -1,68 +1,68 @@ package org.opennaas.extensions.queuemanager.shell; import org.apache.felix.gogo.commands.Argument; import org.apache.felix.gogo.commands.Command; import org.opennaas.core.resources.IResource; import org.opennaas.core.resources.IResourceIdentifier; import org.opennaas.core.resources.IResourceManager; import org.opennaas.core.resources.capability.ICapability; import org.opennaas.core.resources.command.Response; import org.opennaas.core.resources.queue.ModifyParams; import org.opennaas.core.resources.queue.QueueConstants; import org.opennaas.core.resources.shell.GenericKarafCommand; import org.opennaas.extensions.queuemanager.QueueManager; @Command(scope = "queue", name = "remove", description = "Remove an action from the queue") public class RemoveCommand extends GenericKarafCommand { @Argument(index = 0, name = "resourceType:resourceName", description = "Name of the resource owning the queue", required = true, multiValued = false) private String resourceId; @Argument(index = 1, name = "posQueue", description = "Position in the queue of the action to remove", required = true, multiValued = false) private int posQueue; @Override protected Object doExecute() throws Exception { printInitCommand("Remove action from queue"); try { IResourceManager manager = getResourceManager(); String[] argsRouterName = new String[2]; try { argsRouterName = splitResourceName(resourceId); } catch (Exception e) { printError(e.getMessage()); printEndCommand(); return -1; } IResourceIdentifier resourceIdentifier = null; resourceIdentifier = manager.getIdentifierFromResourceName(argsRouterName[0], argsRouterName[1]); /* validate resource identifier */ if (resourceIdentifier == null) { printError("Could not get resource with name: " + argsRouterName[0] + ":" + argsRouterName[1]); printEndCommand(); return -1; } IResource resource = manager.getResource(resourceIdentifier); validateResource(resource); ICapability queue = getCapability(resource.getCapabilities(), QueueManager.QUEUE); // printSymbol("Removing action " + posQueue + "..."); ModifyParams params = ModifyParams.newRemoveOperation(posQueue); Response resp = (Response) queue.sendMessage(QueueConstants.MODIFY, params); - printResponseStatus(resp); + printResponseStatus(resp, resourceId); } catch (Exception e) { printError("Error removing action from queue."); printError(e); printEndCommand(); return -1; } printEndCommand(); return null; } }
true
true
protected Object doExecute() throws Exception { printInitCommand("Remove action from queue"); try { IResourceManager manager = getResourceManager(); String[] argsRouterName = new String[2]; try { argsRouterName = splitResourceName(resourceId); } catch (Exception e) { printError(e.getMessage()); printEndCommand(); return -1; } IResourceIdentifier resourceIdentifier = null; resourceIdentifier = manager.getIdentifierFromResourceName(argsRouterName[0], argsRouterName[1]); /* validate resource identifier */ if (resourceIdentifier == null) { printError("Could not get resource with name: " + argsRouterName[0] + ":" + argsRouterName[1]); printEndCommand(); return -1; } IResource resource = manager.getResource(resourceIdentifier); validateResource(resource); ICapability queue = getCapability(resource.getCapabilities(), QueueManager.QUEUE); // printSymbol("Removing action " + posQueue + "..."); ModifyParams params = ModifyParams.newRemoveOperation(posQueue); Response resp = (Response) queue.sendMessage(QueueConstants.MODIFY, params); printResponseStatus(resp); } catch (Exception e) { printError("Error removing action from queue."); printError(e); printEndCommand(); return -1; } printEndCommand(); return null; }
protected Object doExecute() throws Exception { printInitCommand("Remove action from queue"); try { IResourceManager manager = getResourceManager(); String[] argsRouterName = new String[2]; try { argsRouterName = splitResourceName(resourceId); } catch (Exception e) { printError(e.getMessage()); printEndCommand(); return -1; } IResourceIdentifier resourceIdentifier = null; resourceIdentifier = manager.getIdentifierFromResourceName(argsRouterName[0], argsRouterName[1]); /* validate resource identifier */ if (resourceIdentifier == null) { printError("Could not get resource with name: " + argsRouterName[0] + ":" + argsRouterName[1]); printEndCommand(); return -1; } IResource resource = manager.getResource(resourceIdentifier); validateResource(resource); ICapability queue = getCapability(resource.getCapabilities(), QueueManager.QUEUE); // printSymbol("Removing action " + posQueue + "..."); ModifyParams params = ModifyParams.newRemoveOperation(posQueue); Response resp = (Response) queue.sendMessage(QueueConstants.MODIFY, params); printResponseStatus(resp, resourceId); } catch (Exception e) { printError("Error removing action from queue."); printError(e); printEndCommand(); return -1; } printEndCommand(); return null; }
diff --git a/src/Steganography.java b/src/Steganography.java index f31ec45..3a6774a 100644 --- a/src/Steganography.java +++ b/src/Steganography.java @@ -1,171 +1,171 @@ import org.spongycastle.crypto.digests.SHA256Digest; import org.spongycastle.crypto.engines.ISAACEngine; import org.spongycastle.crypto.params.KeyParameter; import org.spongycastle.crypto.prng.RandomGenerator; import org.spongycastle.crypto.StreamCipher; import org.spongycastle.jce.provider.BouncyCastleProvider; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @title Steganography Research and Proof of Concept * * @author GNU USER * */ public class Steganography { static { // Set bouncy castle as the most preferred security provider Security.insertProviderAt(new BouncyCastleProvider(), 1); } /* * are_same A function which checks if two array of bytes are identical * * @param a first array of bytes * @param b first array of bytes * * @return boolean, true if identical */ public boolean are_same( byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i != a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } /* * Generates a random number given an input value and populates the random output buffer * NOTE: Both the input and output byte arrays must be the same size, ideally you should just * * @param engine The ISAAC engine object to use * @param output The output buffer to populate with the random number public void nextBytes(ISAACEngine engine, byte[] output) { byte[] in = new byte[output.length]; // Generate the random number and store in output engine.processBytes(in, 0, in.length, output, 0); }*/ /*private void doTest(ISAACEngine engine, byte[] seed, byte[] output) { byte[] in = new byte[output.length]; byte[] = new byte[output.length]; engine.init(true, new KeyParameter(key)); engine.processBytes(in, 0, in.length, enc, 0); if (!areEqual(enc, output)) { fail("ciphertext mismatch"); } engine.init(false, new KeyParameter(key)); engine.processBytes(enc, 0, enc.length, enc, 0); if (!areEqual(enc, in)) { fail("plaintext mismatch"); } }*/ /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { byte[] seed = new byte[32]; byte[] random1 = new byte[32]; byte[] random2 = new byte[32]; int length = 0; boolean sequenceMatch = true; List<byte[]> randomSequence1 = new ArrayList(); List<byte[]> randomSequence2 = new ArrayList(); /* * Inititialize the seed derivative function parameters with the * parameters S1 & S2 */ SDFParameters paramSDF = new SDFParameters("test1", "test"); // Generate the seed using SHA256 digest SDFGenerator generatorSDF = new SDFGenerator(new SHA256Digest()); generatorSDF.init(paramSDF); length = generatorSDF.generateBytes(seed, 0, 0); System.out.println("LENGTH: " + length); System.out.println("SEED: " + new String(Hex.encode(seed))); /* * Simulate two seperate users generating a sequence of PRNs using the same shared seed SecureRandom random1 = new SecureRandom(seed); SecureRandom random2 = new SecureRandom(seed); random1.setSeed(seed); random2.setSeed(seed); // Display random generator info System.out.println(random1.getProvider()); System.out.println(random1.getAlgorithm()); */ /* * Simulate two separate users generating a sequence of random numbers using * a shared seed and the ISAAC stream cipher as the PRNG */ ISAACRandomGenerator isaac1 = new ISAACRandomGenerator(); ISAACRandomGenerator isaac2 = new ISAACRandomGenerator(); isaac1.init(new ISAACEngine(), seed); isaac2.init(new ISAACEngine(), seed); /* StreamCipher isaac1 = new ISAACEngine(); StreamCipher isaac2 = new ISAACEngine(); isaac1.init(true, new KeyParameter(seed)); isaac2.init(true, new KeyParameter(seed)); */ - for (int i = 0; i < 10; ++i) + for (int i = 0; i < 100000; ++i) { isaac1.nextBytes(random1); isaac2.nextBytes(random2); System.out.println("Random BYTES " + i + " BOB: " + new String(Hex.encode(random1))); System.out.println("Random BYTES " + i + " ALICE: " + new String(Hex.encode(random2))); System.out.println("Random number " + i + " BOB: " + new BigInteger(random1)); System.out.println("Random number " + i + " ALICE: " + new BigInteger(random2)); System.out.println("Random BIGINT" + i + " BOB: " + isaac1.nextBigInteger()); System.out.println("Random BIGINT" + i + " ALICE: " + isaac2.nextBigInteger()); } } }
true
true
public static void main(String[] args) throws InterruptedException { byte[] seed = new byte[32]; byte[] random1 = new byte[32]; byte[] random2 = new byte[32]; int length = 0; boolean sequenceMatch = true; List<byte[]> randomSequence1 = new ArrayList(); List<byte[]> randomSequence2 = new ArrayList(); /* * Inititialize the seed derivative function parameters with the * parameters S1 & S2 */ SDFParameters paramSDF = new SDFParameters("test1", "test"); // Generate the seed using SHA256 digest SDFGenerator generatorSDF = new SDFGenerator(new SHA256Digest()); generatorSDF.init(paramSDF); length = generatorSDF.generateBytes(seed, 0, 0); System.out.println("LENGTH: " + length); System.out.println("SEED: " + new String(Hex.encode(seed))); /* * Simulate two seperate users generating a sequence of PRNs using the same shared seed SecureRandom random1 = new SecureRandom(seed); SecureRandom random2 = new SecureRandom(seed); random1.setSeed(seed); random2.setSeed(seed); // Display random generator info System.out.println(random1.getProvider()); System.out.println(random1.getAlgorithm()); */ /* * Simulate two separate users generating a sequence of random numbers using * a shared seed and the ISAAC stream cipher as the PRNG */ ISAACRandomGenerator isaac1 = new ISAACRandomGenerator(); ISAACRandomGenerator isaac2 = new ISAACRandomGenerator(); isaac1.init(new ISAACEngine(), seed); isaac2.init(new ISAACEngine(), seed); /* StreamCipher isaac1 = new ISAACEngine(); StreamCipher isaac2 = new ISAACEngine(); isaac1.init(true, new KeyParameter(seed)); isaac2.init(true, new KeyParameter(seed)); */ for (int i = 0; i < 10; ++i) { isaac1.nextBytes(random1); isaac2.nextBytes(random2); System.out.println("Random BYTES " + i + " BOB: " + new String(Hex.encode(random1))); System.out.println("Random BYTES " + i + " ALICE: " + new String(Hex.encode(random2))); System.out.println("Random number " + i + " BOB: " + new BigInteger(random1)); System.out.println("Random number " + i + " ALICE: " + new BigInteger(random2)); System.out.println("Random BIGINT" + i + " BOB: " + isaac1.nextBigInteger()); System.out.println("Random BIGINT" + i + " ALICE: " + isaac2.nextBigInteger()); } }
public static void main(String[] args) throws InterruptedException { byte[] seed = new byte[32]; byte[] random1 = new byte[32]; byte[] random2 = new byte[32]; int length = 0; boolean sequenceMatch = true; List<byte[]> randomSequence1 = new ArrayList(); List<byte[]> randomSequence2 = new ArrayList(); /* * Inititialize the seed derivative function parameters with the * parameters S1 & S2 */ SDFParameters paramSDF = new SDFParameters("test1", "test"); // Generate the seed using SHA256 digest SDFGenerator generatorSDF = new SDFGenerator(new SHA256Digest()); generatorSDF.init(paramSDF); length = generatorSDF.generateBytes(seed, 0, 0); System.out.println("LENGTH: " + length); System.out.println("SEED: " + new String(Hex.encode(seed))); /* * Simulate two seperate users generating a sequence of PRNs using the same shared seed SecureRandom random1 = new SecureRandom(seed); SecureRandom random2 = new SecureRandom(seed); random1.setSeed(seed); random2.setSeed(seed); // Display random generator info System.out.println(random1.getProvider()); System.out.println(random1.getAlgorithm()); */ /* * Simulate two separate users generating a sequence of random numbers using * a shared seed and the ISAAC stream cipher as the PRNG */ ISAACRandomGenerator isaac1 = new ISAACRandomGenerator(); ISAACRandomGenerator isaac2 = new ISAACRandomGenerator(); isaac1.init(new ISAACEngine(), seed); isaac2.init(new ISAACEngine(), seed); /* StreamCipher isaac1 = new ISAACEngine(); StreamCipher isaac2 = new ISAACEngine(); isaac1.init(true, new KeyParameter(seed)); isaac2.init(true, new KeyParameter(seed)); */ for (int i = 0; i < 100000; ++i) { isaac1.nextBytes(random1); isaac2.nextBytes(random2); System.out.println("Random BYTES " + i + " BOB: " + new String(Hex.encode(random1))); System.out.println("Random BYTES " + i + " ALICE: " + new String(Hex.encode(random2))); System.out.println("Random number " + i + " BOB: " + new BigInteger(random1)); System.out.println("Random number " + i + " ALICE: " + new BigInteger(random2)); System.out.println("Random BIGINT" + i + " BOB: " + isaac1.nextBigInteger()); System.out.println("Random BIGINT" + i + " ALICE: " + isaac2.nextBigInteger()); } }
diff --git a/chunker/src/main/java/eu/monnetproject/translation/chunker/ExhaustiveChunker.java b/chunker/src/main/java/eu/monnetproject/translation/chunker/ExhaustiveChunker.java index 42a428f..bed5688 100644 --- a/chunker/src/main/java/eu/monnetproject/translation/chunker/ExhaustiveChunker.java +++ b/chunker/src/main/java/eu/monnetproject/translation/chunker/ExhaustiveChunker.java @@ -1,80 +1,79 @@ /********************************************************************************** * Copyright (c) 2011, Monnet Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Monnet Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE MONNET PROJECT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *********************************************************************************/ package eu.monnetproject.translation.chunker; import eu.monnetproject.translation.Chunk; import eu.monnetproject.translation.ChunkList; import eu.monnetproject.translation.Label; import eu.monnetproject.translation.LanguageModel; import eu.monnetproject.translation.TranslationPhraseChunker; import eu.monnetproject.translation.monitor.Messages; import java.util.Arrays; /** * * @author John McCrae */ public class ExhaustiveChunker implements TranslationPhraseChunker { private final LanguageModel lm; public ExhaustiveChunker(LanguageModel lm) { this.lm = lm; } @Override public ChunkList chunk(Label label) { ChunkListImpl rval = new ChunkListImpl(); final String[] tokens = FairlyGoodTokenizer.split(label.asString()); for(int i = 0; i < tokens.length; i++) { final String lowerCaseTk = tokens[i].toLowerCase(); if(!tokens[i].equals(lowerCaseTk)) { final double origCaseScore = lm.score(Arrays.asList(tokens[i])); final double lowerCaseScore = lm.score(Arrays.asList(lowerCaseTk)); if(lowerCaseScore - origCaseScore > 1.5) { - Messages.severe(tokens[i] + "/" + lowerCaseTk); - tokens[i] = lowerCaseTk; + //tokens[i] = lowerCaseTk; } } } for(int i = 0; i < tokens.length; i++) { for(int j = i+1; j <= tokens.length; j++) { final Chunk chunk = new ChunkImpl(build(tokens,i,j)); rval.add(chunk); } } return rval; } private String build(String[] str, int begin, int end) { final StringBuilder builder = new StringBuilder(); for(int i = begin; i < end; i++) { builder.append(str[i]).append(" "); } return builder.toString().trim(); } }
true
true
public ChunkList chunk(Label label) { ChunkListImpl rval = new ChunkListImpl(); final String[] tokens = FairlyGoodTokenizer.split(label.asString()); for(int i = 0; i < tokens.length; i++) { final String lowerCaseTk = tokens[i].toLowerCase(); if(!tokens[i].equals(lowerCaseTk)) { final double origCaseScore = lm.score(Arrays.asList(tokens[i])); final double lowerCaseScore = lm.score(Arrays.asList(lowerCaseTk)); if(lowerCaseScore - origCaseScore > 1.5) { Messages.severe(tokens[i] + "/" + lowerCaseTk); tokens[i] = lowerCaseTk; } } } for(int i = 0; i < tokens.length; i++) { for(int j = i+1; j <= tokens.length; j++) { final Chunk chunk = new ChunkImpl(build(tokens,i,j)); rval.add(chunk); } } return rval; }
public ChunkList chunk(Label label) { ChunkListImpl rval = new ChunkListImpl(); final String[] tokens = FairlyGoodTokenizer.split(label.asString()); for(int i = 0; i < tokens.length; i++) { final String lowerCaseTk = tokens[i].toLowerCase(); if(!tokens[i].equals(lowerCaseTk)) { final double origCaseScore = lm.score(Arrays.asList(tokens[i])); final double lowerCaseScore = lm.score(Arrays.asList(lowerCaseTk)); if(lowerCaseScore - origCaseScore > 1.5) { //tokens[i] = lowerCaseTk; } } } for(int i = 0; i < tokens.length; i++) { for(int j = i+1; j <= tokens.length; j++) { final Chunk chunk = new ChunkImpl(build(tokens,i,j)); rval.add(chunk); } } return rval; }
diff --git a/com.retech.reader/trunk/com.retech.reader.web/src/main/java/com/retech/reader/web/client/mobile/ui/ContentEditor.java b/com.retech.reader/trunk/com.retech.reader.web/src/main/java/com/retech/reader/web/client/mobile/ui/ContentEditor.java index ca026968..21ce0e2f 100644 --- a/com.retech.reader/trunk/com.retech.reader.web/src/main/java/com/retech/reader/web/client/mobile/ui/ContentEditor.java +++ b/com.retech.reader/trunk/com.retech.reader.web/src/main/java/com/retech/reader/web/client/mobile/ui/ContentEditor.java @@ -1,511 +1,512 @@ package com.retech.reader.web.client.mobile.ui; import com.goodow.wave.bootstrap.shared.MapBinder; import com.goodow.wave.client.shell.WaveShell; import com.goodow.wave.client.wavepanel.WavePanel; import com.google.gwt.activity.shared.Activity; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.dom.client.Touch; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.DragEndEvent; import com.google.gwt.event.dom.client.DragEndHandler; import com.google.gwt.event.dom.client.DragOverEvent; import com.google.gwt.event.dom.client.DragOverHandler; import com.google.gwt.event.dom.client.DragStartEvent; import com.google.gwt.event.dom.client.DragStartHandler; import com.google.gwt.event.dom.client.GestureChangeEvent; import com.google.gwt.event.dom.client.GestureChangeHandler; import com.google.gwt.event.dom.client.TouchEndEvent; import com.google.gwt.event.dom.client.TouchEndHandler; import com.google.gwt.event.dom.client.TouchMoveEvent; import com.google.gwt.event.dom.client.TouchMoveHandler; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.dom.client.TouchStartHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.inject.client.AsyncProvider; import com.google.gwt.logging.client.LogConfiguration; import com.google.gwt.place.shared.PlaceController; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import com.google.web.bindery.requestfactory.shared.EntityProxyId; import com.google.web.bindery.requestfactory.shared.Request; import com.retech.reader.web.client.style.ReaderResources; import com.retech.reader.web.shared.proxy.IssueProxy; import com.retech.reader.web.shared.proxy.PageProxy; import com.retech.reader.web.shared.proxy.ResourceProxy; import com.retech.reader.web.shared.proxy.SectionProxy; import com.retech.reader.web.shared.rpc.ReaderFactory; import org.cloudlet.web.mvp.shared.BasePlace; import org.cloudlet.web.service.shared.KeyUtil; import org.cloudlet.web.service.shared.LocalStorage; import org.cloudlet.web.service.shared.rpc.BaseReceiver; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; @Singleton public class ContentEditor extends WavePanel implements Activity { public static final String LAST_PAGE = "now_reader"; private static final int TOPBAR_TOP = -40; private static final Logger logger = Logger.getLogger(ContentEditor.class.getName()); private final HTML html; private FlowPanel flowPanel; private SectionBrowserView sectionView; private final PlaceController placeContorller; private final ReaderFactory f; private List<PageProxy> pages; private List<SectionProxy> sections; private PageProxy proxy; private int sectionIndex; private int pageIndex; int contentHeight; int contentWidth; private final Provider<BasePlace> place; private final LocalStorage storage; private final KeyUtil keyUtil; private final MapBinder<String, IsWidget> isWidgetMapBinder; private final WaveShell waveShell; private int columnCount; private int columnIndex = 1; private boolean scheduledTwo = false; private boolean scheduledOne = false; private boolean scheduledGesture = false; private int startX1; private int startX2; private int startScale; @Inject public ContentEditor(final PlaceController placeContorller, final ReaderFactory f, final Provider<BasePlace> place, final LocalStorage storage, final KeyUtil keyUtil, final MapBinder<String, IsWidget> isWidgetMapBinder, final WaveShell waveShell) { this.placeContorller = placeContorller; this.f = f; this.place = place; this.storage = storage; this.keyUtil = keyUtil; this.waveShell = waveShell; this.isWidgetMapBinder = isWidgetMapBinder; flowPanel = new FlowPanel(); html = new HTML(); html.addStyleName(ReaderResources.INSTANCE().style().contentHtmlPanel()); this.getElement().getStyle().setMarginTop(1, Unit.EM); flowPanel.add(html); this.setWaveContent(flowPanel); this.addDomHandler(new TouchStartHandler() { @Override public void onTouchStart(final TouchStartEvent event) { JsArray<Touch> touchesStart = event.getTouches(); switch (touchesStart.length()) { case 2: // logger.info("touches: 2 "); scheduledTwo = false; scheduledOne = true; Touch touch1 = touchesStart.get(0); Touch touch2 = touchesStart.get(1); startX1 = touch1.getPageX(); startX2 = touch2.getPageX(); break; case 1: // logger.info("touches: 1 "); scheduledOne = false; scheduledTwo = true; Touch touch = touchesStart.get(0); startX1 = touch.getPageX(); columnCount = html.getElement().getScrollWidth() / contentWidth; // logger.info("columnCount:" + columnCount); break; default: break; } } }, TouchStartEvent.getType()); this.addDomHandler(new TouchMoveHandler() { @Override public void onTouchMove(final TouchMoveEvent event) { event.preventDefault(); JsArray<Touch> touchesMove = event.getTouches(); switch (touchesMove.length()) { case 2: - scheduledGesture = true; if (scheduledTwo || !scheduledOne) { return; } scheduledTwo = true; // logger.info("touch 2 move"); Touch touch1 = touchesMove.get(0); Touch touch2 = touchesMove.get(1); int nowX1 = touch1.getPageX(); int nowX2 = touch2.getPageX(); int subtractX1 = nowX1 - startX1; int subtractX2 = nowX2 - startX2; if (subtractX1 > 0 && subtractX2 > 0) { + // scheduledGesture = true; sectionView.getElement().getStyle().setWidth(100, Unit.PCT); return; } else if (subtractX1 < 0 && subtractX2 < 0) { + // scheduledGesture = true; sectionView.getElement().getStyle().setWidth(0, Unit.PX); return; } break; case 1: if (scheduledOne || !scheduledTwo) { return; } scheduledOne = true; // logger.info("touch 1 move"); Touch touch = touchesMove.get(0); int nowX = touch.getPageX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); break; default: break; } } }, TouchMoveEvent.getType()); this.addDomHandler(new TouchEndHandler() { @Override public void onTouchEnd(final TouchEndEvent event) { // JsArray<Touch> touchesMove = event.getTouches(); // logger.info("onTouchEnd fingers:" + touchesMove.length()); scheduledOne = false; scheduledTwo = false; scheduledGesture = false; } }, TouchEndEvent.getType()); - this.addDomHandler(new GestureChangeHandler() { + flowPanel.addDomHandler(new GestureChangeHandler() { @Override public void onGestureChange(final GestureChangeEvent event) { - if (scheduledGesture || scheduledGesture) { + if (scheduledGesture) { return; } logger.info("scale:" + event.getScale() + ";rotation:" + event.getRotation()); } }, GestureChangeEvent.getType()); html.getElement().setDraggable("true"); html.addDomHandler(new DragStartHandler() { @Override public void onDragStart(final DragStartEvent event) { scheduledOne = false; startX1 = event.getNativeEvent().getClientX(); columnCount = html.getElement().getScrollWidth() / contentWidth; } }, DragStartEvent.getType()); html.addDomHandler(new DragOverHandler() { @Override public void onDragOver(final DragOverEvent event) { if (scheduledOne) { return; } scheduledOne = true; int nowX = event.getNativeEvent().getClientX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); } }, DragOverEvent.getType()); html.addDomHandler(new DragEndHandler() { @Override public void onDragEnd(final DragEndEvent event) { scheduledOne = false; } }, DragEndEvent.getType()); flowPanel.addDomHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { int offsetHeight = html.getOffsetHeight(); int offsetWidth = html.getOffsetWidth(); int clientX = event.getClientX(); int clientY = event.getClientY(); if (clientY >= offsetHeight * 0.25 && clientY <= offsetHeight * 0.75 && clientX >= offsetWidth * 0.25 && clientX <= offsetWidth * 0.75) { Style style = waveShell.getTopBar().getElement().getStyle(); if (style.getTop().equals(TOPBAR_TOP + "px")) { style.clearTop(); style.setOpacity(1); } else { style.setTop(TOPBAR_TOP, Unit.PX); style.clearOpacity(); } } } }, ClickEvent.getType()); // html.addClickHandler(new ClickHandler() { // // @Override // public void onClick(final ClickEvent event) { // int offsetWidth = event.getRelativeElement().getOffsetWidth(); // int x = event.getX(); // goTo(x > offsetWidth / 2 ? 1 : -1); // logger.info(html.getElement().getScrollWidth() + ""); // logger.info((html.getElement().getScrollWidth() - contentWidth) / contentWidth + 1 + ""); // } // // }); } @Override public String mayStop() { return null; } @Override public void onCancel() { } @Override public void onStop() { } @Override public void start(final AcceptsOneWidget panel, final EventBus eventBus) { waveShell.getTopBar().addStyleName(ReaderResources.INSTANCE().style().contentTopBar()); waveShell.getTopBar().getElement().getStyle().setTop(TOPBAR_TOP, Unit.PX); // contentHeight = Window.getClientHeight() - 73; contentHeight = Window.getClientHeight() - 39 - 16; contentWidth = Window.getClientWidth() - 14; Style htmlStyle = html.getElement().getStyle(); htmlStyle.setHeight(contentHeight, Unit.PX); htmlStyle.setProperty("webkitColumnWidth", contentWidth + "px"); flowPanel.getElement().getParentElement().getStyle().setHeight(contentHeight, Unit.PX); // final EntityProxyId<IssueProxy> issueId = // ((BasePlace) placeContorller.getWhere()).getParam(IssueProxy.class); // if (issueId != null) { // PageProxy pageProxy = storage.get(keyUtil.proxyKey(issueId, LAST_PAGE)); // // if (pageProxy != null) { // pageStart(pageProxy); // Storage.getLocalStorageIfSupported().removeItem(keyUtil.proxyKey(issueId, LAST_PAGE)); // // placeContorller.goTo(place.get().setPath(ContentEditor.class.getName()).setParameter( // // pageProxy.stableId())); // return; // } // new BaseReceiver<IssueProxy>() { // // @Override // public void onSuccessAndCached(final IssueProxy issueProxy) { // // new BaseReceiver<PageProxy>() { // // @Override // public void onSuccessAndCached(final PageProxy pageProxy) { // pageStart(pageProxy); // } // // @Override // public Request<PageProxy> provideRequest() { // return f.pageContext().findFirstPageByIssue(issueProxy).with(PageProxy.WITH); // } // }.setKeyForProxy(issueId, PageProxy.class.getName()).fire(); // } // // @Override // public Request<IssueProxy> provideRequest() { // return f.find(issueId); // } // }.setKeyForProxy(issueId).fire(); // return; // } final EntityProxyId<PageProxy> pageId = ((BasePlace) placeContorller.getWhere()).getParam(PageProxy.class); new BaseReceiver<PageProxy>() { @Override public void onSuccessAndCached(final PageProxy pageProxy) { AsyncProvider<IsWidget> sectionBrowserView = isWidgetMapBinder.getAsyncProvider(SectionBrowserView.class.getName()); sectionBrowserView.get(new AsyncCallback<IsWidget>() { @Override public void onFailure(final Throwable caught) { if (LogConfiguration.loggingIsEnabled()) { logger.log(Level.WARNING, "加载" + SectionBrowserView.class.getName() + "失败. 请检查网络连接, 并刷新后重试", caught); } } @Override public void onSuccess(final IsWidget result) { sectionView = (SectionBrowserView) result.asWidget(); sectionView.addStyleName(ReaderResources.INSTANCE().style().contentSectionView()); sectionView.getElement().getStyle().setWidth(0, Unit.PX); sectionView.setIssueId(pageProxy.getSection().getIssue().stableId()); sectionView.start(panel, eventBus); flowPanel.add(sectionView); } }); pageStart(pageProxy); } @Override public Request<PageProxy> provideRequest() { return f.find(pageId).with(PageProxy.WITH); } }.setKeyForProxy(pageId).fire(); } @Override protected void onUnload() { super.onUnload(); this.waveShell.getTopBar().removeStyleName(ReaderResources.INSTANCE().style().contentTopBar()); this.waveShell.getTopBar().getElement().getStyle().clearTop(); this.sectionView.removeStyleName(ReaderResources.INSTANCE().style().contentSectionView()); this.sectionView.getElement().getStyle().clearWidth(); this.html.getElement().getStyle().clearLeft(); } private void changePageProxy(final PageProxy pageProxy) { placeContorller.goTo(place.get().setPath(ContentEditor.class.getName()).setParameter( pageProxy.stableId())); } private void display(final PageProxy pageProxy) { new BaseReceiver<ResourceProxy>() { @Override public void onSuccessAndCached(final ResourceProxy response) { ContentEditor.this.getWaveTitle().setText(proxy.getTitle()); html.setHTML(response.getDataString()); if (pageProxy.getPageNum() != 1) { storage.put(keyUtil.proxyAndKey(proxy.getSection().getIssue().stableId(), LAST_PAGE), proxy); } } @Override public Request<ResourceProxy> provideRequest() { return f.resource().getResource(proxy); } }.setKeyForProxy(proxy.stableId(), ResourceProxy.class.getName()).fire(); } private void findPages(final SectionProxy sectionProxy, final boolean isNextPage, final boolean isNextSection) { new BaseReceiver<List<PageProxy>>() { @Override public void onSuccessAndCached(final List<PageProxy> pages) { ContentEditor.this.pages = pages; if (isNextPage) { if (isNextSection) { changePageProxy(pages.get(0)); } else { changePageProxy(pages.get(pages.size() - 1)); } } } @Override public Request<List<PageProxy>> provideRequest() { return f.pageContext().findPagesBySection(sectionProxy).with(PageProxy.WITH); } }.setKeyForList(sectionProxy.stableId(), PageProxy.class.getName()).fire(); } private void goTo(final int offset) { pageIndex = pages.indexOf(proxy); int index = pageIndex + offset; if (index < 0) { nextSectionIndex(--sectionIndex, false); return; } else if (index + 1 > pages.size()) { nextSectionIndex(++sectionIndex, true); return; } PageProxy pageProxy = pages.get(index); changePageProxy(pageProxy); } private void gotoNextPageAndScrollNext(final int subtractX) { if (subtractX > 0 && columnIndex <= 1) { goTo(-1); return; } else if (subtractX < 0 && columnIndex >= columnCount) { goTo(1); columnIndex = 1; return; } html.getElement().getStyle().setLeft( -100 * ((subtractX > 0 ? --columnIndex : ++columnIndex) - 1), Unit.PCT); } private void nextSectionIndex(final int sectionIndex, final boolean isNextSection) { if (sectionIndex > sections.size() - 1 && pageIndex + 2 > pages.size()) { this.sectionIndex = sections.size() - 1; logger.info("最后一页"); return; } else if (sectionIndex < 0) { this.sectionIndex = 0; logger.info("第一页"); return; } findPages(sections.get(sectionIndex), true, isNextSection); } private void pageStart(final PageProxy pageProxy) { final SectionProxy sectionProxy = pageProxy.getSection(); IssueProxy issue = sectionProxy.getIssue(); this.proxy = pageProxy; display(pageProxy); new BaseReceiver<List<SectionProxy>>() { @Override public void onSuccessAndCached(final List<SectionProxy> sections) { ContentEditor.this.sections = sections; sectionIndex = sectionProxy.getSequence() - 1; } @Override public Request<List<SectionProxy>> provideRequest() { return f.section().findSectionByPage(pageProxy).with(SectionProxy.WITH); } }.setKeyForList(issue.stableId(), SectionProxy.class.getName()).fire(); findPages(sectionProxy, false, false); } }
false
true
public ContentEditor(final PlaceController placeContorller, final ReaderFactory f, final Provider<BasePlace> place, final LocalStorage storage, final KeyUtil keyUtil, final MapBinder<String, IsWidget> isWidgetMapBinder, final WaveShell waveShell) { this.placeContorller = placeContorller; this.f = f; this.place = place; this.storage = storage; this.keyUtil = keyUtil; this.waveShell = waveShell; this.isWidgetMapBinder = isWidgetMapBinder; flowPanel = new FlowPanel(); html = new HTML(); html.addStyleName(ReaderResources.INSTANCE().style().contentHtmlPanel()); this.getElement().getStyle().setMarginTop(1, Unit.EM); flowPanel.add(html); this.setWaveContent(flowPanel); this.addDomHandler(new TouchStartHandler() { @Override public void onTouchStart(final TouchStartEvent event) { JsArray<Touch> touchesStart = event.getTouches(); switch (touchesStart.length()) { case 2: // logger.info("touches: 2 "); scheduledTwo = false; scheduledOne = true; Touch touch1 = touchesStart.get(0); Touch touch2 = touchesStart.get(1); startX1 = touch1.getPageX(); startX2 = touch2.getPageX(); break; case 1: // logger.info("touches: 1 "); scheduledOne = false; scheduledTwo = true; Touch touch = touchesStart.get(0); startX1 = touch.getPageX(); columnCount = html.getElement().getScrollWidth() / contentWidth; // logger.info("columnCount:" + columnCount); break; default: break; } } }, TouchStartEvent.getType()); this.addDomHandler(new TouchMoveHandler() { @Override public void onTouchMove(final TouchMoveEvent event) { event.preventDefault(); JsArray<Touch> touchesMove = event.getTouches(); switch (touchesMove.length()) { case 2: scheduledGesture = true; if (scheduledTwo || !scheduledOne) { return; } scheduledTwo = true; // logger.info("touch 2 move"); Touch touch1 = touchesMove.get(0); Touch touch2 = touchesMove.get(1); int nowX1 = touch1.getPageX(); int nowX2 = touch2.getPageX(); int subtractX1 = nowX1 - startX1; int subtractX2 = nowX2 - startX2; if (subtractX1 > 0 && subtractX2 > 0) { sectionView.getElement().getStyle().setWidth(100, Unit.PCT); return; } else if (subtractX1 < 0 && subtractX2 < 0) { sectionView.getElement().getStyle().setWidth(0, Unit.PX); return; } break; case 1: if (scheduledOne || !scheduledTwo) { return; } scheduledOne = true; // logger.info("touch 1 move"); Touch touch = touchesMove.get(0); int nowX = touch.getPageX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); break; default: break; } } }, TouchMoveEvent.getType()); this.addDomHandler(new TouchEndHandler() { @Override public void onTouchEnd(final TouchEndEvent event) { // JsArray<Touch> touchesMove = event.getTouches(); // logger.info("onTouchEnd fingers:" + touchesMove.length()); scheduledOne = false; scheduledTwo = false; scheduledGesture = false; } }, TouchEndEvent.getType()); this.addDomHandler(new GestureChangeHandler() { @Override public void onGestureChange(final GestureChangeEvent event) { if (scheduledGesture || scheduledGesture) { return; } logger.info("scale:" + event.getScale() + ";rotation:" + event.getRotation()); } }, GestureChangeEvent.getType()); html.getElement().setDraggable("true"); html.addDomHandler(new DragStartHandler() { @Override public void onDragStart(final DragStartEvent event) { scheduledOne = false; startX1 = event.getNativeEvent().getClientX(); columnCount = html.getElement().getScrollWidth() / contentWidth; } }, DragStartEvent.getType()); html.addDomHandler(new DragOverHandler() { @Override public void onDragOver(final DragOverEvent event) { if (scheduledOne) { return; } scheduledOne = true; int nowX = event.getNativeEvent().getClientX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); } }, DragOverEvent.getType()); html.addDomHandler(new DragEndHandler() { @Override public void onDragEnd(final DragEndEvent event) { scheduledOne = false; } }, DragEndEvent.getType()); flowPanel.addDomHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { int offsetHeight = html.getOffsetHeight(); int offsetWidth = html.getOffsetWidth(); int clientX = event.getClientX(); int clientY = event.getClientY(); if (clientY >= offsetHeight * 0.25 && clientY <= offsetHeight * 0.75 && clientX >= offsetWidth * 0.25 && clientX <= offsetWidth * 0.75) { Style style = waveShell.getTopBar().getElement().getStyle(); if (style.getTop().equals(TOPBAR_TOP + "px")) { style.clearTop(); style.setOpacity(1); } else { style.setTop(TOPBAR_TOP, Unit.PX); style.clearOpacity(); } } } }, ClickEvent.getType()); // html.addClickHandler(new ClickHandler() { // // @Override // public void onClick(final ClickEvent event) { // int offsetWidth = event.getRelativeElement().getOffsetWidth(); // int x = event.getX(); // goTo(x > offsetWidth / 2 ? 1 : -1); // logger.info(html.getElement().getScrollWidth() + ""); // logger.info((html.getElement().getScrollWidth() - contentWidth) / contentWidth + 1 + ""); // } // // }); }
public ContentEditor(final PlaceController placeContorller, final ReaderFactory f, final Provider<BasePlace> place, final LocalStorage storage, final KeyUtil keyUtil, final MapBinder<String, IsWidget> isWidgetMapBinder, final WaveShell waveShell) { this.placeContorller = placeContorller; this.f = f; this.place = place; this.storage = storage; this.keyUtil = keyUtil; this.waveShell = waveShell; this.isWidgetMapBinder = isWidgetMapBinder; flowPanel = new FlowPanel(); html = new HTML(); html.addStyleName(ReaderResources.INSTANCE().style().contentHtmlPanel()); this.getElement().getStyle().setMarginTop(1, Unit.EM); flowPanel.add(html); this.setWaveContent(flowPanel); this.addDomHandler(new TouchStartHandler() { @Override public void onTouchStart(final TouchStartEvent event) { JsArray<Touch> touchesStart = event.getTouches(); switch (touchesStart.length()) { case 2: // logger.info("touches: 2 "); scheduledTwo = false; scheduledOne = true; Touch touch1 = touchesStart.get(0); Touch touch2 = touchesStart.get(1); startX1 = touch1.getPageX(); startX2 = touch2.getPageX(); break; case 1: // logger.info("touches: 1 "); scheduledOne = false; scheduledTwo = true; Touch touch = touchesStart.get(0); startX1 = touch.getPageX(); columnCount = html.getElement().getScrollWidth() / contentWidth; // logger.info("columnCount:" + columnCount); break; default: break; } } }, TouchStartEvent.getType()); this.addDomHandler(new TouchMoveHandler() { @Override public void onTouchMove(final TouchMoveEvent event) { event.preventDefault(); JsArray<Touch> touchesMove = event.getTouches(); switch (touchesMove.length()) { case 2: if (scheduledTwo || !scheduledOne) { return; } scheduledTwo = true; // logger.info("touch 2 move"); Touch touch1 = touchesMove.get(0); Touch touch2 = touchesMove.get(1); int nowX1 = touch1.getPageX(); int nowX2 = touch2.getPageX(); int subtractX1 = nowX1 - startX1; int subtractX2 = nowX2 - startX2; if (subtractX1 > 0 && subtractX2 > 0) { // scheduledGesture = true; sectionView.getElement().getStyle().setWidth(100, Unit.PCT); return; } else if (subtractX1 < 0 && subtractX2 < 0) { // scheduledGesture = true; sectionView.getElement().getStyle().setWidth(0, Unit.PX); return; } break; case 1: if (scheduledOne || !scheduledTwo) { return; } scheduledOne = true; // logger.info("touch 1 move"); Touch touch = touchesMove.get(0); int nowX = touch.getPageX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); break; default: break; } } }, TouchMoveEvent.getType()); this.addDomHandler(new TouchEndHandler() { @Override public void onTouchEnd(final TouchEndEvent event) { // JsArray<Touch> touchesMove = event.getTouches(); // logger.info("onTouchEnd fingers:" + touchesMove.length()); scheduledOne = false; scheduledTwo = false; scheduledGesture = false; } }, TouchEndEvent.getType()); flowPanel.addDomHandler(new GestureChangeHandler() { @Override public void onGestureChange(final GestureChangeEvent event) { if (scheduledGesture) { return; } logger.info("scale:" + event.getScale() + ";rotation:" + event.getRotation()); } }, GestureChangeEvent.getType()); html.getElement().setDraggable("true"); html.addDomHandler(new DragStartHandler() { @Override public void onDragStart(final DragStartEvent event) { scheduledOne = false; startX1 = event.getNativeEvent().getClientX(); columnCount = html.getElement().getScrollWidth() / contentWidth; } }, DragStartEvent.getType()); html.addDomHandler(new DragOverHandler() { @Override public void onDragOver(final DragOverEvent event) { if (scheduledOne) { return; } scheduledOne = true; int nowX = event.getNativeEvent().getClientX(); int subtractX = nowX - startX1; gotoNextPageAndScrollNext(subtractX); } }, DragOverEvent.getType()); html.addDomHandler(new DragEndHandler() { @Override public void onDragEnd(final DragEndEvent event) { scheduledOne = false; } }, DragEndEvent.getType()); flowPanel.addDomHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { int offsetHeight = html.getOffsetHeight(); int offsetWidth = html.getOffsetWidth(); int clientX = event.getClientX(); int clientY = event.getClientY(); if (clientY >= offsetHeight * 0.25 && clientY <= offsetHeight * 0.75 && clientX >= offsetWidth * 0.25 && clientX <= offsetWidth * 0.75) { Style style = waveShell.getTopBar().getElement().getStyle(); if (style.getTop().equals(TOPBAR_TOP + "px")) { style.clearTop(); style.setOpacity(1); } else { style.setTop(TOPBAR_TOP, Unit.PX); style.clearOpacity(); } } } }, ClickEvent.getType()); // html.addClickHandler(new ClickHandler() { // // @Override // public void onClick(final ClickEvent event) { // int offsetWidth = event.getRelativeElement().getOffsetWidth(); // int x = event.getX(); // goTo(x > offsetWidth / 2 ? 1 : -1); // logger.info(html.getElement().getScrollWidth() + ""); // logger.info((html.getElement().getScrollWidth() - contentWidth) / contentWidth + 1 + ""); // } // // }); }
diff --git a/src/main/org/hornetq/core/remoting/impl/netty/NettyConnector.java b/src/main/org/hornetq/core/remoting/impl/netty/NettyConnector.java index 7fb56b17f..7c3ecfa34 100644 --- a/src/main/org/hornetq/core/remoting/impl/netty/NettyConnector.java +++ b/src/main/org/hornetq/core/remoting/impl/netty/NettyConnector.java @@ -1,719 +1,719 @@ /* * Copyright 2009 Red Hat, Inc. * Red Hat 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.hornetq.core.remoting.impl.netty; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import org.hornetq.api.core.HornetQException; import org.hornetq.core.logging.Logger; import org.hornetq.core.remoting.impl.ssl.SSLSupport; import org.hornetq.spi.core.protocol.ProtocolType; import org.hornetq.spi.core.remoting.BufferHandler; import org.hornetq.spi.core.remoting.Connection; import org.hornetq.spi.core.remoting.ConnectionLifeCycleListener; import org.hornetq.spi.core.remoting.Connector; import org.hornetq.utils.ConfigurationHelper; import org.hornetq.utils.Future; import org.hornetq.utils.VersionLoader; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.StaticChannelPipeline; import org.jboss.netty.channel.UpstreamMessageEvent; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.http.HttpTunnelingClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.Cookie; import org.jboss.netty.handler.codec.http.CookieDecoder; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultHttpRequest; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.util.Version; import org.jboss.netty.util.VirtualExecutorService; /** * A NettyConnector * * @author <a href="mailto:[email protected]">Tim Fox</a> * @author <a href="mailto:[email protected]">Trustin Lee</a> */ public class NettyConnector implements Connector { // Constants ----------------------------------------------------- private static final Logger log = Logger.getLogger(NettyConnector.class); // Attributes ---------------------------------------------------- private ClientSocketChannelFactory channelFactory; private ClientBootstrap bootstrap; private ChannelGroup channelGroup; private final BufferHandler handler; private final ConnectionLifeCycleListener listener; private final boolean sslEnabled; private final boolean httpEnabled; private final long httpMaxClientIdleTime; private final long httpClientIdleScanPeriod; private final boolean httpRequiresSessionId; private final boolean useNio; private final boolean useServlet; private final String host; private final int port; private final String keyStorePath; private final String keyStorePassword; private final boolean tcpNoDelay; private final int tcpSendBufferSize; private final int tcpReceiveBufferSize; private final long batchDelay; private final ConcurrentMap<Object, Connection> connections = new ConcurrentHashMap<Object, Connection>(); private final String servletPath; private final int nioRemotingThreads; private final VirtualExecutorService virtualExecutor; private final ScheduledExecutorService scheduledThreadPool; private final Executor closeExecutor; private BatchFlusher flusher; private ScheduledFuture<?> batchFlusherFuture; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- // Public -------------------------------------------------------- public NettyConnector(final Map<String, Object> configuration, final BufferHandler handler, final ConnectionLifeCycleListener listener, final Executor closeExecutor, final Executor threadPool, final ScheduledExecutorService scheduledThreadPool) { if (listener == null) { throw new IllegalArgumentException("Invalid argument null listener"); } if (handler == null) { throw new IllegalArgumentException("Invalid argument null handler"); } this.listener = listener; this.handler = handler; sslEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.SSL_ENABLED_PROP_NAME, TransportConstants.DEFAULT_SSL_ENABLED, configuration); httpEnabled = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_ENABLED_PROP_NAME, TransportConstants.DEFAULT_HTTP_ENABLED, configuration); servletPath = ConfigurationHelper.getStringProperty(TransportConstants.SERVLET_PATH, TransportConstants.DEFAULT_SERVLET_PATH, configuration); if (httpEnabled) { httpMaxClientIdleTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_PROP_NAME, TransportConstants.DEFAULT_HTTP_CLIENT_IDLE_TIME, configuration); httpClientIdleScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_CLIENT_IDLE_SCAN_PERIOD, TransportConstants.DEFAULT_HTTP_CLIENT_SCAN_PERIOD, configuration); httpRequiresSessionId = ConfigurationHelper.getBooleanProperty(TransportConstants.HTTP_REQUIRES_SESSION_ID, TransportConstants.DEFAULT_HTTP_REQUIRES_SESSION_ID, configuration); } else { httpMaxClientIdleTime = 0; httpClientIdleScanPeriod = -1; httpRequiresSessionId = false; } useNio = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_NIO_PROP_NAME, TransportConstants.DEFAULT_USE_NIO_CLIENT, configuration); nioRemotingThreads = ConfigurationHelper.getIntProperty(TransportConstants.NIO_REMOTING_THREADS_PROPNAME, -1, configuration); useServlet = ConfigurationHelper.getBooleanProperty(TransportConstants.USE_SERVLET_PROP_NAME, TransportConstants.DEFAULT_USE_SERVLET, configuration); host = ConfigurationHelper.getStringProperty(TransportConstants.HOST_PROP_NAME, TransportConstants.DEFAULT_HOST, configuration); port = ConfigurationHelper.getIntProperty(TransportConstants.PORT_PROP_NAME, TransportConstants.DEFAULT_PORT, configuration); if (sslEnabled) { keyStorePath = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH, configuration); keyStorePassword = ConfigurationHelper.getStringProperty(TransportConstants.KEYSTORE_PASSWORD_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PASSWORD, configuration); } else { keyStorePath = null; keyStorePassword = null; } tcpNoDelay = ConfigurationHelper.getBooleanProperty(TransportConstants.TCP_NODELAY_PROPNAME, TransportConstants.DEFAULT_TCP_NODELAY, configuration); tcpSendBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_SENDBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_SENDBUFFER_SIZE, configuration); tcpReceiveBufferSize = ConfigurationHelper.getIntProperty(TransportConstants.TCP_RECEIVEBUFFER_SIZE_PROPNAME, TransportConstants.DEFAULT_TCP_RECEIVEBUFFER_SIZE, configuration); batchDelay = ConfigurationHelper.getLongProperty(TransportConstants.BATCH_DELAY, TransportConstants.DEFAULT_BATCH_DELAY, configuration); this.closeExecutor = closeExecutor; virtualExecutor = new VirtualExecutorService(threadPool); this.scheduledThreadPool = scheduledThreadPool; } public synchronized void start() { if (channelFactory != null) { return; } if (useNio) { int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } channelFactory = new NioClientSocketChannelFactory(virtualExecutor, virtualExecutor, threadsToUse); } else { channelFactory = new OioClientSocketChannelFactory(virtualExecutor); } // if we are a servlet wrap the socketChannelFactory if (useServlet) { ClientSocketChannelFactory proxyChannelFactory = channelFactory; channelFactory = new HttpTunnelingClientSocketChannelFactory(proxyChannelFactory); } bootstrap = new ClientBootstrap(channelFactory); bootstrap.setOption("tcpNoDelay", tcpNoDelay); if (tcpReceiveBufferSize != -1) { bootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.setOption("sendBufferSize", tcpSendBufferSize); } bootstrap.setOption("keepAlive", true); bootstrap.setOption("reuseAddress", true); channelGroup = new DefaultChannelGroup("hornetq-connector"); final SSLContext context; if (sslEnabled) { try { context = SSLSupport.getInstance(true, keyStorePath, keyStorePassword, null, null); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException("Unable to create NettyConnector for " + host); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { bootstrap.setOption("sslContext", context); } bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { List<ChannelHandler> handlers = new ArrayList<ChannelHandler>(); - if (sslEnabled) + if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); SslHandler handler = new SslHandler(engine); handlers.add(handler); } if (httpEnabled) { handlers.add(new HttpRequestEncoder()); handlers.add(new HttpResponseDecoder()); handlers.add(new HttpHandler()); } handlers.add(new HornetQFrameDecoder2()); handlers.add(new HornetQClientChannelHandler(channelGroup, handler, new Listener())); ChannelPipeline pipeline = new StaticChannelPipeline(handlers.toArray(new ChannelHandler[handlers.size()])); return pipeline; } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } if (!Version.ID.equals(VersionLoader.getVersion().getNettyVersion())) { NettyConnector.log.warn("Unexpected Netty Version was expecting " + VersionLoader.getVersion() .getNettyVersion() + " using " + Version.ID); } NettyConnector.log.debug("Started Netty Connector version " + Version.ID); } public synchronized void close() { if (channelFactory == null) { return; } if (batchFlusherFuture != null) { batchFlusherFuture.cancel(false); flusher.cancel(); flusher = null; batchFlusherFuture = null; } bootstrap = null; channelGroup.close().awaitUninterruptibly(); channelFactory.releaseExternalResources(); channelFactory = null; for (Connection connection : connections.values()) { listener.connectionDestroyed(connection.getID()); } connections.clear(); } public boolean isStarted() { return channelFactory != null; } public Connection createConnection() { if (channelFactory == null) { return null; } SocketAddress address; if (useServlet) { try { URI uri = new URI("http", null, host, port, servletPath, null, null); bootstrap.setOption("serverName", uri.getHost()); bootstrap.setOption("serverPath", uri.getRawPath()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e.getMessage()); } } address = new InetSocketAddress(host, port); ChannelFuture future = bootstrap.connect(address); future.awaitUninterruptibly(); if (future.isSuccess()) { final Channel ch = future.getChannel(); SslHandler sslHandler = ch.getPipeline().get(SslHandler.class); if (sslHandler != null) { ChannelFuture handshakeFuture = sslHandler.handshake(); handshakeFuture.awaitUninterruptibly(); if (handshakeFuture.isSuccess()) { ch.getPipeline().get(HornetQChannelHandler.class).active = true; } else { ch.close().awaitUninterruptibly(); return null; } } else { ch.getPipeline().get(HornetQChannelHandler.class).active = true; } NettyConnection conn = new NettyConnection(ch, new Listener(), !httpEnabled && batchDelay > 0, false); return conn; } else { Throwable t = future.getCause(); if (t != null && !(t instanceof ConnectException)) { NettyConnector.log.error("Failed to create netty connection", future.getCause()); } return null; } } // Public -------------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- // Inner classes ------------------------------------------------- private final class HornetQClientChannelHandler extends HornetQChannelHandler { HornetQClientChannelHandler(final ChannelGroup group, final BufferHandler handler, final ConnectionLifeCycleListener listener) { super(group, handler, listener); } } class HttpHandler extends SimpleChannelHandler { private Channel channel; private long lastSendTime = 0; private boolean waitingGet = false; private HttpIdleTimer task; private final String url = "http://" + host + ":" + port + servletPath; private final Future handShakeFuture = new Future(); private boolean active = false; private boolean handshaking = false; private final CookieDecoder cookieDecoder = new CookieDecoder(); private String cookie; private final CookieEncoder cookieEncoder = new CookieEncoder(false); @Override public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { super.channelConnected(ctx, e); channel = e.getChannel(); if (httpClientIdleScanPeriod > 0) { task = new HttpIdleTimer(); java.util.concurrent.Future<?> future = scheduledThreadPool.scheduleAtFixedRate(task, httpClientIdleScanPeriod, httpClientIdleScanPeriod, TimeUnit.MILLISECONDS); task.setFuture(future); } } @Override public void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception { if (task != null) { task.close(); } super.channelClosed(ctx, e); } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { HttpResponse response = (HttpResponse)e.getMessage(); if (httpRequiresSessionId && !active) { Set<Cookie> cookieMap = cookieDecoder.decode(response.getHeader(HttpHeaders.Names.SET_COOKIE)); for (Cookie cookie : cookieMap) { if (cookie.getName().equals("JSESSIONID")) { cookieEncoder.addCookie(cookie); this.cookie = cookieEncoder.encode(); } } active = true; handShakeFuture.run(); } MessageEvent event = new UpstreamMessageEvent(e.getChannel(), response.getContent(), e.getRemoteAddress()); waitingGet = false; ctx.sendUpstream(event); } @Override public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { if (e.getMessage() instanceof ChannelBuffer) { if (httpRequiresSessionId && !active) { if (handshaking) { handshaking = true; } else { if (!handShakeFuture.await(5000)) { throw new RuntimeException("Handshake failed after timeout"); } } } HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, url); if (cookie != null) { httpRequest.addHeader(HttpHeaders.Names.COOKIE, cookie); } ChannelBuffer buf = (ChannelBuffer)e.getMessage(); httpRequest.setContent(buf); httpRequest.addHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.writerIndex())); Channels.write(ctx, e.getFuture(), httpRequest, e.getRemoteAddress()); lastSendTime = System.currentTimeMillis(); } else { Channels.write(ctx, e.getFuture(), e.getMessage(), e.getRemoteAddress()); lastSendTime = System.currentTimeMillis(); } } private class HttpIdleTimer implements Runnable { private boolean closed = false; private java.util.concurrent.Future<?> future; public synchronized void run() { if (closed) { return; } if (!waitingGet && System.currentTimeMillis() > lastSendTime + httpMaxClientIdleTime) { HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, url); waitingGet = true; channel.write(httpRequest); } } public synchronized void setFuture(final java.util.concurrent.Future<?> future) { this.future = future; } public void close() { if (future != null) { future.cancel(false); } closed = true; } } } private class Listener implements ConnectionLifeCycleListener { public void connectionCreated(final Connection connection, final ProtocolType protocol) { if (connections.putIfAbsent(connection.getID(), connection) != null) { throw new IllegalArgumentException("Connection already exists with id " + connection.getID()); } } public void connectionDestroyed(final Object connectionID) { if (connections.remove(connectionID) != null) { // Execute on different thread to avoid deadlocks closeExecutor.execute(new Runnable() { public void run() { listener.connectionDestroyed(connectionID); } }); } } public void connectionException(final Object connectionID, final HornetQException me) { // Execute on different thread to avoid deadlocks closeExecutor.execute(new Runnable() { public void run() { listener.connectionException(connectionID, me); } }); } } private class BatchFlusher implements Runnable { private boolean cancelled; public synchronized void run() { if (!cancelled) { for (Connection connection : connections.values()) { connection.checkFlushBatchBuffer(); } } } public synchronized void cancel() { cancelled = true; } } }
true
true
public synchronized void start() { if (channelFactory != null) { return; } if (useNio) { int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } channelFactory = new NioClientSocketChannelFactory(virtualExecutor, virtualExecutor, threadsToUse); } else { channelFactory = new OioClientSocketChannelFactory(virtualExecutor); } // if we are a servlet wrap the socketChannelFactory if (useServlet) { ClientSocketChannelFactory proxyChannelFactory = channelFactory; channelFactory = new HttpTunnelingClientSocketChannelFactory(proxyChannelFactory); } bootstrap = new ClientBootstrap(channelFactory); bootstrap.setOption("tcpNoDelay", tcpNoDelay); if (tcpReceiveBufferSize != -1) { bootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.setOption("sendBufferSize", tcpSendBufferSize); } bootstrap.setOption("keepAlive", true); bootstrap.setOption("reuseAddress", true); channelGroup = new DefaultChannelGroup("hornetq-connector"); final SSLContext context; if (sslEnabled) { try { context = SSLSupport.getInstance(true, keyStorePath, keyStorePassword, null, null); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException("Unable to create NettyConnector for " + host); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { bootstrap.setOption("sslContext", context); } bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { List<ChannelHandler> handlers = new ArrayList<ChannelHandler>(); if (sslEnabled) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); SslHandler handler = new SslHandler(engine); handlers.add(handler); } if (httpEnabled) { handlers.add(new HttpRequestEncoder()); handlers.add(new HttpResponseDecoder()); handlers.add(new HttpHandler()); } handlers.add(new HornetQFrameDecoder2()); handlers.add(new HornetQClientChannelHandler(channelGroup, handler, new Listener())); ChannelPipeline pipeline = new StaticChannelPipeline(handlers.toArray(new ChannelHandler[handlers.size()])); return pipeline; } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } if (!Version.ID.equals(VersionLoader.getVersion().getNettyVersion())) { NettyConnector.log.warn("Unexpected Netty Version was expecting " + VersionLoader.getVersion() .getNettyVersion() + " using " + Version.ID); } NettyConnector.log.debug("Started Netty Connector version " + Version.ID); }
public synchronized void start() { if (channelFactory != null) { return; } if (useNio) { int threadsToUse; if (nioRemotingThreads == -1) { // Default to number of cores * 3 threadsToUse = Runtime.getRuntime().availableProcessors() * 3; } else { threadsToUse = this.nioRemotingThreads; } channelFactory = new NioClientSocketChannelFactory(virtualExecutor, virtualExecutor, threadsToUse); } else { channelFactory = new OioClientSocketChannelFactory(virtualExecutor); } // if we are a servlet wrap the socketChannelFactory if (useServlet) { ClientSocketChannelFactory proxyChannelFactory = channelFactory; channelFactory = new HttpTunnelingClientSocketChannelFactory(proxyChannelFactory); } bootstrap = new ClientBootstrap(channelFactory); bootstrap.setOption("tcpNoDelay", tcpNoDelay); if (tcpReceiveBufferSize != -1) { bootstrap.setOption("receiveBufferSize", tcpReceiveBufferSize); } if (tcpSendBufferSize != -1) { bootstrap.setOption("sendBufferSize", tcpSendBufferSize); } bootstrap.setOption("keepAlive", true); bootstrap.setOption("reuseAddress", true); channelGroup = new DefaultChannelGroup("hornetq-connector"); final SSLContext context; if (sslEnabled) { try { context = SSLSupport.getInstance(true, keyStorePath, keyStorePassword, null, null); } catch (Exception e) { close(); IllegalStateException ise = new IllegalStateException("Unable to create NettyConnector for " + host); ise.initCause(e); throw ise; } } else { context = null; // Unused } if (context != null && useServlet) { bootstrap.setOption("sslContext", context); } bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { List<ChannelHandler> handlers = new ArrayList<ChannelHandler>(); if (sslEnabled && !useServlet) { SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(true); engine.setWantClientAuth(true); SslHandler handler = new SslHandler(engine); handlers.add(handler); } if (httpEnabled) { handlers.add(new HttpRequestEncoder()); handlers.add(new HttpResponseDecoder()); handlers.add(new HttpHandler()); } handlers.add(new HornetQFrameDecoder2()); handlers.add(new HornetQClientChannelHandler(channelGroup, handler, new Listener())); ChannelPipeline pipeline = new StaticChannelPipeline(handlers.toArray(new ChannelHandler[handlers.size()])); return pipeline; } }); if (batchDelay > 0) { flusher = new BatchFlusher(); batchFlusherFuture = scheduledThreadPool.scheduleWithFixedDelay(flusher, batchDelay, batchDelay, TimeUnit.MILLISECONDS); } if (!Version.ID.equals(VersionLoader.getVersion().getNettyVersion())) { NettyConnector.log.warn("Unexpected Netty Version was expecting " + VersionLoader.getVersion() .getNettyVersion() + " using " + Version.ID); } NettyConnector.log.debug("Started Netty Connector version " + Version.ID); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java index ac81b57d2..173c08a13 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java @@ -1,142 +1,143 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies 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: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.editors; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages; import org.eclipse.mylyn.tasks.core.IRepositoryPerson; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.core.data.TaskDataModel; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ImageHyperlink; /** * @author Steffen Pingel */ public class PersonAttributeEditor extends TextAttributeEditor { public PersonAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) { super(manager, taskAttribute); } @Override public Text getText() { return super.getText(); } @Override public void createControl(Composite parent, FormToolkit toolkit) { String userName = getModel().getTaskRepository().getUserName(); if (isReadOnly() || userName == null || userName.length() == 0) { super.createControl(parent, toolkit); } else { final Composite composite = new Composite(parent, SWT.NONE); GridLayout parentLayout = new GridLayout(2, false); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.horizontalSpacing = 0; composite.setLayout(parentLayout); composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); super.createControl(composite, toolkit); getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE); GridDataFactory.fillDefaults().grab(true, false).applyTo(getText()); final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS); selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip); selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { String userName = getModel().getTaskRepository().getUserName(); if (userName != null && userName.length() > 0) { getText().setText(userName); setValue(userName); } } }); - GridDataFactory.fillDefaults().exclude(true).applyTo(selfLink); + GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).exclude(true).applyTo(selfLink); MouseTrackListener mouseListener = new MouseTrackAdapter() { int version = 0; @Override public void mouseEnter(MouseEvent e) { ((GridData) selfLink.getLayoutData()).exclude = false; composite.layout(); selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.redraw(); version++; } @Override public void mouseExit(MouseEvent e) { final int lastVersion = version; Display.getDefault().asyncExec(new Runnable() { public void run() { if (version != lastVersion || selfLink.isDisposed()) { return; } selfLink.setImage(null); selfLink.redraw(); ((GridData) selfLink.getLayoutData()).exclude = true; composite.layout(); } }); } }; + composite.addMouseTrackListener(mouseListener); getText().addMouseTrackListener(mouseListener); selfLink.addMouseTrackListener(mouseListener); toolkit.paintBordersFor(composite); setControl(composite); } } @Override public String getValue() { IRepositoryPerson repositoryPerson = getAttributeMapper().getRepositoryPerson(getTaskAttribute()); if (repositoryPerson != null) { return (isReadOnly()) ? repositoryPerson.toString() : repositoryPerson.getPersonId(); } return ""; //$NON-NLS-1$ } @Override public void setValue(String text) { IRepositoryPerson person = getAttributeMapper().getTaskRepository().createPerson(text); getAttributeMapper().setRepositoryPerson(getTaskAttribute(), person); attributeChanged(); } @Override protected void decorateIncoming(Color color) { if (getControl() != null) { getControl().setBackground(color); } if (getText() != null && getText() != getControl()) { getText().setBackground(color); } } }
false
true
public void createControl(Composite parent, FormToolkit toolkit) { String userName = getModel().getTaskRepository().getUserName(); if (isReadOnly() || userName == null || userName.length() == 0) { super.createControl(parent, toolkit); } else { final Composite composite = new Composite(parent, SWT.NONE); GridLayout parentLayout = new GridLayout(2, false); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.horizontalSpacing = 0; composite.setLayout(parentLayout); composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); super.createControl(composite, toolkit); getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE); GridDataFactory.fillDefaults().grab(true, false).applyTo(getText()); final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS); selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip); selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { String userName = getModel().getTaskRepository().getUserName(); if (userName != null && userName.length() > 0) { getText().setText(userName); setValue(userName); } } }); GridDataFactory.fillDefaults().exclude(true).applyTo(selfLink); MouseTrackListener mouseListener = new MouseTrackAdapter() { int version = 0; @Override public void mouseEnter(MouseEvent e) { ((GridData) selfLink.getLayoutData()).exclude = false; composite.layout(); selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.redraw(); version++; } @Override public void mouseExit(MouseEvent e) { final int lastVersion = version; Display.getDefault().asyncExec(new Runnable() { public void run() { if (version != lastVersion || selfLink.isDisposed()) { return; } selfLink.setImage(null); selfLink.redraw(); ((GridData) selfLink.getLayoutData()).exclude = true; composite.layout(); } }); } }; getText().addMouseTrackListener(mouseListener); selfLink.addMouseTrackListener(mouseListener); toolkit.paintBordersFor(composite); setControl(composite); } }
public void createControl(Composite parent, FormToolkit toolkit) { String userName = getModel().getTaskRepository().getUserName(); if (isReadOnly() || userName == null || userName.length() == 0) { super.createControl(parent, toolkit); } else { final Composite composite = new Composite(parent, SWT.NONE); GridLayout parentLayout = new GridLayout(2, false); parentLayout.marginHeight = 0; parentLayout.marginWidth = 0; parentLayout.horizontalSpacing = 0; composite.setLayout(parentLayout); composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); super.createControl(composite, toolkit); getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE); GridDataFactory.fillDefaults().grab(true, false).applyTo(getText()); final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS); selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip); selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { String userName = getModel().getTaskRepository().getUserName(); if (userName != null && userName.length() > 0) { getText().setText(userName); setValue(userName); } } }); GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).exclude(true).applyTo(selfLink); MouseTrackListener mouseListener = new MouseTrackAdapter() { int version = 0; @Override public void mouseEnter(MouseEvent e) { ((GridData) selfLink.getLayoutData()).exclude = false; composite.layout(); selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL)); selfLink.redraw(); version++; } @Override public void mouseExit(MouseEvent e) { final int lastVersion = version; Display.getDefault().asyncExec(new Runnable() { public void run() { if (version != lastVersion || selfLink.isDisposed()) { return; } selfLink.setImage(null); selfLink.redraw(); ((GridData) selfLink.getLayoutData()).exclude = true; composite.layout(); } }); } }; composite.addMouseTrackListener(mouseListener); getText().addMouseTrackListener(mouseListener); selfLink.addMouseTrackListener(mouseListener); toolkit.paintBordersFor(composite); setControl(composite); } }
diff --git a/test/commons/grails/util/GrailsUtilTests.java b/test/commons/grails/util/GrailsUtilTests.java index 2176db65f..805808b3e 100644 --- a/test/commons/grails/util/GrailsUtilTests.java +++ b/test/commons/grails/util/GrailsUtilTests.java @@ -1,53 +1,53 @@ /* Copyright 2004-2005 Graeme Rocher * * 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 grails.util; import junit.framework.TestCase; import org.codehaus.groovy.grails.commons.GrailsApplication; /** * Tests for the GrailsUtils class * * @author Graeme Rocher * @since 0.4 * <p/> * Created: Jan 22, 2007 * Time: 6:21:53 PM */ public class GrailsUtilTests extends TestCase { public void testEnvironment() { System.setProperty(GrailsApplication.ENVIRONMENT, ""); - assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment()); + assertEquals(GrailsApplication.ENV_APPLICATION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "prod"); assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "dev"); assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "test"); assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment"); assertEquals("myenvironment", GrailsUtil.getEnvironment()); } protected void tearDown() throws Exception { System.setProperty(GrailsApplication.ENVIRONMENT, ""); } }
true
true
public void testEnvironment() { System.setProperty(GrailsApplication.ENVIRONMENT, ""); assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "prod"); assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "dev"); assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "test"); assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment"); assertEquals("myenvironment", GrailsUtil.getEnvironment()); }
public void testEnvironment() { System.setProperty(GrailsApplication.ENVIRONMENT, ""); assertEquals(GrailsApplication.ENV_APPLICATION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "prod"); assertEquals(GrailsApplication.ENV_PRODUCTION, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "dev"); assertEquals(GrailsApplication.ENV_DEVELOPMENT, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "test"); assertEquals(GrailsApplication.ENV_TEST, GrailsUtil.getEnvironment()); System.setProperty(GrailsApplication.ENVIRONMENT, "myenvironment"); assertEquals("myenvironment", GrailsUtil.getEnvironment()); }