diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/org/neo4j/kernel/impl/traversal/TraverserImpl.java b/src/main/java/org/neo4j/kernel/impl/traversal/TraverserImpl.java
index c3b8de41..26b7dd32 100644
--- a/src/main/java/org/neo4j/kernel/impl/traversal/TraverserImpl.java
+++ b/src/main/java/org/neo4j/kernel/impl/traversal/TraverserImpl.java
@@ -1,133 +1,140 @@
/**
* Copyright (c) 2002-2010 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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.neo4j.kernel.impl.traversal;
import java.util.Iterator;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.traversal.BranchSelector;
import org.neo4j.graphdb.traversal.TraversalBranch;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.graphdb.traversal.UniquenessFilter;
import org.neo4j.helpers.collection.CombiningIterator;
import org.neo4j.helpers.collection.IterableWrapper;
import org.neo4j.helpers.collection.PrefetchingIterator;
class TraverserImpl implements Traverser
{
private final TraversalDescriptionImpl description;
private final Node startNode;
TraverserImpl( TraversalDescriptionImpl description, Node startNode )
{
this.description = description;
this.startNode = startNode;
}
public Iterator<Path> iterator()
{
return new TraverserIterator();
}
public Iterable<Node> nodes()
{
return new IterableWrapper<Node, Path>( this )
{
@Override
protected Node underlyingObjectToObject( Path position )
{
return position.endNode();
}
};
}
public Iterable<Relationship> relationships()
{
return new IterableWrapper<Relationship, Path>( this )
{
@Override
public Iterator<Relationship> iterator()
{
Iterator<Relationship> iter = super.iterator();
- Relationship first = iter.next();
- // If the first position represents the start node, the first
- // relationship will be null, in that case skip it.
- if ( first == null ) return iter;
- // Otherwise re-include it.
- return new CombiningIterator<Relationship>( first, iter );
+ if ( iter.hasNext() )
+ {
+ Relationship first = iter.next();
+ // If the first position represents the start node, the
+ // first relationship will be null, in that case skip it.
+ if ( first == null ) return iter;
+ // Otherwise re-include it.
+ return new CombiningIterator<Relationship>( first, iter );
+ }
+ else
+ {
+ return iter;
+ }
}
@Override
protected Relationship underlyingObjectToObject( Path position )
{
return position.lastRelationship();
}
};
}
class TraverserIterator extends PrefetchingIterator<Path>
{
final UniquenessFilter uniquness;
private final BranchSelector sourceSelector;
final TraversalDescriptionImpl description;
final Node startNode;
TraverserIterator()
{
this.description = TraverserImpl.this.description;
this.uniquness = description.uniqueness.create( description.uniquenessParameter );
this.startNode = TraverserImpl.this.startNode;
this.sourceSelector = description.branchSelector.create(
new StartNodeTraversalBranch( this, startNode,
description.expander ) );
}
boolean okToProceedFirst( TraversalBranch source )
{
return this.uniquness.checkFirst( source );
}
boolean okToProceed( TraversalBranch source )
{
return this.uniquness.check( source, true );
}
@Override
protected Path fetchNextOrNull()
{
TraversalBranch result = null;
while ( true )
{
result = sourceSelector.next();
if ( result == null )
{
return null;
}
if ( result.evaluation().includes() )
{
return result.position();
}
}
}
}
}
| true | true | public Iterable<Relationship> relationships()
{
return new IterableWrapper<Relationship, Path>( this )
{
@Override
public Iterator<Relationship> iterator()
{
Iterator<Relationship> iter = super.iterator();
Relationship first = iter.next();
// If the first position represents the start node, the first
// relationship will be null, in that case skip it.
if ( first == null ) return iter;
// Otherwise re-include it.
return new CombiningIterator<Relationship>( first, iter );
}
@Override
protected Relationship underlyingObjectToObject( Path position )
{
return position.lastRelationship();
}
};
}
| public Iterable<Relationship> relationships()
{
return new IterableWrapper<Relationship, Path>( this )
{
@Override
public Iterator<Relationship> iterator()
{
Iterator<Relationship> iter = super.iterator();
if ( iter.hasNext() )
{
Relationship first = iter.next();
// If the first position represents the start node, the
// first relationship will be null, in that case skip it.
if ( first == null ) return iter;
// Otherwise re-include it.
return new CombiningIterator<Relationship>( first, iter );
}
else
{
return iter;
}
}
@Override
protected Relationship underlyingObjectToObject( Path position )
{
return position.lastRelationship();
}
};
}
|
diff --git a/Library/src/br/ufpa/adtn/routing/prophet/ProphetLinkConnection.java b/Library/src/br/ufpa/adtn/routing/prophet/ProphetLinkConnection.java
index 57ea294..df3e2d3 100644
--- a/Library/src/br/ufpa/adtn/routing/prophet/ProphetLinkConnection.java
+++ b/Library/src/br/ufpa/adtn/routing/prophet/ProphetLinkConnection.java
@@ -1,97 +1,97 @@
/**
* Amazon-DTN - Lightweight Delay Tolerant Networking Implementation
* Copyright (C) 2013 Dórian C. Langbeck
*
* 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 br.ufpa.adtn.routing.prophet;
import br.ufpa.adtn.core.BPAgent;
import br.ufpa.adtn.core.EID;
import br.ufpa.adtn.routing.MessageLinkConnection;
import br.ufpa.adtn.routing.prophet.ProphetDataRouting.NeighborPredict;
import br.ufpa.adtn.routing.prophet.ProphetUtil.BundleSpec;
import br.ufpa.adtn.util.Logger;
/**
* This class is the abstraction of a communication link with a PROPHET node. Responsible for
* implementing the method of triggering parked event to begin the process of communication
* with other neighbor, creating a ProphetMessageConnection. Has decision logic of Protocol
* to set bundle routes according to their delivery predictability metric.
*
* @author Douglas Cirqueira
*/
public class ProphetLinkConnection extends MessageLinkConnection<ProphetLinkConnection, ProphetBundleRouter, ProphetMessageConnection, ProphetTLV> {
private static final Logger LOGGER = new Logger("ProphetLinkConnection");
private final ProphetDataRouting dataRout;
public ProphetLinkConnection(ProphetDataRouting dataRout) {
super(ProphetTLV.PARSER);
this.dataRout = dataRout;
}
@Override
protected void onParked() {
LOGGER.v("onParked event");
if (getRouter().updatePresence(this))
getMessageProvider().create();
}
@Override
public ProphetMessageConnection createMessageConnection() {
return new ProphetMessageConnection();
}
public ProphetDataRouting getProphetDataRouting() {
return dataRout;
}
public BundleSpec[] update(NeighborPredict[] preds) {
/*
* Considering that I'm node A, my neighbor is node B
* and others are C.
*/
final EID remote_eid = getRegistrationEndpointID();
for (int i = 0, len = preds.length; i < len; i++) {
final NeighborPredict np = preds[i];
final EID c_eid = np.getEID();
- if (c_eid == getLocalEndpointID())
+ if (c_eid.equals(getLocalEndpointID()))
continue;
final float p_ac = dataRout.getPredict(c_eid);
final float p_bc = np.getPredict();
final float p_ab = dataRout.getPredict(remote_eid);
//Updating transitivity
dataRout.updateTransitivity(c_eid, p_ab, p_bc);
//Check better candidate to delivering
if (p_ac < p_bc){
BPAgent.routeLink(c_eid, remote_eid);
LOGGER.d("RouteLink to " + remote_eid);
}
else {
BPAgent.routeUnlink(c_eid, remote_eid);
LOGGER.d("RouteUnlink to " + remote_eid);
}
}
// Decide which bundles will be offered and return it.
return ProphetUtil.getSpec(BPAgent.getBundlesFor(remote_eid));
}
}
| true | true | public BundleSpec[] update(NeighborPredict[] preds) {
/*
* Considering that I'm node A, my neighbor is node B
* and others are C.
*/
final EID remote_eid = getRegistrationEndpointID();
for (int i = 0, len = preds.length; i < len; i++) {
final NeighborPredict np = preds[i];
final EID c_eid = np.getEID();
if (c_eid == getLocalEndpointID())
continue;
final float p_ac = dataRout.getPredict(c_eid);
final float p_bc = np.getPredict();
final float p_ab = dataRout.getPredict(remote_eid);
//Updating transitivity
dataRout.updateTransitivity(c_eid, p_ab, p_bc);
//Check better candidate to delivering
if (p_ac < p_bc){
BPAgent.routeLink(c_eid, remote_eid);
LOGGER.d("RouteLink to " + remote_eid);
}
else {
BPAgent.routeUnlink(c_eid, remote_eid);
LOGGER.d("RouteUnlink to " + remote_eid);
}
}
// Decide which bundles will be offered and return it.
return ProphetUtil.getSpec(BPAgent.getBundlesFor(remote_eid));
}
| public BundleSpec[] update(NeighborPredict[] preds) {
/*
* Considering that I'm node A, my neighbor is node B
* and others are C.
*/
final EID remote_eid = getRegistrationEndpointID();
for (int i = 0, len = preds.length; i < len; i++) {
final NeighborPredict np = preds[i];
final EID c_eid = np.getEID();
if (c_eid.equals(getLocalEndpointID()))
continue;
final float p_ac = dataRout.getPredict(c_eid);
final float p_bc = np.getPredict();
final float p_ab = dataRout.getPredict(remote_eid);
//Updating transitivity
dataRout.updateTransitivity(c_eid, p_ab, p_bc);
//Check better candidate to delivering
if (p_ac < p_bc){
BPAgent.routeLink(c_eid, remote_eid);
LOGGER.d("RouteLink to " + remote_eid);
}
else {
BPAgent.routeUnlink(c_eid, remote_eid);
LOGGER.d("RouteUnlink to " + remote_eid);
}
}
// Decide which bundles will be offered and return it.
return ProphetUtil.getSpec(BPAgent.getBundlesFor(remote_eid));
}
|
diff --git a/src/com/android/musicfx/ControlPanelEffect.java b/src/com/android/musicfx/ControlPanelEffect.java
index 8abb4f3..db46c3e 100644
--- a/src/com/android/musicfx/ControlPanelEffect.java
+++ b/src/com/android/musicfx/ControlPanelEffect.java
@@ -1,1419 +1,1419 @@
/*
* Copyright (C) 2010-2011 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.musicfx;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.audiofx.AudioEffect;
import android.media.audiofx.BassBoost;
import android.media.audiofx.Equalizer;
import android.media.audiofx.PresetReverb;
import android.media.audiofx.Virtualizer;
import android.util.Log;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
/**
* The Common class defines constants to be used by the control panels.
*/
public class ControlPanelEffect {
private final static String TAG = "MusicFXControlPanelEffect";
/**
* Audio session priority
*/
private static final int PRIORITY = 0;
/**
* The control mode specifies if control panel updates effects and preferences or only
* preferences.
*/
static enum ControlMode {
/**
* Control panel updates effects and preferences. Applicable when audio session is delivered
* by user.
*/
CONTROL_EFFECTS,
/**
* Control panel only updates preferences. Applicable when there was no audio or invalid
* session provided by user.
*/
CONTROL_PREFERENCES
}
static enum Key {
global_enabled, virt_enabled, virt_strength, virt_type, bb_enabled, bb_strength, te_enabled, te_strength, avl_enabled, lm_enabled, lm_strength, eq_enabled, eq_num_bands, eq_level_range, eq_center_freq, eq_band_level, eq_num_presets, eq_preset_name, eq_preset_user_band_level, eq_preset_user_band_level_default, eq_preset_opensl_es_band_level, eq_preset_ci_extreme_band_level, eq_current_preset, pr_enabled, pr_current_preset
}
// Effect/audio session Mappings
/**
* Hashmap initial capacity
*/
private static final int HASHMAP_INITIAL_CAPACITY = 16;
/**
* Hashmap load factor
*/
private static final float HASHMAP_LOAD_FACTOR = 0.75f;
/**
* ConcurrentHashMap concurrency level
*/
private static final int HASHMAP_CONCURRENCY_LEVEL = 2;
/**
* Map containing the Virtualizer audio session, effect mappings.
*/
private static final ConcurrentHashMap<Integer, Virtualizer> mVirtualizerInstances = new ConcurrentHashMap<Integer, Virtualizer>(
HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL);
/**
* Map containing the BB audio session, effect mappings.
*/
private static final ConcurrentHashMap<Integer, BassBoost> mBassBoostInstances = new ConcurrentHashMap<Integer, BassBoost>(
HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL);
/**
* Map containing the EQ audio session, effect mappings.
*/
private static final ConcurrentHashMap<Integer, Equalizer> mEQInstances = new ConcurrentHashMap<Integer, Equalizer>(
HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL);
/**
* Map containing the PR audio session, effect mappings.
*/
private static final ConcurrentHashMap<Integer, PresetReverb> mPresetReverbInstances = new ConcurrentHashMap<Integer, PresetReverb>(
HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL);
/**
* Map containing the package name, audio session mappings.
*/
private static final ConcurrentHashMap<String, Integer> mPackageSessions = new ConcurrentHashMap<String, Integer>(
HASHMAP_INITIAL_CAPACITY, HASHMAP_LOAD_FACTOR, HASHMAP_CONCURRENCY_LEVEL);
// Defaults
final static boolean GLOBAL_ENABLED_DEFAULT = false;
private final static boolean VIRTUALIZER_ENABLED_DEFAULT = true;
private final static int VIRTUALIZER_STRENGTH_DEFAULT = 1000;
private final static boolean BASS_BOOST_ENABLED_DEFAULT = true;
private final static int BASS_BOOST_STRENGTH_DEFAULT = 667;
private final static boolean PRESET_REVERB_ENABLED_DEFAULT = false;
private final static int PRESET_REVERB_CURRENT_PRESET_DEFAULT = 0; // None
// EQ defaults
private final static boolean EQUALIZER_ENABLED_DEFAULT = true;
private final static String EQUALIZER_PRESET_NAME_DEFAULT = "Preset";
private final static short EQUALIZER_NUMBER_BANDS_DEFAULT = 5;
private final static short EQUALIZER_NUMBER_PRESETS_DEFAULT = 0;
private final static short[] EQUALIZER_BAND_LEVEL_RANGE_DEFAULT = { -1500, 1500 };
private final static int[] EQUALIZER_CENTER_FREQ_DEFAULT = { 60000, 230000, 910000, 3600000,
14000000 };
private final static short[] EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL = { 0, 800, 400, 100, 1000 };
private final static short[] EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT = { 0, 0, 0, 0, 0 };
private final static short[][] EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT = new short[EQUALIZER_NUMBER_PRESETS_DEFAULT][EQUALIZER_NUMBER_BANDS_DEFAULT];
// EQ effect properties which are invariable over all EQ effects sessions
private static short[] mEQBandLevelRange = EQUALIZER_BAND_LEVEL_RANGE_DEFAULT;
private static short mEQNumBands = EQUALIZER_NUMBER_BANDS_DEFAULT;
private static int[] mEQCenterFreq = EQUALIZER_CENTER_FREQ_DEFAULT;
private static short mEQNumPresets = EQUALIZER_NUMBER_PRESETS_DEFAULT;
private static short[][] mEQPresetOpenSLESBandLevel = EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT;
private static String[] mEQPresetNames;
private static boolean mIsEQInitialized = false;
private final static Object mEQInitLock = new Object();
/**
* Default int argument used in methods to see that the arg is a dummy. Used for method
* overloading.
*/
private final static int DUMMY_ARGUMENT = -1;
/**
* Inits effects preferences for the given context and package name in the control panel. If
* preferences for the given package name don't exist, they are created and initialized.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
*/
public static void initEffectsPreferences(final Context context, final String packageName,
final int audioSession) {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
final ControlMode controlMode = getControlMode(audioSession);
// init preferences
try {
// init global on/off switch
final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(),
GLOBAL_ENABLED_DEFAULT);
editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled);
Log.v(TAG, "isGlobalEnabled = " + isGlobalEnabled);
// Virtualizer
final boolean isVIEnabled = prefs.getBoolean(Key.virt_enabled.toString(),
VIRTUALIZER_ENABLED_DEFAULT);
final int vIStrength = prefs.getInt(Key.virt_strength.toString(),
VIRTUALIZER_STRENGTH_DEFAULT);
editor.putBoolean(Key.virt_enabled.toString(), isVIEnabled);
editor.putInt(Key.virt_strength.toString(), vIStrength);
// BassBoost
final boolean isBBEnabled = prefs.getBoolean(Key.bb_enabled.toString(),
BASS_BOOST_ENABLED_DEFAULT);
final int bBStrength = prefs.getInt(Key.bb_strength.toString(),
BASS_BOOST_STRENGTH_DEFAULT);
editor.putBoolean(Key.bb_enabled.toString(), isBBEnabled);
editor.putInt(Key.bb_strength.toString(), bBStrength);
// Equalizer
synchronized (mEQInitLock) {
// If EQ is not initialized already create "dummy" audio session created by
// MediaPlayer and create effect on it to retrieve the invariable EQ properties
if (!mIsEQInitialized) {
final MediaPlayer mediaPlayer = new MediaPlayer();
final int session = mediaPlayer.getAudioSessionId();
Equalizer equalizerEffect = null;
try {
Log.d(TAG, "Creating dummy EQ effect on session " + session);
equalizerEffect = new Equalizer(PRIORITY, session);
mEQBandLevelRange = equalizerEffect.getBandLevelRange();
mEQNumBands = equalizerEffect.getNumberOfBands();
mEQCenterFreq = new int[mEQNumBands];
for (short band = 0; band < mEQNumBands; band++) {
mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band);
}
mEQNumPresets = equalizerEffect.getNumberOfPresets();
mEQPresetNames = new String[mEQNumPresets];
mEQPresetOpenSLESBandLevel = new short[mEQNumPresets][mEQNumBands];
for (short preset = 0; preset < mEQNumPresets; preset++) {
mEQPresetNames[preset] = equalizerEffect.getPresetName(preset);
equalizerEffect.usePreset(preset);
for (short band = 0; band < mEQNumBands; band++) {
mEQPresetOpenSLESBandLevel[preset][band] = equalizerEffect
.getBandLevel(band);
}
}
mIsEQInitialized = true;
} catch (final IllegalStateException e) {
Log.e(TAG, "Equalizer: " + e);
} catch (final IllegalArgumentException e) {
Log.e(TAG, "Equalizer: " + e);
} catch (final UnsupportedOperationException e) {
Log.e(TAG, "Equalizer: " + e);
} catch (final RuntimeException e) {
Log.e(TAG, "Equalizer: " + e);
} finally {
if (equalizerEffect != null) {
Log.d(TAG, "Releasing dummy EQ effect");
equalizerEffect.release();
}
mediaPlayer.release();
// When there was a failure set some good defaults
if (!mIsEQInitialized) {
mEQPresetOpenSLESBandLevel = new short[mEQNumPresets][mEQNumBands];
for (short preset = 0; preset < mEQNumPresets; preset++) {
// Init preset names to a dummy name
mEQPresetNames[preset] = prefs.getString(
Key.eq_preset_name.toString() + preset,
EQUALIZER_PRESET_NAME_DEFAULT + preset);
if (preset < EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT.length) {
mEQPresetOpenSLESBandLevel[preset] = Arrays.copyOf(
EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT[preset],
mEQNumBands);
}
}
}
}
}
editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]);
editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]);
editor.putInt(Key.eq_num_bands.toString(), mEQNumBands);
editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets);
// Resetting the EQ arrays depending on the real # bands with defaults if
// band < default size else 0 by copying default arrays over new ones
final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands);
// If no preset prefs set use CI EXTREME (= numPresets)
final short eQPreset = (short) prefs.getInt(Key.eq_current_preset.toString(),
mEQNumPresets);
editor.putInt(Key.eq_current_preset.toString(), eQPreset);
final short[] bandLevel = new short[mEQNumBands];
for (short band = 0; band < mEQNumBands; band++) {
if (controlMode == ControlMode.CONTROL_PREFERENCES) {
if (eQPreset < mEQNumPresets) {
// OpenSL ES effect presets
bandLevel[band] = mEQPresetOpenSLESBandLevel[eQPreset][band];
} else if (eQPreset == mEQNumPresets) {
// CI EXTREME
bandLevel[band] = eQPresetCIExtremeBandLevel[band];
} else {
// User
bandLevel[band] = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]);
}
editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]);
editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevel[band]);
editor.putInt(Key.eq_preset_user_band_level_default.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
for (short preset = 0; preset < mEQNumPresets; preset++) {
editor.putString(Key.eq_preset_name.toString() + preset, mEQPresetNames[preset]);
for (short band = 0; band < mEQNumBands; band++) {
editor.putInt(Key.eq_preset_opensl_es_band_level.toString() + preset + "_"
+ band, mEQPresetOpenSLESBandLevel[preset][band]);
}
}
}
final boolean isEQEnabled = prefs.getBoolean(Key.eq_enabled.toString(),
EQUALIZER_ENABLED_DEFAULT);
editor.putBoolean(Key.eq_enabled.toString(), isEQEnabled);
// Preset reverb
final boolean isEnabledPR = prefs.getBoolean(Key.pr_enabled.toString(),
PRESET_REVERB_ENABLED_DEFAULT);
final short presetPR = (short) prefs.getInt(Key.pr_current_preset.toString(),
PRESET_REVERB_CURRENT_PRESET_DEFAULT);
editor.putBoolean(Key.pr_enabled.toString(), isEnabledPR);
editor.putInt(Key.pr_current_preset.toString(), presetPR);
editor.commit();
} catch (final RuntimeException e) {
Log.e(TAG, "initEffectsPreferences: processingEnabled: " + e);
}
}
/**
* Gets the effect control mode based on the given audio session in the control panel. Control
* mode defines if the control panel is controlling effects and/or preferences
*
* @param audioSession
* System wide unique audio session identifier.
* @return effect control mode
*/
public static ControlMode getControlMode(final int audioSession) {
if (audioSession == AudioEffect.ERROR_BAD_VALUE) {
return ControlMode.CONTROL_PREFERENCES;
}
return ControlMode.CONTROL_EFFECTS;
}
/**
* Sets boolean parameter to value for given key
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @param value
*/
public static void setParameterBoolean(final Context context, final String packageName,
final int audioSession, final Key key, final boolean value) {
try {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final ControlMode controlMode = getControlMode(audioSession);
boolean enabled = value;
// Global on/off
if (key == Key.global_enabled) {
boolean processingEnabled = false;
if (value == true) {
// enable all with respect to preferences
if (controlMode == ControlMode.CONTROL_EFFECTS) {
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
if (virtualizerEffect != null) {
virtualizerEffect.setEnabled(prefs.getBoolean(
Key.virt_enabled.toString(), VIRTUALIZER_ENABLED_DEFAULT));
final int vIStrength = prefs.getInt(Key.virt_strength.toString(),
VIRTUALIZER_STRENGTH_DEFAULT);
setParameterInt(context, packageName,
audioSession, Key.virt_strength, vIStrength);
}
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
if (bassBoostEffect != null) {
bassBoostEffect.setEnabled(prefs.getBoolean(Key.bb_enabled.toString(),
BASS_BOOST_ENABLED_DEFAULT));
final int bBStrength = prefs.getInt(Key.bb_strength.toString(),
BASS_BOOST_STRENGTH_DEFAULT);
setParameterInt(context, packageName,
audioSession, Key.bb_strength, bBStrength);
}
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
if (equalizerEffect != null) {
equalizerEffect.setEnabled(prefs.getBoolean(Key.eq_enabled.toString(),
EQUALIZER_ENABLED_DEFAULT));
final int[] bandLevels = getParameterIntArray(context,
packageName, audioSession, Key.eq_band_level);
final int len = bandLevels.length;
for (short band = 0; band < len; band++) {
final int level = bandLevels[band];
setParameterInt(context, packageName,
audioSession, Key.eq_band_level, level, band);
}
}
// XXX: Preset Reverb not used for the moment, so commented out the effect
// creation to not use MIPS
// final PresetReverb presetReverbEffect =
// getPresetReverbEffect(audioSession);
// if (presetReverbEffect != null) {
// presetReverbEffect.setEnabled(prefs.getBoolean(
// Key.pr_enabled.toString(), PRESET_REVERB_ENABLED_DEFAULT));
// }
}
processingEnabled = true;
Log.v(TAG, "processingEnabled=" + processingEnabled);
} else {
// disable all
if (controlMode == ControlMode.CONTROL_EFFECTS) {
final Virtualizer virtualizerEffect = getVirtualizerEffectNoCreate(audioSession);
if (virtualizerEffect != null) {
mVirtualizerInstances.remove(audioSession, virtualizerEffect);
virtualizerEffect.setEnabled(false);
virtualizerEffect.release();
}
final BassBoost bassBoostEffect = getBassBoostEffectNoCreate(audioSession);
if (bassBoostEffect != null) {
mBassBoostInstances.remove(audioSession, bassBoostEffect);
bassBoostEffect.setEnabled(false);
bassBoostEffect.release();
}
final Equalizer equalizerEffect = getEqualizerEffectNoCreate(audioSession);
if (equalizerEffect != null) {
mEQInstances.remove(audioSession, equalizerEffect);
equalizerEffect.setEnabled(false);
equalizerEffect.release();
}
// XXX: Preset Reverb not used for the moment, so commented out the effect
// creation to not use MIPS
// final PresetReverb presetReverbEffect =
// getPresetReverbEffect(audioSession);
// if (presetReverbEffect != null) {
// presetReverbEffect.setEnabled(false);
// }
}
processingEnabled = false;
Log.v(TAG, "processingEnabled=" + processingEnabled);
}
enabled = processingEnabled;
} else if (controlMode == ControlMode.CONTROL_EFFECTS) {
final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(),
GLOBAL_ENABLED_DEFAULT);
if (isGlobalEnabled == true) {
// Set effect parameters
switch (key) {
case global_enabled:
// Global, already handled, to get out error free
break;
// Virtualizer
case virt_enabled:
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
if (virtualizerEffect != null) {
virtualizerEffect.setEnabled(value);
enabled = virtualizerEffect.getEnabled();
}
break;
// BassBoost
case bb_enabled:
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
if (bassBoostEffect != null) {
bassBoostEffect.setEnabled(value);
enabled = bassBoostEffect.getEnabled();
}
break;
// Equalizer
case eq_enabled:
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
if (equalizerEffect != null) {
equalizerEffect.setEnabled(value);
enabled = equalizerEffect.getEnabled();
}
break;
// PresetReverb
case pr_enabled:
// XXX: Preset Reverb not used for the moment, so commented out the effect
// creation to not use MIPS
// final PresetReverb presetReverbEffect =
// getPresetReverbEffect(audioSession);
// if (presetReverbEffect != null) {
// presetReverbEffect.setEnabled(value);
// enabled = presetReverbEffect.getEnabled();
// }
break;
default:
Log.e(TAG, "Unknown/unsupported key " + key);
return;
}
}
}
// Set preferences
final SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key.toString(), enabled);
editor.commit();
} catch (final RuntimeException e) {
Log.e(TAG, "setParameterBoolean: " + key + "; " + value + "; " + e);
}
}
/**
* Gets boolean parameter for given key
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value
*/
public static Boolean getParameterBoolean(final Context context, final String packageName,
final int audioSession, final Key key) {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
boolean value = false;
try {
value = prefs.getBoolean(key.toString(), value);
} catch (final RuntimeException e) {
Log.e(TAG, "getParameterBoolean: " + key + "; " + value + "; " + e);
}
return value;
}
/**
* Sets int parameter for given key and value arg0, arg1
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @param arg0
* @param arg1
*/
public static void setParameterInt(final Context context, final String packageName,
final int audioSession, final Key key, final int arg0, final int arg1) {
String strKey = key.toString();
int value = arg0;
try {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
final ControlMode controlMode = getControlMode(audioSession);
// Set effect parameters
if (controlMode == ControlMode.CONTROL_EFFECTS) {
switch (key) {
// Virtualizer
case virt_strength: {
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
if (virtualizerEffect != null) {
virtualizerEffect.setStrength((short) value);
value = virtualizerEffect.getRoundedStrength();
}
break;
}
// BassBoost
case bb_strength: {
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
if (bassBoostEffect != null) {
bassBoostEffect.setStrength((short) value);
value = bassBoostEffect.getRoundedStrength();
}
break;
}
// Equalizer
case eq_band_level: {
if (arg1 == DUMMY_ARGUMENT) {
throw new IllegalArgumentException("Dummy arg passed.");
}
final short band = (short) arg1;
strKey = strKey + band;
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
if (equalizerEffect != null) {
equalizerEffect.setBandLevel(band, (short) value);
value = equalizerEffect.getBandLevel(band);
// save band level in User preset
editor.putInt(Key.eq_preset_user_band_level.toString() + band, value);
}
break;
}
case eq_current_preset: {
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
if (equalizerEffect != null) {
final short preset = (short) value;
final int numBands = prefs.getInt(Key.eq_num_bands.toString(),
EQUALIZER_NUMBER_BANDS_DEFAULT);
final int numPresets = prefs.getInt(Key.eq_num_presets.toString(),
EQUALIZER_NUMBER_PRESETS_DEFAULT);
if (preset < numPresets) {
// OpenSL ES EQ Effect presets
equalizerEffect.usePreset(preset);
value = equalizerEffect.getCurrentPreset();
} else {
final short[] eQPresetCIExtremeBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, numBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, numBands);
// Set the band levels manually for custom presets
for (short band = 0; band < numBands; band++) {
short bandLevel = 0;
if (preset == numPresets) {
// CI EXTREME
bandLevel = (short) prefs.getInt(
Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevelDefault[band]);
} else {
// User
bandLevel = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
equalizerEffect.setBandLevel(band, bandLevel);
}
}
// update band levels
for (short band = 0; band < numBands; band++) {
final short level = equalizerEffect.getBandLevel(band);
editor.putInt(Key.eq_band_level.toString() + band, level);
}
}
break;
}
case eq_preset_user_band_level:
// Fall through
case eq_preset_user_band_level_default:
// Fall through
case eq_preset_ci_extreme_band_level: {
if (arg1 == DUMMY_ARGUMENT) {
throw new IllegalArgumentException("Dummy arg passed.");
}
final short band = (short) arg1;
strKey = strKey + band;
break;
}
case pr_current_preset:
// XXX: Preset Reverb not used for the moment, so commented out the effect
// creation to not use MIPS
// final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession);
// if (presetReverbEffect != null) {
// presetReverbEffect.setPreset((short) value);
// value = presetReverbEffect.getPreset();
// }
break;
default:
Log.e(TAG, "setParameterInt: Unknown/unsupported key " + key);
return;
}
} else {
switch (key) {
// Virtualizer
case virt_strength:
// Do nothing
break;
case virt_type:
// Do nothing
break;
// BassBoost
case bb_strength:
// Do nothing
break;
// Equalizer
case eq_band_level: {
if (arg1 == DUMMY_ARGUMENT) {
throw new IllegalArgumentException("Dummy arg passed.");
}
final short band = (short) arg1;
strKey = strKey + band;
editor.putInt(Key.eq_preset_user_band_level.toString() + band, value);
break;
}
case eq_current_preset: {
final short preset = (short) value;
final int numBands = prefs.getInt(Key.eq_num_bands.toString(),
EQUALIZER_NUMBER_BANDS_DEFAULT);
final int numPresets = prefs.getInt(Key.eq_num_presets.toString(),
EQUALIZER_NUMBER_PRESETS_DEFAULT);
final short[][] eQPresetOpenSLESBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_OPENSL_ES_BAND_LEVEL_DEFAULT, numBands);
final short[] eQPresetCIExtremeBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, numBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, numBands);
for (short band = 0; band < numBands; band++) {
short bandLevel = 0;
if (preset < numPresets) {
// OpenSL ES EQ Effect presets
bandLevel = (short) prefs.getInt(
Key.eq_preset_opensl_es_band_level.toString() + preset + "_"
+ band, eQPresetOpenSLESBandLevelDefault[preset][band]);
} else if (preset == numPresets) {
// CI EXTREME
bandLevel = (short) prefs.getInt(
Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevelDefault[band]);
} else {
// User
bandLevel = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
editor.putInt(Key.eq_band_level.toString() + band, bandLevel);
}
break;
}
case eq_preset_user_band_level:
// Fall through
case eq_preset_user_band_level_default:
// Fall through
case eq_preset_ci_extreme_band_level: {
if (arg1 == DUMMY_ARGUMENT) {
throw new IllegalArgumentException("Dummy arg passed.");
}
final short band = (short) arg1;
strKey = strKey + band;
break;
}
case pr_current_preset:
// Do nothing
break;
default:
Log.e(TAG, "setParameterInt: Unknown/unsupported key " + key);
return;
}
}
// Set preferences
editor.putInt(strKey, value);
editor.apply();
} catch (final RuntimeException e) {
Log.e(TAG, "setParameterInt: " + key + "; " + arg0 + "; " + arg1 + "; " + e);
}
}
/**
* Sets int parameter for given key and value arg
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @param arg
*/
public static void setParameterInt(final Context context, final String packageName,
final int audioSession, final Key key, final int arg) {
setParameterInt(context, packageName, audioSession, key, arg, DUMMY_ARGUMENT);
}
/**
* Gets int parameter given key
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value
*/
public static int getParameterInt(final Context context, final String packageName,
final int audioSession, final String key) {
int value = 0;
try {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
value = prefs.getInt(key, value);
} catch (final RuntimeException e) {
Log.e(TAG, "getParameterInt: " + key + "; " + e);
}
return value;
}
/**
* Gets int parameter given key
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value
*/
public static int getParameterInt(final Context context, final String packageName,
final int audioSession, final Key key) {
return getParameterInt(context, packageName, audioSession, key.toString());
}
/**
* Gets int parameter given key and arg
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param audioSession
* @param key
* @param arg
* @return parameter value
*/
public static int getParameterInt(final Context context, final String packageName,
final int audioSession, final Key key, final int arg) {
return getParameterInt(context, packageName, audioSession, key.toString() + arg);
}
/**
* Gets int parameter given key, arg0 and arg1
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param audioSession
* @param key
* @param arg0
* @param arg1
* @return parameter value
*/
public static int getParameterInt(final Context context, final String packageName,
final int audioSession, final Key key, final int arg0, final int arg1) {
return getParameterInt(context, packageName, audioSession, key.toString() + arg0 + "_"
+ arg1);
}
/**
* Gets integer array parameter given key. Returns null if not found.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value array
*/
public static int[] getParameterIntArray(final Context context, final String packageName,
final int audioSession, final Key key) {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
int[] intArray = null;
try {
// Get effect parameters
switch (key) {
case eq_level_range: {
intArray = new int[2];
break;
}
case eq_center_freq:
// Fall through
case eq_band_level:
// Fall through
case eq_preset_user_band_level:
// Fall through
case eq_preset_user_band_level_default:
// Fall through
case eq_preset_ci_extreme_band_level: {
final int numBands = prefs.getInt(Key.eq_num_bands.toString(), 0);
intArray = new int[numBands];
break;
}
default:
Log.e(TAG, "getParameterIntArray: Unknown/unsupported key " + key);
return null;
}
for (int i = 0; i < intArray.length; i++) {
intArray[i] = prefs.getInt(key.toString() + i, 0);
}
} catch (final RuntimeException e) {
Log.e(TAG, "getParameterIntArray: " + key + "; " + e);
}
return intArray;
}
/**
* Gets string parameter given key. Returns empty string if not found.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value
*/
public static String getParameterString(final Context context, final String packageName,
final int audioSession, final String key) {
String value = "";
try {
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
// Get effect parameters
value = prefs.getString(key, value);
} catch (final RuntimeException e) {
Log.e(TAG, "getParameterString: " + key + "; " + e);
}
return value;
}
/**
* Gets string parameter given key.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param key
* @return parameter value
*/
public static String getParameterString(final Context context, final String packageName,
final int audioSession, final Key key) {
return getParameterString(context, packageName, audioSession, key.toString());
}
/**
* Gets string parameter given key and arg.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param args
* @return parameter value
*/
public static String getParameterString(final Context context, final String packageName,
final int audioSession, final Key key, final int arg) {
return getParameterString(context, packageName, audioSession, key.toString() + arg);
}
/**
* Opens/initializes the effects session for the given audio session with preferences linked to
* the given package name and context.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
*/
public static void openSession(final Context context, final String packageName,
final int audioSession) {
Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")");
final String methodTag = "openSession: ";
// init preferences
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(),
GLOBAL_ENABLED_DEFAULT);
editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled);
if (!isGlobalEnabled) {
return;
}
// Manage audioSession information
// Retrieve AudioSession Id from map
boolean isExistingAudioSession = false;
try {
final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName,
audioSession);
if (currentAudioSession != null) {
// Compare with passed argument
if (currentAudioSession == audioSession) {
// FIXME: Normally, we should exit the function here
// BUT: we have to take care of the virtualizer because of
// a bug in the Android Effects Framework
// editor.commit();
// return;
isExistingAudioSession = true;
} else {
closeSession(context, packageName, currentAudioSession);
}
}
} catch (final NullPointerException e) {
Log.e(TAG, methodTag + e);
editor.commit();
return;
}
// Because the audioSession is new, get effects & settings from shared preferences
// Virtualizer
// create effect
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
{
final String errorTag = methodTag + "Virtualizer error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(),
VIRTUALIZER_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.virt_strength.toString(),
VIRTUALIZER_STRENGTH_DEFAULT);
// init settings
Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength="
+ strength);
virtualizerEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
virtualizerEffect.setEnabled(isEnabled);
} else {
virtualizerEffect.setEnabled(false);
}
// get parameters
settings = virtualizerEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.virt_enabled.toString(), isEnabled);
editor.putInt(Key.virt_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// In case of an existing audio session
// Exit after the virtualizer has been re-enabled
if (isExistingAudioSession) {
- editor.commit();
+ editor.apply();
return;
}
// BassBoost
// create effect
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
{
final String errorTag = methodTag + "BassBoost error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(),
BASS_BOOST_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.bb_strength.toString(),
BASS_BOOST_STRENGTH_DEFAULT);
// init settings
BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength="
+ strength);
bassBoostEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
bassBoostEffect.setEnabled(isEnabled);
} else {
bassBoostEffect.setEnabled(false);
}
// get parameters
settings = bassBoostEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.bb_enabled.toString(), isEnabled);
editor.putInt(Key.bb_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// Equalizer
// create effect
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
{
final String errorTag = methodTag + "Equalizer error: ";
try {
final short eQNumBands;
final short[] bandLevel;
final int[] eQCenterFreq;
final short eQNumPresets;
final String[] eQPresetNames;
short eQPreset;
synchronized (mEQInitLock) {
// read parameters
mEQBandLevelRange = equalizerEffect.getBandLevelRange();
mEQNumBands = equalizerEffect.getNumberOfBands();
mEQCenterFreq = new int[mEQNumBands];
mEQNumPresets = equalizerEffect.getNumberOfPresets();
mEQPresetNames = new String[mEQNumPresets];
for (short preset = 0; preset < mEQNumPresets; preset++) {
mEQPresetNames[preset] = equalizerEffect.getPresetName(preset);
editor.putString(Key.eq_preset_name.toString() + preset,
mEQPresetNames[preset]);
}
editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]);
editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]);
editor.putInt(Key.eq_num_bands.toString(), mEQNumBands);
editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets);
// Resetting the EQ arrays depending on the real # bands with defaults if band <
// default size else 0 by copying default arrays over new ones
final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands);
// If no preset prefs set use CI EXTREME (= numPresets)
eQPreset = (short) prefs
.getInt(Key.eq_current_preset.toString(), mEQNumPresets);
if (eQPreset < mEQNumPresets) {
// OpenSL ES effect presets
equalizerEffect.usePreset(eQPreset);
eQPreset = equalizerEffect.getCurrentPreset();
} else {
for (short band = 0; band < mEQNumBands; band++) {
short level = 0;
if (eQPreset == mEQNumPresets) {
// CI EXTREME
level = eQPresetCIExtremeBandLevel[band];
} else {
// User
level = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
equalizerEffect.setBandLevel(band, level);
}
}
editor.putInt(Key.eq_current_preset.toString(), eQPreset);
bandLevel = new short[mEQNumBands];
for (short band = 0; band < mEQNumBands; band++) {
mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band);
bandLevel[band] = equalizerEffect.getBandLevel(band);
editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]);
editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]);
editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevel[band]);
editor.putInt(Key.eq_preset_user_band_level_default.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
eQNumBands = mEQNumBands;
eQCenterFreq = mEQCenterFreq;
eQNumPresets = mEQNumPresets;
eQPresetNames = mEQPresetNames;
}
final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(),
EQUALIZER_ENABLED_DEFAULT);
editor.putBoolean(Key.eq_enabled.toString(), isEnabled);
if (isGlobalEnabled == true) {
equalizerEffect.setEnabled(isEnabled);
} else {
equalizerEffect.setEnabled(false);
}
// dump
Log.v(TAG, "Parameters: Equalizer");
Log.v(TAG, "bands=" + eQNumBands);
String str = "levels=";
for (short band = 0; band < eQNumBands; band++) {
str = str + bandLevel[band] + "; ";
}
Log.v(TAG, str);
str = "center=";
for (short band = 0; band < eQNumBands; band++) {
str = str + eQCenterFreq[band] + "; ";
}
Log.v(TAG, str);
str = "presets=";
for (short preset = 0; preset < eQNumPresets; preset++) {
str = str + eQPresetNames[preset] + "; ";
}
Log.v(TAG, str);
Log.v(TAG, "current=" + eQPreset);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// XXX: Preset Reverb not used for the moment, so commented out the effect creation to not
// use MIPS left in the code for (future) reference.
// Preset reverb
// create effect
// final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession);
// {
// final String errorTag = methodTag + "PresetReverb error: ";
//
// try {
// // read parameters
// final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(),
// PRESET_REVERB_ENABLED_DEFAULT);
// final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(),
// PRESET_REVERB_CURRENT_PRESET_DEFAULT);
//
// // init settings
// PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset="
// + preset);
//
// // read/update preferences
// presetReverbEffect.setProperties(settings);
//
// // set parameters
// if (isGlobalEnabled == true) {
// presetReverbEffect.setEnabled(isEnabled);
// } else {
// presetReverbEffect.setEnabled(false);
// }
//
// // get parameters
// settings = presetReverbEffect.getProperties();
// Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
//
// // update preferences
// editor.putBoolean(Key.pr_enabled.toString(), isEnabled);
// editor.putInt(Key.pr_current_preset.toString(), settings.preset);
// } catch (final RuntimeException e) {
// Log.e(TAG, errorTag + e);
// }
// }
editor.commit();
}
/**
* Closes the audio session (release effects) for the given session
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
*/
public static void closeSession(final Context context, final String packageName,
final int audioSession) {
Log.v(TAG, "closeSession(" + context + ", " + packageName + ", " + audioSession + ")");
// PresetReverb
final PresetReverb presetReverb = mPresetReverbInstances.remove(audioSession);
if (presetReverb != null) {
presetReverb.release();
}
// Equalizer
final Equalizer equalizer = mEQInstances.remove(audioSession);
if (equalizer != null) {
equalizer.release();
}
// BassBoost
final BassBoost bassBoost = mBassBoostInstances.remove(audioSession);
if (bassBoost != null) {
bassBoost.release();
}
// Virtualizer
final Virtualizer virtualizer = mVirtualizerInstances.remove(audioSession);
if (virtualizer != null) {
virtualizer.release();
}
mPackageSessions.remove(packageName);
}
/**
* Enables or disables all effects (global enable/disable) for a given context, package name and
* audio session. It sets/inits the control mode and preferences and then sets the global
* enabled parameter.
*
* @param context
* @param packageName
* @param audioSession
* System wide unique audio session identifier.
* @param enabled
*/
public static void setEnabledAll(final Context context, final String packageName,
final int audioSession, final boolean enabled) {
initEffectsPreferences(context, packageName, audioSession);
setParameterBoolean(context, packageName, audioSession, Key.global_enabled, enabled);
}
/**
* Gets the virtualizer effect for the given audio session. If the effect on the session doesn't
* exist yet, create it and add to collection.
*
* @param audioSession
* System wide unique audio session identifier.
* @return virtualizerEffect
*/
private static Virtualizer getVirtualizerEffectNoCreate(final int audioSession) {
return mVirtualizerInstances.get(audioSession);
}
private static Virtualizer getVirtualizerEffect(final int audioSession) {
Virtualizer virtualizerEffect = getVirtualizerEffectNoCreate(audioSession);
if (virtualizerEffect == null) {
try {
final Virtualizer newVirtualizerEffect = new Virtualizer(PRIORITY, audioSession);
virtualizerEffect = mVirtualizerInstances.putIfAbsent(audioSession,
newVirtualizerEffect);
if (virtualizerEffect == null) {
// put succeeded, use new value
virtualizerEffect = newVirtualizerEffect;
}
} catch (final IllegalArgumentException e) {
Log.e(TAG, "Virtualizer: " + e);
} catch (final UnsupportedOperationException e) {
Log.e(TAG, "Virtualizer: " + e);
} catch (final RuntimeException e) {
Log.e(TAG, "Virtualizer: " + e);
}
}
return virtualizerEffect;
}
/**
* Gets the bass boost effect for the given audio session. If the effect on the session doesn't
* exist yet, create it and add to collection.
*
* @param audioSession
* System wide unique audio session identifier.
* @return bassBoostEffect
*/
private static BassBoost getBassBoostEffectNoCreate(final int audioSession) {
return mBassBoostInstances.get(audioSession);
}
private static BassBoost getBassBoostEffect(final int audioSession) {
BassBoost bassBoostEffect = getBassBoostEffectNoCreate(audioSession);
if (bassBoostEffect == null) {
try {
final BassBoost newBassBoostEffect = new BassBoost(PRIORITY, audioSession);
bassBoostEffect = mBassBoostInstances.putIfAbsent(audioSession, newBassBoostEffect);
if (bassBoostEffect == null) {
// put succeeded, use new value
bassBoostEffect = newBassBoostEffect;
}
} catch (final IllegalArgumentException e) {
Log.e(TAG, "BassBoost: " + e);
} catch (final UnsupportedOperationException e) {
Log.e(TAG, "BassBoost: " + e);
} catch (final RuntimeException e) {
Log.e(TAG, "BassBoost: " + e);
}
}
return bassBoostEffect;
}
/**
* Gets the equalizer effect for the given audio session. If the effect on the session doesn't
* exist yet, create it and add to collection.
*
* @param audioSession
* System wide unique audio session identifier.
* @return equalizerEffect
*/
private static Equalizer getEqualizerEffectNoCreate(final int audioSession) {
return mEQInstances.get(audioSession);
}
private static Equalizer getEqualizerEffect(final int audioSession) {
Equalizer equalizerEffect = getEqualizerEffectNoCreate(audioSession);
if (equalizerEffect == null) {
try {
final Equalizer newEqualizerEffect = new Equalizer(PRIORITY, audioSession);
equalizerEffect = mEQInstances.putIfAbsent(audioSession, newEqualizerEffect);
if (equalizerEffect == null) {
// put succeeded, use new value
equalizerEffect = newEqualizerEffect;
}
} catch (final IllegalArgumentException e) {
Log.e(TAG, "Equalizer: " + e);
} catch (final UnsupportedOperationException e) {
Log.e(TAG, "Equalizer: " + e);
} catch (final RuntimeException e) {
Log.e(TAG, "Equalizer: " + e);
}
}
return equalizerEffect;
}
// XXX: Preset Reverb not used for the moment, so commented out the effect creation to not
// use MIPS
// /**
// * Gets the preset reverb effect for the given audio session. If the effect on the session
// * doesn't exist yet, create it and add to collection.
// *
// * @param audioSession
// * System wide unique audio session identifier.
// * @return presetReverbEffect
// */
// private static PresetReverb getPresetReverbEffect(final int audioSession) {
// PresetReverb presetReverbEffect = mPresetReverbInstances.get(audioSession);
// if (presetReverbEffect == null) {
// try {
// final PresetReverb newPresetReverbEffect = new PresetReverb(PRIORITY, audioSession);
// presetReverbEffect = mPresetReverbInstances.putIfAbsent(audioSession,
// newPresetReverbEffect);
// if (presetReverbEffect == null) {
// // put succeeded, use new value
// presetReverbEffect = newPresetReverbEffect;
// }
// } catch (final IllegalArgumentException e) {
// Log.e(TAG, "PresetReverb: " + e);
// } catch (final UnsupportedOperationException e) {
// Log.e(TAG, "PresetReverb: " + e);
// } catch (final RuntimeException e) {
// Log.e(TAG, "PresetReverb: " + e);
// }
// }
// return presetReverbEffect;
// }
}
| true | true | public static void openSession(final Context context, final String packageName,
final int audioSession) {
Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")");
final String methodTag = "openSession: ";
// init preferences
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(),
GLOBAL_ENABLED_DEFAULT);
editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled);
if (!isGlobalEnabled) {
return;
}
// Manage audioSession information
// Retrieve AudioSession Id from map
boolean isExistingAudioSession = false;
try {
final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName,
audioSession);
if (currentAudioSession != null) {
// Compare with passed argument
if (currentAudioSession == audioSession) {
// FIXME: Normally, we should exit the function here
// BUT: we have to take care of the virtualizer because of
// a bug in the Android Effects Framework
// editor.commit();
// return;
isExistingAudioSession = true;
} else {
closeSession(context, packageName, currentAudioSession);
}
}
} catch (final NullPointerException e) {
Log.e(TAG, methodTag + e);
editor.commit();
return;
}
// Because the audioSession is new, get effects & settings from shared preferences
// Virtualizer
// create effect
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
{
final String errorTag = methodTag + "Virtualizer error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(),
VIRTUALIZER_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.virt_strength.toString(),
VIRTUALIZER_STRENGTH_DEFAULT);
// init settings
Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength="
+ strength);
virtualizerEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
virtualizerEffect.setEnabled(isEnabled);
} else {
virtualizerEffect.setEnabled(false);
}
// get parameters
settings = virtualizerEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.virt_enabled.toString(), isEnabled);
editor.putInt(Key.virt_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// In case of an existing audio session
// Exit after the virtualizer has been re-enabled
if (isExistingAudioSession) {
editor.commit();
return;
}
// BassBoost
// create effect
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
{
final String errorTag = methodTag + "BassBoost error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(),
BASS_BOOST_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.bb_strength.toString(),
BASS_BOOST_STRENGTH_DEFAULT);
// init settings
BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength="
+ strength);
bassBoostEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
bassBoostEffect.setEnabled(isEnabled);
} else {
bassBoostEffect.setEnabled(false);
}
// get parameters
settings = bassBoostEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.bb_enabled.toString(), isEnabled);
editor.putInt(Key.bb_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// Equalizer
// create effect
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
{
final String errorTag = methodTag + "Equalizer error: ";
try {
final short eQNumBands;
final short[] bandLevel;
final int[] eQCenterFreq;
final short eQNumPresets;
final String[] eQPresetNames;
short eQPreset;
synchronized (mEQInitLock) {
// read parameters
mEQBandLevelRange = equalizerEffect.getBandLevelRange();
mEQNumBands = equalizerEffect.getNumberOfBands();
mEQCenterFreq = new int[mEQNumBands];
mEQNumPresets = equalizerEffect.getNumberOfPresets();
mEQPresetNames = new String[mEQNumPresets];
for (short preset = 0; preset < mEQNumPresets; preset++) {
mEQPresetNames[preset] = equalizerEffect.getPresetName(preset);
editor.putString(Key.eq_preset_name.toString() + preset,
mEQPresetNames[preset]);
}
editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]);
editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]);
editor.putInt(Key.eq_num_bands.toString(), mEQNumBands);
editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets);
// Resetting the EQ arrays depending on the real # bands with defaults if band <
// default size else 0 by copying default arrays over new ones
final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands);
// If no preset prefs set use CI EXTREME (= numPresets)
eQPreset = (short) prefs
.getInt(Key.eq_current_preset.toString(), mEQNumPresets);
if (eQPreset < mEQNumPresets) {
// OpenSL ES effect presets
equalizerEffect.usePreset(eQPreset);
eQPreset = equalizerEffect.getCurrentPreset();
} else {
for (short band = 0; band < mEQNumBands; band++) {
short level = 0;
if (eQPreset == mEQNumPresets) {
// CI EXTREME
level = eQPresetCIExtremeBandLevel[band];
} else {
// User
level = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
equalizerEffect.setBandLevel(band, level);
}
}
editor.putInt(Key.eq_current_preset.toString(), eQPreset);
bandLevel = new short[mEQNumBands];
for (short band = 0; band < mEQNumBands; band++) {
mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band);
bandLevel[band] = equalizerEffect.getBandLevel(band);
editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]);
editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]);
editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevel[band]);
editor.putInt(Key.eq_preset_user_band_level_default.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
eQNumBands = mEQNumBands;
eQCenterFreq = mEQCenterFreq;
eQNumPresets = mEQNumPresets;
eQPresetNames = mEQPresetNames;
}
final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(),
EQUALIZER_ENABLED_DEFAULT);
editor.putBoolean(Key.eq_enabled.toString(), isEnabled);
if (isGlobalEnabled == true) {
equalizerEffect.setEnabled(isEnabled);
} else {
equalizerEffect.setEnabled(false);
}
// dump
Log.v(TAG, "Parameters: Equalizer");
Log.v(TAG, "bands=" + eQNumBands);
String str = "levels=";
for (short band = 0; band < eQNumBands; band++) {
str = str + bandLevel[band] + "; ";
}
Log.v(TAG, str);
str = "center=";
for (short band = 0; band < eQNumBands; band++) {
str = str + eQCenterFreq[band] + "; ";
}
Log.v(TAG, str);
str = "presets=";
for (short preset = 0; preset < eQNumPresets; preset++) {
str = str + eQPresetNames[preset] + "; ";
}
Log.v(TAG, str);
Log.v(TAG, "current=" + eQPreset);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// XXX: Preset Reverb not used for the moment, so commented out the effect creation to not
// use MIPS left in the code for (future) reference.
// Preset reverb
// create effect
// final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession);
// {
// final String errorTag = methodTag + "PresetReverb error: ";
//
// try {
// // read parameters
// final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(),
// PRESET_REVERB_ENABLED_DEFAULT);
// final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(),
// PRESET_REVERB_CURRENT_PRESET_DEFAULT);
//
// // init settings
// PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset="
// + preset);
//
// // read/update preferences
// presetReverbEffect.setProperties(settings);
//
// // set parameters
// if (isGlobalEnabled == true) {
// presetReverbEffect.setEnabled(isEnabled);
// } else {
// presetReverbEffect.setEnabled(false);
// }
//
// // get parameters
// settings = presetReverbEffect.getProperties();
// Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
//
// // update preferences
// editor.putBoolean(Key.pr_enabled.toString(), isEnabled);
// editor.putInt(Key.pr_current_preset.toString(), settings.preset);
// } catch (final RuntimeException e) {
// Log.e(TAG, errorTag + e);
// }
// }
editor.commit();
}
| public static void openSession(final Context context, final String packageName,
final int audioSession) {
Log.v(TAG, "openSession(" + context + ", " + packageName + ", " + audioSession + ")");
final String methodTag = "openSession: ";
// init preferences
final SharedPreferences prefs = context.getSharedPreferences(packageName,
Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
final boolean isGlobalEnabled = prefs.getBoolean(Key.global_enabled.toString(),
GLOBAL_ENABLED_DEFAULT);
editor.putBoolean(Key.global_enabled.toString(), isGlobalEnabled);
if (!isGlobalEnabled) {
return;
}
// Manage audioSession information
// Retrieve AudioSession Id from map
boolean isExistingAudioSession = false;
try {
final Integer currentAudioSession = mPackageSessions.putIfAbsent(packageName,
audioSession);
if (currentAudioSession != null) {
// Compare with passed argument
if (currentAudioSession == audioSession) {
// FIXME: Normally, we should exit the function here
// BUT: we have to take care of the virtualizer because of
// a bug in the Android Effects Framework
// editor.commit();
// return;
isExistingAudioSession = true;
} else {
closeSession(context, packageName, currentAudioSession);
}
}
} catch (final NullPointerException e) {
Log.e(TAG, methodTag + e);
editor.commit();
return;
}
// Because the audioSession is new, get effects & settings from shared preferences
// Virtualizer
// create effect
final Virtualizer virtualizerEffect = getVirtualizerEffect(audioSession);
{
final String errorTag = methodTag + "Virtualizer error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.virt_enabled.toString(),
VIRTUALIZER_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.virt_strength.toString(),
VIRTUALIZER_STRENGTH_DEFAULT);
// init settings
Virtualizer.Settings settings = new Virtualizer.Settings("Virtualizer;strength="
+ strength);
virtualizerEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
virtualizerEffect.setEnabled(isEnabled);
} else {
virtualizerEffect.setEnabled(false);
}
// get parameters
settings = virtualizerEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.virt_enabled.toString(), isEnabled);
editor.putInt(Key.virt_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// In case of an existing audio session
// Exit after the virtualizer has been re-enabled
if (isExistingAudioSession) {
editor.apply();
return;
}
// BassBoost
// create effect
final BassBoost bassBoostEffect = getBassBoostEffect(audioSession);
{
final String errorTag = methodTag + "BassBoost error: ";
try {
// read parameters
final boolean isEnabled = prefs.getBoolean(Key.bb_enabled.toString(),
BASS_BOOST_ENABLED_DEFAULT);
final int strength = prefs.getInt(Key.bb_strength.toString(),
BASS_BOOST_STRENGTH_DEFAULT);
// init settings
BassBoost.Settings settings = new BassBoost.Settings("BassBoost;strength="
+ strength);
bassBoostEffect.setProperties(settings);
// set parameters
if (isGlobalEnabled == true) {
bassBoostEffect.setEnabled(isEnabled);
} else {
bassBoostEffect.setEnabled(false);
}
// get parameters
settings = bassBoostEffect.getProperties();
Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
// update preferences
editor.putBoolean(Key.bb_enabled.toString(), isEnabled);
editor.putInt(Key.bb_strength.toString(), settings.strength);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// Equalizer
// create effect
final Equalizer equalizerEffect = getEqualizerEffect(audioSession);
{
final String errorTag = methodTag + "Equalizer error: ";
try {
final short eQNumBands;
final short[] bandLevel;
final int[] eQCenterFreq;
final short eQNumPresets;
final String[] eQPresetNames;
short eQPreset;
synchronized (mEQInitLock) {
// read parameters
mEQBandLevelRange = equalizerEffect.getBandLevelRange();
mEQNumBands = equalizerEffect.getNumberOfBands();
mEQCenterFreq = new int[mEQNumBands];
mEQNumPresets = equalizerEffect.getNumberOfPresets();
mEQPresetNames = new String[mEQNumPresets];
for (short preset = 0; preset < mEQNumPresets; preset++) {
mEQPresetNames[preset] = equalizerEffect.getPresetName(preset);
editor.putString(Key.eq_preset_name.toString() + preset,
mEQPresetNames[preset]);
}
editor.putInt(Key.eq_level_range.toString() + 0, mEQBandLevelRange[0]);
editor.putInt(Key.eq_level_range.toString() + 1, mEQBandLevelRange[1]);
editor.putInt(Key.eq_num_bands.toString(), mEQNumBands);
editor.putInt(Key.eq_num_presets.toString(), mEQNumPresets);
// Resetting the EQ arrays depending on the real # bands with defaults if band <
// default size else 0 by copying default arrays over new ones
final short[] eQPresetCIExtremeBandLevel = Arrays.copyOf(
EQUALIZER_PRESET_CIEXTREME_BAND_LEVEL, mEQNumBands);
final short[] eQPresetUserBandLevelDefault = Arrays.copyOf(
EQUALIZER_PRESET_USER_BAND_LEVEL_DEFAULT, mEQNumBands);
// If no preset prefs set use CI EXTREME (= numPresets)
eQPreset = (short) prefs
.getInt(Key.eq_current_preset.toString(), mEQNumPresets);
if (eQPreset < mEQNumPresets) {
// OpenSL ES effect presets
equalizerEffect.usePreset(eQPreset);
eQPreset = equalizerEffect.getCurrentPreset();
} else {
for (short band = 0; band < mEQNumBands; band++) {
short level = 0;
if (eQPreset == mEQNumPresets) {
// CI EXTREME
level = eQPresetCIExtremeBandLevel[band];
} else {
// User
level = (short) prefs.getInt(
Key.eq_preset_user_band_level.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
equalizerEffect.setBandLevel(band, level);
}
}
editor.putInt(Key.eq_current_preset.toString(), eQPreset);
bandLevel = new short[mEQNumBands];
for (short band = 0; band < mEQNumBands; band++) {
mEQCenterFreq[band] = equalizerEffect.getCenterFreq(band);
bandLevel[band] = equalizerEffect.getBandLevel(band);
editor.putInt(Key.eq_band_level.toString() + band, bandLevel[band]);
editor.putInt(Key.eq_center_freq.toString() + band, mEQCenterFreq[band]);
editor.putInt(Key.eq_preset_ci_extreme_band_level.toString() + band,
eQPresetCIExtremeBandLevel[band]);
editor.putInt(Key.eq_preset_user_band_level_default.toString() + band,
eQPresetUserBandLevelDefault[band]);
}
eQNumBands = mEQNumBands;
eQCenterFreq = mEQCenterFreq;
eQNumPresets = mEQNumPresets;
eQPresetNames = mEQPresetNames;
}
final boolean isEnabled = prefs.getBoolean(Key.eq_enabled.toString(),
EQUALIZER_ENABLED_DEFAULT);
editor.putBoolean(Key.eq_enabled.toString(), isEnabled);
if (isGlobalEnabled == true) {
equalizerEffect.setEnabled(isEnabled);
} else {
equalizerEffect.setEnabled(false);
}
// dump
Log.v(TAG, "Parameters: Equalizer");
Log.v(TAG, "bands=" + eQNumBands);
String str = "levels=";
for (short band = 0; band < eQNumBands; band++) {
str = str + bandLevel[band] + "; ";
}
Log.v(TAG, str);
str = "center=";
for (short band = 0; band < eQNumBands; band++) {
str = str + eQCenterFreq[band] + "; ";
}
Log.v(TAG, str);
str = "presets=";
for (short preset = 0; preset < eQNumPresets; preset++) {
str = str + eQPresetNames[preset] + "; ";
}
Log.v(TAG, str);
Log.v(TAG, "current=" + eQPreset);
} catch (final RuntimeException e) {
Log.e(TAG, errorTag + e);
}
}
// XXX: Preset Reverb not used for the moment, so commented out the effect creation to not
// use MIPS left in the code for (future) reference.
// Preset reverb
// create effect
// final PresetReverb presetReverbEffect = getPresetReverbEffect(audioSession);
// {
// final String errorTag = methodTag + "PresetReverb error: ";
//
// try {
// // read parameters
// final boolean isEnabled = prefs.getBoolean(Key.pr_enabled.toString(),
// PRESET_REVERB_ENABLED_DEFAULT);
// final short preset = (short) prefs.getInt(Key.pr_current_preset.toString(),
// PRESET_REVERB_CURRENT_PRESET_DEFAULT);
//
// // init settings
// PresetReverb.Settings settings = new PresetReverb.Settings("PresetReverb;preset="
// + preset);
//
// // read/update preferences
// presetReverbEffect.setProperties(settings);
//
// // set parameters
// if (isGlobalEnabled == true) {
// presetReverbEffect.setEnabled(isEnabled);
// } else {
// presetReverbEffect.setEnabled(false);
// }
//
// // get parameters
// settings = presetReverbEffect.getProperties();
// Log.v(TAG, "Parameters: " + settings.toString() + ";enabled=" + isEnabled);
//
// // update preferences
// editor.putBoolean(Key.pr_enabled.toString(), isEnabled);
// editor.putInt(Key.pr_current_preset.toString(), settings.preset);
// } catch (final RuntimeException e) {
// Log.e(TAG, errorTag + e);
// }
// }
editor.commit();
}
|
diff --git a/xsl/webhelp/indexer/src/com/nexwave/nquindexer/SaxHTMLIndex.java b/xsl/webhelp/indexer/src/com/nexwave/nquindexer/SaxHTMLIndex.java
index d9538aed5..ce5cdda58 100755
--- a/xsl/webhelp/indexer/src/com/nexwave/nquindexer/SaxHTMLIndex.java
+++ b/xsl/webhelp/indexer/src/com/nexwave/nquindexer/SaxHTMLIndex.java
@@ -1,253 +1,253 @@
package com.nexwave.nquindexer;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.io.StringReader;
// specific dita ot
import com.nexwave.nsidita.DocFileInfo;
//Stemmers
import com.nexwave.stemmer.snowball.SnowballStemmer;
import com.nexwave.stemmer.snowball.ext.EnglishStemmer;
import com.nexwave.stemmer.snowball.ext.FrenchStemmer;
import com.nexwave.stemmer.snowball.ext.GermanStemmer;
//CJK Tokenizing
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.cjk.CJKTokenizer;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
/**
* Parser for the html files generated by DITA-OT.
* Extracts the title, the shortdesc and the text within the "content" div tag. <div id="content">
*
* @version 1.1 2010
*
* @author N. Quaine
* @author Kasun Gajasinghe <http://kasunbg.blogspot.com>
*/
public class SaxHTMLIndex extends SaxDocFileParser{
//KasunBG: apparently tempDico stores all the keywords and a pointer to the files containing the index in a Map
//example: ("keyword1", "0,2,4"), ("docbook", "1,2,5")
private Map<String,String> tempDico;
private int i = 0;
private ArrayList <String> cleanUpList = null;
private ArrayList <String> cleanUpPunctuation = null;
//methods
/**
* Constructor
*/
public SaxHTMLIndex () {
super();
}
/**
* Constructor
*/
public SaxHTMLIndex (ArrayList <String> cleanUpStrings) {
super();
cleanUpList = cleanUpStrings;
}
/**
* Constructor
*/
public SaxHTMLIndex (ArrayList <String> cleanUpStrings, ArrayList <String> cleanUpChars) {
super();
cleanUpList = cleanUpStrings;
cleanUpPunctuation = cleanUpChars;
}
/**
* Initializer
*/
public int init(Map<String,String> tempMap){
tempDico = tempMap;
return 0;
}
/**
* Parses the file to extract all the words for indexing and
* some data characterizing the file.
* @param file contains the fullpath of the document to parse
* @param indexerLanguage this will be used to tell the program which stemmer to be used.
* @return a DitaFileInfo object filled with data describing the file
*/
public DocFileInfo runExtractData(File file, String indexerLanguage) {
//initialization
fileDesc = new DocFileInfo(file);
strbf = new StringBuffer("");
// Fill strbf by parsing the file
parseDocument(file);
String str = cleanBuffer(strbf);
str = str.replaceAll("\\s+"," "); //there's still redundant spaces in the middle
// System.out.println(file.toString()+" "+ str +"\n");
String[] items = str.split("\\s"); //contains all the words in the array
//get items one-by-one, tunnel through the stemmer, and get the stem.
//Then, add them to tempSet
//Do Stemming for words in items
//TODO currently, stemming support is for english and german only. Add support for other languages as well.
String[] tokenizedItems;
- if(indexerLanguage.equalsIgnoreCase("jp") || indexerLanguage.equalsIgnoreCase("cn")
+ if(indexerLanguage.equalsIgnoreCase("ja") || indexerLanguage.equalsIgnoreCase("cn")
|| indexerLanguage.equalsIgnoreCase("ko")){
LinkedList<String> tokens = new LinkedList<String>();
try{
CJKAnalyzer analyzer = new CJKAnalyzer(org.apache.lucene.util.Version.LUCENE_30);
Reader reader = new StringReader(str);
TokenStream stream = analyzer.tokenStream("", reader);
TermAttribute termAtt = (TermAttribute) stream.addAttribute(TermAttribute.class);
OffsetAttribute offAtt = (OffsetAttribute) stream.addAttribute(OffsetAttribute.class);
while (stream.incrementToken()) {
String term = termAtt.term();
tokens.add(term);
// System.out.println(term + " " + offAtt.startOffset() + " " + offAtt.endOffset());
}
tokenizedItems = tokens.toArray(new String[tokens.size()]);
}catch (IOException ex){
tokenizedItems = items;
System.out.println("Error tokenizing content using CJK Analyzer. IOException");
ex.printStackTrace();
}
} else {
SnowballStemmer stemmer;
if(indexerLanguage.equalsIgnoreCase("en")){
stemmer = new EnglishStemmer();
} else if (indexerLanguage.equalsIgnoreCase("de")){
stemmer= new GermanStemmer();
} else if (indexerLanguage.equalsIgnoreCase("fr")){
stemmer= new FrenchStemmer();
} else {
stemmer = null;//Languages which stemming is not yet supproted.So, No stemmers will be used.
}
if(stemmer != null) //If a stemmer available
tokenizedItems = stemmer.doStem(items);
else //if no stemmer available for the particular language
tokenizedItems = items;
}
/* for(String stemmedItem: tokenizedItems){
System.out.print(stemmedItem+"| ");
}*/
//items: remove the duplicated strings first
HashSet <String> tempSet = new HashSet<String>();
tempSet.addAll(Arrays.asList(tokenizedItems));
Iterator it = tempSet.iterator();
String s;
while (it.hasNext()) {
s = (String)it.next();
if (tempDico.containsKey(s)) {
String temp = tempDico.get(s);
temp = temp.concat(",").concat(Integer.toString(i));
//System.out.println("temp="+s+"="+temp);
tempDico.put(s, temp);
}else {
tempDico.put(s, Integer.toString(i));
}
}
i++;
return fileDesc;
}
/**
* Cleans the string buffer containing all the text retrieved from
* the html file: remove punctuation, clean white spaces, remove the words
* which you do not want to index.
* NOTE: You may customize this function:
* This version takes into account english and japanese. Depending on your
* needs,
* you may have to add/remove some characters/words through props files
* or by modifying tte default code,
* you may want to separate the language processing (doc only in japanese,
* doc only in english, check the language metadata ...).
*/
private String cleanBuffer (StringBuffer strbf) {
String str = strbf.toString().toLowerCase();
StringBuffer tempStrBuf = new StringBuffer("");
StringBuffer tempCharBuf = new StringBuffer("");
if ((cleanUpList == null) || (cleanUpList.isEmpty())){
// Default clean-up
// Should perhaps eliminate the words at the end of the table?
tempStrBuf.append("(?i)\\bthe\\b|\\ba\\b|\\ban\\b|\\bto\\b|\\band\\b|\\bor\\b");//(?i) ignores the case
tempStrBuf.append("|\\bis\\b|\\bare\\b|\\bin\\b|\\bwith\\b|\\bbe\\b|\\bcan\\b");
tempStrBuf.append("|\\beach\\b|\\bhas\\b|\\bhave\\b|\\bof\\b|\\b\\xA9\\b|\\bnot\\b");
tempStrBuf.append("|\\bfor\\b|\\bthis\\b|\\bas\\b|\\bit\\b|\\bhe\\b|\\bshe\\b");
tempStrBuf.append("|\\byou\\b|\\bby\\b|\\bso\\b|\\bon\\b|\\byour\\b|\\bat\\b");
tempStrBuf.append("|\\b-or-\\b|\\bso\\b|\\bon\\b|\\byour\\b|\\bat\\b");
tempStrBuf.append("|\\bI\\b|\\bme\\b|\\bmy\\b");
str = str.replaceFirst("Copyright � 1998-2007 NexWave Solutions.", " ");
//nqu 25.01.2008 str = str.replaceAll("\\b.\\b|\\\\", " ");
// remove contiguous white charaters
//nqu 25.01.2008 str = str.replaceAll("\\s+", " ");
}else {
// Clean-up using the props files
tempStrBuf.append("\\ba\\b");
Iterator it = cleanUpList.iterator();
while (it.hasNext()){
tempStrBuf.append("|\\b"+it.next()+"\\b");
}
}
if ((cleanUpPunctuation != null) && (!cleanUpPunctuation.isEmpty())){
tempCharBuf.append("\\u3002");
Iterator it = cleanUpPunctuation.iterator();
while (it.hasNext()){
tempCharBuf.append("|"+it.next());
}
}
str = minimalClean(str, tempStrBuf, tempCharBuf);
return str;
}
private String minimalClean(String str, StringBuffer tempStrBuf, StringBuffer tempCharBuf) {
String tempPunctuation = new String(tempCharBuf);
str = str.replaceAll("\\s+", " ");
str = str.replaceAll("->", " ");
str = str.replaceAll(IndexerConstants.EUPUNCTUATION1, " ");
str = str.replaceAll(IndexerConstants.EUPUNCTUATION2, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION1, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION2, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION3, " ");
if (tempPunctuation.length() > 0)
{
str = str.replaceAll(tempPunctuation, " ");
}
//remove useless words
str = str.replaceAll(tempStrBuf.toString(), " ");
// Redo punctuation after removing some words: (TODO: useful?)
str = str.replaceAll(IndexerConstants.EUPUNCTUATION1, " ");
str = str.replaceAll(IndexerConstants.EUPUNCTUATION2, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION1, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION2, " ");
str = str.replaceAll(IndexerConstants.JPPUNCTUATION3, " ");
if (tempPunctuation.length() > 0)
{
str = str.replaceAll(tempPunctuation, " ");
} return str;
}
}
| true | true | public DocFileInfo runExtractData(File file, String indexerLanguage) {
//initialization
fileDesc = new DocFileInfo(file);
strbf = new StringBuffer("");
// Fill strbf by parsing the file
parseDocument(file);
String str = cleanBuffer(strbf);
str = str.replaceAll("\\s+"," "); //there's still redundant spaces in the middle
// System.out.println(file.toString()+" "+ str +"\n");
String[] items = str.split("\\s"); //contains all the words in the array
//get items one-by-one, tunnel through the stemmer, and get the stem.
//Then, add them to tempSet
//Do Stemming for words in items
//TODO currently, stemming support is for english and german only. Add support for other languages as well.
String[] tokenizedItems;
if(indexerLanguage.equalsIgnoreCase("jp") || indexerLanguage.equalsIgnoreCase("cn")
|| indexerLanguage.equalsIgnoreCase("ko")){
LinkedList<String> tokens = new LinkedList<String>();
try{
CJKAnalyzer analyzer = new CJKAnalyzer(org.apache.lucene.util.Version.LUCENE_30);
Reader reader = new StringReader(str);
TokenStream stream = analyzer.tokenStream("", reader);
TermAttribute termAtt = (TermAttribute) stream.addAttribute(TermAttribute.class);
OffsetAttribute offAtt = (OffsetAttribute) stream.addAttribute(OffsetAttribute.class);
while (stream.incrementToken()) {
String term = termAtt.term();
tokens.add(term);
// System.out.println(term + " " + offAtt.startOffset() + " " + offAtt.endOffset());
}
tokenizedItems = tokens.toArray(new String[tokens.size()]);
}catch (IOException ex){
tokenizedItems = items;
System.out.println("Error tokenizing content using CJK Analyzer. IOException");
ex.printStackTrace();
}
} else {
SnowballStemmer stemmer;
if(indexerLanguage.equalsIgnoreCase("en")){
stemmer = new EnglishStemmer();
} else if (indexerLanguage.equalsIgnoreCase("de")){
stemmer= new GermanStemmer();
} else if (indexerLanguage.equalsIgnoreCase("fr")){
stemmer= new FrenchStemmer();
} else {
stemmer = null;//Languages which stemming is not yet supproted.So, No stemmers will be used.
}
if(stemmer != null) //If a stemmer available
tokenizedItems = stemmer.doStem(items);
else //if no stemmer available for the particular language
tokenizedItems = items;
}
/* for(String stemmedItem: tokenizedItems){
System.out.print(stemmedItem+"| ");
}*/
| public DocFileInfo runExtractData(File file, String indexerLanguage) {
//initialization
fileDesc = new DocFileInfo(file);
strbf = new StringBuffer("");
// Fill strbf by parsing the file
parseDocument(file);
String str = cleanBuffer(strbf);
str = str.replaceAll("\\s+"," "); //there's still redundant spaces in the middle
// System.out.println(file.toString()+" "+ str +"\n");
String[] items = str.split("\\s"); //contains all the words in the array
//get items one-by-one, tunnel through the stemmer, and get the stem.
//Then, add them to tempSet
//Do Stemming for words in items
//TODO currently, stemming support is for english and german only. Add support for other languages as well.
String[] tokenizedItems;
if(indexerLanguage.equalsIgnoreCase("ja") || indexerLanguage.equalsIgnoreCase("cn")
|| indexerLanguage.equalsIgnoreCase("ko")){
LinkedList<String> tokens = new LinkedList<String>();
try{
CJKAnalyzer analyzer = new CJKAnalyzer(org.apache.lucene.util.Version.LUCENE_30);
Reader reader = new StringReader(str);
TokenStream stream = analyzer.tokenStream("", reader);
TermAttribute termAtt = (TermAttribute) stream.addAttribute(TermAttribute.class);
OffsetAttribute offAtt = (OffsetAttribute) stream.addAttribute(OffsetAttribute.class);
while (stream.incrementToken()) {
String term = termAtt.term();
tokens.add(term);
// System.out.println(term + " " + offAtt.startOffset() + " " + offAtt.endOffset());
}
tokenizedItems = tokens.toArray(new String[tokens.size()]);
}catch (IOException ex){
tokenizedItems = items;
System.out.println("Error tokenizing content using CJK Analyzer. IOException");
ex.printStackTrace();
}
} else {
SnowballStemmer stemmer;
if(indexerLanguage.equalsIgnoreCase("en")){
stemmer = new EnglishStemmer();
} else if (indexerLanguage.equalsIgnoreCase("de")){
stemmer= new GermanStemmer();
} else if (indexerLanguage.equalsIgnoreCase("fr")){
stemmer= new FrenchStemmer();
} else {
stemmer = null;//Languages which stemming is not yet supproted.So, No stemmers will be used.
}
if(stemmer != null) //If a stemmer available
tokenizedItems = stemmer.doStem(items);
else //if no stemmer available for the particular language
tokenizedItems = items;
}
/* for(String stemmedItem: tokenizedItems){
System.out.print(stemmedItem+"| ");
}*/
|
diff --git a/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelsRcpModule.java b/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelsRcpModule.java
index e0cd85042..8bfca08bf 100644
--- a/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelsRcpModule.java
+++ b/plugins/org.eclipse.recommenders.models.rcp/src/org/eclipse/recommenders/internal/models/rcp/ModelsRcpModule.java
@@ -1,197 +1,197 @@
/**
* Copyright (c) 2010, 2013 Darmstadt University of Technology.
* 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:
* Olav Lenz - initial API and implementation
*/
package org.eclipse.recommenders.internal.models.rcp;
import static com.google.inject.Scopes.SINGLETON;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.core.internal.net.ProxyManager;
import org.eclipse.core.net.proxy.IProxyService;
import org.eclipse.core.runtime.Platform;
import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.recommenders.models.IModelArchiveCoordinateAdvisor;
import org.eclipse.recommenders.models.IModelIndex;
import org.eclipse.recommenders.models.IModelRepository;
import org.eclipse.recommenders.models.IProjectCoordinateAdvisor;
import org.eclipse.recommenders.models.advisors.JREDirectoryNameAdvisor;
import org.eclipse.recommenders.models.advisors.JREExecutionEnvironmentAdvisor;
import org.eclipse.recommenders.models.advisors.JREReleaseFileAdvisor;
import org.eclipse.recommenders.models.advisors.MavenCentralFingerprintSearchAdvisor;
import org.eclipse.recommenders.models.advisors.MavenPomPropertiesAdvisor;
import org.eclipse.recommenders.models.advisors.MavenPomXmlAdvisor;
import org.eclipse.recommenders.models.advisors.ModelIndexBundleSymbolicNameAdvisor;
import org.eclipse.recommenders.models.advisors.ModelIndexFingerprintAdvisor;
import org.eclipse.recommenders.models.advisors.OsgiManifestAdvisor;
import org.eclipse.recommenders.models.advisors.ProjectCoordinateAdvisorService;
import org.eclipse.recommenders.models.rcp.IProjectCoordinateProvider;
import org.eclipse.ui.IWorkbench;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.eventbus.EventBus;
import com.google.common.io.Files;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.name.Names;
@SuppressWarnings("restriction")
public class ModelsRcpModule extends AbstractModule implements Module {
private static final Logger LOG = LoggerFactory.getLogger(ModelsRcpModule.class);
public static final String IDENTIFIED_PACKAGE_FRAGMENT_ROOTS = "IDENTIFIED_PACKAGE_FRAGMENT_ROOTS";
public static final String REPOSITORY_BASEDIR = "REPOSITORY_BASEDIR";
public static final String INDEX_BASEDIR = "INDEX_BASEDIR";
public static final String MANUAL_MAPPINGS = "MANUAL_MAPPINGS";
public static final String AVAILABLE_ADVISORS = "DEFAULT_ADVISORS";
@Override
protected void configure() {
requestStaticInjection(Dependencies.class);
//
bind(IProjectCoordinateProvider.class).to(ProjectCoordinateProvider.class).in(SINGLETON);
// bind all clients of IRecommendersModelIndex or its super interface IModelArchiveCoordinateProvider to a
// single instance in Eclipse:
bind(EclipseModelIndex.class).in(SINGLETON);
bind(IModelArchiveCoordinateAdvisor.class).to(EclipseModelIndex.class);
bind(IModelIndex.class).to(EclipseModelIndex.class);
createAndBindNamedFile("index", INDEX_BASEDIR);
//
bind(EclipseModelRepository.class).in(SINGLETON);
bind(IModelRepository.class).to(EclipseModelRepository.class);
createAndBindNamedFile("repository", REPOSITORY_BASEDIR);
// configure caching
bind(ManualProjectCoordinateAdvisor.class).in(SINGLETON);
createAndBindNamedFile("caches/manual-mappings.json", MANUAL_MAPPINGS);
createAndBindNamedFile("caches/identified-project-coordinates.json", IDENTIFIED_PACKAGE_FRAGMENT_ROOTS);
}
private void createAndBindNamedFile(String fileName, String name) {
Bundle bundle = FrameworkUtil.getBundle(getClass());
File stateLocation = Platform.getStateLocation(bundle).toFile();
File file = new File(stateLocation, fileName);
try {
Files.createParentDirs(file);
} catch (IOException e) {
LOG.error("failed to bind file name", e);
}
bind(File.class).annotatedWith(Names.named(name)).toInstance(file);
}
@Singleton
@Provides
public EclipseDependencyListener provideMappingProvider(EventBus bus) {
return new EclipseDependencyListener(bus);
}
@Provides
public IProxyService provideProxyService() {
return ProxyManager.getProxyManager();
}
@Singleton
@Provides
@Named(AVAILABLE_ADVISORS)
public List<String> provideAdvisors() {
List<String> availableAdvisors = Lists.newArrayList();
ManualProjectCoordinateAdvisor.class.getName();
availableAdvisors.add(ManualProjectCoordinateAdvisor.class.getName());
availableAdvisors.add(MavenPomPropertiesAdvisor.class.getName());
availableAdvisors.add(JREExecutionEnvironmentAdvisor.class.getName());
availableAdvisors.add(JREReleaseFileAdvisor.class.getName());
availableAdvisors.add(JREDirectoryNameAdvisor.class.getName());
availableAdvisors.add(MavenPomXmlAdvisor.class.getName());
availableAdvisors.add(ModelIndexBundleSymbolicNameAdvisor.class.getName());
availableAdvisors.add(ModelIndexFingerprintAdvisor.class.getName());
availableAdvisors.add(OsgiManifestAdvisor.class.getName());
availableAdvisors.add(MavenCentralFingerprintSearchAdvisor.class.getName());
availableAdvisors.add("!" + NestedJarProjectCoordinateAdvisor.class.getName());
return ImmutableList.copyOf(availableAdvisors);
}
@Singleton
@Provides
public ProjectCoordinateAdvisorService provideMappingProvider(ModelsRcpPreferences prefs, IModelIndex index,
ManualProjectCoordinateAdvisor manualMappingStrategy) throws Exception {
List<IProjectCoordinateAdvisor> availableAdvisors = Lists.newArrayList();
ProjectCoordinateAdvisorService mappingProvider = new ProjectCoordinateAdvisorService();
for (String advisorName : prefs.advisors.split(";")) {
IProjectCoordinateAdvisor advisor = createAdvisor(advisorName, manualMappingStrategy, index).orNull();
if (advisor != null){
availableAdvisors.add(advisor);
}
}
mappingProvider.setAdvisors(Advisors.createAdvisorList(availableAdvisors, prefs.advisors));
return mappingProvider;
}
private Optional<IProjectCoordinateAdvisor> createAdvisor(String advisorName,
ManualProjectCoordinateAdvisor manualMappingStrategy, IModelIndex index) {
if (advisorName.equals(ManualProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(manualMappingStrategy);
}
if (advisorName.equals(MavenPomPropertiesAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomPropertiesAdvisor());
}
if (advisorName.equals(JREExecutionEnvironmentAdvisor.class.getName())) {
- return Optional.<IProjectCoordinateAdvisor>of(new MavenPomPropertiesAdvisor());
+ return Optional.<IProjectCoordinateAdvisor>of(new JREExecutionEnvironmentAdvisor());
}
if (advisorName.equals(JREReleaseFileAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREReleaseFileAdvisor());
}
if (advisorName.equals(JREDirectoryNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREDirectoryNameAdvisor());
}
if (advisorName.equals(MavenPomXmlAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomXmlAdvisor());
}
if (advisorName.equals(ModelIndexBundleSymbolicNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexBundleSymbolicNameAdvisor(index));
}
if (advisorName.equals(ModelIndexFingerprintAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexFingerprintAdvisor(index));
}
if (advisorName.equals(OsgiManifestAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new OsgiManifestAdvisor());
}
if (advisorName.equals(MavenCentralFingerprintSearchAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenCentralFingerprintSearchAdvisor());
}
if (advisorName.equals(NestedJarProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new NestedJarProjectCoordinateAdvisor());
}
return Optional.<IProjectCoordinateAdvisor>absent();
}
@Provides
@Singleton
public ModelsRcpPreferences provide(IWorkbench wb) {
IEclipseContext context = (IEclipseContext) wb.getService(IEclipseContext.class);
ModelsRcpPreferences prefs = ContextInjectionFactory.make(ModelsRcpPreferences.class, context);
return prefs;
}
}
| true | true | private Optional<IProjectCoordinateAdvisor> createAdvisor(String advisorName,
ManualProjectCoordinateAdvisor manualMappingStrategy, IModelIndex index) {
if (advisorName.equals(ManualProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(manualMappingStrategy);
}
if (advisorName.equals(MavenPomPropertiesAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomPropertiesAdvisor());
}
if (advisorName.equals(JREExecutionEnvironmentAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomPropertiesAdvisor());
}
if (advisorName.equals(JREReleaseFileAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREReleaseFileAdvisor());
}
if (advisorName.equals(JREDirectoryNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREDirectoryNameAdvisor());
}
if (advisorName.equals(MavenPomXmlAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomXmlAdvisor());
}
if (advisorName.equals(ModelIndexBundleSymbolicNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexBundleSymbolicNameAdvisor(index));
}
if (advisorName.equals(ModelIndexFingerprintAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexFingerprintAdvisor(index));
}
if (advisorName.equals(OsgiManifestAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new OsgiManifestAdvisor());
}
if (advisorName.equals(MavenCentralFingerprintSearchAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenCentralFingerprintSearchAdvisor());
}
if (advisorName.equals(NestedJarProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new NestedJarProjectCoordinateAdvisor());
}
return Optional.<IProjectCoordinateAdvisor>absent();
}
| private Optional<IProjectCoordinateAdvisor> createAdvisor(String advisorName,
ManualProjectCoordinateAdvisor manualMappingStrategy, IModelIndex index) {
if (advisorName.equals(ManualProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(manualMappingStrategy);
}
if (advisorName.equals(MavenPomPropertiesAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomPropertiesAdvisor());
}
if (advisorName.equals(JREExecutionEnvironmentAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREExecutionEnvironmentAdvisor());
}
if (advisorName.equals(JREReleaseFileAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREReleaseFileAdvisor());
}
if (advisorName.equals(JREDirectoryNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new JREDirectoryNameAdvisor());
}
if (advisorName.equals(MavenPomXmlAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenPomXmlAdvisor());
}
if (advisorName.equals(ModelIndexBundleSymbolicNameAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexBundleSymbolicNameAdvisor(index));
}
if (advisorName.equals(ModelIndexFingerprintAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new ModelIndexFingerprintAdvisor(index));
}
if (advisorName.equals(OsgiManifestAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new OsgiManifestAdvisor());
}
if (advisorName.equals(MavenCentralFingerprintSearchAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new MavenCentralFingerprintSearchAdvisor());
}
if (advisorName.equals(NestedJarProjectCoordinateAdvisor.class.getName())) {
return Optional.<IProjectCoordinateAdvisor>of(new NestedJarProjectCoordinateAdvisor());
}
return Optional.<IProjectCoordinateAdvisor>absent();
}
|
diff --git a/src/main/java/nl/lolmewn/sortal/EventListener.java b/src/main/java/nl/lolmewn/sortal/EventListener.java
index 52d0837..9c75f33 100644
--- a/src/main/java/nl/lolmewn/sortal/EventListener.java
+++ b/src/main/java/nl/lolmewn/sortal/EventListener.java
@@ -1,632 +1,635 @@
/*
* EventListener.java
*
* Copyright (c) 2012 Lolmewn <[email protected]>.
*
* Sortal 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.
*
* Sortal 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 Sortal. If not, see <http ://www.gnu.org/licenses/>.
*/
package nl.lolmewn.sortal;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
/**
*
* @author Lolmewn <[email protected]>
*/
public class EventListener implements Listener {
private Main plugin;
private Main getPlugin() {
return this.plugin;
}
private Localisation getLocalisation() {
return this.getPlugin().getSettings().getLocalisation();
}
public EventListener(Main main) {
this.plugin = main;
}
@EventHandler
public void onSignChange(SignChangeEvent event) {
for (int i = 0; i < event.getLines().length; i++) {
if (this.getPlugin().getSettings().isDebug()) {
this.getPlugin().getLogger().log(Level.INFO, String.format("[Debug] Checking line "
+ "%s of the sign", i));
}
if (event.getLine(i).toLowerCase().contains("[sortal]")
|| event.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) {
if (!event.getPlayer().hasPermission("sortal.placesign")) {
event.getPlayer().sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
}
}
@EventHandler
public void onPlayerHitSign(PlayerInteractEvent event) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Block b = event.getClickedBlock();
Player p = event.getPlayer();
if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST)
|| b.getType().equals(Material.WALL_SIGN)) {
this.getPlugin().debug("Sign has been clicked");
//It's a sign
Sign s = (Sign) b.getState();
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
if (sortalSign(s, p)) {
event.setCancelled(true);
}
return;
}
int found = -1;
for (int i = 0; i < s.getLines().length; i++) {
if (s.getLine(i).toLowerCase().contains("[sortal]")
|| s.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) {
//It's a sortal sign
found = i;
break;
}
}
if (found == -1) {
if (!this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
return; //nvm it's not a sortal sign of any kind.
}
if (!p.hasPermission("sortal.warp")) {
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign.hasWarp()) {
this.getPlugin().debug(String.format("[Debug] Sign clicked has warp: %s", sign.getWarp()));
if (this.getPlugin().getSettings().isPerWarpPerm()) {
this.getPlugin().debug("[Debug] WarpPerPerm = true");
if (!p.hasPermission("sortal.warp." + sign.getWarp())) {
this.getPlugin().debug(String.format("[Debug] No perms! Needed: sortal.warp.%s", sign.getWarp()));
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(sign.getWarp());
if (w == null) {
this.getPlugin().debug("[Debug] Warp w == null, cancelling");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (!canPay(w, sign, p)) {
this.getPlugin().debug(String.format("[Debug] Can't pay: %s", getPrice(w, sign)));
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().debug(String.format("[Debug] Player is paying.."));
this.getPlugin().pay(p, this.getPrice(w, sign));
Location loc = w.getLocation();
+ if(!loc.getChunk().isLoaded()){loc.getChunk().load();}
if (loc.getYaw() == 0 && loc.getPitch() == 0) {
loc.setYaw(p.getLocation().getYaw());
loc.setPitch(p.getLocation().getPitch());
}
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
this.getPlugin().debug(String.format("[Debug] Teleported to: %s", w.getName()));
p.sendMessage(this.getLocalisation().getPlayerTeleported(w.getName()));
event.setCancelled(true); //Cancel, don't place block.
return;
}
this.getPlugin().debug(String.format("[Debug] Error in sign!"));
p.sendMessage(this.getLocalisation().getErrorInSign()); //Sign does have something but no warp -> weird.
event.setCancelled(true);
return; //have to return, otherwise it'll check the next lines
}
if (!p.hasPermission("sortal.warp")) {
this.getPlugin().debug("No perms - need sortal.warp");
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
String nextLine = s.getLine(found + 1);
if (nextLine == null || nextLine.equals("")) {
//Well, that didn't really work out well..
this.getPlugin().debug("nextLine == null || \"\" ");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (nextLine.contains("w:")) {
//It's a warp
String warp = nextLine.split(":")[1];
if (this.getPlugin().getSettings().isPerWarpPerm()) {
if (!p.hasPermission("sortal.warp." + warp)) {
this.getPlugin().debug("No perms - need sortal.warp." + warp);
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!this.getPlugin().getWarpManager().hasWarp(warp)) {
this.getPlugin().debug("Warp not found!");
p.sendMessage(this.getLocalisation().getWarpNotFound(warp));
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(warp);
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(w, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
+ if(!w.getLocation().getChunk().isLoaded()){w.getLocation().getChunk().load();}
this.getPlugin().pay(p, this.getPrice(w, sign));
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(warp));
event.setCancelled(true);
return;
}
if (nextLine.contains(",")) {
String[] split = nextLine.split(",");
World w;
int add = 0;
if (split.length == 3) {
w = p.getWorld();
} else {
w = this.getPlugin().getServer().getWorld(split[0]);
if (w == null) {
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
add = 1;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(null, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(null, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(null, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().pay(p, this.getPrice(null, sign));
int x = Integer.parseInt(split[0 + add]), y = Integer.parseInt(split[1 + add]),
z = Integer.parseInt(split[2 + add]);
Location dest = new Location(w, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch());
+ if(!dest.getChunk().isLoaded()){dest.getChunk().load();}
p.teleport(dest, TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(
dest.getBlockX() + ", " + dest.getBlockY() + ", " + dest.getBlockZ()));
event.setCancelled(true);
return;
}
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
}
}
}
private boolean sortalSign(Sign s, Player player) {
//checks whether
if (this.getPlugin().setcost.containsKey(player.getName())) {
if (this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
//It's a registered sign
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
sign.setPrice(this.getPlugin().setcost.remove(player.getName()));
player.sendMessage("Price set to " + sign.getPrice() + " for this sign!");
return true;
}
for (String line : s.getLines()) {
if (line.toLowerCase().contains("[sortal]") || line.contains(this.getPlugin().getSettings().getSignContains())) {
SignInfo sign = this.getPlugin().getWarpManager().addSign(s.getLocation());
sign.setPrice(this.getPlugin().setcost.remove(player.getName()));
sign.setOwner(player.getName());
player.sendMessage("Price set to " + this.getPlugin().getWarpManager().getSign(s.getLocation()).getPrice() + " for this sign!");
return true;
}
}
player.sendMessage("This is not a valid sortal sign!");
return true;
}
if (this.getPlugin().register.containsKey(player.getName())) {
if (this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
//It's a registered sign
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
sign.setWarp(this.getPlugin().register.remove(player.getName()));
player.sendMessage("Sign is now pointing to " + sign.getWarp());
return true;
}
SignInfo sign = this.getPlugin().getWarpManager().addSign(s.getLocation());
String warp = this.getPlugin().register.remove(player.getName());
sign.setWarp(warp);
sign.setOwner(player.getName());
player.sendMessage("Sign is now pointing to " + warp);
return true;
}
if (this.getPlugin().unregister.contains(player.getName())) {
if (!this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
player.sendMessage("This sign isn't registered, please hit a registered sign to unregister!");
return true;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (!sign.hasWarp()) {
player.sendMessage("This sign isn't pointing to a warp!");
return true;
}
if (!sign.hasPrice()) {
//Sign doesn't have a price and warp gets removed, remove whole sign info
if (this.getPlugin().getSettings().useMySQL()) {
sign.delete(this.getPlugin().getMySQL(), this.getPlugin().getSignTable());
} else {
sign.delete(this.getPlugin().getWarpManager().signFile);
}
player.sendMessage("Unregistered sign! No data left for sign, removing..");
this.getPlugin().unregister.remove(player.getName());
return true;
}
sign.setWarp(null);
this.getPlugin().unregister.remove(player.getName());
player.sendMessage("Sign unregistered!");
return true;
}
if (this.getPlugin().setuses.containsKey(player.getName())) {
SignInfo info;
if (this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
info = this.getPlugin().getWarpManager().getSign(s.getLocation());
} else {
info = this.getPlugin().getWarpManager().addSign(s.getLocation());
}
String uses = this.getPlugin().setuses.remove(player.getName());
String[] split = uses.split(",");
info.setUses(Integer.parseInt(split[1]));
info.setUsedTotalBased(split[0].equals("total") ? true : false);
player.sendMessage("Uses set to " + info.getUses() + " for this sign, " + (info.isUsedTotalBased() ? "total based" : "player based") + "!");
return true;
}
if (this.getPlugin().setPrivate.contains(player.getName())) {
SignInfo sign;
if (this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
} else {
sign = this.getPlugin().getWarpManager().addSign(s.getLocation());
}
sign.setIsPrivate(!sign.isPrivate());
player.sendMessage("This sign is now " + (sign.isPrivate() ? "private" : "public"));
this.getPlugin().setPrivate.remove(player.getName());
if (this.getPlugin().setPrivateUsers.containsKey(player.getName())) {
for (String name : this.getPlugin().setPrivateUsers.get(player.getName())) {
sign.addPrivateUser(name);
}
player.sendMessage(this.getPlugin().setPrivateUsers.remove(player.getName()).size() + " players added!");
return true;
}
return true;
}
if (this.getPlugin().setPrivateUsers.containsKey(player.getName())) {
if (!this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
player.sendMessage("Please hit a private sign!");
return true;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (!sign.isPrivate()) {
player.sendMessage("Please hit a private sign!");
return true;
}
for (String name : this.getPlugin().setPrivateUsers.get(player.getName())) {
sign.addPrivateUser(name);
}
player.sendMessage(this.getPlugin().setPrivateUsers.remove(player.getName()).size() + " players added!");
return true;
}
return false;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Block b = event.getBlock();
if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST)
|| b.getType().equals(Material.WALL_SIGN)) {
Sign s = (Sign) b.getState();
for (String line : s.getLines()) {
if (line.toLowerCase().contains("[sortal]") || line.toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) {
if (!event.getPlayer().hasPermission("sortal.breaksign")) {
event.getPlayer().sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
}
//no [Sortal] or whatever on sign, maybe registered?
if (this.getPlugin().getWarpManager().hasSignInfo(b.getLocation())) {
if (!event.getPlayer().hasPermission("sortal.breaksign")) {
event.getPlayer().sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
}
SignInfo i = this.getPlugin().getWarpManager().getSign(b.getLocation());
if (this.getPlugin().getSettings().useMySQL()) {
i.delete(this.getPlugin().getMySQL(), this.getPlugin().getSignTable());
} else {
i.delete(this.getPlugin().getWarpManager().signFile);
}
}
}
}
/*
* @return returns true if the check was completed without denial
*/
private boolean usesCheck(Warp w, SignInfo sign, Player p) {
UserInfo f = this.getPlugin().getWarpManager().getUserInfo(p.getName());
if (w == null && sign == null) {
this.getPlugin().debug("[Debug] Uses end code 1");
return true;
}
if (w == null) {
if (sign.getUses() == -1) {
this.getPlugin().debug("[Debug] Uses end code 2.1");
return true;
}
}
if (sign == null) {
if (w.getUses() == -1) {
this.getPlugin().debug("[Debug] Uses end code 2.2");
return true;
}
}
if (w == null) {
//warp is unlimited then
if (sign.isUsedTotalBased()) {
if (sign.getUsed() >= sign.getUses()) {
this.getPlugin().debug("[Debug] Uses end code 3");
//Used more often than allowed
return false;
}
sign.setUsed(sign.getUsed() + 1);
this.getPlugin().debug("[Debug] Uses end code 4");
return true;
} else {
if (sign.getUses() > f.getUsedLocation(sign.getLocation())) {
//Not used as many times as allowed
f.addtoUsedLocation(sign.getLocation(), 1);
this.getPlugin().debug("[Debug] Uses end code 5");
return true;
}
this.getPlugin().debug("[Debug] Uses end code 6");
return false;
}
}
if (sign == null) {
//warp is unlimited then
if (w.isUsedTotalBased()) {
if (w.getUsed() >= w.getUses()) {
this.getPlugin().debug("[Debug] Uses end code 7");
//Used more often than allowed
return false;
}
w.setUsed(w.getUsed() + 1);
this.getPlugin().debug("[Debug] Uses end code 8");
return true;
} else {
if (w.getUses() > f.getUsedWarp(w.getName())) {
//Not used as many times as allowed
f.addtoUsedWarp(w.getName(), 1);
this.getPlugin().debug("[Debug] Uses end code 9," + w.getUses() + "," + f.getUsedWarp(w.getName()));
return true;
}
this.getPlugin().debug("[Debug] Uses end code 10");
return false;
}
}
if (sign.getUses() == -1 && w.getUses() == -1) {
//both are unlimited
this.getPlugin().debug("[Debug] Uses end code 11");
return true;
}
if (w.getUses() == -1) {
//warp is unlimited, sign isn't or it'd already returned true
if (sign.isUsedTotalBased()) {
if (sign.getUsed() >= sign.getUses()) {
//Used more often than allowed
this.getPlugin().debug("[Debug] Uses end code 12");
return false;
} else {
sign.setUsed(sign.getUsed() + 1);
this.getPlugin().debug("[Debug] Uses end code 13");
return true;
}
} else {
if (sign.getUses() > f.getUsedLocation(sign.getLocation())) {
//Not used as many times as allowed
f.addtoUsedLocation(sign.getLocation(), 1);
this.getPlugin().debug("[Debug] Uses end code 14");
return true;
} else {
this.getPlugin().debug("[Debug] Uses end code 15");
return false;
}
}
}
if (sign.getUses() == -1) {
if (w.isUsedTotalBased()) {
if (w.getUsed() >= w.getUses()) {
//Used more often than allowed
this.getPlugin().debug("[Debug] Uses end code 16");
return false;
} else {
w.setUsed(w.getUsed() + 1);
this.getPlugin().debug("[Debug] Uses end code 17");
return true;
}
} else {
if (w.getUses() > f.getUsedWarp(w.getName())) {
//Not used as many times as allowed
f.addtoUsedWarp(w.getName(), 1);
this.getPlugin().debug("[Debug] Uses end code 18");
return true;
} else {
this.getPlugin().debug("[Debug] Uses end code 19");
return false;
}
}
}
//They both aren't -1, doing epic face check
if (w.isUsedTotalBased()) {
if (w.getUsed() >= w.getUses()) {
this.getPlugin().debug("[Debug] Uses end code 20");
//Used more often than allowed
return false;
}
if (sign.isUsedTotalBased()) {
if (sign.getUsed() >= sign.getUses()) {
this.getPlugin().debug("[Debug] Uses end code 21");
//Used more often than allowed
return false;
}
this.getPlugin().debug("[Debug] Uses end code 22");
sign.setUsed(sign.getUsed() + 1);
w.setUsed(w.getUsed() + 1);
return true;
}
if (sign.getUses() > f.getUsedLocation(sign.getLocation())) {
this.getPlugin().debug("[Debug] Uses end code 23");
w.setUsed(w.getUsed() + 1);
f.addtoUsedLocation(sign.getLocation(), 1);
return true;
}
this.getPlugin().debug("[Debug] Uses end code 24");
return false;
}
if (sign.isUsedTotalBased()) {
if (sign.getUsed() >= sign.getUses()) {
this.getPlugin().debug("[Debug] Uses end code 25");
return false;
}
//w cant be usedTotalBased
if (w.getUses() > f.getUsedWarp(w.getName())) {
this.getPlugin().debug("[Debug] Uses end code 26");
sign.setUsed(sign.getUsed() + 1);
f.addtoUsedWarp(w.getName(), 1);
return true;
}
this.getPlugin().debug("[Debug] Uses end code 27");
return false;
} else {
if (w.getUses() <= f.getUsedWarp(w.getName())) {
this.getPlugin().debug("[Debug] Uses end code 28");
return false;
}
if (sign.getUses() <= f.getUsedLocation(sign.getLocation())) {
this.getPlugin().debug("[Debug] Uses end code 29");
return false;
}
f.addtoUsedLocation(sign.getLocation(), 1);
f.addtoUsedWarp(w.getName(), 1);
this.getPlugin().debug("[Debug] Uses end code 30");
return true;
}
//both player based
}
private boolean canPay(Warp w, SignInfo sign, Player p) {
if (this.getPlugin().canPay(p, this.getPrice(w, sign))) {
return true;
}
return false;
}
private int getPrice(Warp w, SignInfo sign) {
if (sign != null && sign.hasPrice()) {
return sign.getPrice();
} else if (w != null && w.hasPrice()) {
return w.getPrice();
} else {
return this.getPlugin().getSettings().getWarpUsePrice();
}
}
private boolean isPrivateUser(SignInfo sign, Player p) {
if(!sign.isPrivate()){
return true;
}
this.getPlugin().debug("[Debug] Sign is private");
if (!sign.isPrivateUser(p.getName())) {
this.getPlugin().debug("[Debug] Not a PrivateUser");
//not a private user, maybe setting overrides
if (this.getPlugin().getSettings().isSignCreatorIsPrivateUser()) {
this.getPlugin().debug("[Debug] Setting is true, checking owner");
if (sign.hasOwner()) {
this.getPlugin().debug("[Debug] Sign has owner!");
if(sign.getOwner().equals(p.getName())){
this.getPlugin().debug("[Debug] Wow! They're the same!");
return true;
}
this.getPlugin().debug("[Debug] Aww.. Another owner for this sign!");
return false;
}
this.getPlugin().debug("[Debug] Sign has no owner");
return false;
}
this.getPlugin().debug("[Debug] Setting is false -> false");
return false;
}
this.getPlugin().debug("[Debug] Player is a private user.");
return true;
}
}
| false | true | public void onPlayerHitSign(PlayerInteractEvent event) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Block b = event.getClickedBlock();
Player p = event.getPlayer();
if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST)
|| b.getType().equals(Material.WALL_SIGN)) {
this.getPlugin().debug("Sign has been clicked");
//It's a sign
Sign s = (Sign) b.getState();
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
if (sortalSign(s, p)) {
event.setCancelled(true);
}
return;
}
int found = -1;
for (int i = 0; i < s.getLines().length; i++) {
if (s.getLine(i).toLowerCase().contains("[sortal]")
|| s.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) {
//It's a sortal sign
found = i;
break;
}
}
if (found == -1) {
if (!this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
return; //nvm it's not a sortal sign of any kind.
}
if (!p.hasPermission("sortal.warp")) {
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign.hasWarp()) {
this.getPlugin().debug(String.format("[Debug] Sign clicked has warp: %s", sign.getWarp()));
if (this.getPlugin().getSettings().isPerWarpPerm()) {
this.getPlugin().debug("[Debug] WarpPerPerm = true");
if (!p.hasPermission("sortal.warp." + sign.getWarp())) {
this.getPlugin().debug(String.format("[Debug] No perms! Needed: sortal.warp.%s", sign.getWarp()));
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(sign.getWarp());
if (w == null) {
this.getPlugin().debug("[Debug] Warp w == null, cancelling");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (!canPay(w, sign, p)) {
this.getPlugin().debug(String.format("[Debug] Can't pay: %s", getPrice(w, sign)));
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().debug(String.format("[Debug] Player is paying.."));
this.getPlugin().pay(p, this.getPrice(w, sign));
Location loc = w.getLocation();
if (loc.getYaw() == 0 && loc.getPitch() == 0) {
loc.setYaw(p.getLocation().getYaw());
loc.setPitch(p.getLocation().getPitch());
}
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
this.getPlugin().debug(String.format("[Debug] Teleported to: %s", w.getName()));
p.sendMessage(this.getLocalisation().getPlayerTeleported(w.getName()));
event.setCancelled(true); //Cancel, don't place block.
return;
}
this.getPlugin().debug(String.format("[Debug] Error in sign!"));
p.sendMessage(this.getLocalisation().getErrorInSign()); //Sign does have something but no warp -> weird.
event.setCancelled(true);
return; //have to return, otherwise it'll check the next lines
}
if (!p.hasPermission("sortal.warp")) {
this.getPlugin().debug("No perms - need sortal.warp");
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
String nextLine = s.getLine(found + 1);
if (nextLine == null || nextLine.equals("")) {
//Well, that didn't really work out well..
this.getPlugin().debug("nextLine == null || \"\" ");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (nextLine.contains("w:")) {
//It's a warp
String warp = nextLine.split(":")[1];
if (this.getPlugin().getSettings().isPerWarpPerm()) {
if (!p.hasPermission("sortal.warp." + warp)) {
this.getPlugin().debug("No perms - need sortal.warp." + warp);
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!this.getPlugin().getWarpManager().hasWarp(warp)) {
this.getPlugin().debug("Warp not found!");
p.sendMessage(this.getLocalisation().getWarpNotFound(warp));
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(warp);
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(w, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().pay(p, this.getPrice(w, sign));
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(warp));
event.setCancelled(true);
return;
}
if (nextLine.contains(",")) {
String[] split = nextLine.split(",");
World w;
int add = 0;
if (split.length == 3) {
w = p.getWorld();
} else {
w = this.getPlugin().getServer().getWorld(split[0]);
if (w == null) {
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
add = 1;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(null, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(null, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(null, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().pay(p, this.getPrice(null, sign));
int x = Integer.parseInt(split[0 + add]), y = Integer.parseInt(split[1 + add]),
z = Integer.parseInt(split[2 + add]);
Location dest = new Location(w, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch());
p.teleport(dest, TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(
dest.getBlockX() + ", " + dest.getBlockY() + ", " + dest.getBlockZ()));
event.setCancelled(true);
return;
}
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
}
}
}
| public void onPlayerHitSign(PlayerInteractEvent event) {
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
Block b = event.getClickedBlock();
Player p = event.getPlayer();
if (b.getType().equals(Material.SIGN) || b.getType().equals(Material.SIGN_POST)
|| b.getType().equals(Material.WALL_SIGN)) {
this.getPlugin().debug("Sign has been clicked");
//It's a sign
Sign s = (Sign) b.getState();
if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
if (sortalSign(s, p)) {
event.setCancelled(true);
}
return;
}
int found = -1;
for (int i = 0; i < s.getLines().length; i++) {
if (s.getLine(i).toLowerCase().contains("[sortal]")
|| s.getLine(i).toLowerCase().contains(this.getPlugin().getSettings().getSignContains())) {
//It's a sortal sign
found = i;
break;
}
}
if (found == -1) {
if (!this.getPlugin().getWarpManager().hasSignInfo(s.getLocation())) {
return; //nvm it's not a sortal sign of any kind.
}
if (!p.hasPermission("sortal.warp")) {
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign.hasWarp()) {
this.getPlugin().debug(String.format("[Debug] Sign clicked has warp: %s", sign.getWarp()));
if (this.getPlugin().getSettings().isPerWarpPerm()) {
this.getPlugin().debug("[Debug] WarpPerPerm = true");
if (!p.hasPermission("sortal.warp." + sign.getWarp())) {
this.getPlugin().debug(String.format("[Debug] No perms! Needed: sortal.warp.%s", sign.getWarp()));
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(sign.getWarp());
if (w == null) {
this.getPlugin().debug("[Debug] Warp w == null, cancelling");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (!canPay(w, sign, p)) {
this.getPlugin().debug(String.format("[Debug] Can't pay: %s", getPrice(w, sign)));
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().debug(String.format("[Debug] Player is paying.."));
this.getPlugin().pay(p, this.getPrice(w, sign));
Location loc = w.getLocation();
if(!loc.getChunk().isLoaded()){loc.getChunk().load();}
if (loc.getYaw() == 0 && loc.getPitch() == 0) {
loc.setYaw(p.getLocation().getYaw());
loc.setPitch(p.getLocation().getPitch());
}
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
this.getPlugin().debug(String.format("[Debug] Teleported to: %s", w.getName()));
p.sendMessage(this.getLocalisation().getPlayerTeleported(w.getName()));
event.setCancelled(true); //Cancel, don't place block.
return;
}
this.getPlugin().debug(String.format("[Debug] Error in sign!"));
p.sendMessage(this.getLocalisation().getErrorInSign()); //Sign does have something but no warp -> weird.
event.setCancelled(true);
return; //have to return, otherwise it'll check the next lines
}
if (!p.hasPermission("sortal.warp")) {
this.getPlugin().debug("No perms - need sortal.warp");
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
String nextLine = s.getLine(found + 1);
if (nextLine == null || nextLine.equals("")) {
//Well, that didn't really work out well..
this.getPlugin().debug("nextLine == null || \"\" ");
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
if (nextLine.contains("w:")) {
//It's a warp
String warp = nextLine.split(":")[1];
if (this.getPlugin().getSettings().isPerWarpPerm()) {
if (!p.hasPermission("sortal.warp." + warp)) {
this.getPlugin().debug("No perms - need sortal.warp." + warp);
p.sendMessage(this.getLocalisation().getNoPerms());
event.setCancelled(true);
return;
}
}
if (!this.getPlugin().getWarpManager().hasWarp(warp)) {
this.getPlugin().debug("Warp not found!");
p.sendMessage(this.getLocalisation().getWarpNotFound(warp));
event.setCancelled(true);
return;
}
Warp w = this.getPlugin().getWarpManager().getWarp(warp);
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(w, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(w, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(w, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
if(!w.getLocation().getChunk().isLoaded()){w.getLocation().getChunk().load();}
this.getPlugin().pay(p, this.getPrice(w, sign));
p.teleport(w.getLocation(), TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(warp));
event.setCancelled(true);
return;
}
if (nextLine.contains(",")) {
String[] split = nextLine.split(",");
World w;
int add = 0;
if (split.length == 3) {
w = p.getWorld();
} else {
w = this.getPlugin().getServer().getWorld(split[0]);
if (w == null) {
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
return;
}
add = 1;
}
SignInfo sign = this.getPlugin().getWarpManager().getSign(s.getLocation());
if (sign != null) {
if (!isPrivateUser(sign, p)) {
p.sendMessage(this.getLocalisation().getIsPrivateSign());
event.setCancelled(true);
return;
}
}
if (!canPay(null, sign, p)) {
p.sendMessage(this.getLocalisation().getNoMoney(Integer.toString(getPrice(null, sign))));
event.setCancelled(true);
return;
}
if (!usesCheck(null, sign, p)) {
p.sendMessage(this.getLocalisation().getMaxUsesReached());
event.setCancelled(true);
return;
}
this.getPlugin().pay(p, this.getPrice(null, sign));
int x = Integer.parseInt(split[0 + add]), y = Integer.parseInt(split[1 + add]),
z = Integer.parseInt(split[2 + add]);
Location dest = new Location(w, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch());
if(!dest.getChunk().isLoaded()){dest.getChunk().load();}
p.teleport(dest, TeleportCause.PLUGIN);
p.sendMessage(this.getLocalisation().getPlayerTeleported(
dest.getBlockX() + ", " + dest.getBlockY() + ", " + dest.getBlockZ()));
event.setCancelled(true);
return;
}
p.sendMessage(this.getLocalisation().getErrorInSign());
event.setCancelled(true);
}
}
}
|
diff --git a/src/org/jruby/ast/ConstNode.java b/src/org/jruby/ast/ConstNode.java
index 532783eac..5047abfb0 100644
--- a/src/org/jruby/ast/ConstNode.java
+++ b/src/org/jruby/ast/ConstNode.java
@@ -1,127 +1,128 @@
/*
***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001-2002 Jan Arne Petersen <[email protected]>
* Copyright (C) 2001-2002 Benoit Cerrina <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
* Copyright (C) 2004 Thomas E Enebo <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ast;
import java.util.List;
import org.jruby.Ruby;
import org.jruby.ast.types.INameNode;
import org.jruby.ast.visitor.NodeVisitor;
import org.jruby.evaluator.Instruction;
import org.jruby.lexer.yacc.ISourcePosition;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
/**
* The access to a Constant.
*/
public class ConstNode extends Node implements INameNode {
public static volatile int failedCallSites;
private String name;
private transient IRubyObject cachedValue = null;
private int generation = -1;
public ConstNode(ISourcePosition position, String name) {
super(position, NodeType.CONSTNODE);
this.name = name;
}
/**
* Accept for the visitor pattern.
* @param iVisitor the visitor
**/
public Instruction accept(NodeVisitor iVisitor) {
return iVisitor.visitConstNode(this);
}
/**
* Gets the name.
* @return Returns a String
*/
public String getName() {
return name;
}
public List<Node> childNodes() {
return EMPTY_LIST;
}
@Override
public String toString() {
return "ConstNode [" + name + "]";
}
public void setName(String name) {
this.name = name;
}
@Override
public IRubyObject interpret(Ruby runtime, ThreadContext context, IRubyObject self, Block aBlock) {
IRubyObject value = getValue(context);
// We can callsite cache const_missing if we want
return value != null ? value :
context.getRubyClass().callMethod(context, "const_missing", runtime.fastNewSymbol(name));
}
@Override
public String definition(Ruby runtime, ThreadContext context, IRubyObject self, Block aBlock) {
return context.getConstantDefined(name) ? "constant" : null;
}
public IRubyObject getValue(ThreadContext context) {
IRubyObject value = cachedValue; // Store to temp so it does null out on us mid-stream
return isCached(context, value) ? value : reCache(context, name);
}
private boolean isCached(ThreadContext context, IRubyObject value) {
return value != null && generation == context.getRubyClass().getConstantSerialNumber();
}
public IRubyObject reCache(ThreadContext context, String name) {
+ int newGeneration = context.getRubyClass().getConstantSerialNumber();
IRubyObject value = context.getConstant(name);
cachedValue = value;
- if (value != null) generation = context.getRubyClass().getConstantSerialNumber();
+ if (value != null) generation = newGeneration;
return value;
}
public void invalidate() {
cachedValue = null;
failedCallSites++;
}
}
| false | true | public IRubyObject reCache(ThreadContext context, String name) {
IRubyObject value = context.getConstant(name);
cachedValue = value;
if (value != null) generation = context.getRubyClass().getConstantSerialNumber();
return value;
}
| public IRubyObject reCache(ThreadContext context, String name) {
int newGeneration = context.getRubyClass().getConstantSerialNumber();
IRubyObject value = context.getConstant(name);
cachedValue = value;
if (value != null) generation = newGeneration;
return value;
}
|
diff --git a/src/cz/krtinec/birthday/widgets/UpdateService.java b/src/cz/krtinec/birthday/widgets/UpdateService.java
index 6f4e6b9..4767341 100644
--- a/src/cz/krtinec/birthday/widgets/UpdateService.java
+++ b/src/cz/krtinec/birthday/widgets/UpdateService.java
@@ -1,56 +1,58 @@
package cz.krtinec.birthday.widgets;
import java.io.IOException;
import java.io.InputStream;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.widget.RemoteViews;
import cz.krtinec.birthday.Birthday;
import cz.krtinec.birthday.R;
import cz.krtinec.birthday.data.BirthdayProvider;
import cz.krtinec.birthday.dto.BContact;
public abstract class UpdateService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public abstract RemoteViews updateViews();
public abstract ComponentName getComponentName();
@Override
public void onStart(Intent intent, int startId) {
AppWidgetManager manager = AppWidgetManager.getInstance(this);
RemoteViews views = updateViews();
Intent i = new Intent(getApplicationContext(), Birthday.class);
views.setOnClickPendingIntent(R.id.layout, PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT));
manager.updateAppWidget(getComponentName(), views);
}
protected void replaceIconWithPhoto(RemoteViews views, BContact contact, int viewId) {
InputStream is = BirthdayProvider.openPhoto(this, contact.getId());
if (is != null) {
Bitmap bitmap = BitmapFactory.decodeStream(is);
views.setImageViewBitmap(viewId, bitmap);
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
+ } else {
+ views.setImageViewResource(viewId, R.drawable.icon);
}
}
}
| true | true | protected void replaceIconWithPhoto(RemoteViews views, BContact contact, int viewId) {
InputStream is = BirthdayProvider.openPhoto(this, contact.getId());
if (is != null) {
Bitmap bitmap = BitmapFactory.decodeStream(is);
views.setImageViewBitmap(viewId, bitmap);
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| protected void replaceIconWithPhoto(RemoteViews views, BContact contact, int viewId) {
InputStream is = BirthdayProvider.openPhoto(this, contact.getId());
if (is != null) {
Bitmap bitmap = BitmapFactory.decodeStream(is);
views.setImageViewBitmap(viewId, bitmap);
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
views.setImageViewResource(viewId, R.drawable.icon);
}
}
|
diff --git a/common/logisticspipes/network/PacketHandler.java b/common/logisticspipes/network/PacketHandler.java
index f600975a..0db2599b 100644
--- a/common/logisticspipes/network/PacketHandler.java
+++ b/common/logisticspipes/network/PacketHandler.java
@@ -1,92 +1,92 @@
package logisticspipes.network;
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 logisticspipes.network.packets.abstracts.ModernPacket;
import logisticspipes.proxy.MainProxy;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
public class PacketHandler implements IPacketHandler {
public static List<ModernPacket> packetlist;
public static Map<Class<? extends ModernPacket>, ModernPacket> packetmap;
@SuppressWarnings("unchecked")
public static <T extends ModernPacket> T getPacket(Class<T> clazz) {
return (T)packetmap.get(clazz).template();
}
@SuppressWarnings("unchecked")
public PacketHandler() {
try {
final List<ClassInfo> classes = new ArrayList<ClassInfo>(ClassPath
.from(this.getClass().getClassLoader()).getTopLevelClasses(
"logisticspipes.network.packets"));
Collections.sort(classes, new Comparator<ClassInfo>() {
@Override
public int compare(ClassInfo o1, ClassInfo o2) {
return o1.getSimpleName().compareTo(o2.getSimpleName());
}
});
packetlist = new ArrayList<ModernPacket>(classes.size());
packetmap = new HashMap<Class<? extends ModernPacket>, ModernPacket>(
classes.size());
int currentid = 200;// TODO: Only 200 until all packets get
// converted
System.out.println("Loading " + classes.size() + " Packets");
for (ClassInfo c : classes) {
- currentid++;
try {
final Class<?> cls = c.load();
final ModernPacket instance = (ModernPacket) cls
.getConstructors()[0].newInstance(currentid);
packetlist.add(instance);
packetmap
.put((Class<? extends ModernPacket>) cls, instance);
System.out.println("Packet: " + c.getSimpleName()
+ " loaded");
} catch (NoClassDefFoundError e) {
System.out.println("Not loading packet "
+ c.getSimpleName()
+ " (it is probably a client-side packet)");
packetlist.add(null);
}
+ currentid++;
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Override
public void onPacketData(INetworkManager manager,
Packet250CustomPayload packet, Player player) {
if (packet.data == null) {
new Exception("Packet content has been null").printStackTrace();
}
if (MainProxy.isClient(((EntityPlayer) player).worldObj)) {
ClientPacketHandler.onPacketData(manager, packet, player);
} else {
ServerPacketHandler.onPacketData(manager, packet, player);
}
}
}
| false | true | public PacketHandler() {
try {
final List<ClassInfo> classes = new ArrayList<ClassInfo>(ClassPath
.from(this.getClass().getClassLoader()).getTopLevelClasses(
"logisticspipes.network.packets"));
Collections.sort(classes, new Comparator<ClassInfo>() {
@Override
public int compare(ClassInfo o1, ClassInfo o2) {
return o1.getSimpleName().compareTo(o2.getSimpleName());
}
});
packetlist = new ArrayList<ModernPacket>(classes.size());
packetmap = new HashMap<Class<? extends ModernPacket>, ModernPacket>(
classes.size());
int currentid = 200;// TODO: Only 200 until all packets get
// converted
System.out.println("Loading " + classes.size() + " Packets");
for (ClassInfo c : classes) {
currentid++;
try {
final Class<?> cls = c.load();
final ModernPacket instance = (ModernPacket) cls
.getConstructors()[0].newInstance(currentid);
packetlist.add(instance);
packetmap
.put((Class<? extends ModernPacket>) cls, instance);
System.out.println("Packet: " + c.getSimpleName()
+ " loaded");
} catch (NoClassDefFoundError e) {
System.out.println("Not loading packet "
+ c.getSimpleName()
+ " (it is probably a client-side packet)");
packetlist.add(null);
}
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
| public PacketHandler() {
try {
final List<ClassInfo> classes = new ArrayList<ClassInfo>(ClassPath
.from(this.getClass().getClassLoader()).getTopLevelClasses(
"logisticspipes.network.packets"));
Collections.sort(classes, new Comparator<ClassInfo>() {
@Override
public int compare(ClassInfo o1, ClassInfo o2) {
return o1.getSimpleName().compareTo(o2.getSimpleName());
}
});
packetlist = new ArrayList<ModernPacket>(classes.size());
packetmap = new HashMap<Class<? extends ModernPacket>, ModernPacket>(
classes.size());
int currentid = 200;// TODO: Only 200 until all packets get
// converted
System.out.println("Loading " + classes.size() + " Packets");
for (ClassInfo c : classes) {
try {
final Class<?> cls = c.load();
final ModernPacket instance = (ModernPacket) cls
.getConstructors()[0].newInstance(currentid);
packetlist.add(instance);
packetmap
.put((Class<? extends ModernPacket>) cls, instance);
System.out.println("Packet: " + c.getSimpleName()
+ " loaded");
} catch (NoClassDefFoundError e) {
System.out.println("Not loading packet "
+ c.getSimpleName()
+ " (it is probably a client-side packet)");
packetlist.add(null);
}
currentid++;
}
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java b/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java
index 28db705e..1b83e1d2 100644
--- a/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java
+++ b/src/main/java/org/asteriskjava/manager/internal/ManagerReaderImpl.java
@@ -1,346 +1,346 @@
/*
* Copyright 2004-2006 Stefan Reuter
*
* 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.asteriskjava.manager.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.asteriskjava.manager.DefaultManagerConnection;
import org.asteriskjava.manager.event.DisconnectEvent;
import org.asteriskjava.manager.event.ManagerEvent;
import org.asteriskjava.manager.event.ProtocolIdentifierReceivedEvent;
import org.asteriskjava.manager.response.CommandResponse;
import org.asteriskjava.manager.response.ManagerResponse;
import org.asteriskjava.util.DateUtil;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;
import org.asteriskjava.util.SocketConnectionFacade;
/**
* Default implementation of the ManagerReader interface.
*
* @author srt
* @version $Id$
*/
public class ManagerReaderImpl implements ManagerReader
{
/**
* Instance logger.
*/
private final Log logger = LogFactory.getLog(getClass());
/**
* The event builder utility to convert a map of attributes reveived from asterisk to instances
* of registered event classes.
*/
private final EventBuilder eventBuilder;
/**
* The response builder utility to convert a map of attributes reveived from asterisk to
* instances of well known response classes.
*/
private final ResponseBuilder responseBuilder;
/**
* The dispatcher to use for dispatching events and responses.
*/
private final Dispatcher dispatcher;
/**
* The source to use when creating {@link ManagerEvent}s.
*/
private final Object source;
/**
* The socket to use for reading from the asterisk server.
*/
private SocketConnectionFacade socket;
/**
* If set to <code>true</code>, terminates and closes the reader.
*/
private boolean die = false;
/**
* <code>true</code> if the main loop has finished.
*/
private boolean dead = false;
/**
* Exception that caused this reader to terminate if any.
*/
private IOException terminationException;
/**
* Creates a new ManagerReaderImpl.
*
* @param dispatcher the dispatcher to use for dispatching events and responses.
* @param source the source to use when creating {@link ManagerEvent}s
*/
public ManagerReaderImpl(final Dispatcher dispatcher, Object source)
{
this.dispatcher = dispatcher;
this.source = source;
this.eventBuilder = new EventBuilderImpl();
this.responseBuilder = new ResponseBuilderImpl();
}
/**
* Sets the socket to use for reading from the asterisk server.
*
* @param socket the socket to use for reading from the asterisk server.
*/
public void setSocket(final SocketConnectionFacade socket)
{
this.socket = socket;
}
public void registerEventClass(Class eventClass)
{
eventBuilder.registerEventClass(eventClass);
}
/**
* Reads line by line from the asterisk server, sets the protocol identifier as soon as it is
* received and dispatches the received events and responses via the associated dispatcher.
*
* @see DefaultManagerConnection#dispatchEvent(ManagerEvent)
* @see DefaultManagerConnection#dispatchResponse(ManagerResponse)
* @see DefaultManagerConnection#setProtocolIdentifier(String)
*/
public void run()
{
final Map<String, String> buffer = new HashMap<String, String>();
final List<String> commandResult = new ArrayList<String>();
String line;
boolean processingCommandResult = false;
if (socket == null)
{
throw new IllegalStateException("Unable to run: socket is null.");
}
this.die = false;
this.dead = false;
try
{
// main loop
while ((line = socket.readLine()) != null && !this.die)
{
// dirty hack for handling the CommandAction. Needs fix when manager protocol is
// enhanced.
if (processingCommandResult)
{
// in case of an error Asterisk sends a Usage: and an END COMMAND
// that is prepended by a space :(
if ("--END COMMAND--".equals(line) || " --END COMMAND--".equals(line))
{
CommandResponse commandResponse = new CommandResponse();
for (int crIdx = 0; crIdx < commandResult.size(); crIdx++)
{
String[] crNVPair = ((String) commandResult.get(crIdx)).split(" *: *", 2);
if (crNVPair[0].equalsIgnoreCase("ActionID"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
// Register the action id with the command result
commandResponse.setActionId(crNVPair[1]);
}
else if (crNVPair[0].equalsIgnoreCase("Privilege"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
}
else
{
// Didn't find a name:value pattern, so we're now in the
// command results. Stop processing the nv pairs.
break;
}
}
commandResponse.setResponse("Follows");
commandResponse.setDateReceived(DateUtil.getDate());
// clone commandResult as it is reused
commandResponse.setResult(new ArrayList<String>(commandResult));
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("actionid", commandResponse.getActionId());
attributes.put("response", commandResponse.getResponse());
commandResponse.setAttributes(attributes);
dispatcher.dispatchResponse(commandResponse);
processingCommandResult = false;
}
else
{
commandResult.add(line);
}
continue;
}
// Reponse: Follows indicates that the output starting on the next line until
// --END COMMAND-- must be treated as raw output of a command executed by a
// CommandAction.
if ("Response: Follows".equalsIgnoreCase(line))
{
processingCommandResult = true;
commandResult.clear();
continue;
}
// maybe we will find a better way to identify the protocol identifier but for now
// this works quite well.
if (line.startsWith("Asterisk Call Manager/") ||
line.startsWith("Asterisk Manager Proxy/"))
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(source);
protocolIdentifierReceivedEvent.setProtocolIdentifier(line);
protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(protocolIdentifierReceivedEvent);
continue;
}
// an empty line indicates a normal response's or event's end so we build
// the corresponding value object and dispatch it through the ManagerConnection.
if (line.length() == 0)
{
- if (buffer.containsKey("response"))
- {
- ManagerResponse response = buildResponse(buffer);
- logger.debug("attempting to build response");
- if (response != null)
- {
- dispatcher.dispatchResponse(response);
- }
- }
- else if (buffer.containsKey("event"))
+ if (buffer.containsKey("event"))
{
logger.debug("attempting to build event: " + buffer.get("event"));
ManagerEvent event = buildEvent(source, buffer);
if (event != null)
{
dispatcher.dispatchEvent(event);
}
else
{
logger.debug("buildEvent returned null");
}
}
+ else if (buffer.containsKey("response"))
+ {
+ ManagerResponse response = buildResponse(buffer);
+ logger.debug("attempting to build response");
+ if (response != null)
+ {
+ dispatcher.dispatchResponse(response);
+ }
+ }
else
{
if (buffer.size() > 0)
{
logger.debug("buffer contains neither response nor event");
}
}
buffer.clear();
}
else
{
int delimiterIndex;
delimiterIndex = line.indexOf(":");
if (delimiterIndex > 0 && line.length() > delimiterIndex + 2)
{
String name;
String value;
name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH);
value = line.substring(delimiterIndex + 2);
buffer.put(name, value);
logger.debug("Got name [" + name + "], value: [" + value + "]");
}
}
}
this.dead = true;
logger.debug("Reached end of stream, terminating reader.");
}
catch (IOException e)
{
this.terminationException = e;
this.dead = true;
logger.info("Terminating reader thread: " + e.getMessage());
}
finally
{
this.dead = true;
// cleans resources and reconnects if needed
DisconnectEvent disconnectEvent = new DisconnectEvent(source);
disconnectEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(disconnectEvent);
}
}
public void die()
{
this.die = true;
}
public boolean isDead()
{
return dead;
}
public IOException getTerminationException()
{
return terminationException;
}
private ManagerResponse buildResponse(Map<String, String> buffer)
{
ManagerResponse response;
response = responseBuilder.buildResponse(buffer);
if (response != null)
{
response.setDateReceived(DateUtil.getDate());
}
return response;
}
private ManagerEvent buildEvent(Object source, Map<String, String> buffer)
{
ManagerEvent event;
event = eventBuilder.buildEvent(source, buffer);
if (event != null)
{
event.setDateReceived(DateUtil.getDate());
}
return event;
}
}
| false | true | public void run()
{
final Map<String, String> buffer = new HashMap<String, String>();
final List<String> commandResult = new ArrayList<String>();
String line;
boolean processingCommandResult = false;
if (socket == null)
{
throw new IllegalStateException("Unable to run: socket is null.");
}
this.die = false;
this.dead = false;
try
{
// main loop
while ((line = socket.readLine()) != null && !this.die)
{
// dirty hack for handling the CommandAction. Needs fix when manager protocol is
// enhanced.
if (processingCommandResult)
{
// in case of an error Asterisk sends a Usage: and an END COMMAND
// that is prepended by a space :(
if ("--END COMMAND--".equals(line) || " --END COMMAND--".equals(line))
{
CommandResponse commandResponse = new CommandResponse();
for (int crIdx = 0; crIdx < commandResult.size(); crIdx++)
{
String[] crNVPair = ((String) commandResult.get(crIdx)).split(" *: *", 2);
if (crNVPair[0].equalsIgnoreCase("ActionID"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
// Register the action id with the command result
commandResponse.setActionId(crNVPair[1]);
}
else if (crNVPair[0].equalsIgnoreCase("Privilege"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
}
else
{
// Didn't find a name:value pattern, so we're now in the
// command results. Stop processing the nv pairs.
break;
}
}
commandResponse.setResponse("Follows");
commandResponse.setDateReceived(DateUtil.getDate());
// clone commandResult as it is reused
commandResponse.setResult(new ArrayList<String>(commandResult));
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("actionid", commandResponse.getActionId());
attributes.put("response", commandResponse.getResponse());
commandResponse.setAttributes(attributes);
dispatcher.dispatchResponse(commandResponse);
processingCommandResult = false;
}
else
{
commandResult.add(line);
}
continue;
}
// Reponse: Follows indicates that the output starting on the next line until
// --END COMMAND-- must be treated as raw output of a command executed by a
// CommandAction.
if ("Response: Follows".equalsIgnoreCase(line))
{
processingCommandResult = true;
commandResult.clear();
continue;
}
// maybe we will find a better way to identify the protocol identifier but for now
// this works quite well.
if (line.startsWith("Asterisk Call Manager/") ||
line.startsWith("Asterisk Manager Proxy/"))
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(source);
protocolIdentifierReceivedEvent.setProtocolIdentifier(line);
protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(protocolIdentifierReceivedEvent);
continue;
}
// an empty line indicates a normal response's or event's end so we build
// the corresponding value object and dispatch it through the ManagerConnection.
if (line.length() == 0)
{
if (buffer.containsKey("response"))
{
ManagerResponse response = buildResponse(buffer);
logger.debug("attempting to build response");
if (response != null)
{
dispatcher.dispatchResponse(response);
}
}
else if (buffer.containsKey("event"))
{
logger.debug("attempting to build event: " + buffer.get("event"));
ManagerEvent event = buildEvent(source, buffer);
if (event != null)
{
dispatcher.dispatchEvent(event);
}
else
{
logger.debug("buildEvent returned null");
}
}
else
{
if (buffer.size() > 0)
{
logger.debug("buffer contains neither response nor event");
}
}
buffer.clear();
}
else
{
int delimiterIndex;
delimiterIndex = line.indexOf(":");
if (delimiterIndex > 0 && line.length() > delimiterIndex + 2)
{
String name;
String value;
name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH);
value = line.substring(delimiterIndex + 2);
buffer.put(name, value);
logger.debug("Got name [" + name + "], value: [" + value + "]");
}
}
}
this.dead = true;
logger.debug("Reached end of stream, terminating reader.");
}
catch (IOException e)
{
this.terminationException = e;
this.dead = true;
logger.info("Terminating reader thread: " + e.getMessage());
}
finally
{
this.dead = true;
// cleans resources and reconnects if needed
DisconnectEvent disconnectEvent = new DisconnectEvent(source);
disconnectEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(disconnectEvent);
}
}
| public void run()
{
final Map<String, String> buffer = new HashMap<String, String>();
final List<String> commandResult = new ArrayList<String>();
String line;
boolean processingCommandResult = false;
if (socket == null)
{
throw new IllegalStateException("Unable to run: socket is null.");
}
this.die = false;
this.dead = false;
try
{
// main loop
while ((line = socket.readLine()) != null && !this.die)
{
// dirty hack for handling the CommandAction. Needs fix when manager protocol is
// enhanced.
if (processingCommandResult)
{
// in case of an error Asterisk sends a Usage: and an END COMMAND
// that is prepended by a space :(
if ("--END COMMAND--".equals(line) || " --END COMMAND--".equals(line))
{
CommandResponse commandResponse = new CommandResponse();
for (int crIdx = 0; crIdx < commandResult.size(); crIdx++)
{
String[] crNVPair = ((String) commandResult.get(crIdx)).split(" *: *", 2);
if (crNVPair[0].equalsIgnoreCase("ActionID"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
// Register the action id with the command result
commandResponse.setActionId(crNVPair[1]);
}
else if (crNVPair[0].equalsIgnoreCase("Privilege"))
{
// Remove the command response nvpair from the
// command result array and decrement index so we
// don't skip the "new" current line
commandResult.remove(crIdx--);
}
else
{
// Didn't find a name:value pattern, so we're now in the
// command results. Stop processing the nv pairs.
break;
}
}
commandResponse.setResponse("Follows");
commandResponse.setDateReceived(DateUtil.getDate());
// clone commandResult as it is reused
commandResponse.setResult(new ArrayList<String>(commandResult));
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("actionid", commandResponse.getActionId());
attributes.put("response", commandResponse.getResponse());
commandResponse.setAttributes(attributes);
dispatcher.dispatchResponse(commandResponse);
processingCommandResult = false;
}
else
{
commandResult.add(line);
}
continue;
}
// Reponse: Follows indicates that the output starting on the next line until
// --END COMMAND-- must be treated as raw output of a command executed by a
// CommandAction.
if ("Response: Follows".equalsIgnoreCase(line))
{
processingCommandResult = true;
commandResult.clear();
continue;
}
// maybe we will find a better way to identify the protocol identifier but for now
// this works quite well.
if (line.startsWith("Asterisk Call Manager/") ||
line.startsWith("Asterisk Manager Proxy/"))
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
protocolIdentifierReceivedEvent = new ProtocolIdentifierReceivedEvent(source);
protocolIdentifierReceivedEvent.setProtocolIdentifier(line);
protocolIdentifierReceivedEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(protocolIdentifierReceivedEvent);
continue;
}
// an empty line indicates a normal response's or event's end so we build
// the corresponding value object and dispatch it through the ManagerConnection.
if (line.length() == 0)
{
if (buffer.containsKey("event"))
{
logger.debug("attempting to build event: " + buffer.get("event"));
ManagerEvent event = buildEvent(source, buffer);
if (event != null)
{
dispatcher.dispatchEvent(event);
}
else
{
logger.debug("buildEvent returned null");
}
}
else if (buffer.containsKey("response"))
{
ManagerResponse response = buildResponse(buffer);
logger.debug("attempting to build response");
if (response != null)
{
dispatcher.dispatchResponse(response);
}
}
else
{
if (buffer.size() > 0)
{
logger.debug("buffer contains neither response nor event");
}
}
buffer.clear();
}
else
{
int delimiterIndex;
delimiterIndex = line.indexOf(":");
if (delimiterIndex > 0 && line.length() > delimiterIndex + 2)
{
String name;
String value;
name = line.substring(0, delimiterIndex).toLowerCase(Locale.ENGLISH);
value = line.substring(delimiterIndex + 2);
buffer.put(name, value);
logger.debug("Got name [" + name + "], value: [" + value + "]");
}
}
}
this.dead = true;
logger.debug("Reached end of stream, terminating reader.");
}
catch (IOException e)
{
this.terminationException = e;
this.dead = true;
logger.info("Terminating reader thread: " + e.getMessage());
}
finally
{
this.dead = true;
// cleans resources and reconnects if needed
DisconnectEvent disconnectEvent = new DisconnectEvent(source);
disconnectEvent.setDateReceived(DateUtil.getDate());
dispatcher.dispatchEvent(disconnectEvent);
}
}
|
diff --git a/src/main/org/openscience/gittodo/app/SetDone.java b/src/main/org/openscience/gittodo/app/SetDone.java
index bc30530..43566eb 100644
--- a/src/main/org/openscience/gittodo/app/SetDone.java
+++ b/src/main/org/openscience/gittodo/app/SetDone.java
@@ -1,38 +1,39 @@
/*
* Copyright 2008 Egon Willighagen <[email protected]>
*
* License: LGPL v3
*/
package org.openscience.gittodo.app;
import java.util.Map;
import org.openscience.gittodo.io.ItemWriter;
import org.openscience.gittodo.model.IGTDRepository;
import org.openscience.gittodo.model.Item;
import org.openscience.gittodo.model.Repository;
public class SetDone {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Syntax: set-done <ITEM-ID> <ITEM-ID-2> ...");
System.exit(0);
}
IGTDRepository repos = new Repository();
- for (int i=1; i< args.length; i++) {
- Integer itemID = Integer.parseInt(args[0]);
+ for (int i=0; i< args.length; i++) {
+ Integer itemID = Integer.parseInt(args[i]);
Map<Integer,Item> items = repos.items();
Item item = items.get(itemID);
if (item == null) {
System.out.println("No item with ID: " + itemID);
} else {
+ System.out.println("Closed item: " + itemID);
item.setState(Item.STATE.CLOSED);
ItemWriter writer = new ItemWriter(item);
writer.write();
writer.close();
}
}
}
}
| false | true | public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Syntax: set-done <ITEM-ID> <ITEM-ID-2> ...");
System.exit(0);
}
IGTDRepository repos = new Repository();
for (int i=1; i< args.length; i++) {
Integer itemID = Integer.parseInt(args[0]);
Map<Integer,Item> items = repos.items();
Item item = items.get(itemID);
if (item == null) {
System.out.println("No item with ID: " + itemID);
} else {
item.setState(Item.STATE.CLOSED);
ItemWriter writer = new ItemWriter(item);
writer.write();
writer.close();
}
}
}
| public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.out.println("Syntax: set-done <ITEM-ID> <ITEM-ID-2> ...");
System.exit(0);
}
IGTDRepository repos = new Repository();
for (int i=0; i< args.length; i++) {
Integer itemID = Integer.parseInt(args[i]);
Map<Integer,Item> items = repos.items();
Item item = items.get(itemID);
if (item == null) {
System.out.println("No item with ID: " + itemID);
} else {
System.out.println("Closed item: " + itemID);
item.setState(Item.STATE.CLOSED);
ItemWriter writer = new ItemWriter(item);
writer.write();
writer.close();
}
}
}
|
diff --git a/src/main/java/uk/ac/susx/tag/wag/Main.java b/src/main/java/uk/ac/susx/tag/wag/Main.java
index b6f1bcb..da16ec3 100644
--- a/src/main/java/uk/ac/susx/tag/wag/Main.java
+++ b/src/main/java/uk/ac/susx/tag/wag/Main.java
@@ -1,483 +1,483 @@
package uk.ac.susx.tag.wag;
import com.beust.jcommander.*;
import com.beust.jcommander.converters.BaseConverter;
import com.beust.jcommander.internal.Lists;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.ImmutableList;
import com.google.common.io.*;
import uk.ac.susx.tag.util.IOUtils;
import uk.ac.susx.tag.util.StringConverterFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.EnumSet;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: hiam20
* Date: 18/02/2013
* Time: 14:33
* To change this template use File | Settings | File Templates.
*/
public class Main {
private enum OutputFormat {
TSV, CSV
}
private final List<ByteSource> sources;
private final CharSink sink;
private final EnumSet<AliasType> producedTypes;
private final int pageLimit;
private final boolean produceIdentityAliases;
private final OutputFormat outputFormat;
private final EnumSet<WriteTabulatedAliasHandler.Column> outputColumns;
/**
* Private constructor. Use the builder to instantiate: {@link #builder()}.
*
* @param sources
* @param sink
* @param producedTypes
* @param pageLimit
* @param produceIdentityAliases
*/
private Main(List<ByteSource> sources, CharSink sink,
EnumSet<AliasType> producedTypes, int pageLimit, boolean produceIdentityAliases,
OutputFormat outputFormat, EnumSet<WriteTabulatedAliasHandler.Column> outputColumns) {
this.sources = sources;
this.sink = sink;
this.producedTypes = producedTypes;
this.pageLimit = pageLimit;
this.produceIdentityAliases = produceIdentityAliases;
this.outputFormat = outputFormat;
this.outputColumns = outputColumns;
}
public static Builder builder() {
return new Builder();
}
void run() throws Exception {
final Closer outCloser = Closer.create();
try {
// Set up the output stuff
final Writer writer = outCloser.register(sink.openBufferedStream());
final PrintWriter outWriter = outCloser.register(new PrintWriter(writer));
final AliasHandler handler;
switch (outputFormat) {
case TSV:
handler = WriteTabulatedAliasHandler.newTsvInstance(outWriter, outputColumns);
break;
case CSV:
handler = WriteTabulatedAliasHandler.newCsvInstance(outWriter, outputColumns);
break;
default:
throw new AssertionError(outputFormat);
}
final WikiAliasGenerator generator =
new WikiAliasGenerator(handler, producedTypes);
generator.setIdentityAliasesProduced(produceIdentityAliases);
for (final ByteSource source : sources) {
final Closer inCloser = Closer.create();
try {
// Set up the input stuff
final BufferedInputStream in = inCloser.register(source.openBufferedStream());
generator.process(in, pageLimit, source.size());
outWriter.flush();
} catch (Throwable throwable) {
throw inCloser.rethrow(throwable);
} finally {
inCloser.close();
}
}
} catch (Throwable throwable) {
throw outCloser.rethrow(throwable);
} finally {
outCloser.close();
}
}
public static void main(String[] args) throws Exception {
final Builder builder = Main.builder();
StringConverterFactory converter = StringConverterFactory.newInstance(true);
final JCommander jc = new JCommander();
jc.setProgramName("wag");
jc.addObject(builder);
jc.addConverterFactory(converter);
jc.parse(args);
if (builder.globals.isUsageRequested()) {
jc.usage();
} else {
Main m = builder.build();
m.run();
}
}
public static class GlobalCommandDelegate {
@Parameter(
names = {"-h", "--help"},
description = "Display this usage screen.",
help = true)
private boolean usageRequested = false;
public GlobalCommandDelegate() {
}
public boolean isUsageRequested() {
return usageRequested;
}
}
/**
* Note that some fields are prefixed with an underscore so JCommander can't tell
*/
@Parameters(commandDescription = "Wikipedia Alias Generator (WAG) extras various form or semantic relations that " +
"indicative of a page title alias.")
public static class Builder {
/**
*
*/
private static final Logger LOG = Logger.getLogger(Builder.class.getName());
/**
*
*/
@ParametersDelegate
private final GlobalCommandDelegate globals = new GlobalCommandDelegate();
/**
* The wiki-dumps to parse as specified either by a file or URL
*/
@Parameter(description = "FILE1 [FILE2 [...]]",
required = true)
private List<String> inputs = Lists.newArrayList();
/**
* The destination file for discovered aliases.
*/
@Parameter(names = {"-o", "--output"},
description = "output file to write aliases to. (\"-\" for stdout.)")
private File outputFile = new File("-");
/**
* Character encoding to use for writing data.
*/
private Charset outputCharset = Charset.defaultCharset();
/**
* Whether or not the output file can be overwritten (if it exists)
*/
private boolean outputClobberingEnabled = false;
/**
* Whether or not to produce identity aliases; relations that point the themselves.
*/
@Parameter(names = {"-I", "--identityAliases"},
description = "Produce identity aliases (relations that point to themselves.)",
variableArity = true)
private boolean produceIdentityAliases = true;
/**
*
*/
@Parameter(names = {"-t", "--types"},
description = "Set of alias types to produce.",
converter = AliasTypeStringConverter.class)
private List<AliasType> producedAliasTypes = Lists.newArrayList(AliasType.STANDARD);
/**
*
*/
@Parameter(names = {"-l", "--limit"},
description = "Limit the job to process on the first pages. (Set to -1 for no limit)")
private int pageLimit = -1;
/**
*
*/
@Parameter(names = {"-of", "--outputFormat"},
description = "Output format.",
converter = OutputFormatStringConverter.class)
private OutputFormat outputFormat = OutputFormat.TSV;
/**
*
*/
@Parameter(names = {"-oc", "--outputColumns"},
description = "Output format.",
converter = ColumnStringConverter.class)
private List<WriteTabulatedAliasHandler.Column> outputColumns
= Lists.newArrayList(EnumSet.allOf(WriteTabulatedAliasHandler.Column.class));
/**
*
*/
public Builder() {
}
/**
* Set the character encoding to use when writing aliases to the output.
* <p/>
* Note that the input sinkCharset should be set within the XML file, in the encoding deceleration. For
* example,
* to read UTF-8 the XML file should start: {@code <?xml version="1.0" encoding="UTF-8"?>}
*
* @param outputCharset character encoding to use for writing files.
*/
@Parameter(names = {"-c", "--charset"},
description = "character encoding to use for writing aliases")
public Builder setOutputCharset(Charset outputCharset) {
this.outputCharset = checkNotNull(outputCharset, "outputCharset");
return this;
}
/**
* Add the specified files to the list of input resource.
* <p/>
*
* @param inputFiles wiki xml dump resources
* @return this builder (for method chaining)
* @throws NullPointerException of {@code inputFiles} is {@code null}
*/
public Builder addInputFiles(List<File> inputFiles) {
for (File input : inputFiles)
this.inputs.add(input.toString());
return this;
}
/**
* Add the specified URLs to the list of input resource.
*
* @param inputUrls wiki xml dump resourcess
* @return this builder (for method chaining)
* @throws NullPointerException of {@code inputUrls} is {@code null}
*/
public Builder setInputUrls(List<URL> inputUrls) {
for (URL inputUrl : inputUrls)
this.inputs.add(inputUrl.toString());
return this;
}
/**
* Set the output file to write aliases to.
*
* @param outputFile destination to write discovered aliases
* @return this builder (for method chaining)
* @throws NullPointerException of {@code outputFile} is {@code null}
*/
public Builder setOutputFile(File outputFile) {
this.outputFile = checkNotNull(outputFile, "outputFile");
return this;
}
/**
* Set whether or not the output file can be overwritten if it already exists.
*
* @param outputClobberingEnabled overwrite output files
* @return this builder (for method chaining)
*/
@Parameter(names = {"-C", "--clobber"},
description = "overwrite output files if they already exist")
public Builder setOutputClobberingEnabled(boolean outputClobberingEnabled) {
this.outputClobberingEnabled = outputClobberingEnabled;
return this;
}
/**
* Whether or not to produce identity aliases; relations that point the themselves.
*
* @param produceIdentityAliases true to produce identity aliases, false otherwise.
* @return this builder (for method chaining)
*/
public Builder setProduceIdentityAliases(boolean produceIdentityAliases) {
this.produceIdentityAliases = produceIdentityAliases;
return this;
}
/**
* @return throw IllegalArgumentException if one of the required arguments is unspecified.
*/
public Main build() throws IOException {
// Check the input file and setup the source
final ImmutableList.Builder<ByteSource> sources = ImmutableList.builder();
for (final String input : inputs) {
try {
final URL inputUrl = new URL(input);
LOG.log(Level.INFO, "Setting source to URL: " + inputUrl);
sources.add(Resources.asByteSource(inputUrl));
} catch (MalformedURLException ex) {
final File inputFile = new File(input);
if (!inputFile.exists())
throw new IllegalArgumentException("The input file does not exists: " + inputFile);
if (!inputFile.isFile())
throw new IllegalArgumentException("The input file is not a regular file: " + inputFile);
if (!inputFile.canRead())
throw new IllegalArgumentException("The input file is not readable: " + inputFile);
LOG.log(Level.INFO, "Setting source to file: " + inputFile);
sources.add(Files.asByteSource(inputFile));
}
}
// Check the output character encoding
if (!outputCharset.canEncode()) {
// Note: This is extremely unlikely to happen. Only auto-decoders do not
// support encoding, and it would be a silly user who requests such.
throw new IllegalArgumentException("Output character set does not support encoding: " + outputCharset);
}
// Check the output file and setup the sink
final CharSink sink;
if (outputFile.toString().equals("-")) {
// Stdout
LOG.log(Level.INFO, "Setting sink to file stdout.");
sink = new CharSink() {
@Override
public Writer openStream() throws IOException {
return new PrintWriter(System.out);
}
};
} else {
// To a file
if (outputFile.exists()) {
if (!outputFile.isFile()) {
throw new IllegalArgumentException("The output file already exists, " +
"and is not a regular file: " + outputFile);
} else if (!outputFile.canWrite()) {
throw new IllegalArgumentException("The output file already exists," +
" and is not writable: " + outputFile);
} else if (outputClobberingEnabled) {
LOG.log(Level.WARNING, "Overwriting output file that already exists: {0}",
outputFile);
} else {
throw new IllegalArgumentException("The output file already exists and " +
"clobbering is disabled: " + outputFile);
}
} else {
- // Output does not exist so check it is creatable
- if (!IOUtils.isCreatable(outputFile))
- throw new IllegalArgumentException("Output file is not creatable." + outputFile);
+ // Output does not exist so check it is creatable
+ if (!IOUtils.isCreatable(outputFile))
+ throw new IllegalArgumentException("Output file is not creatable." + outputFile);
// Make parent directories
if (outputFile.getParentFile() != null) {
- if (!outputFile.exists() && !outputFile.mkdirs()) {
+ if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Output file parent directory does not exist, " +
"and is not creatable: " + outputFile);
}
}
}
LOG.log(Level.INFO, "Setting sink to file: " + outputFile);
final FileWriteMode[] modes = {};
sink = Files.asCharSink(outputFile, outputCharset, modes);
}
if (producedAliasTypes.isEmpty()) {
throw new IllegalArgumentException("Produced alias types list is empty.");
}
return new Main(
sources.build(),
sink,
EnumSet.copyOf(producedAliasTypes),
pageLimit,
produceIdentityAliases,
outputFormat,
EnumSet.copyOf(outputColumns));
}
}
public static final class AliasTypeStringConverter extends EnumStringConverter<AliasType> {
public AliasTypeStringConverter(String name) {
super(name, AliasType.class);
}
public AliasTypeStringConverter() {
super(AliasType.class);
}
}
public static final class ColumnStringConverter extends EnumStringConverter<WriteTabulatedAliasHandler.Column> {
public ColumnStringConverter(String name) {
super(name, WriteTabulatedAliasHandler.Column.class);
}
public ColumnStringConverter() {
super(WriteTabulatedAliasHandler.Column.class);
}
}
public static final class OutputFormatStringConverter extends EnumStringConverter<OutputFormat> {
public OutputFormatStringConverter(String name) {
super(name, OutputFormat.class);
}
public OutputFormatStringConverter() {
super(OutputFormat.class);
}
}
public static class FileOrUrlConverter extends BaseConverter<Object> {
public FileOrUrlConverter(String optionName) {
super(optionName);
}
@Override
public Object convert(String value) {
try {
return new URL(value);
} catch (MalformedURLException ex) {
return new File(value);
}
}
}
}
| false | true | public Main build() throws IOException {
// Check the input file and setup the source
final ImmutableList.Builder<ByteSource> sources = ImmutableList.builder();
for (final String input : inputs) {
try {
final URL inputUrl = new URL(input);
LOG.log(Level.INFO, "Setting source to URL: " + inputUrl);
sources.add(Resources.asByteSource(inputUrl));
} catch (MalformedURLException ex) {
final File inputFile = new File(input);
if (!inputFile.exists())
throw new IllegalArgumentException("The input file does not exists: " + inputFile);
if (!inputFile.isFile())
throw new IllegalArgumentException("The input file is not a regular file: " + inputFile);
if (!inputFile.canRead())
throw new IllegalArgumentException("The input file is not readable: " + inputFile);
LOG.log(Level.INFO, "Setting source to file: " + inputFile);
sources.add(Files.asByteSource(inputFile));
}
}
// Check the output character encoding
if (!outputCharset.canEncode()) {
// Note: This is extremely unlikely to happen. Only auto-decoders do not
// support encoding, and it would be a silly user who requests such.
throw new IllegalArgumentException("Output character set does not support encoding: " + outputCharset);
}
// Check the output file and setup the sink
final CharSink sink;
if (outputFile.toString().equals("-")) {
// Stdout
LOG.log(Level.INFO, "Setting sink to file stdout.");
sink = new CharSink() {
@Override
public Writer openStream() throws IOException {
return new PrintWriter(System.out);
}
};
} else {
// To a file
if (outputFile.exists()) {
if (!outputFile.isFile()) {
throw new IllegalArgumentException("The output file already exists, " +
"and is not a regular file: " + outputFile);
} else if (!outputFile.canWrite()) {
throw new IllegalArgumentException("The output file already exists," +
" and is not writable: " + outputFile);
} else if (outputClobberingEnabled) {
LOG.log(Level.WARNING, "Overwriting output file that already exists: {0}",
outputFile);
} else {
throw new IllegalArgumentException("The output file already exists and " +
"clobbering is disabled: " + outputFile);
}
} else {
// Output does not exist so check it is creatable
if (!IOUtils.isCreatable(outputFile))
throw new IllegalArgumentException("Output file is not creatable." + outputFile);
// Make parent directories
if (outputFile.getParentFile() != null) {
if (!outputFile.exists() && !outputFile.mkdirs()) {
throw new IllegalArgumentException("Output file parent directory does not exist, " +
"and is not creatable: " + outputFile);
}
}
}
LOG.log(Level.INFO, "Setting sink to file: " + outputFile);
final FileWriteMode[] modes = {};
sink = Files.asCharSink(outputFile, outputCharset, modes);
}
if (producedAliasTypes.isEmpty()) {
throw new IllegalArgumentException("Produced alias types list is empty.");
}
return new Main(
sources.build(),
sink,
EnumSet.copyOf(producedAliasTypes),
pageLimit,
produceIdentityAliases,
outputFormat,
EnumSet.copyOf(outputColumns));
}
| public Main build() throws IOException {
// Check the input file and setup the source
final ImmutableList.Builder<ByteSource> sources = ImmutableList.builder();
for (final String input : inputs) {
try {
final URL inputUrl = new URL(input);
LOG.log(Level.INFO, "Setting source to URL: " + inputUrl);
sources.add(Resources.asByteSource(inputUrl));
} catch (MalformedURLException ex) {
final File inputFile = new File(input);
if (!inputFile.exists())
throw new IllegalArgumentException("The input file does not exists: " + inputFile);
if (!inputFile.isFile())
throw new IllegalArgumentException("The input file is not a regular file: " + inputFile);
if (!inputFile.canRead())
throw new IllegalArgumentException("The input file is not readable: " + inputFile);
LOG.log(Level.INFO, "Setting source to file: " + inputFile);
sources.add(Files.asByteSource(inputFile));
}
}
// Check the output character encoding
if (!outputCharset.canEncode()) {
// Note: This is extremely unlikely to happen. Only auto-decoders do not
// support encoding, and it would be a silly user who requests such.
throw new IllegalArgumentException("Output character set does not support encoding: " + outputCharset);
}
// Check the output file and setup the sink
final CharSink sink;
if (outputFile.toString().equals("-")) {
// Stdout
LOG.log(Level.INFO, "Setting sink to file stdout.");
sink = new CharSink() {
@Override
public Writer openStream() throws IOException {
return new PrintWriter(System.out);
}
};
} else {
// To a file
if (outputFile.exists()) {
if (!outputFile.isFile()) {
throw new IllegalArgumentException("The output file already exists, " +
"and is not a regular file: " + outputFile);
} else if (!outputFile.canWrite()) {
throw new IllegalArgumentException("The output file already exists," +
" and is not writable: " + outputFile);
} else if (outputClobberingEnabled) {
LOG.log(Level.WARNING, "Overwriting output file that already exists: {0}",
outputFile);
} else {
throw new IllegalArgumentException("The output file already exists and " +
"clobbering is disabled: " + outputFile);
}
} else {
// Output does not exist so check it is creatable
if (!IOUtils.isCreatable(outputFile))
throw new IllegalArgumentException("Output file is not creatable." + outputFile);
// Make parent directories
if (outputFile.getParentFile() != null) {
if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
throw new IllegalArgumentException("Output file parent directory does not exist, " +
"and is not creatable: " + outputFile);
}
}
}
LOG.log(Level.INFO, "Setting sink to file: " + outputFile);
final FileWriteMode[] modes = {};
sink = Files.asCharSink(outputFile, outputCharset, modes);
}
if (producedAliasTypes.isEmpty()) {
throw new IllegalArgumentException("Produced alias types list is empty.");
}
return new Main(
sources.build(),
sink,
EnumSet.copyOf(producedAliasTypes),
pageLimit,
produceIdentityAliases,
outputFormat,
EnumSet.copyOf(outputColumns));
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java
index 8ff28e7..0a13394 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/LiveWebConnectorTemplatesTest.java
@@ -1,127 +1,127 @@
/*******************************************************************************
* Copyright (c) 2006 - 2006 Mylar eclipse.org project 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:
* Mylar project committers - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.tests.integration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.extensions.ActiveTestSuite;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.ITaskFactory;
import org.eclipse.mylyn.tasks.core.QueryHitCollector;
import org.eclipse.mylyn.tasks.core.RepositoryTaskData;
import org.eclipse.mylyn.tasks.core.RepositoryTemplate;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
/**
* @author Eugene Kuleshov
*/
public class LiveWebConnectorTemplatesTest extends TestCase {
private final RepositoryTemplate template;
public LiveWebConnectorTemplatesTest(RepositoryTemplate template) {
super("testRepositoryTemplate");
this.template = template;
}
public void testRepositoryTemplate() throws Throwable {
IProgressMonitor monitor = new NullProgressMonitor();
- MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null);
+ MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.ID_PLUGIN, IStatus.OK, "Query result", null);
final List<AbstractTask> hits = new ArrayList<AbstractTask>();
QueryHitCollector collector = new QueryHitCollector(new ITaskFactory() {
public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException {
// ignore
return null;
}
}) {
@Override
public void accept(AbstractTask hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for (Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
// if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
// }
}
TaskRepository repository = new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE, template.repositoryUrl, params);
String url = repository.getUrl();
// HACK: repositories that require auth
if ("http://demo.otrs.org".equals(url)) {
repository.setAuthenticationCredentials("skywalker", "skywalker");
} else if ("http://changelogic.araneaframework.org".equals(url)) {
repository.setAuthenticationCredentials("mylar2", "mylar123");
}
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository);
assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0);
String regexp = WebRepositoryConnector.evaluateParams(template
.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector,
repository);
assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus
.isOK());
try {
assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0);
} catch (Throwable t) {
System.err.println(taskQueryUrl);
System.err.println(buffer);
System.err.println("--------------------------------------------------------");
throw t;
}
}
@Override
public String getName() {
return template.label;
}
private static final String excluded = "http://demo.otrs.org,";
public static TestSuite suite() {
TestSuite suite = new ActiveTestSuite(LiveWebConnectorTemplatesTest.class.getName());
AbstractRepositoryConnector repositoryConnector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(
WebRepositoryConnector.REPOSITORY_TYPE);
for (RepositoryTemplate template : repositoryConnector.getTemplates()) {
if (excluded.indexOf(template.repositoryUrl + ",") == -1) {
suite.addTest(new LiveWebConnectorTemplatesTest(template));
}
}
return suite;
}
}
| true | true | public void testRepositoryTemplate() throws Throwable {
IProgressMonitor monitor = new NullProgressMonitor();
MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null);
final List<AbstractTask> hits = new ArrayList<AbstractTask>();
QueryHitCollector collector = new QueryHitCollector(new ITaskFactory() {
public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException {
// ignore
return null;
}
}) {
@Override
public void accept(AbstractTask hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for (Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
// if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
// }
}
TaskRepository repository = new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE, template.repositoryUrl, params);
String url = repository.getUrl();
// HACK: repositories that require auth
if ("http://demo.otrs.org".equals(url)) {
repository.setAuthenticationCredentials("skywalker", "skywalker");
} else if ("http://changelogic.araneaframework.org".equals(url)) {
repository.setAuthenticationCredentials("mylar2", "mylar123");
}
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository);
assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0);
String regexp = WebRepositoryConnector.evaluateParams(template
.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector,
repository);
assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus
.isOK());
try {
assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0);
} catch (Throwable t) {
System.err.println(taskQueryUrl);
System.err.println(buffer);
System.err.println("--------------------------------------------------------");
throw t;
}
}
| public void testRepositoryTemplate() throws Throwable {
IProgressMonitor monitor = new NullProgressMonitor();
MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.ID_PLUGIN, IStatus.OK, "Query result", null);
final List<AbstractTask> hits = new ArrayList<AbstractTask>();
QueryHitCollector collector = new QueryHitCollector(new ITaskFactory() {
public AbstractTask createTask(RepositoryTaskData taskData, IProgressMonitor monitor) throws CoreException {
// ignore
return null;
}
}) {
@Override
public void accept(AbstractTask hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for (Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
// if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
// }
}
TaskRepository repository = new TaskRepository(WebRepositoryConnector.REPOSITORY_TYPE, template.repositoryUrl, params);
String url = repository.getUrl();
// HACK: repositories that require auth
if ("http://demo.otrs.org".equals(url)) {
repository.setAuthenticationCredentials("skywalker", "skywalker");
} else if ("http://changelogic.araneaframework.org".equals(url)) {
repository.setAuthenticationCredentials("mylar2", "mylar123");
}
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository);
assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0);
String regexp = WebRepositoryConnector.evaluateParams(template
.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector,
repository);
assertTrue("Query failed\n" + taskQueryUrl + "\n" + regexp + "\n" + resultingStatus.toString(), queryStatus
.isOK());
try {
assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0);
} catch (Throwable t) {
System.err.println(taskQueryUrl);
System.err.println(buffer);
System.err.println("--------------------------------------------------------");
throw t;
}
}
|
diff --git a/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/BindBeanMetaDataFactory.java b/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/BindBeanMetaDataFactory.java
index d6628dc6..eb26fe97 100644
--- a/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/BindBeanMetaDataFactory.java
+++ b/aop-mc-int/src/main/org/jboss/aop/microcontainer/beans/beanmetadatafactory/BindBeanMetaDataFactory.java
@@ -1,127 +1,127 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.aop.microcontainer.beans.beanmetadatafactory;
import java.util.ArrayList;
import java.util.List;
import org.jboss.aop.microcontainer.beans.AspectBinding;
import org.jboss.beans.metadata.plugins.AbstractBeanMetaData;
import org.jboss.beans.metadata.plugins.AbstractInjectionValueMetaData;
import org.jboss.beans.metadata.plugins.AbstractListMetaData;
import org.jboss.beans.metadata.spi.BeanMetaData;
import org.jboss.util.id.GUID;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
* @version $Revision: 1.1 $
*/
public class BindBeanMetaDataFactory extends AspectManagerAwareBeanMetaDataFactory
{
private static final long serialVersionUID = 1L;
private String pointcut;
private String cflow;
private List<BaseInterceptorData> interceptors = new ArrayList<BaseInterceptorData>();
public BindBeanMetaDataFactory()
{
//Meeded to satisfy validation in BeanFactoryHandler.endElement()
setBeanClass("IGNORED");
}
public void setPointcut(String pointcut)
{
this.pointcut = pointcut;
}
public void setCflow(String cflow)
{
this.cflow = cflow;
}
@Override
public List<BeanMetaData> getBeans()
{
ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>();
//Create AspectBinding
AbstractBeanMetaData binding = new AbstractBeanMetaData();
if (name == null)
{
name = GUID.asString();
}
binding.setName(name);
BeanMetaDataUtil.setSimpleProperty(binding, "name", name);
binding.setBean(AspectBinding.class.getName());
BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut);
if (cflow != null)
{
BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow);
}
util.setAspectManagerProperty(binding, "manager");
result.add(binding);
if (interceptors.size() > 0)
{
AbstractListMetaData almd = new AbstractListMetaData();
int i = 0;
for (BaseInterceptorData interceptor : interceptors)
{
AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName());
String intName = name + "$" + i++;
bmd.setName(intName);
util.setAspectManagerProperty(bmd, "manager");
BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated");
BeanMetaDataUtil.setDependencyProperty(builder);
if (interceptor instanceof AdviceData)
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
if (((AdviceData)interceptor).getAdviceMethod() != null)
{
BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod());
}
BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType());
}
else
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
}
result.add(bmd);
almd.add(new AbstractInjectionValueMetaData(intName));
- BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);
}
+ BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);
}
return result;
}
public void addInterceptor(BaseInterceptorData interceptorData)
{
interceptors.add(interceptorData);
}
}
| false | true | public List<BeanMetaData> getBeans()
{
ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>();
//Create AspectBinding
AbstractBeanMetaData binding = new AbstractBeanMetaData();
if (name == null)
{
name = GUID.asString();
}
binding.setName(name);
BeanMetaDataUtil.setSimpleProperty(binding, "name", name);
binding.setBean(AspectBinding.class.getName());
BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut);
if (cflow != null)
{
BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow);
}
util.setAspectManagerProperty(binding, "manager");
result.add(binding);
if (interceptors.size() > 0)
{
AbstractListMetaData almd = new AbstractListMetaData();
int i = 0;
for (BaseInterceptorData interceptor : interceptors)
{
AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName());
String intName = name + "$" + i++;
bmd.setName(intName);
util.setAspectManagerProperty(bmd, "manager");
BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated");
BeanMetaDataUtil.setDependencyProperty(builder);
if (interceptor instanceof AdviceData)
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
if (((AdviceData)interceptor).getAdviceMethod() != null)
{
BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod());
}
BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType());
}
else
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
}
result.add(bmd);
almd.add(new AbstractInjectionValueMetaData(intName));
BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);
}
}
return result;
}
| public List<BeanMetaData> getBeans()
{
ArrayList<BeanMetaData> result = new ArrayList<BeanMetaData>();
//Create AspectBinding
AbstractBeanMetaData binding = new AbstractBeanMetaData();
if (name == null)
{
name = GUID.asString();
}
binding.setName(name);
BeanMetaDataUtil.setSimpleProperty(binding, "name", name);
binding.setBean(AspectBinding.class.getName());
BeanMetaDataUtil.setSimpleProperty(binding, "pointcut", pointcut);
if (cflow != null)
{
BeanMetaDataUtil.setSimpleProperty(binding, "cflow", cflow);
}
util.setAspectManagerProperty(binding, "manager");
result.add(binding);
if (interceptors.size() > 0)
{
AbstractListMetaData almd = new AbstractListMetaData();
int i = 0;
for (BaseInterceptorData interceptor : interceptors)
{
AbstractBeanMetaData bmd = new AbstractBeanMetaData(interceptor.getBeanClassName());
String intName = name + "$" + i++;
bmd.setName(intName);
util.setAspectManagerProperty(bmd, "manager");
BeanMetaDataUtil.DependencyBuilder builder = new BeanMetaDataUtil.DependencyBuilder(bmd, "binding", name).setState("Instantiated");
BeanMetaDataUtil.setDependencyProperty(builder);
if (interceptor instanceof AdviceData)
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "aspect", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
if (((AdviceData)interceptor).getAdviceMethod() != null)
{
BeanMetaDataUtil.setSimpleProperty(bmd, "aspectMethod", ((AdviceData)interceptor).getAdviceMethod());
}
BeanMetaDataUtil.setSimpleProperty(bmd, "type", ((AdviceData)interceptor).getType());
}
else
{
BeanMetaDataUtil.DependencyBuilder db = new BeanMetaDataUtil.DependencyBuilder(bmd, "stack", interceptor.getRefName());
BeanMetaDataUtil.setDependencyProperty(db);
}
result.add(bmd);
almd.add(new AbstractInjectionValueMetaData(intName));
}
BeanMetaDataUtil.setSimpleProperty(binding, "advices", almd);
}
return result;
}
|
diff --git a/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java b/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
index a7420c7a..6136e9c4 100644
--- a/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
+++ b/modules/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java
@@ -1,100 +1,100 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.rest.api.cycle;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.activiti.cycle.ContentRepresentation;
import org.activiti.cycle.CycleDefaultMimeType;
import org.activiti.cycle.CycleService;
import org.activiti.cycle.RenderInfo;
import org.activiti.cycle.RepositoryArtifact;
import org.activiti.cycle.impl.CycleServiceImpl;
import org.activiti.cycle.impl.transform.TransformationException;
import org.activiti.rest.util.ActivitiRequest;
import org.activiti.rest.util.ActivitiWebScript;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
/**
*
* @author Nils Preusker ([email protected])
*/
public class ContentRepresentationGet extends ActivitiWebScript {
private static Logger log = Logger.getLogger(ContentRepresentationGet.class.getName());
private CycleService cycleService;
private void init(ActivitiRequest req) {
String cuid = req.getCurrentUserId();
HttpSession session = req.getHttpServletRequest().getSession(true);
this.cycleService = CycleServiceImpl.getCycleService(cuid, session);
}
@Override
protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
init(req);
String connectorId = req.getMandatoryString("connectorId");
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId);
// Get representation by id to determine whether it is an image...
try {
model.put("connectorId", connectorId);
model.put("artifactId", artifactId);
ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId);
switch (contentRepresentation.getRenderInfo()) {
case IMAGE:
case HTML:
// For images and HTML we don't need to send the content, the URL will
// be put together in the UI
// and the content will be requested via ContentGet.
break;
case HTML_REFERENCE:
case BINARY:
case CODE:
case TEXT_PLAIN:
String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("renderInfo", contentRepresentation.getRenderInfo().name());
model.put("contentRepresentationId", contentRepresentation.getId());
model.put("contentType", contentRepresentation.getMimeType().getContentType());
} catch (TransformationException e) {
// Show errors that occur during transformations as HTML in the UI
model.put("renderInfo", RenderInfo.HTML);
- model.put("contentRepresentationId", "Exception");
+ model.put("contentRepresentationId", representationId);
model.put("content", e.getRenderContent());
model.put("contentType", CycleDefaultMimeType.HTML.getContentType());
} catch (Exception ex) {
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
}
| true | true | protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
init(req);
String connectorId = req.getMandatoryString("connectorId");
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId);
// Get representation by id to determine whether it is an image...
try {
model.put("connectorId", connectorId);
model.put("artifactId", artifactId);
ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId);
switch (contentRepresentation.getRenderInfo()) {
case IMAGE:
case HTML:
// For images and HTML we don't need to send the content, the URL will
// be put together in the UI
// and the content will be requested via ContentGet.
break;
case HTML_REFERENCE:
case BINARY:
case CODE:
case TEXT_PLAIN:
String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("renderInfo", contentRepresentation.getRenderInfo().name());
model.put("contentRepresentationId", contentRepresentation.getId());
model.put("contentType", contentRepresentation.getMimeType().getContentType());
} catch (TransformationException e) {
// Show errors that occur during transformations as HTML in the UI
model.put("renderInfo", RenderInfo.HTML);
model.put("contentRepresentationId", "Exception");
model.put("content", e.getRenderContent());
model.put("contentType", CycleDefaultMimeType.HTML.getContentType());
} catch (Exception ex) {
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
| protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) {
init(req);
String connectorId = req.getMandatoryString("connectorId");
String artifactId = req.getString("artifactId");
String representationId = req.getString("representationId");
RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId);
// Get representation by id to determine whether it is an image...
try {
model.put("connectorId", connectorId);
model.put("artifactId", artifactId);
ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId);
switch (contentRepresentation.getRenderInfo()) {
case IMAGE:
case HTML:
// For images and HTML we don't need to send the content, the URL will
// be put together in the UI
// and the content will be requested via ContentGet.
break;
case HTML_REFERENCE:
case BINARY:
case CODE:
case TEXT_PLAIN:
String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString();
model.put("content", content);
}
model.put("renderInfo", contentRepresentation.getRenderInfo().name());
model.put("contentRepresentationId", contentRepresentation.getId());
model.put("contentType", contentRepresentation.getMimeType().getContentType());
} catch (TransformationException e) {
// Show errors that occur during transformations as HTML in the UI
model.put("renderInfo", RenderInfo.HTML);
model.put("contentRepresentationId", representationId);
model.put("content", e.getRenderContent());
model.put("contentType", CycleDefaultMimeType.HTML.getContentType());
} catch (Exception ex) {
log.log(Level.WARNING, "Exception while loading content representation", ex);
// TODO:Better concept how this is handled in the GUI
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString();
model.put("exception", stackTrace);
}
}
|
diff --git a/src/main/java/org/mvel2/MVELRuntime.java b/src/main/java/org/mvel2/MVELRuntime.java
index 5de46be3..a4ba0d86 100644
--- a/src/main/java/org/mvel2/MVELRuntime.java
+++ b/src/main/java/org/mvel2/MVELRuntime.java
@@ -1,238 +1,238 @@
/**
* MVEL 2.0
* Copyright (C) 2007 The Codehaus
* Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor
*
* 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.mvel2;
import static org.mvel2.Operator.*;
import org.mvel2.ast.ASTNode;
import org.mvel2.ast.LineLabel;
import org.mvel2.compiler.CompiledExpression;
import org.mvel2.debug.Debugger;
import org.mvel2.debug.DebuggerContext;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.integration.impl.ClassImportResolverFactory;
import org.mvel2.integration.impl.ImmutableDefaultFactory;
import org.mvel2.util.ASTLinkedList;
import org.mvel2.util.ExecutionStack;
import static org.mvel2.util.PropertyTools.isEmpty;
/**
* This class contains the runtime for running compiled MVEL expressions.
*/
@SuppressWarnings({"CaughtExceptionImmediatelyRethrown"})
public class MVELRuntime {
public static final ImmutableDefaultFactory IMMUTABLE_DEFAULT_FACTORY = new ImmutableDefaultFactory();
private static ThreadLocal<DebuggerContext> debuggerContext;
/**
* Main interpreter.
*
* @param debugger Run in debug mode
* @param expression The compiled expression object
* @param ctx The root context object
* @param variableFactory The variable factory to be injected
* @return The resultant value
* @see org.mvel2.MVEL
*/
public static Object execute(boolean debugger, final CompiledExpression expression, final Object ctx,
VariableResolverFactory variableFactory) {
ASTLinkedList node = new ASTLinkedList(expression.getInstructions().firstNode());
if (expression.isImportInjectionRequired()) {
variableFactory = new ClassImportResolverFactory(expression.getParserContext().getParserConfiguration(), variableFactory);
}
ExecutionStack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (debugger || (debugger = hasDebuggerContext())) {
try {
debuggerContext.get().checkBreak((LineLabel) tk, variableFactory, expression);
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
else if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
switch (operator = tk.getOperator()) {
case NOOP:
continue;
case TERNARY:
if (!stk.popBoolean()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
- stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
+ stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.isReduceable()) {
if ((Integer) stk.pop() == CHOR) {
v1 = stk.pop();
v2 = stk.pop();
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("failed to compile sub expression", e);
}
}
return stk.pop();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
/**
* Register a debugger breakpoint.
*
* @param source - the source file the breakpoint is registered in
* @param line - the line number of the breakpoint
*/
public static void registerBreakpoint(String source, int line) {
ensureDebuggerContext();
debuggerContext.get().registerBreakpoint(source, line);
}
/**
* Remove a specific breakpoint.
*
* @param source - the source file the breakpoint is registered in
* @param line - the line number of the breakpoint to be removed
*/
public static void removeBreakpoint(String source, int line) {
if (hasDebuggerContext()) {
debuggerContext.get().removeBreakpoint(source, line);
}
}
/**
* Tests whether or not a debugger context exist.
*
* @return boolean
*/
private static boolean hasDebuggerContext() {
return debuggerContext != null && debuggerContext.get() != null;
}
/**
* Ensures that debugger context exists.
*/
private static void ensureDebuggerContext() {
if (debuggerContext == null) debuggerContext = new ThreadLocal<DebuggerContext>();
if (debuggerContext.get() == null) debuggerContext.set(new DebuggerContext());
}
/**
* Reset all the currently registered breakpoints.
*/
public static void clearAllBreakpoints() {
if (hasDebuggerContext()) {
debuggerContext.get().clearAllBreakpoints();
}
}
/**
* Tests whether or not breakpoints have been declared.
*
* @return boolean
*/
public static boolean hasBreakpoints() {
return hasDebuggerContext() && debuggerContext.get().hasBreakpoints();
}
/**
* Sets the Debugger instance to handle breakpoints. A debugger may only be registered once per thread.
* Calling this method more than once will result in the second and subsequent calls to simply fail silently.
* To re-register the Debugger, you must call {@link #resetDebugger}
*
* @param debugger - debugger instance
*/
public static void setThreadDebugger(Debugger debugger) {
ensureDebuggerContext();
debuggerContext.get().setDebugger(debugger);
}
/**
* Reset all information registered in the debugger, including the actual attached Debugger and registered
* breakpoints.
*/
public static void resetDebugger() {
debuggerContext = null;
}
}
| true | true | public static Object execute(boolean debugger, final CompiledExpression expression, final Object ctx,
VariableResolverFactory variableFactory) {
ASTLinkedList node = new ASTLinkedList(expression.getInstructions().firstNode());
if (expression.isImportInjectionRequired()) {
variableFactory = new ClassImportResolverFactory(expression.getParserContext().getParserConfiguration(), variableFactory);
}
ExecutionStack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (debugger || (debugger = hasDebuggerContext())) {
try {
debuggerContext.get().checkBreak((LineLabel) tk, variableFactory, expression);
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
else if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
switch (operator = tk.getOperator()) {
case NOOP:
continue;
case TERNARY:
if (!stk.popBoolean()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.isReduceable()) {
if ((Integer) stk.pop() == CHOR) {
v1 = stk.pop();
v2 = stk.pop();
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("failed to compile sub expression", e);
}
}
return stk.pop();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
| public static Object execute(boolean debugger, final CompiledExpression expression, final Object ctx,
VariableResolverFactory variableFactory) {
ASTLinkedList node = new ASTLinkedList(expression.getInstructions().firstNode());
if (expression.isImportInjectionRequired()) {
variableFactory = new ClassImportResolverFactory(expression.getParserContext().getParserConfiguration(), variableFactory);
}
ExecutionStack stk = new ExecutionStack();
Object v1, v2;
ASTNode tk = null;
Integer operator;
try {
while ((tk = node.nextNode()) != null) {
if (tk.fields == -1) {
/**
* This may seem silly and redundant, however, when an MVEL script recurses into a block
* or substatement, a new runtime loop is entered. Since the debugger state is not
* passed through the AST, it is not possible to forward the state directly. So when we
* encounter a debugging symbol, we check the thread local to see if there is are registered
* breakpoints. If we find them, we assume that we are debugging.
*
* The consequence of this of course, is that it's not ideal to compile expressions with
* debugging symbols which you plan to use in a production enviroment.
*/
if (debugger || (debugger = hasDebuggerContext())) {
try {
debuggerContext.get().checkBreak((LineLabel) tk, variableFactory, expression);
}
catch (NullPointerException e) {
// do nothing for now. this isn't as calus as it seems.
}
}
continue;
}
else if (stk.isEmpty()) {
stk.push(tk.getReducedValueAccelerated(ctx, ctx, variableFactory));
}
switch (operator = tk.getOperator()) {
case NOOP:
continue;
case TERNARY:
if (!stk.popBoolean()) {
//noinspection StatementWithEmptyBody
while (node.hasMoreNodes() && !node.nextNode().isOperator(TERNARY_ELSE)) ;
}
stk.clear();
continue;
case TERNARY_ELSE:
return stk.pop();
case END_OF_STMT:
/**
* If the program doesn't end here then we wipe anything off the stack that remains.
* Althought it may seem like intuitive stack optimizations could be leveraged by
* leaving hanging values on the stack, trust me it's not a good idea.
*/
if (node.hasMoreNodes()) {
stk.clear();
}
continue;
}
stk.push(node.nextNode().getReducedValueAccelerated(ctx, ctx, variableFactory), operator);
try {
while (stk.isReduceable()) {
if ((Integer) stk.pop() == CHOR) {
v1 = stk.pop();
v2 = stk.pop();
if (!isEmpty(v2) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
}
else stk.push(null);
}
}
}
catch (ClassCastException e) {
throw new CompileException("syntax error or incomptable types", e);
}
catch (CompileException e) {
throw e;
}
catch (Exception e) {
throw new CompileException("failed to compile sub expression", e);
}
}
return stk.pop();
}
catch (NullPointerException e) {
if (tk != null && tk.isOperator() && !node.hasMoreNodes()) {
throw new CompileException("incomplete statement: "
+ tk.getName() + " (possible use of reserved keyword as identifier: " + tk.getName() + ")");
}
else {
throw e;
}
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java b/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
index 8e117c1e3..944a06d83 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
@@ -1,1805 +1,1805 @@
package net.aufdemrand.denizen.scripts.containers.core;
import net.aufdemrand.denizen.Settings;
import net.aufdemrand.denizen.objects.*;
import net.aufdemrand.denizen.objects.aH.Argument;
import net.aufdemrand.denizen.scripts.ScriptBuilder;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.scripts.commands.core.DetermineCommand;
import net.aufdemrand.denizen.scripts.queues.core.InstantQueue;
import net.aufdemrand.denizen.tags.TagManager;
import net.aufdemrand.denizen.utilities.Conversion;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.entity.Position;
import net.aufdemrand.denizen.utilities.Utilities;
import net.citizensnpcs.api.CitizensAPI;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLevelChangeEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
public class WorldScriptHelper implements Listener {
public static Map<String, WorldScriptContainer> world_scripts = new ConcurrentHashMap<String, WorldScriptContainer>(8, 0.9f, 1);
public WorldScriptHelper() {
DenizenAPI.getCurrentInstance().getServer().getPluginManager()
.registerEvents(this, DenizenAPI.getCurrentInstance());
}
/////////////////////
// EVENT HANDLER
/////////////////
public static String doEvents(List<String> eventNames, dNPC npc, Player player, Map<String, Object> context) {
String determination = "none";
// dB.log("Fired for '" + eventNames.toString() + "'");
for (WorldScriptContainer script : world_scripts.values()) {
if (script == null) continue;
for (String eventName : eventNames) {
if (!script.contains("EVENTS.ON " + eventName.toUpperCase())) continue;
// Fetch script from Event
//
// Note: a "new dPlayer(null)" will not be null itself,
// so keep a ternary operator here
List<ScriptEntry> entries = script.getEntries
(player != null ? new dPlayer(player) : null,
npc, "events.on " + eventName);
if (entries.isEmpty()) continue;
dB.report("Event",
aH.debugObj("Type", "On " + eventName)
+ script.getAsScriptArg().debug()
+ (npc != null ? aH.debugObj("NPC", npc.toString()) : "")
+ (player != null ? aH.debugObj("Player", player.getName()) : "")
+ (context != null ? aH.debugObj("Context", context.toString()) : ""));
dB.echoDebug(dB.DebugElement.Header, "Building event 'On " + eventName.toUpperCase() + "' for " + script.getName());
if (context != null) {
for (Map.Entry<String, Object> entry : context.entrySet()) {
ScriptBuilder.addObjectToEntries(entries, entry.getKey(), entry.getValue());
}
}
// Create new ID -- this is what we will look for when determining an outcome
long id = DetermineCommand.getNewId();
// Add the reqId to each of the entries
ScriptBuilder.addObjectToEntries(entries, "ReqId", id);
InstantQueue.getQueue(null).addEntries(entries).start();
if (DetermineCommand.hasOutcome(id))
determination = DetermineCommand.getOutcome(id);
}
}
return determination;
}
/////////////////////
// BLOCK EVENTS
/////////////////
@EventHandler
public void blockBreak(BlockBreakEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Block block = event.getBlock();
String blockType = block.getType().name();
context.put("location", new dLocation(block.getLocation()));
context.put("type", new Element(blockType));
dItem item = new dItem(event.getPlayer().getItemInHand());
List<String> events = new ArrayList<String>();
events.add("player breaks block");
events.add("player breaks " + blockType);
events.add("player breaks block with " + item.identify());
events.add("player breaks " + blockType + " with " + item.identify());
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add("player breaks block with " +
item.identify().split(":")[0]);
events.add("player breaks " + blockType + " with " +
item.identify().split(":")[0]);
}
if (item.isItemscript()) {
events.add("player breaks block with itemscript "
+ item.getMaterial());
events.add("player breaks " + blockType + " with itemscript "
+ item.getMaterial());
}
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
// Make nothing drop, usually used as "drop:nothing"
else if (determination.toUpperCase().startsWith("NOTHING")) {
event.setCancelled(true);
block.setType(Material.AIR);
}
// Get a dList of dItems to drop
else if (Argument.valueOf(determination).matchesArgumentList(dItem.class)) {
// Cancel the event
event.setCancelled(true);
block.setType(Material.AIR);
// Get the list of items
Object list = dList.valueOf(determination).filter(dItem.class);
@SuppressWarnings("unchecked")
List<dItem> newItems = (List<dItem>) list;
for (dItem newItem : newItems) {
block.getWorld().dropItemNaturally(block.getLocation(),
newItem.getItemStack()); // Drop each item
}
}
}
@EventHandler
public void blockBurn(BlockBurnEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
String determination = doEvents(Arrays.asList
("block burns",
event.getBlock().getType().name() + " burns"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void blockIgnite(BlockIgniteEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
String determination = doEvents(Arrays.asList
("block ignites",
event.getBlock().getType().name() + " ignites"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void blockPhysics(BlockPhysicsEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
String determination = doEvents(Arrays.asList
("block moves",
event.getBlock().getType().name() + " moves"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void blockPlace(BlockPlaceEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
String determination = doEvents(Arrays.asList
("player places block",
"player places " + event.getBlock().getType().name()),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void blockRedstone(BlockRedstoneEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
List<String> events = new ArrayList<String>();
if (event.getNewCurrent() > 0) {
events.add("block powered");
events.add(event.getBlock().getType().name() + " powered");
}
else {
events.add("block unpowered");
events.add(event.getBlock().getType().name() + " unpowered");
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setNewCurrent(event.getOldCurrent());
}
@EventHandler
public void blockFromTo(BlockFromToEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("type", new Element(event.getBlock().getType().name()));
context.put("destination", new dLocation(event.getToBlock().getLocation()));
String determination = doEvents(Arrays.asList
("block spreads",
event.getBlock().getType().name() + " spreads"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void signChange(SignChangeEvent event) {
final Map<String, Object> context = new HashMap<String, Object>();
final Player player = event.getPlayer();
final Block block = event.getBlock();
Sign sign = (Sign) block.getState();
final String[] oldLines = sign.getLines();
context.put("old", new dList(Arrays.asList(oldLines)));
context.put("location", new dLocation(block.getLocation()));
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(), new Runnable() {
public void run() {
Sign sign = (Sign) block.getState();
context.put("new", new dList(Arrays.asList(sign.getLines())));
String determination = doEvents(Arrays.asList
("player changes sign"),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
Utilities.setSignLines(sign, oldLines);
}
}, 1);
}
/////////////////////
// CUSTOM EVENTS
/////////////////
public void serverStartEvent() {
// Start the 'timeEvent'
Bukkit.getScheduler().scheduleSyncRepeatingTask(DenizenAPI.getCurrentInstance(),
new Runnable() {
@Override
public void run() {
timeEvent();
}
}, Settings.WorldScriptTimeEventResolution().getTicks(), Settings.WorldScriptTimeEventResolution().getTicks());
// Fire the 'Server Start' event
doEvents(Arrays.asList("server start"),
null, null, null);
}
private Map<String, Integer> current_time = new HashMap<String, Integer>();
public void timeEvent() {
for (World world : Bukkit.getWorlds()) {
int hour = Double.valueOf(world.getTime() / 1000).intValue();
hour = hour + 6;
// Get the hour
if (hour >= 24) hour = hour - 24;
if (!current_time.containsKey(world.getName())
|| current_time.get(world.getName()) != hour) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("time", new Element(String.valueOf(hour)));
context.put("world", new dWorld(world));
doEvents(Arrays.asList("time changes in " + world.getName(),
hour + ":00 in " + world.getName()),
null, null, context);
current_time.put(world.getName(), hour);
}
}
}
/////////////////////
// HANGING EVENTS
/////////////////
@EventHandler
public void hangingBreak(HangingBreakEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Player player = null;
dNPC npc = null;
String hangingType = event.getEntity().getType().name();
String cause = event.getCause().name();
context.put("hanging", new dEntity(event.getEntity()));
context.put("cause", new Element(cause));
List<String> events = new ArrayList<String>();
events.add("hanging breaks");
events.add("hanging breaks because " + cause);
events.add(hangingType + " breaks");
events.add(hangingType +
" breaks because " + cause);
if (event instanceof HangingBreakByEntityEvent) {
HangingBreakByEntityEvent subEvent = (HangingBreakByEntityEvent) event;
Entity entity = subEvent.getRemover();
String entityType = entity.getType().name();
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
npc = DenizenAPI.getDenizenNPC(CitizensAPI.getNPCRegistry().getNPC(entity));
context.put("entity", npc);
entityType = "npc";
}
else if (entity instanceof Player) {
player = (Player) entity;
context.put("entity", new dPlayer((Player) entity));
}
else {
context.put("entity", new dEntity(entity));
}
events.add("entity breaks hanging");
events.add("entity breaks hanging because " + cause);
events.add("entity breaks " + hangingType);
events.add("entity breaks " + hangingType + " because " + cause);
events.add(entityType + " breaks hanging");
events.add(entityType + " breaks hanging because " + cause);
events.add(entityType + " breaks " + hangingType);
events.add(entityType + " breaks " + hangingType + " because " + cause);
}
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// ENTITY EVENTS
/////////////////
@EventHandler
public void creatureSpawn(CreatureSpawnEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
context.put("reason", new Element(event.getSpawnReason().name()));
String determination = doEvents(Arrays.asList
("entity spawns",
"entity spawns because " + event.getSpawnReason().name(),
entity.getType().name() + " spawns",
entity.getType().name() + " spawns because " +
event.getSpawnReason().name()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void entityCombust(EntityCombustEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
context.put("duration", new Duration((long) event.getDuration()));
String determination = doEvents(Arrays.asList
("entity combusts",
entity.getType().name() + " combusts"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void entityDamage(EntityDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
boolean isFatal = false;
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getType();
String cause = event.getCause().name();
String determination;
dPlayer player = null;
dNPC npc = null;
if (entity.isNPC()) {
context.put("entity", new dNPC(entity.getNPC()));
entityType = "npc";
}
else if (entity.isPlayer()) {
player = new dPlayer(entity.getPlayer());
context.put("entity", new dPlayer(entity.getPlayer()));
}
else {
context.put("entity", entity);
}
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity instanceof LivingEntity) {
if (event.getDamage() >= ((LivingEntity) entity).getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
- if (isFatal == true) {
+ if (isFatal) {
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
dPlayer subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getType();
if (damager.isNPC()) {
subNPC = new dNPC(entity.getNPC());
context.put("damager", new dNPC(damager.getNPC()));
damagerType = "npc";
// If we had no NPC in our regular context, use this one
- if (npc == null) npc = subNPC;
+ npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = new dPlayer(damager.getPlayer());
context.put("damager", new dPlayer((Player) damager));
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
else {
context.put("damager", damager);
if (damager instanceof Projectile) {
if (((Projectile) damager).getShooter() != null)
context.put("shooter", new dEntity(((Projectile) damager).getShooter()));
else
context.put("shooter", Element.valueOf("null"));
}
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
- if (isFatal == true) {
+ if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
- determination = doEvents(subEvents, subNPC, subPlayer.getPlayerEntity(), context);
+ determination = doEvents(subEvents, subNPC, (subPlayer != null?subPlayer.getPlayerEntity():null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc,
(player != null && player.isOnline() ? player.getPlayerEntity() : null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
@EventHandler
public void entityExplode(EntityExplodeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
if (entity == null) return;
context.put("entity", new dEntity(entity));
context.put("location", new dLocation(event.getLocation()));
String blocks = "";
for (Block block : event.blockList()) {
blocks = blocks + new dLocation(block.getLocation()) + "|";
}
context.put("blocks", blocks.length() > 0 ? new dList(blocks) : null);
String determination = doEvents(Arrays.asList
("entity explodes",
entity.getType().name() + " explodes"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void entityRegainHealth(EntityRegainHealthEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
String entityType = entity.getType().name();
context.put("reason", new Element(event.getRegainReason().name()));
context.put("amount", new Element(event.getAmount()));
Player player = null;
dNPC npc = null;
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
npc = DenizenAPI.getDenizenNPC(CitizensAPI.getNPCRegistry().getNPC(entity));
context.put("entity", npc);
entityType = "npc";
}
else if (entity instanceof Player) {
player = (Player) entity;
context.put("entity", new dPlayer(player));
}
else {
context.put("entity", new dEntity(entity));
}
String determination = doEvents(Arrays.asList
("entity heals",
"entity heals because " + event.getRegainReason().name(),
entityType + " heals",
entityType + " heals because " + event.getRegainReason().name()),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setAmount(aH.getDoubleFrom(determination));
}
}
@EventHandler
public void entityShootBow(EntityShootBowEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
String entityType = entity.getType().name();
Entity projectile = event.getProjectile();
Player player = null;
dNPC npc = null;
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
npc = DenizenAPI.getDenizenNPC(CitizensAPI.getNPCRegistry().getNPC(entity));
context.put("entity", npc);
entityType = "npc";
}
else if (entity instanceof Player) {
player = (Player) entity;
context.put("entity", new dPlayer((Player) entity));
}
else {
context.put("entity", new dEntity(entity));
}
context.put("bow", new dItem(event.getBow()));
context.put("projectile", new dEntity(projectile));
String determination = doEvents(Arrays.asList
("entity shoots bow",
entityType + " shoots bow"),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED")) {
event.setCancelled(true);
}
// Don't use event.setProjectile() because it doesn't work
else if (Argument.valueOf(determination).matchesArgumentList(dEntity.class)) {
event.setCancelled(true);
// Get the list of entities
Object list = dList.valueOf(determination).filter(dEntity.class);
@SuppressWarnings("unchecked")
List<dEntity> newProjectiles = (List<dEntity>) list;
// Go through all the entities, spawning/teleporting them
for (dEntity newProjectile : newProjectiles) {
if (newProjectile.isSpawned() == false) {
newProjectile.spawnAt(projectile.getLocation());
}
else {
newProjectile.teleport(projectile.getLocation());
}
// Set the entity as the shooter of the projectile
if (newProjectile.getBukkitEntity() instanceof Projectile
&& entity instanceof LivingEntity) {
((Projectile) newProjectile.getBukkitEntity())
.setShooter((LivingEntity) entity);
}
}
// Mount the projectiles on top of each other
Position.mount(Conversion.convert(newProjectiles));
// Get the last entity on the list, i.e. the one at the bottom
// if there are many mounted on top of each other
Entity lastProjectile = newProjectiles.get
(newProjectiles.size() - 1).getBukkitEntity();
// Give it the same velocity as the arrow that would
// have been shot by the bow
lastProjectile.setVelocity(projectile.getVelocity());
}
}
@EventHandler
public void entityTame(EntityTameEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
Player player = null;
List<String> events = new ArrayList<String>();
events.add("entity tamed");
events.add(entity.getType().name() + " tamed");
if (event.getOwner() instanceof Player) {
player = (Player) event.getOwner();
events.add("player tames entity");
events.add("player tames " + entity.getType().name());
}
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void entityTarget(EntityTargetEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
Entity target = event.getTarget();
Player player = null;
String reason = event.getReason().name();
String entityType = entity.getType().name();
context.put("entity", new dEntity(entity));
context.put("reason", new Element(reason));
List<String> events = new ArrayList<String>();
events.add("entity targets");
events.add("entity targets because " + reason);
events.add(entityType + " targets");
events.add(entityType + " targets because " + reason);
if (target != null) {
if (event.getTarget() instanceof Player) {
player = (Player) target;
context.put("target", new dPlayer(player));
}
else {
context.put("target", new dEntity(target));
}
String targetType = target.getType().name();
events.add("entity targets entity");
events.add("entity targets entity because " + reason);
events.add("entity targets " + targetType);
events.add("entity targets " + targetType + " because " + reason);
events.add(entityType + " targets entity");
events.add(entityType + " targets entity because " + reason);
events.add(entityType + " targets " + targetType);
events.add(entityType + " targets " + targetType + " because " + reason);
}
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
// If the determination matches a dEntity, change the event's target
//
// Note: this only works with a handful of monster types, like spiders
// and endermen for instance
else if (dEntity.matches(determination)) {
final dEntity attacker = new dEntity(entity);
final dEntity newTarget = dEntity.valueOf(determination);
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(), new Runnable() {
public void run() {
attacker.target(newTarget.getLivingEntity());
}
}, 1);
}
}
@EventHandler
public void entityTeleport(EntityTeleportEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
context.put("origin", new dLocation(event.getFrom()));
context.put("destination", new dLocation(event.getTo()));
String determination = doEvents(Arrays.asList
("entity teleports",
entity.getType().name() + " teleports"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void explosionPrimeEvent(ExplosionPrimeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
context.put("radius", new Element(String.valueOf(event.getRadius())));
context.put("fire", new Element(event.getFire()));
String determination = doEvents(Arrays.asList
("entity explosion primes",
entity.getType().name() + " explosion primes"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void foodLevelChange(FoodLevelChangeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntity();
context.put("entity", entity instanceof Player ?
new dPlayer((Player) entity) :
new dEntity(entity));
String determination = doEvents(Arrays.asList
(entity.getType().name() + " changes food level"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setFoodLevel(aH.getIntegerFrom(determination));
}
}
@EventHandler
public void itemDespawn(ItemDespawnEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
dItem item = new dItem(event.getEntity().getItemStack());
context.put("item", item);
context.put("entity", new dEntity(event.getEntity()));
List<String> events = new ArrayList<String>();
events.add("item despawns");
events.add(item.identify() + " despawns");
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add(item.identify().split(":")[0] + " despawns");
}
if (item.isItemscript()) {
events.add("itemscript " + item.getMaterial() + " despawns");
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void itemSpawn(ItemSpawnEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
dItem item = new dItem(event.getEntity().getItemStack());
context.put("item", item);
context.put("entity", new dEntity(event.getEntity()));
List<String> events = new ArrayList<String>();
events.add("item spawns");
events.add(item.identify() + " spawns");
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add(item.identify().split(":")[0] + " spawns");
}
if (item.isItemscript()) {
events.add("itemscript " + item.getMaterial() + " spawns");
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// INVENTORY EVENTS
/////////////////
@EventHandler
public void inventoryClickEvent(InventoryClickEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
dItem item = new dItem(event.getCurrentItem());
Player player = (Player) event.getWhoClicked();
String type = event.getInventory().getType().name();
String click = event.getClick().name();
context.put("item", item);
context.put("inventory", new dInventory(event.getInventory()));
context.put("click", new Element(click));
List<String> events = new ArrayList<String>();
events.add("player clicks in inventory");
events.add("player clicks in " + type + " inventory");
String interaction = "player " + click + " clicks";
events.add(interaction + " in inventory");
events.add(interaction + " in " + type + " inventory");
if (item.getItemStack() != null) {
events.add(interaction + " on " +
item.identify() + " in inventory");
events.add(interaction + " on " +
item.identify() + " in " + type + " inventory");
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add(interaction + " on " +
item.identify().split(":")[0] + " in inventory");
events.add(interaction + " on " +
item.identify().split(":")[0] + " in " + type + " inventory");
}
if (item.isItemscript()) {
events.add(interaction + " on " +
item.getMaterial() + " in inventory");
events.add(interaction + " on " +
item.getMaterial() + " in " + type + " inventory");
}
}
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// PLAYER EVENTS
/////////////////
@EventHandler(priority = EventPriority.LOWEST)
public void playerChat(final AsyncPlayerChatEvent event) {
final Map<String, Object> context = new HashMap<String, Object>();
context.put("message", new Element(event.getMessage()));
Callable<String> call = new Callable<String>() {
public String call() {
return doEvents(Arrays.asList("player chats"),
null, event.getPlayer(), context);
}
};
String determination = null;
try {
determination = event.isAsynchronous() ? Bukkit.getScheduler().callSyncMethod(DenizenAPI.getCurrentInstance(), call).get() : call.call();
} catch (InterruptedException e) {
// TODO: Need to find a way to fix this eventually
// e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (determination == null)
return;
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (determination.equals("none") == false) {
event.setMessage(determination);
}
}
@EventHandler
public void bedEnterEvent(PlayerBedEnterEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBed().getLocation()));
String determination = doEvents
(Arrays.asList("player enters bed"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void bedLeaveEvent(PlayerBedLeaveEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getBed().getLocation()));
doEvents(Arrays.asList
("player leaves bed"),
null, event.getPlayer(), context);
}
@EventHandler
public void playerBucketEmpty(PlayerBucketEmptyEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("item", new dItem(event.getBucket()));
context.put("location", new dLocation(event.getBlockClicked().getLocation()));
String determination = doEvents(Arrays.asList
("player empties bucket"),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (determination.equals("none") == false) {
ItemStack is = dItem.valueOf(determination).getItemStack();
event.setItemStack( is != null ? is : new ItemStack(Material.AIR));
}
}
@EventHandler
public void playerBucketFill(PlayerBucketFillEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("item", new dItem(event.getBucket()));
context.put("location", new dLocation(event.getBlockClicked().getLocation()));
String determination = doEvents(Arrays.asList
("player fills bucket"),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (determination.equals("none") == false) {
ItemStack is = dItem.valueOf(determination).getItemStack();
event.setItemStack( is != null ? is : new ItemStack(Material.AIR));
}
}
@EventHandler
public void playerCommandEvent(PlayerCommandPreprocessEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
// Well, this is ugly :(
// Fill tags in any arguments
dPlayer player = dPlayer.valueOf(event.getPlayer().getName());
List<String> args = Arrays.asList(
aH.buildArgs(
TagManager.tag(player, null,
(event.getMessage().split(" ").length > 1 ? event.getMessage().split(" ", 2)[1] : ""))));
dList args_list = new dList(args);
String command = event.getMessage().split(" ")[0].replace("/", "").toUpperCase();
// Fill context
context.put("args", args_list);
context.put("command", new Element(command));
context.put("raw_args", new Element((event.getMessage().split(" ").length > 1 ? event.getMessage().split(" ", 2)[1] : "")));
context.put("server", Element.FALSE);
String determination;
// Run any event scripts and get the determination.
determination = doEvents(Arrays.asList
("command",
command + " command"), null, event.getPlayer(), context).toUpperCase();
// If a script has determined fulfilled, cancel this event so the player doesn't
// receive the default 'Invalid command' gibberish from bukkit.
if (determination.equals("FULFILLED") || determination.equals("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerDeath(PlayerDeathEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("message", new Element(event.getDeathMessage()));
String determination = doEvents(Arrays.asList
("player dies",
"player death"),
null, event.getEntity(), context);
// Handle message
if (determination.equals("none") == false) {
event.setDeathMessage(determination);
}
}
@EventHandler
public void playerFish(PlayerFishEvent event) {
Entity entity = event.getCaught();
String state = event.getState().name();
dNPC npc = null;
Map<String, Object> context = new HashMap<String, Object>();
context.put("hook", new dEntity(event.getHook()));
context.put("state", new Element(state));
List<String> events = new ArrayList<String>();
events.add("player fishes");
events.add("player fishes while " + state);
if (entity != null) {
String entityType = entity.getType().name();
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
npc = DenizenAPI.getDenizenNPC(CitizensAPI.getNPCRegistry().getNPC(entity));
context.put("entity", npc);
entityType = "npc";
}
else if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
}
else {
context.put("entity", new dEntity(entity));
}
events.add("player fishes " + entityType);
events.add("player fishes " + entityType + " while " + state);
}
String determination = doEvents(events, npc, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerGameModeChange(PlayerGameModeChangeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("gamemode", new Element(event.getNewGameMode().name()));
String determination = doEvents(Arrays.asList
("player changes gamemode",
"player changes gamemode to " + event.getNewGameMode().name()),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerInteract(PlayerInteractEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Action action = event.getAction();
dItem item = null;
List<String> events = new ArrayList<String>();
String interaction;
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK)
interaction = "player left clicks";
else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)
interaction = "player right clicks";
// The only other action is PHYSICAL, which is triggered when a player
// stands on a pressure plate
else interaction = "player stands";
events.add(interaction);
if (event.hasItem()) {
item = new dItem(event.getItem());
context.put("item", item);
events.add(interaction + " with item");
events.add(interaction + " with " + item.identify());
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add(interaction + " with " + item.identify().split(":")[0]);
}
if (item.isItemscript()) {
events.add(interaction + " with itemscript " + item.getMaterial());
}
}
if (event.hasBlock()) {
Block block = event.getClickedBlock();
context.put("location", new dLocation(block.getLocation()));
interaction = interaction + " on " + block.getType().name();
events.add(interaction);
if (event.hasItem()) {
events.add(interaction + " with item");
events.add(interaction + " with " + item.identify());
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add(interaction + " with " + item.identify().split(":")[0]);
}
if (item.isItemscript()) {
events.add(interaction + " with itemscript " + item.getMaterial());
}
}
}
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerInteractEntity(PlayerInteractEntityEvent event) {
Entity entity = event.getRightClicked();
String entityType = entity.getType().name();
dNPC npc = null;
dItem item = new dItem(event.getPlayer().getItemInHand());
String determination;
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getRightClicked().getLocation()));
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
npc = DenizenAPI.getDenizenNPC
(CitizensAPI.getNPCRegistry().getNPC(entity));
context.put("entity", npc);
entityType = "npc";
}
else if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
}
else {
context.put("entity", new dEntity(entity));
}
List<String> events = new ArrayList<String>();
events.add("player right clicks entity");
events.add("player right clicks " + entityType);
events.add("player right clicks entity with " +
item.identify());
events.add("player right clicks " + entityType + " with " +
item.identify());
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add("player right clicks entity with " +
item.identify().split(":")[0]);
events.add("player right clicks " + entityType + " with " +
item.identify().split(":")[0]);
}
if (item.isItemscript()) {
events.add("player right clicks entity with itemscript " +
item.getMaterial());
events.add("player right clicks " + entityType + " with itemscript " +
item.getMaterial());
}
if (entity instanceof ItemFrame) {
dItem itemFrame = new dItem(((ItemFrame) entity).getItem());
context.put("itemframe", itemFrame);
events.add("player right clicks " + entityType + " " +
itemFrame.identify());
if (itemFrame.identify().equals(itemFrame.identify().split(":")[0]) == false) {
events.add("player right clicks " + entityType + " " +
itemFrame.identify().split(":")[0]);
}
if (itemFrame.isItemscript()) {
events.add("player right clicks " + entityType +
" itemscript " + item.getMaterial());
}
}
determination = doEvents(events, npc, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerItemConsume(PlayerItemConsumeEvent event) {
dItem item = new dItem(event.getItem());
Map<String, Object> context = new HashMap<String, Object>();
context.put("item", item);
List<String> events = new ArrayList<String>();
events.add("player consumes " + item.identify());
if (item.identify().equals(item.identify().split(":")[0]) == false) {
events.add("player consumes " + item.identify().split(":")[0]);
}
if (item.isItemscript()) {
events.add("player consumes itemscript " + item.getMaterial());
}
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void playerMoveEvent(PlayerMoveEvent event) {
if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return;
String name = dLocation.getSaved(event.getPlayer().getLocation());
if (name != null) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("notable", new Element(name));
String determination = doEvents(Arrays.asList
("player walks over notable",
"player walks over " + name,
"walked over notable",
"walked over " + name),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED") ||
determination.toUpperCase().startsWith("FROZEN"))
event.setCancelled(true);
}
}
@EventHandler
public void playerPickupItem(PlayerPickupItemEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("item", new dItem(event.getItem().getItemStack()));
context.put("entity", new dEntity(event.getItem()));
context.put("location", new dLocation(event.getItem().getLocation()));
Entity item = event.getItem();
List<String> events = new ArrayList<String>();
if (item instanceof Arrow) {
events.add("player pickup arrow");
events.add("player take arrow");
events.add("player picks up arrow");
events.add("player takes arrow");
}
events.add("player pickup item");
events.add("player take item");
events.add("player picks up item");
events.add("player takes item");
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void joinEvent(PlayerJoinEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("message", new Element(event.getJoinMessage()));
String determination = doEvents(Arrays.asList
("player joins",
"player join"),
null, event.getPlayer(), context);
// Handle message
if (determination.equals("none") == false) {
event.setJoinMessage(determination);
}
}
@EventHandler
public void levelChangeEvent(PlayerLevelChangeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("level", new Element(event.getNewLevel()));
doEvents(Arrays.asList
("player levels up",
"player levels up to " + event.getNewLevel(),
"player levels up from " + event.getOldLevel()),
null, event.getPlayer(), context);
}
@EventHandler
public void loginEvent(PlayerLoginEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("hostname", new Element(event.getHostname()));
String determination = doEvents(Arrays.asList
("player logs in", "player login"),
null, event.getPlayer(), context);
// Handle determine kicked
if (determination.toUpperCase().startsWith("KICKED"))
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, determination);
}
@EventHandler
public void quitEvent(PlayerQuitEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("message", new Element(event.getQuitMessage()));
String determination = doEvents(Arrays.asList
("player quits",
"player quit"),
null, event.getPlayer(), context);
// Handle determine message
if (determination.equals("none") == false) {
event.setQuitMessage(determination);
}
}
@EventHandler
public void respawnEvent(PlayerRespawnEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
context.put("location", new dLocation(event.getRespawnLocation()));
List<String> events = new ArrayList<String>();
events.add("player respawns");
if (event.isBedSpawn()) {
events.add("player respawns at bed");
}
else {
events.add("player respawns elsewhere");
}
String determination = doEvents(events, null, event.getPlayer(), context);
// Handle determine message
if (dLocation.matches(determination)) {
dLocation location = dLocation.valueOf(determination);
if (location != null) event.setRespawnLocation(location);
}
}
/////////////////////
// SERVER EVENTS
/////////////////
@EventHandler
public void serverCommandEvent(ServerCommandEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
List<String> args = Arrays.asList(
aH.buildArgs(
TagManager.tag(null, null,
(event.getCommand().split(" ").length > 1 ? event.getCommand().split(" ", 2)[1] : ""))));
dList args_list = new dList(args);
String command = event.getCommand().split(" ")[0].replace("/", "").toUpperCase();
// Fill context
context.put("args", args_list);
context.put("command", new Element(command));
context.put("raw_args", new Element((event.getCommand().split(" ").length > 1 ? event.getCommand().split(" ", 2)[1] : "")));
context.put("server", Element.TRUE);
doEvents(Arrays.asList("command",
command + " command"),
null, null, context);
}
/////////////////////
// VEHICLE EVENTS
/////////////////
@EventHandler
public void vehicleDamage(VehicleDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getAttacker();
Vehicle vehicle = event.getVehicle();
if (entity == null || vehicle == null)
return;
String entityType = entity.getType().name();
String vehicleType = vehicle.getType().name();
Player player = null;
context.put("damage", new Element(event.getDamage()));
context.put("vehicle", new dEntity(vehicle));
if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
player = (Player) entity;
}
else {
context.put("entity", new dEntity(entity));
}
String determination = doEvents(Arrays.asList
("entity damages vehicle",
entityType + " damages vehicle",
"entity damages " + vehicleType,
entityType + " damages " + vehicleType),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
@EventHandler
public void vehicleDestroy(VehicleDestroyEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getAttacker();
Vehicle vehicle = event.getVehicle();
if (entity == null || vehicle == null)
return;
String entityType = entity.getType().name();
String vehicleType = vehicle.getType().name();
Player player = null;
context.put("vehicle", new dEntity(vehicle));
if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
player = (Player) entity;
}
else {
context.put("entity", new dEntity(entity));
}
String determination = doEvents(Arrays.asList
("entity destroys vehicle",
entityType + " destroys vehicle",
"entity destroys " + vehicleType,
entityType + " destroys " + vehicleType),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void vehicleEnter(VehicleEnterEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getEntered();
Vehicle vehicle = event.getVehicle();
if (entity == null || vehicle == null)
return;
String entityType = entity.getType().name();
String vehicleType = vehicle.getType().name();
Player player = null;
context.put("vehicle", new dEntity(vehicle));
if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
player = (Player) entity;
}
else {
context.put("entity", new dEntity(entity));
}
String determination = doEvents(Arrays.asList
("entity enters vehicle",
entityType + " enters vehicle",
"entity enters " + vehicleType,
entityType + " enters " + vehicleType),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void vehicleExit(VehicleExitEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
Entity entity = event.getExited();
Vehicle vehicle = event.getVehicle();
if (entity == null || vehicle == null)
return;
String entityType = entity.getType().name();
String vehicleType = vehicle.getType().name();
Player player = null;
context.put("vehicle", new dEntity(vehicle));
if (entity instanceof Player) {
context.put("entity", new dPlayer((Player) entity));
player = (Player) entity;
}
else {
context.put("entity", new dEntity(entity));
}
String determination = doEvents(Arrays.asList
("entity exits vehicle",
entityType + " exits vehicle",
"entity exits " + vehicleType,
entityType + " exits " + vehicleType),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// WEATHER EVENTS
/////////////////
@EventHandler
public void lightningStrike(LightningStrikeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
String world = event.getWorld().getName();
context.put("world", new dWorld(event.getWorld()));
context.put("location", new dLocation(event.getLightning().getLocation()));
String determination = doEvents(Arrays.asList
("lightning strikes",
"lightning strikes in " + world),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
@EventHandler
public void weatherChange(WeatherChangeEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
String world = event.getWorld().getName();
context.put("world", new dWorld(event.getWorld()));
List<String> events = new ArrayList<String>();
events.add("weather changes");
events.add("weather changes in " + world);
if (event.toWeatherState() == true) {
context.put("weather", new Element("rain"));
events.add("weather rains");
events.add("weather rains in " + world);
}
else {
context.put("weather", new Element("clear"));
events.add("weather clears");
events.add("weather clears in " + world);
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
}
| false | true | public void entityDamage(EntityDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
boolean isFatal = false;
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getType();
String cause = event.getCause().name();
String determination;
dPlayer player = null;
dNPC npc = null;
if (entity.isNPC()) {
context.put("entity", new dNPC(entity.getNPC()));
entityType = "npc";
}
else if (entity.isPlayer()) {
player = new dPlayer(entity.getPlayer());
context.put("entity", new dPlayer(entity.getPlayer()));
}
else {
context.put("entity", entity);
}
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity instanceof LivingEntity) {
if (event.getDamage() >= ((LivingEntity) entity).getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal == true) {
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
dPlayer subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getType();
if (damager.isNPC()) {
subNPC = new dNPC(entity.getNPC());
context.put("damager", new dNPC(damager.getNPC()));
damagerType = "npc";
// If we had no NPC in our regular context, use this one
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = new dPlayer(damager.getPlayer());
context.put("damager", new dPlayer((Player) damager));
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
else {
context.put("damager", damager);
if (damager instanceof Projectile) {
if (((Projectile) damager).getShooter() != null)
context.put("shooter", new dEntity(((Projectile) damager).getShooter()));
else
context.put("shooter", Element.valueOf("null"));
}
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal == true) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, subPlayer.getPlayerEntity(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc,
(player != null && player.isOnline() ? player.getPlayerEntity() : null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
| public void entityDamage(EntityDamageEvent event) {
Map<String, Object> context = new HashMap<String, Object>();
boolean isFatal = false;
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getType();
String cause = event.getCause().name();
String determination;
dPlayer player = null;
dNPC npc = null;
if (entity.isNPC()) {
context.put("entity", new dNPC(entity.getNPC()));
entityType = "npc";
}
else if (entity.isPlayer()) {
player = new dPlayer(entity.getPlayer());
context.put("entity", new dPlayer(entity.getPlayer()));
}
else {
context.put("entity", entity);
}
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity instanceof LivingEntity) {
if (event.getDamage() >= ((LivingEntity) entity).getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
dPlayer subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getType();
if (damager.isNPC()) {
subNPC = new dNPC(entity.getNPC());
context.put("damager", new dNPC(damager.getNPC()));
damagerType = "npc";
// If we had no NPC in our regular context, use this one
npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = new dPlayer(damager.getPlayer());
context.put("damager", new dPlayer((Player) damager));
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
else {
context.put("damager", damager);
if (damager instanceof Projectile) {
if (((Projectile) damager).getShooter() != null)
context.put("shooter", new dEntity(((Projectile) damager).getShooter()));
else
context.put("shooter", Element.valueOf("null"));
}
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, (subPlayer != null?subPlayer.getPlayerEntity():null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc,
(player != null && player.isOnline() ? player.getPlayerEntity() : null), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
|
diff --git a/src/com/android/musicvis/vis3/Visualization3RS.java b/src/com/android/musicvis/vis3/Visualization3RS.java
index 27a3f14..3f33131 100644
--- a/src/com/android/musicvis/vis3/Visualization3RS.java
+++ b/src/com/android/musicvis/vis3/Visualization3RS.java
@@ -1,128 +1,128 @@
/*
* Copyright (C) 2009 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.musicvis.vis3;
import com.android.musicvis.GenericWaveRS;
import com.android.musicvis.R;
import com.android.musicvis.RenderScriptScene;
import com.android.musicvis.AudioCapture;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.Primitive;
import android.renderscript.ProgramVertex;
import android.renderscript.ScriptC;
import android.renderscript.Type;
import android.renderscript.Element.Builder;
import android.util.Log;
import android.view.SurfaceHolder;
import java.util.TimeZone;
class Visualization3RS extends GenericWaveRS {
private short [] mAnalyzer = new short[512];
float lastOffset;
Visualization3RS(int width, int height) {
super(width, height, R.drawable.ice);
lastOffset = 0;
}
@Override
public void setOffset(float xOffset, float yOffset, int xPixels, int yPixels) {
mWorldState.yRotation = (xOffset * 4) * 360;
updateWorldState();
}
@Override
public void start() {
if (mAudioCapture == null) {
mAudioCapture = new AudioCapture(AudioCapture.TYPE_FFT, 512);
}
super.start();
}
@Override
public void stop() {
super.stop();
if (mAudioCapture != null) {
mAudioCapture.release();
mAudioCapture = null;
}
}
@Override
public void update() {
int len = 0;
if (mAudioCapture != null) {
mVizData = mAudioCapture.getFormattedData(64, 1);
len = mVizData.length;
}
if (len == 0) {
if (mWorldState.idle == 0) {
mWorldState.idle = 1;
updateWorldState();
}
return;
}
if (len > mAnalyzer.length) len = mAnalyzer.length;
if (mWorldState.idle != 0) {
mWorldState.idle = 0;
updateWorldState();
}
for (int i = 0; i < len; i++) {
short newval = (short)(mVizData[i] * (i/16+2));
short oldval = mAnalyzer[i];
if (newval >= oldval - 800) {
// use new high value
} else {
newval = (short)(oldval - 800);
}
mAnalyzer[i] = newval;
}
// distribute the data over mWidth samples in the middle of the mPointData array
final int outlen = mPointData.length / 8;
- final int width = mWidth;
- final int skip = (outlen - mWidth) / 2;
+ final int width = mWidth > outlen ? outlen : mWidth;
+ final int skip = (outlen - width) / 2;
int srcidx = 0;
int cnt = 0;
for (int i = 0; i < width; i++) {
float val = mAnalyzer[srcidx] / 50;
if (val < 1f && val > -1f) val = 1;
mPointData[(i + skip) * 8 + 1] = val;
mPointData[(i + skip) * 8 + 5] = -val;
cnt += mAnalyzer.length;
if (cnt > width) {
srcidx++;
cnt -= width;
}
}
mPointAlloc.data(mPointData);
}
}
| true | true | public void update() {
int len = 0;
if (mAudioCapture != null) {
mVizData = mAudioCapture.getFormattedData(64, 1);
len = mVizData.length;
}
if (len == 0) {
if (mWorldState.idle == 0) {
mWorldState.idle = 1;
updateWorldState();
}
return;
}
if (len > mAnalyzer.length) len = mAnalyzer.length;
if (mWorldState.idle != 0) {
mWorldState.idle = 0;
updateWorldState();
}
for (int i = 0; i < len; i++) {
short newval = (short)(mVizData[i] * (i/16+2));
short oldval = mAnalyzer[i];
if (newval >= oldval - 800) {
// use new high value
} else {
newval = (short)(oldval - 800);
}
mAnalyzer[i] = newval;
}
// distribute the data over mWidth samples in the middle of the mPointData array
final int outlen = mPointData.length / 8;
final int width = mWidth;
final int skip = (outlen - mWidth) / 2;
int srcidx = 0;
int cnt = 0;
for (int i = 0; i < width; i++) {
float val = mAnalyzer[srcidx] / 50;
if (val < 1f && val > -1f) val = 1;
mPointData[(i + skip) * 8 + 1] = val;
mPointData[(i + skip) * 8 + 5] = -val;
cnt += mAnalyzer.length;
if (cnt > width) {
srcidx++;
cnt -= width;
}
}
mPointAlloc.data(mPointData);
}
| public void update() {
int len = 0;
if (mAudioCapture != null) {
mVizData = mAudioCapture.getFormattedData(64, 1);
len = mVizData.length;
}
if (len == 0) {
if (mWorldState.idle == 0) {
mWorldState.idle = 1;
updateWorldState();
}
return;
}
if (len > mAnalyzer.length) len = mAnalyzer.length;
if (mWorldState.idle != 0) {
mWorldState.idle = 0;
updateWorldState();
}
for (int i = 0; i < len; i++) {
short newval = (short)(mVizData[i] * (i/16+2));
short oldval = mAnalyzer[i];
if (newval >= oldval - 800) {
// use new high value
} else {
newval = (short)(oldval - 800);
}
mAnalyzer[i] = newval;
}
// distribute the data over mWidth samples in the middle of the mPointData array
final int outlen = mPointData.length / 8;
final int width = mWidth > outlen ? outlen : mWidth;
final int skip = (outlen - width) / 2;
int srcidx = 0;
int cnt = 0;
for (int i = 0; i < width; i++) {
float val = mAnalyzer[srcidx] / 50;
if (val < 1f && val > -1f) val = 1;
mPointData[(i + skip) * 8 + 1] = val;
mPointData[(i + skip) * 8 + 5] = -val;
cnt += mAnalyzer.length;
if (cnt > width) {
srcidx++;
cnt -= width;
}
}
mPointAlloc.data(mPointData);
}
|
diff --git a/src/ibis/util/ThreadPool.java b/src/ibis/util/ThreadPool.java
index f047d70c..32a8d1cf 100644
--- a/src/ibis/util/ThreadPool.java
+++ b/src/ibis/util/ThreadPool.java
@@ -1,173 +1,173 @@
package ibis.util;
import ibis.ipl.IbisError;
import java.util.LinkedList;
import org.apache.log4j.Logger;
/**
* @author Niels Drost
*
* Threadpool which uses timeouts to determine the number of threads...
* There is no maximum number of threads in this pool, to prevent deadlocks.
*
*/
public final class ThreadPool {
static final Logger logger = GetLogger.getLogger(ThreadPool.class);
private static final class PoolThread extends Thread {
private static final int TIMEOUT = 30 * 1000; //30 seconds
Runnable work = null;
String name = null;
boolean expired = false;
private static int nrOfThreads = 0;
private static synchronized void newThread() {
nrOfThreads++;
logger.debug("new thread. Threadcount: " + nrOfThreads);
}
private static synchronized void threadGone() {
nrOfThreads--;
logger.debug("thread gone. Threadcount: " + nrOfThreads);
}
private PoolThread() {
//DO NOT USE
}
PoolThread(Runnable runnable, String name) {
this.work = runnable;
this.name = name;
if (logger.isDebugEnabled()) {
newThread();
}
}
synchronized boolean issue(Runnable newWork, String newName) {
if (expired) {
logger.debug("issue(): thread has expired");
return false;
}
if (this.work != null) {
throw new IbisError("tried to issue work to already running"
+ " poolthread");
}
work = newWork;
name = newName;
notifyAll();
return true;
}
public void run() {
while (true) {
Runnable currentWork;
String currentName;
synchronized (this) {
if (this.work == null) {
waiting(this);
try {
wait(TIMEOUT);
} catch (InterruptedException e) {
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
}
if (this.work == null) {
//still no work, exit
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
currentWork = this.work;
currentName = this.name;
}
try {
setName(currentName);
currentWork.run();
} catch (Throwable t) {
String errorString = "caught exception in pool thread "
+ currentName + ": " + t + "\n Stacktrace: \n";
StackTraceElement e[] = t.getStackTrace();
for(int i = 0; i < e.length; i++) {
- errorString = errorString + "\t\t" + e.toString() + "\n";
+ errorString = errorString + "\t\t" + e[i].toString() + "\n";
}
logger.error(errorString);
}
synchronized (this) {
this.work = null;
this.name = null;
}
}
}
}
//list of waiting Poolthreads
private static final LinkedList threadPool = new LinkedList();
/**
* Prevent creation of a threadpool object.
*/
private ThreadPool() {
//DO NOT USE
}
static synchronized void waiting(PoolThread thread) {
threadPool.add(thread);
}
/**
* Associates a thread from the <code>ThreadPool</code> with the
* specified {@link Runnable}. If no thread is available, a new one
* is created. When the {@link Runnable} is finished, the thread is
* added to the pool of available threads.
*
* @param runnable the <code>Runnable</code> to be executed.
* @param name set the thread name for the duration of this run
*/
public static synchronized void createNew(Runnable runnable, String name) {
PoolThread poolThread;
if (!threadPool.isEmpty()) {
poolThread = (PoolThread) threadPool.removeLast();
if (poolThread.issue(runnable, name)) {
//issue of work succeeded, return
return;
}
//shortest waiting poolThread in list timed out,
//assume all threads timed out
if (logger.isDebugEnabled()) {
logger.debug("clearing thread pool of size "
+ threadPool.size());
}
threadPool.clear();
}
//no usable thread found, create a new thread
poolThread = new PoolThread(runnable, name);
poolThread.setDaemon(true);
poolThread.start();
}
}
| true | true | public void run() {
while (true) {
Runnable currentWork;
String currentName;
synchronized (this) {
if (this.work == null) {
waiting(this);
try {
wait(TIMEOUT);
} catch (InterruptedException e) {
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
}
if (this.work == null) {
//still no work, exit
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
currentWork = this.work;
currentName = this.name;
}
try {
setName(currentName);
currentWork.run();
} catch (Throwable t) {
String errorString = "caught exception in pool thread "
+ currentName + ": " + t + "\n Stacktrace: \n";
StackTraceElement e[] = t.getStackTrace();
for(int i = 0; i < e.length; i++) {
errorString = errorString + "\t\t" + e.toString() + "\n";
}
logger.error(errorString);
}
synchronized (this) {
this.work = null;
this.name = null;
}
}
}
| public void run() {
while (true) {
Runnable currentWork;
String currentName;
synchronized (this) {
if (this.work == null) {
waiting(this);
try {
wait(TIMEOUT);
} catch (InterruptedException e) {
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
}
if (this.work == null) {
//still no work, exit
expired = true;
if (logger.isDebugEnabled()) {
threadGone();
}
return;
}
currentWork = this.work;
currentName = this.name;
}
try {
setName(currentName);
currentWork.run();
} catch (Throwable t) {
String errorString = "caught exception in pool thread "
+ currentName + ": " + t + "\n Stacktrace: \n";
StackTraceElement e[] = t.getStackTrace();
for(int i = 0; i < e.length; i++) {
errorString = errorString + "\t\t" + e[i].toString() + "\n";
}
logger.error(errorString);
}
synchronized (this) {
this.work = null;
this.name = null;
}
}
}
|
diff --git a/management/src/main/java/org/mortbay/management/ObjectMBean.java b/management/src/main/java/org/mortbay/management/ObjectMBean.java
index 516a6f942..1f31d6b3b 100644
--- a/management/src/main/java/org/mortbay/management/ObjectMBean.java
+++ b/management/src/main/java/org/mortbay/management/ObjectMBean.java
@@ -1,679 +1,679 @@
//========================================================================
//Copyright 2004 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package org.mortbay.management;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.modelmbean.ModelMBean;
import org.mortbay.log.Log;
import org.mortbay.util.LazyList;
import org.mortbay.util.Loader;
import org.mortbay.util.TypeUtil;
/* ------------------------------------------------------------ */
/** ObjectMBean.
* A dynamic MBean that can wrap an arbitary Object instance.
* the attributes and methods exposed by this bean are controlled by
* the merge of property bundles discovered by names related to all
* superclasses and all superinterfaces.
*
* Attributes and methods exported may be "Object" and must exist on the
* wrapped object, or "MBean" and must exist on a subclass of OBjectMBean
* or "MObject" which exists on the wrapped object, but whose values are
* converted to MBean object names.
*
*/
public class ObjectMBean implements DynamicMBean
{
private static Class[] OBJ_ARG = new Class[]{Object.class};
private Object _managed;
private MBeanInfo _info;
private Map _getters=new HashMap();
private Map _setters=new HashMap();
private Map _methods=new HashMap();
private Set _convert=new HashSet();
private ClassLoader _loader;
private MBeanContainer _mbeanContainer;
private static String OBJECT_NAME_CLASS = ObjectName.class.getName();
private static String OBJECT_NAME_ARRAY_CLASS = ObjectName[].class.getName();
/* ------------------------------------------------------------ */
/**
* Create MBean for Object. Attempts to create an MBean for the object by searching the package
* and class name space. For example an object of the type
*
* <PRE>
* class com.acme.MyClass extends com.acme.util.BaseClass implements com.acme.Iface
* </PRE>
*
* Then this method would look for the following classes:
* <UL>
* <LI>com.acme.management.MyClassMBean
* <LI>com.acme.util.management.BaseClassMBean
* <LI>org.mortbay.management.ObjectMBean
* </UL>
*
* @param o The object
* @return A new instance of an MBean for the object or null.
*/
public static Object mbeanFor(Object o)
{
try
{
Class oClass = o.getClass();
Object mbean = null;
while (mbean == null && oClass != null)
{
String pName = oClass.getPackage().getName();
String cName = oClass.getName().substring(pName.length() + 1);
String mName = pName + ".management." + cName + "MBean";
try
{
Class mClass = (Object.class.equals(oClass))?oClass=ObjectMBean.class:Loader.loadClass(oClass,mName,true);
if (Log.isDebugEnabled())
Log.debug("mbeanFor " + o + " mClass=" + mClass);
try
{
Constructor constructor = mClass.getConstructor(OBJ_ARG);
mbean=constructor.newInstance(new Object[]{o});
}
catch(Exception e)
{
Log.ignore(e);
if (ModelMBean.class.isAssignableFrom(mClass))
{
mbean=mClass.newInstance();
((ModelMBean)mbean).setManagedResource(o, "objectReference");
}
}
if (Log.isDebugEnabled())
Log.debug("mbeanFor " + o + " is " + mbean);
return mbean;
}
catch (ClassNotFoundException e)
{
if (e.toString().endsWith("MBean"))
Log.ignore(e);
else
Log.warn(e);
}
catch (Error e)
{
Log.warn(e);
mbean = null;
}
catch (Exception e)
{
Log.warn(e);
mbean = null;
}
oClass = oClass.getSuperclass();
}
}
catch (Exception e)
{
Log.ignore(e);
}
return null;
}
public ObjectMBean(Object managedObject)
{
_managed = managedObject;
_loader = Thread.currentThread().getContextClassLoader();
}
protected void setMBeanContainer(MBeanContainer container)
{
this._mbeanContainer = container;
}
public MBeanInfo getMBeanInfo()
{
try
{
if (_info==null)
{
// Start with blank lazy lists attributes etc.
String desc=null;
Object attributes=null;
Object constructors=null;
Object operations=null;
Object notifications=null;
// Find list of classes that can influence the mbean
Class o_class=_managed.getClass();
Object influences = findInfluences(null, _managed.getClass());
// Set to record defined items
Set defined=new HashSet();
// For each influence
for (int i=0;i<LazyList.size(influences);i++)
{
Class oClass = (Class)LazyList.get(influences, i);
// look for a bundle defining methods
if (Object.class.equals(oClass))
oClass=ObjectMBean.class;
String pName = oClass.getPackage().getName();
String cName = oClass.getName().substring(pName.length() + 1);
String rName = pName.replace('.', '/') + "/management/" + cName+"-mbean";
try
{
Log.debug(rName);
ResourceBundle bundle = Loader.getResourceBundle(o_class, rName,true,Locale.getDefault());
// Extract meta data from bundle
Enumeration e = bundle.getKeys();
while (e.hasMoreElements())
{
String key = (String)e.nextElement();
String value = bundle.getString(key);
// Determin if key is for mbean , attribute or for operation
if (key.equals(cName))
{
// set the mbean description
if (desc==null)
desc=value;
}
else if (key.indexOf('(')>0)
{
// define an operation
if (!defined.contains(key) && key.indexOf('[')<0)
{
defined.add(key);
operations=LazyList.add(operations,defineOperation(key, value, bundle));
}
}
else
{
// define an attribute
if (!defined.contains(key))
{
defined.add(key);
attributes=LazyList.add(attributes,defineAttribute(key, value));
}
}
}
}
catch(MissingResourceException e)
{
Log.ignore(e);
}
}
_info = new MBeanInfo(o_class.getName(),
desc,
(MBeanAttributeInfo[])LazyList.toArray(attributes, MBeanAttributeInfo.class),
(MBeanConstructorInfo[])LazyList.toArray(constructors, MBeanConstructorInfo.class),
(MBeanOperationInfo[])LazyList.toArray(operations, MBeanOperationInfo.class),
(MBeanNotificationInfo[])LazyList.toArray(notifications, MBeanNotificationInfo.class));
}
}
catch(RuntimeException e)
{
Log.warn(e);
throw e;
}
return _info;
}
/* ------------------------------------------------------------ */
public Object getAttribute(String name) throws AttributeNotFoundException, MBeanException, ReflectionException
{
if (Log.isDebugEnabled())
Log.debug("getAttribute " + name);
Method getter = (Method) _getters.get(name);
if (getter == null)
throw new AttributeNotFoundException(name);
try
{
Object o = _managed;
if (getter.getDeclaringClass().isInstance(this))
o = this; // mbean method
// get the attribute
Object r=getter.invoke(o, (java.lang.Object[]) null);
// convert to ObjectName if need be.
if (r!=null && _convert.contains(name))
{
if (r.getClass().isArray())
{
ObjectName[] on = new ObjectName[Array.getLength(r)];
for (int i=0;i<on.length;i++)
on[i]=_mbeanContainer.findMBean(Array.get(r, i));
r=on;
}
else
{
ObjectName mbean = _mbeanContainer.findMBean(r);
if (mbean==null)
return null;
r=mbean;
}
}
return r;
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new AttributeNotFoundException(e.toString());
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
}
/* ------------------------------------------------------------ */
public AttributeList getAttributes(String[] names)
{
Log.debug("getAttributes");
AttributeList results = new AttributeList(names.length);
for (int i = 0; i < names.length; i++)
{
try
{
results.add(new Attribute(names[i], getAttribute(names[i])));
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
}
}
return results;
}
/* ------------------------------------------------------------ */
public void setAttribute(Attribute attr) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
if (attr == null)
return;
if (Log.isDebugEnabled())
Log.debug("setAttribute " + attr.getName() + "=" + attr.getValue());
Method setter = (Method) _setters.get(attr.getName());
if (setter == null)
throw new AttributeNotFoundException(attr.getName());
try
{
Object o = _managed;
if (setter.getDeclaringClass().isInstance(this))
o = this;
// get the value
Object value = attr.getValue();
// convert from ObjectName if need be
if (value!=null && _convert.contains(attr.getName()))
{
if (value.getClass().isArray())
{
Class t=setter.getParameterTypes()[0].getComponentType();
Object na = Array.newInstance(t,Array.getLength(value));
for (int i=Array.getLength(value);i-->0;)
Array.set(na, i, _mbeanContainer.findBean((ObjectName)Array.get(value, i)));
value=na;
}
else
value=_mbeanContainer.findBean((ObjectName)value);
}
// do the setting
setter.invoke(o, new Object[]{ value });
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new AttributeNotFoundException(e.toString());
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
}
/* ------------------------------------------------------------ */
public AttributeList setAttributes(AttributeList attrs)
{
Log.debug("setAttributes");
AttributeList results = new AttributeList(attrs.size());
Iterator iter = attrs.iterator();
while (iter.hasNext())
{
try
{
Attribute attr = (Attribute) iter.next();
setAttribute(attr);
results.add(new Attribute(attr.getName(), getAttribute(attr.getName())));
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
}
}
return results;
}
/* ------------------------------------------------------------ */
public Object invoke(String name, Object[] params, String[] signature) throws MBeanException, ReflectionException
{
if (Log.isDebugEnabled())
Log.debug("invoke " + name);
String methodKey = name + "(";
if (signature != null)
for (int i = 0; i < signature.length; i++)
methodKey += (i > 0 ? "," : "") + signature[i];
methodKey += ")";
ClassLoader old_loader=Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(_loader);
Method method = (Method) _methods.get(methodKey);
if (method == null)
throw new NoSuchMethodException(methodKey);
Object o = _managed;
if (method.getDeclaringClass().isInstance(this))
o = this;
return method.invoke(o, params);
}
catch (NoSuchMethodException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException(e);
}
catch (IllegalAccessException e)
{
Log.warn(Log.EXCEPTION, e);
throw new MBeanException(e);
}
catch (InvocationTargetException e)
{
Log.warn(Log.EXCEPTION, e);
throw new ReflectionException((Exception) e.getTargetException());
}
finally
{
Thread.currentThread().setContextClassLoader(old_loader);
}
}
private static Object findInfluences(Object influences, Class aClass)
{
if (aClass!=null)
{
// This class is an influence
influences=LazyList.add(influences,aClass);
// So are the super classes
influences=findInfluences(influences,aClass.getSuperclass());
// So are the interfaces
Class[] ifs = aClass.getInterfaces();
for (int i=0;ifs!=null && i<ifs.length;i++)
influences=findInfluences(influences,ifs[i]);
}
return influences;
}
/* ------------------------------------------------------------ */
/**
* Define an attribute on the managed object. The meta data is defined by looking for standard
* getter and setter methods. Descriptions are obtained with a call to findDescription with the
* attribute name.
*
* @param name
* @param metaData "description" or "access:description" or "type:access:description" where type is
* the "Object","MBean" or "MObject" to indicate the method is on the object, the MBean or on the object but converted to an MBean, access
* is either "RW" or "RO".
*/
public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
- throw new IllegalArgumentException("Multiple getters for attr " + name);
+ throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
- throw new IllegalArgumentException("Multiple getters for attr " + name);
+ throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
- throw new IllegalArgumentException("Multiple setters for attr " + name);
+ throw new IllegalArgumentException("Multiple setters for attr " + name+ " in "+oClass);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
- throw new IllegalArgumentException("Type conflict for attr " + name);
+ throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
- throw new IllegalArgumentException("No getter or setters found for " + name);
+ throw new IllegalArgumentException("No getter or setters found for " + name+ " in "+oClass);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
/* ------------------------------------------------------------ */
/**
* Define an operation on the managed object. Defines an operation with parameters. Refection is
* used to determine find the method and it's return type. The description of the method is
* found with a call to findDescription on "name(signature)". The name and description of each
* parameter is found with a call to findDescription with "name(partialSignature", the returned
* description is for the last parameter of the partial signature and is assumed to start with
* the parameter name, followed by a colon.
*
* @param metaData "description" or "impact:description" or "type:impact:description", type is
* the "Object","MBean" or "MObject" to indicate the method is on the object, the MBean or on the
* object but converted to an MBean, and impact is either "ACTION","INFO","ACTION_INFO" or "UNKNOWN".
*/
private MBeanOperationInfo defineOperation(String signature, String metaData, ResourceBundle bundle)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
String impact_name = i<0?"UNKNOWN":tokens[i--];
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
if (Log.isDebugEnabled())
Log.debug("defineOperation "+signature+" "+onMBean+":"+impact_name+":"+description);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
try
{
// Resolve the impact
int impact=MBeanOperationInfo.UNKNOWN;
if (impact_name==null || impact_name.equals("UNKNOWN"))
impact=MBeanOperationInfo.UNKNOWN;
else if (impact_name.equals("ACTION"))
impact=MBeanOperationInfo.ACTION;
else if (impact_name.equals("INFO"))
impact=MBeanOperationInfo.INFO;
else if (impact_name.equals("ACTION_INFO"))
impact=MBeanOperationInfo.ACTION_INFO;
else
Log.warn("Unknown impact '"+impact_name+"' for "+signature);
// split the signature
String[] parts=signature.split("[\\(\\)]");
String method_name=parts[0];
String arguments=parts.length==2?parts[1]:null;
String[] args=arguments==null?new String[0]:arguments.split(" *, *");
// Check types and normalize signature.
Class[] types = new Class[args.length];
MBeanParameterInfo[] pInfo = new MBeanParameterInfo[args.length];
signature=method_name;
for (i = 0; i < args.length; i++)
{
Class type = TypeUtil.fromName(args[i]);
if (type == null)
type = Thread.currentThread().getContextClassLoader().loadClass(args[i]);
types[i] = type;
args[i] = type.isPrimitive() ? TypeUtil.toName(type) : args[i];
signature+=(i>0?",":"(")+args[i];
}
signature+=(i>0?")":"()");
// Build param infos
for (i = 0; i < args.length; i++)
{
String param_desc = bundle.getString(signature + "[" + i + "]");
parts=param_desc.split(" *: *",2);
if (Log.isDebugEnabled())
Log.debug(parts[0]+": "+parts[1]);
pInfo[i] = new MBeanParameterInfo(parts[0].trim(), args[i], parts[1].trim());
}
// build the operation info
Method method = oClass.getMethod(method_name, types);
Class returnClass = method.getReturnType();
_methods.put(signature, method);
if (convert)
_convert.add(signature);
return new MBeanOperationInfo(method_name, description, pInfo, returnClass.isPrimitive() ? TypeUtil.toName(returnClass) : (returnClass.getName()), impact);
}
catch (Exception e)
{
Log.warn("Operation '"+signature+"'", e);
throw new IllegalArgumentException(e.toString());
}
}
}
| false | true | public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
throw new IllegalArgumentException("Multiple setters for attr " + name);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
throw new IllegalArgumentException("Type conflict for attr " + name);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
throw new IllegalArgumentException("No getter or setters found for " + name);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
| public MBeanAttributeInfo defineAttribute(String name, String metaData)
{
String[] tokens=metaData.split(":",3);
int i=tokens.length-1;
String description=tokens[i--];
boolean writable= i<0 || "RW".equalsIgnoreCase(tokens[i--]);
boolean onMBean= i==0 && "MBean".equalsIgnoreCase(tokens[0]);
boolean convert= i==0 && "MObject".equalsIgnoreCase(tokens[0]);
String uName = name.substring(0, 1).toUpperCase() + name.substring(1);
Class oClass = onMBean ? this.getClass() : _managed.getClass();
if (Log.isDebugEnabled())
Log.debug("defineAttribute "+name+" "+onMBean+":"+writable+":"+oClass+":"+description);
Class type = null;
Method getter = null;
Method setter = null;
Method[] methods = oClass.getMethods();
for (int m = 0; m < methods.length; m++)
{
if ((methods[m].getModifiers() & Modifier.PUBLIC) == 0)
continue;
// Look for a getter
if (methods[m].getName().equals("get" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// Look for an is getter
if (methods[m].getName().equals("is" + uName) && methods[m].getParameterTypes().length == 0)
{
if (getter != null)
throw new IllegalArgumentException("Multiple getters for attr " + name+ " in "+oClass);
getter = methods[m];
if (type != null && !type.equals(methods[m].getReturnType()))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getReturnType();
}
// look for a setter
if (writable && methods[m].getName().equals("set" + uName) && methods[m].getParameterTypes().length == 1)
{
if (setter != null)
throw new IllegalArgumentException("Multiple setters for attr " + name+ " in "+oClass);
setter = methods[m];
if (type != null && !type.equals(methods[m].getParameterTypes()[0]))
throw new IllegalArgumentException("Type conflict for attr " + name+ " in "+oClass);
type = methods[m].getParameterTypes()[0];
}
}
if (convert && type.isPrimitive() && !type.isArray())
throw new IllegalArgumentException("Cannot convert primative " + name);
if (getter == null && setter == null)
throw new IllegalArgumentException("No getter or setters found for " + name+ " in "+oClass);
try
{
// Remember the methods
_getters.put(name, getter);
_setters.put(name, setter);
MBeanAttributeInfo info=null;
if (convert)
{
_convert.add(name);
if (type.isArray())
info= new MBeanAttributeInfo(name,OBJECT_NAME_ARRAY_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
else
info= new MBeanAttributeInfo(name,OBJECT_NAME_CLASS,description,getter!=null,setter!=null,getter!=null&&getter.getName().startsWith("is"));
}
else
info= new MBeanAttributeInfo(name,description,getter,setter);
return info;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION, e);
throw new IllegalArgumentException(e.toString());
}
}
|
diff --git a/ext/WarblerJar.java b/ext/WarblerJar.java
index ac669bf..d5436b2 100644
--- a/ext/WarblerJar.java
+++ b/ext/WarblerJar.java
@@ -1,192 +1,193 @@
/**
* Copyright (c) 2010-2012 Engine Yard, Inc.
* Copyright (c) 2007-2009 Sun Microsystems, Inc.
* This source code is available under the MIT license.
* See the file LICENSE.txt for details.
*/
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyString;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.Block;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.ByteList;
import org.jruby.util.JRubyFile;
public class WarblerJar {
public static void create(Ruby runtime) {
RubyModule task = runtime.getClassFromPath("Warbler::Jar");
task.defineAnnotatedMethods(WarblerJar.class);
}
@JRubyMethod
public static IRubyObject create_jar(ThreadContext context, IRubyObject recv, IRubyObject jar_path, IRubyObject entries) {
final Ruby runtime = recv.getRuntime();
if (!(entries instanceof RubyHash)) {
throw runtime.newArgumentError("expected a hash for the second argument");
}
RubyHash hash = (RubyHash) entries;
try {
FileOutputStream file = newFile(jar_path);
try {
ZipOutputStream zip = new ZipOutputStream(file);
addEntries(context, zip, hash);
zip.finish();
} finally {
close(file);
}
} catch (IOException e) {
if (runtime.isDebug()) {
e.printStackTrace();
}
throw runtime.newIOErrorFromException(e);
}
return runtime.getNil();
}
@JRubyMethod
public static IRubyObject entry_in_jar(ThreadContext context, IRubyObject recv, IRubyObject jar_path, IRubyObject entry) {
final Ruby runtime = recv.getRuntime();
try {
InputStream entryStream = getStream(jar_path.convertToString().getUnicodeValue(),
entry.convertToString().getUnicodeValue());
try {
byte[] buf = new byte[16384];
ByteList blist = new ByteList();
int bytesRead = -1;
while ((bytesRead = entryStream.read(buf)) != -1) {
blist.append(buf, 0, bytesRead);
}
IRubyObject stringio = runtime.getModule("StringIO");
return stringio.callMethod(context, "new", runtime.newString(blist));
} finally {
close(entryStream);
}
} catch (IOException e) {
if (runtime.isDebug()) {
e.printStackTrace();
}
throw runtime.newIOErrorFromException(e);
}
}
private static void addEntries(ThreadContext context, ZipOutputStream zip, RubyHash entries) throws IOException {
RubyArray keys = entries.keys().sort(context, Block.NULL_BLOCK);
for (int i = 0; i < keys.getLength(); i++) {
IRubyObject key = keys.entry(i);
IRubyObject value = entries.op_aref(context, key);
addEntry(context, zip, key.convertToString().getUnicodeValue(), value);
}
}
private static void addEntry(ThreadContext context, ZipOutputStream zip, String entryName, IRubyObject value) throws IOException {
if (value.respondsTo("read")) {
RubyString str = (RubyString) value.callMethod(context, "read").checkStringType();
- byte[] contents = str.getByteList().getUnsafeBytes();
+ ByteList strByteList = str.getByteList();
+ byte[] contents = strByteList.getUnsafeBytes();
zip.putNextEntry(new ZipEntry(entryName));
- zip.write(contents);
+ zip.write(contents, strByteList.getBegin(), strByteList.getRealSize());
} else {
File f;
if (value.isNil() || (f = getFile(value)).isDirectory()) {
zip.putNextEntry(new ZipEntry(entryName + "/"));
} else {
String path = f.getPath();
if (!f.exists()) {
path = value.convertToString().getUnicodeValue();
}
InputStream inFile = getStream(path, null);
try {
zip.putNextEntry(new ZipEntry(entryName));
byte[] buf = new byte[16384];
int bytesRead = -1;
while ((bytesRead = inFile.read(buf)) != -1) {
zip.write(buf, 0, bytesRead);
}
} finally {
close(inFile);
}
}
}
}
private static FileOutputStream newFile(IRubyObject jar_path) throws IOException {
return new FileOutputStream(getFile(jar_path));
}
private static File getFile(IRubyObject path) {
return JRubyFile.create(path.getRuntime().getCurrentDirectory(),
path.convertToString().getUnicodeValue());
}
private static void close(Closeable c) {
try {
c.close();
} catch (Exception e) {
}
}
private static Pattern PROTOCOL = Pattern.compile("^[a-z][a-z0-9]+:");
private static InputStream getStream(String jar, String entry) throws IOException {
Matcher m = PROTOCOL.matcher(jar);
while (m.find()) {
jar = jar.substring(m.end());
m = PROTOCOL.matcher(jar);
}
String[] path = jar.split("!/");
InputStream stream = new FileInputStream(path[0]);
for (int i = 1; i < path.length; i++) {
stream = entryInJar(stream, path[i]);
}
if (entry == null) {
return stream;
}
return entryInJar(stream, entry);
}
private static String trimTrailingSlashes(String path) {
if (path.endsWith("/")) {
return path.substring(0, path.length() - 1);
} else {
return path;
}
}
private static InputStream entryInJar(InputStream jar, String entry) throws IOException {
entry = trimTrailingSlashes(entry);
ZipInputStream jstream = new ZipInputStream(jar);
ZipEntry zentry = null;
while ((zentry = jstream.getNextEntry()) != null) {
if (trimTrailingSlashes(zentry.getName()).equals(entry)) {
return jstream;
}
jstream.closeEntry();
}
throw new FileNotFoundException("entry '" + entry + "' not found in " + jar);
}
}
| false | true | private static void addEntry(ThreadContext context, ZipOutputStream zip, String entryName, IRubyObject value) throws IOException {
if (value.respondsTo("read")) {
RubyString str = (RubyString) value.callMethod(context, "read").checkStringType();
byte[] contents = str.getByteList().getUnsafeBytes();
zip.putNextEntry(new ZipEntry(entryName));
zip.write(contents);
} else {
File f;
if (value.isNil() || (f = getFile(value)).isDirectory()) {
zip.putNextEntry(new ZipEntry(entryName + "/"));
} else {
String path = f.getPath();
if (!f.exists()) {
path = value.convertToString().getUnicodeValue();
}
InputStream inFile = getStream(path, null);
try {
zip.putNextEntry(new ZipEntry(entryName));
byte[] buf = new byte[16384];
int bytesRead = -1;
while ((bytesRead = inFile.read(buf)) != -1) {
zip.write(buf, 0, bytesRead);
}
} finally {
close(inFile);
}
}
}
}
| private static void addEntry(ThreadContext context, ZipOutputStream zip, String entryName, IRubyObject value) throws IOException {
if (value.respondsTo("read")) {
RubyString str = (RubyString) value.callMethod(context, "read").checkStringType();
ByteList strByteList = str.getByteList();
byte[] contents = strByteList.getUnsafeBytes();
zip.putNextEntry(new ZipEntry(entryName));
zip.write(contents, strByteList.getBegin(), strByteList.getRealSize());
} else {
File f;
if (value.isNil() || (f = getFile(value)).isDirectory()) {
zip.putNextEntry(new ZipEntry(entryName + "/"));
} else {
String path = f.getPath();
if (!f.exists()) {
path = value.convertToString().getUnicodeValue();
}
InputStream inFile = getStream(path, null);
try {
zip.putNextEntry(new ZipEntry(entryName));
byte[] buf = new byte[16384];
int bytesRead = -1;
while ((bytesRead = inFile.read(buf)) != -1) {
zip.write(buf, 0, bytesRead);
}
} finally {
close(inFile);
}
}
}
}
|
diff --git a/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java b/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java
index 1e7b2ec2..94236d2b 100644
--- a/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java
+++ b/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java
@@ -1,126 +1,129 @@
package bndtools.internal.decorator;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Version;
import aQute.bnd.build.Project;
import aQute.bnd.build.Workspace;
import aQute.bnd.header.Attrs;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Descriptors.PackageRef;
import aQute.bnd.osgi.Packages;
import aQute.bnd.osgi.Processor;
import bndtools.Central;
import bndtools.Logger;
import bndtools.api.ILogger;
import bndtools.utils.SWTConcurrencyUtil;
public class ExportedPackageDecoratorJob extends Job implements ISchedulingRule {
private static final ILogger logger = Logger.getLogger();
private static final ConcurrentMap<String,ExportedPackageDecoratorJob> instances = new ConcurrentHashMap<String,ExportedPackageDecoratorJob>();
private final IProject project;
public static void scheduleForProject(IProject project) {
ExportedPackageDecoratorJob job = new ExportedPackageDecoratorJob(project);
if (instances.putIfAbsent(project.getFullPath().toPortableString(), job) == null) {
job.schedule(1000);
}
}
ExportedPackageDecoratorJob(IProject project) {
super("Update exported packages: " + project.getName());
this.project = project;
setRule(this);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
instances.remove(project.getFullPath().toPortableString());
try {
Project model = Workspace.getProject(project.getLocation().toFile());
+ if (model == null) {
+ return Status.OK_STATUS;
+ }
Collection< ? extends Builder> builders = model.getSubBuilders();
Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>();
Set<String> allContained = new HashSet<String>();
for (Builder builder : builders) {
try {
builder.build();
Packages exports = builder.getExports();
if (exports != null) {
for (Entry<PackageRef,Attrs> export : exports.entrySet()) {
Version version;
String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE);
try {
version = Version.parseVersion(versionStr);
String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN());
SortedSet<Version> versions = allExports.get(pkgName);
if (versions == null) {
versions = new TreeSet<Version>();
allExports.put(pkgName, versions);
}
versions.add(version);
} catch (IllegalArgumentException e) {
// Seems to be an invalid export, ignore it...
}
}
}
Packages contained = builder.getContained();
for (PackageRef pkgRef : contained.keySet()) {
String pkgName = Processor.removeDuplicateMarker(pkgRef.getFQN());
allContained.add(pkgName);
}
} catch (Exception e) {
logger.logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e);
}
}
Central.setProjectPackageModel(project, allExports, allContained);
Display display = PlatformUI.getWorkbench().getDisplay();
SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() {
public void run() {
PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.packageDecorator");
}
});
} catch (Exception e) {
logger.logWarning("Error persisting package model for project: " + project.getName(), e);
}
return Status.OK_STATUS;
}
public boolean contains(ISchedulingRule rule) {
return this == rule;
}
public boolean isConflicting(ISchedulingRule rule) {
return rule instanceof ExportedPackageDecoratorJob;
}
}
| true | true | protected IStatus run(IProgressMonitor monitor) {
instances.remove(project.getFullPath().toPortableString());
try {
Project model = Workspace.getProject(project.getLocation().toFile());
Collection< ? extends Builder> builders = model.getSubBuilders();
Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>();
Set<String> allContained = new HashSet<String>();
for (Builder builder : builders) {
try {
builder.build();
Packages exports = builder.getExports();
if (exports != null) {
for (Entry<PackageRef,Attrs> export : exports.entrySet()) {
Version version;
String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE);
try {
version = Version.parseVersion(versionStr);
String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN());
SortedSet<Version> versions = allExports.get(pkgName);
if (versions == null) {
versions = new TreeSet<Version>();
allExports.put(pkgName, versions);
}
versions.add(version);
} catch (IllegalArgumentException e) {
// Seems to be an invalid export, ignore it...
}
}
}
Packages contained = builder.getContained();
for (PackageRef pkgRef : contained.keySet()) {
String pkgName = Processor.removeDuplicateMarker(pkgRef.getFQN());
allContained.add(pkgName);
}
} catch (Exception e) {
logger.logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e);
}
}
Central.setProjectPackageModel(project, allExports, allContained);
Display display = PlatformUI.getWorkbench().getDisplay();
SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() {
public void run() {
PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.packageDecorator");
}
});
} catch (Exception e) {
logger.logWarning("Error persisting package model for project: " + project.getName(), e);
}
return Status.OK_STATUS;
}
| protected IStatus run(IProgressMonitor monitor) {
instances.remove(project.getFullPath().toPortableString());
try {
Project model = Workspace.getProject(project.getLocation().toFile());
if (model == null) {
return Status.OK_STATUS;
}
Collection< ? extends Builder> builders = model.getSubBuilders();
Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>();
Set<String> allContained = new HashSet<String>();
for (Builder builder : builders) {
try {
builder.build();
Packages exports = builder.getExports();
if (exports != null) {
for (Entry<PackageRef,Attrs> export : exports.entrySet()) {
Version version;
String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE);
try {
version = Version.parseVersion(versionStr);
String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN());
SortedSet<Version> versions = allExports.get(pkgName);
if (versions == null) {
versions = new TreeSet<Version>();
allExports.put(pkgName, versions);
}
versions.add(version);
} catch (IllegalArgumentException e) {
// Seems to be an invalid export, ignore it...
}
}
}
Packages contained = builder.getContained();
for (PackageRef pkgRef : contained.keySet()) {
String pkgName = Processor.removeDuplicateMarker(pkgRef.getFQN());
allContained.add(pkgName);
}
} catch (Exception e) {
logger.logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e);
}
}
Central.setProjectPackageModel(project, allExports, allContained);
Display display = PlatformUI.getWorkbench().getDisplay();
SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() {
public void run() {
PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.packageDecorator");
}
});
} catch (Exception e) {
logger.logWarning("Error persisting package model for project: " + project.getName(), e);
}
return Status.OK_STATUS;
}
|
diff --git a/src/main/java/network/Telnet.java b/src/main/java/network/Telnet.java
index c650a727..d258d38b 100755
--- a/src/main/java/network/Telnet.java
+++ b/src/main/java/network/Telnet.java
@@ -1,70 +1,70 @@
import java.net.*;
import java.io.*;
/**
* Telnet - connect to a given host and service
* This does not hold a candle to a real Telnet client, but
* shows some ideas on how to implement such a thing.
* @version $Id$
*/
public class Telnet {
String host;
int portNum;
public static void main(String[] argv) {
new Telnet().talkTo(argv);
}
private void talkTo(String av[]) {
if (av.length >= 1)
host = av[0];
else
host = "localhost";
if (av.length >= 2)
portNum = Integer.parseInt(av[1]);
else portNum = 23;
- System.out.println("Host" + host + "; port " + portNum);
+ System.out.println("Host " + host + "; port " + portNum);
try {
Socket s = new Socket(host, portNum);
// Connect the remote to our stdout
new Pipe(s.getInputStream(), System.out).start();
// Connect our stdin to the remote
new Pipe(System.in, s.getOutputStream()).start();
} catch(IOException e) {
System.out.println(e);
return;
}
System.out.println("Connected OK");
}
}
/** This class handles one side of the connection. */
/* This class handles one half of a full-duplex connection.
* Line-at-a-time mode. Streams, not writers, are used.
*/
class Pipe extends Thread {
DataInputStream is;
PrintStream os;
// Constructor
Pipe(InputStream is, OutputStream os) {
this.is = new DataInputStream(is);
this.os = new PrintStream(os);
}
// Do something method
public void run() {
String line;
try {
while ((line = is.readLine()) != null) {
os.print(line);
os.print("\r\n");
os.flush();
}
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
| true | true | private void talkTo(String av[]) {
if (av.length >= 1)
host = av[0];
else
host = "localhost";
if (av.length >= 2)
portNum = Integer.parseInt(av[1]);
else portNum = 23;
System.out.println("Host" + host + "; port " + portNum);
try {
Socket s = new Socket(host, portNum);
// Connect the remote to our stdout
new Pipe(s.getInputStream(), System.out).start();
// Connect our stdin to the remote
new Pipe(System.in, s.getOutputStream()).start();
} catch(IOException e) {
System.out.println(e);
return;
}
System.out.println("Connected OK");
}
| private void talkTo(String av[]) {
if (av.length >= 1)
host = av[0];
else
host = "localhost";
if (av.length >= 2)
portNum = Integer.parseInt(av[1]);
else portNum = 23;
System.out.println("Host " + host + "; port " + portNum);
try {
Socket s = new Socket(host, portNum);
// Connect the remote to our stdout
new Pipe(s.getInputStream(), System.out).start();
// Connect our stdin to the remote
new Pipe(System.in, s.getOutputStream()).start();
} catch(IOException e) {
System.out.println(e);
return;
}
System.out.println("Connected OK");
}
|
diff --git a/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java b/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java
index 2de5593a9..d03e88a87 100644
--- a/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java
+++ b/dspace-api/src/main/java/org/dspace/content/packager/RoleIngester.java
@@ -1,389 +1,389 @@
/**
* RoleIngester.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2010, The DSpace 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:
*
* - 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 DSpace Foundation nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.content.packager;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.crosswalk.CrosswalkException;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.EPersonDeletionException;
import org.dspace.eperson.Group;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Create EPersons and Groups from a file of external representations.
*
* @author mwood
*/
public class RoleIngester implements PackageIngester
{
private static final Logger log = LoggerFactory
.getLogger(RoleIngester.class);
/**
* Common code to ingest roles from a Document.
*
* @param context
* @param document
* @throws SQLException
* @throws AuthorizeException
* @throws PackageException
*/
static void ingestDocument(Context context, PackageParameters params,
Document document) throws SQLException, AuthorizeException,
PackageException
{
String myEmail = context.getCurrentUser().getEmail();
String myNetid = context.getCurrentUser().getNetid();
// Ingest users (EPersons) first so Groups can use them
NodeList users = document
.getElementsByTagName(RoleDisseminator.EPERSON);
for (int i = 0; i < users.getLength(); i++)
{
Element user = (Element) users.item(i);
// int userID = Integer.valueOf(user.getAttribute("ID")); // FIXME
// no way to set ID!
NodeList emails = user.getElementsByTagName(RoleDisseminator.EMAIL);
NodeList netids = user.getElementsByTagName(RoleDisseminator.NETID);
EPerson eperson;
EPerson collider;
String email = null;
String netid = null;
String identity;
if (emails.getLength() > 0)
{
email = emails.item(0).getTextContent();
if (email.equals(myEmail))
continue; // Cannot operate on my own EPerson!
identity = email;
collider = EPerson.findByEmail(context, identity);
// collider = EPerson.find(context, userID);
}
else if (netids.getLength() > 0)
{
netid = netids.item(0).getTextContent();
if (netid.equals(myNetid))
continue; // Cannot operate on my own EPerson!
identity = netid;
collider = EPerson.findByNetid(context, identity);
}
else
throw new PackageException(
"EPerson has neither email nor netid.");
if (null != collider)
if (params.replaceModeEnabled()) // -r -f
{
eperson = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing EPerson {} was not restored from the package.",
identity);
continue;
}
else
throw new PackageException("EPerson " + identity
+ " already exists.");
else
{
eperson = EPerson.create(context);
log.info("Created EPerson {}.", identity);
}
eperson.setEmail(email);
eperson.setNetid(netid);
NodeList data;
data = user.getElementsByTagName(RoleDisseminator.FIRST_NAME);
if (data.getLength() > 0)
eperson.setFirstName(data.item(0).getTextContent());
else
eperson.setFirstName(null);
data = user.getElementsByTagName(RoleDisseminator.LAST_NAME);
if (data.getLength() > 0)
eperson.setLastName(data.item(0).getTextContent());
else
eperson.setLastName(null);
data = user.getElementsByTagName(RoleDisseminator.LANGUAGE);
if (data.getLength() > 0)
eperson.setLanguage(data.item(0).getTextContent());
else
eperson.setLanguage(null);
data = user.getElementsByTagName(RoleDisseminator.CAN_LOGIN);
eperson.setCanLogIn(data.getLength() > 0);
data = user
.getElementsByTagName(RoleDisseminator.REQUIRE_CERTIFICATE);
eperson.setRequireCertificate(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.SELF_REGISTERED);
eperson.setSelfRegistered(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.PASSWORD_HASH);
if (data.getLength() > 0)
eperson.setPasswordHash(data.item(0).getTextContent());
else
eperson.setPasswordHash(null);
// Do not update eperson! Let subsequent problems roll it back.
}
// Now ingest the Groups
NodeList groups = document.getElementsByTagName(RoleDisseminator.GROUP);
// Create the groups and add their EPerson members
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
// int groupID = Integer.valueOf(group.getAttribute("ID")); // FIXME
// no way to set ID!
Group groupObj; // The group to restore
Group collider = Group.findByName(context, name); // Existing group?
if (null != collider)
{ // Group already exists, so empty it
if (params.replaceModeEnabled()) // -r -f
{
for (Group member : collider.getMemberGroups())
collider.removeMember(member);
for (EPerson member : collider.getMembers())
collider.removeMember(member);
log.info("Existing Group {} was cleared.", name);
groupObj = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing Group {} was not replaced from the package.",
name);
continue;
}
else
throw new PackageException("Group " + name
- + "already exists");
+ + " already exists");
}
else
{ // No such group exists
groupObj = Group.create(context);
groupObj.setName(name);
log.info("Created Group {}.", name);
}
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
EPerson memberEPerson = EPerson.findByEmail(context, memberName);
groupObj.addMember(memberEPerson);
}
// Do not groupObj.update! We want to roll back on subsequent
// failures.
}
// Go back and add Group members, now that all groups exist
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
Group groupObj = Group.findByName(context, name);
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER_GROUP);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
Group memberGroup = Group.findByName(context, memberName);
groupObj.addMember(memberGroup);
}
// Do not groupObj.update!
}
}
/**
* Ingest roles from an InputStream.
*
* @param context
* @param stream
* @throws PackageException
* @throws SQLException
* @throws AuthorizeException
*/
static public void ingestStream(Context context, PackageParameters params,
InputStream stream) throws PackageException, SQLException,
AuthorizeException
{
Document document;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setCoalescing(true);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(stream);
}
catch (ParserConfigurationException e)
{
throw new PackageException(e);
}
catch (SAXException e)
{
throw new PackageException(e);
}
catch (IOException e)
{
throw new PackageException(e);
}
/*
* TODO ? finally { close(stream); }
*/
ingestDocument(context, params, document);
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.content.packager.PackageIngester#ingest(org.dspace.core.Context
* , org.dspace.content.DSpaceObject, java.io.File,
* org.dspace.content.packager.PackageParameters, java.lang.String)
*/
public DSpaceObject ingest(Context context, DSpaceObject parent,
File pkgFile, PackageParameters params, String license)
throws PackageException, CrosswalkException, AuthorizeException,
SQLException, IOException
{
Document document;
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringComments(true);
dbf.setCoalescing(true);
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(pkgFile);
}
catch (ParserConfigurationException e)
{
throw new PackageException(e);
}
catch (SAXException e)
{
throw new PackageException(e);
}
ingestDocument(context, params, document);
/* Does not create a DSpaceObject */
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.content.packager.PackageIngester#ingestAll(org.dspace.core
* .Context, org.dspace.content.DSpaceObject, java.io.File,
* org.dspace.content.packager.PackageParameters, java.lang.String)
*/
public List<DSpaceObject> ingestAll(Context context, DSpaceObject parent,
File pkgFile, PackageParameters params, String license)
throws PackageException, UnsupportedOperationException,
CrosswalkException, AuthorizeException, SQLException, IOException
{
throw new PackageException(
"ingestAll() is not implemented, as ingest() method already handles ingestion of all roles from an external file.");
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.content.packager.PackageIngester#replace(org.dspace.core.Context
* , org.dspace.content.DSpaceObject, java.io.File,
* org.dspace.content.packager.PackageParameters)
*/
public DSpaceObject replace(Context context, DSpaceObject dso,
File pkgFile, PackageParameters params) throws PackageException,
UnsupportedOperationException, CrosswalkException,
AuthorizeException, SQLException, IOException
{
// TODO Auto-generated method stub
throw new PackageException("replace is not implemented yet"); // FIXME
}
/*
* (non-Javadoc)
*
* @see
* org.dspace.content.packager.PackageIngester#replaceAll(org.dspace.core
* .Context, org.dspace.content.DSpaceObject, java.io.File,
* org.dspace.content.packager.PackageParameters)
*/
public List<DSpaceObject> replaceAll(Context context, DSpaceObject dso,
File pkgFile, PackageParameters params) throws PackageException,
UnsupportedOperationException, CrosswalkException,
AuthorizeException, SQLException, IOException
{
// TODO Auto-generated method stub
throw new PackageException("replaceAll is not implemented");
}
}
| true | true | static void ingestDocument(Context context, PackageParameters params,
Document document) throws SQLException, AuthorizeException,
PackageException
{
String myEmail = context.getCurrentUser().getEmail();
String myNetid = context.getCurrentUser().getNetid();
// Ingest users (EPersons) first so Groups can use them
NodeList users = document
.getElementsByTagName(RoleDisseminator.EPERSON);
for (int i = 0; i < users.getLength(); i++)
{
Element user = (Element) users.item(i);
// int userID = Integer.valueOf(user.getAttribute("ID")); // FIXME
// no way to set ID!
NodeList emails = user.getElementsByTagName(RoleDisseminator.EMAIL);
NodeList netids = user.getElementsByTagName(RoleDisseminator.NETID);
EPerson eperson;
EPerson collider;
String email = null;
String netid = null;
String identity;
if (emails.getLength() > 0)
{
email = emails.item(0).getTextContent();
if (email.equals(myEmail))
continue; // Cannot operate on my own EPerson!
identity = email;
collider = EPerson.findByEmail(context, identity);
// collider = EPerson.find(context, userID);
}
else if (netids.getLength() > 0)
{
netid = netids.item(0).getTextContent();
if (netid.equals(myNetid))
continue; // Cannot operate on my own EPerson!
identity = netid;
collider = EPerson.findByNetid(context, identity);
}
else
throw new PackageException(
"EPerson has neither email nor netid.");
if (null != collider)
if (params.replaceModeEnabled()) // -r -f
{
eperson = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing EPerson {} was not restored from the package.",
identity);
continue;
}
else
throw new PackageException("EPerson " + identity
+ " already exists.");
else
{
eperson = EPerson.create(context);
log.info("Created EPerson {}.", identity);
}
eperson.setEmail(email);
eperson.setNetid(netid);
NodeList data;
data = user.getElementsByTagName(RoleDisseminator.FIRST_NAME);
if (data.getLength() > 0)
eperson.setFirstName(data.item(0).getTextContent());
else
eperson.setFirstName(null);
data = user.getElementsByTagName(RoleDisseminator.LAST_NAME);
if (data.getLength() > 0)
eperson.setLastName(data.item(0).getTextContent());
else
eperson.setLastName(null);
data = user.getElementsByTagName(RoleDisseminator.LANGUAGE);
if (data.getLength() > 0)
eperson.setLanguage(data.item(0).getTextContent());
else
eperson.setLanguage(null);
data = user.getElementsByTagName(RoleDisseminator.CAN_LOGIN);
eperson.setCanLogIn(data.getLength() > 0);
data = user
.getElementsByTagName(RoleDisseminator.REQUIRE_CERTIFICATE);
eperson.setRequireCertificate(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.SELF_REGISTERED);
eperson.setSelfRegistered(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.PASSWORD_HASH);
if (data.getLength() > 0)
eperson.setPasswordHash(data.item(0).getTextContent());
else
eperson.setPasswordHash(null);
// Do not update eperson! Let subsequent problems roll it back.
}
// Now ingest the Groups
NodeList groups = document.getElementsByTagName(RoleDisseminator.GROUP);
// Create the groups and add their EPerson members
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
// int groupID = Integer.valueOf(group.getAttribute("ID")); // FIXME
// no way to set ID!
Group groupObj; // The group to restore
Group collider = Group.findByName(context, name); // Existing group?
if (null != collider)
{ // Group already exists, so empty it
if (params.replaceModeEnabled()) // -r -f
{
for (Group member : collider.getMemberGroups())
collider.removeMember(member);
for (EPerson member : collider.getMembers())
collider.removeMember(member);
log.info("Existing Group {} was cleared.", name);
groupObj = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing Group {} was not replaced from the package.",
name);
continue;
}
else
throw new PackageException("Group " + name
+ "already exists");
}
else
{ // No such group exists
groupObj = Group.create(context);
groupObj.setName(name);
log.info("Created Group {}.", name);
}
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
EPerson memberEPerson = EPerson.findByEmail(context, memberName);
groupObj.addMember(memberEPerson);
}
// Do not groupObj.update! We want to roll back on subsequent
// failures.
}
// Go back and add Group members, now that all groups exist
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
Group groupObj = Group.findByName(context, name);
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER_GROUP);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
Group memberGroup = Group.findByName(context, memberName);
groupObj.addMember(memberGroup);
}
// Do not groupObj.update!
}
}
| static void ingestDocument(Context context, PackageParameters params,
Document document) throws SQLException, AuthorizeException,
PackageException
{
String myEmail = context.getCurrentUser().getEmail();
String myNetid = context.getCurrentUser().getNetid();
// Ingest users (EPersons) first so Groups can use them
NodeList users = document
.getElementsByTagName(RoleDisseminator.EPERSON);
for (int i = 0; i < users.getLength(); i++)
{
Element user = (Element) users.item(i);
// int userID = Integer.valueOf(user.getAttribute("ID")); // FIXME
// no way to set ID!
NodeList emails = user.getElementsByTagName(RoleDisseminator.EMAIL);
NodeList netids = user.getElementsByTagName(RoleDisseminator.NETID);
EPerson eperson;
EPerson collider;
String email = null;
String netid = null;
String identity;
if (emails.getLength() > 0)
{
email = emails.item(0).getTextContent();
if (email.equals(myEmail))
continue; // Cannot operate on my own EPerson!
identity = email;
collider = EPerson.findByEmail(context, identity);
// collider = EPerson.find(context, userID);
}
else if (netids.getLength() > 0)
{
netid = netids.item(0).getTextContent();
if (netid.equals(myNetid))
continue; // Cannot operate on my own EPerson!
identity = netid;
collider = EPerson.findByNetid(context, identity);
}
else
throw new PackageException(
"EPerson has neither email nor netid.");
if (null != collider)
if (params.replaceModeEnabled()) // -r -f
{
eperson = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing EPerson {} was not restored from the package.",
identity);
continue;
}
else
throw new PackageException("EPerson " + identity
+ " already exists.");
else
{
eperson = EPerson.create(context);
log.info("Created EPerson {}.", identity);
}
eperson.setEmail(email);
eperson.setNetid(netid);
NodeList data;
data = user.getElementsByTagName(RoleDisseminator.FIRST_NAME);
if (data.getLength() > 0)
eperson.setFirstName(data.item(0).getTextContent());
else
eperson.setFirstName(null);
data = user.getElementsByTagName(RoleDisseminator.LAST_NAME);
if (data.getLength() > 0)
eperson.setLastName(data.item(0).getTextContent());
else
eperson.setLastName(null);
data = user.getElementsByTagName(RoleDisseminator.LANGUAGE);
if (data.getLength() > 0)
eperson.setLanguage(data.item(0).getTextContent());
else
eperson.setLanguage(null);
data = user.getElementsByTagName(RoleDisseminator.CAN_LOGIN);
eperson.setCanLogIn(data.getLength() > 0);
data = user
.getElementsByTagName(RoleDisseminator.REQUIRE_CERTIFICATE);
eperson.setRequireCertificate(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.SELF_REGISTERED);
eperson.setSelfRegistered(data.getLength() > 0);
data = user.getElementsByTagName(RoleDisseminator.PASSWORD_HASH);
if (data.getLength() > 0)
eperson.setPasswordHash(data.item(0).getTextContent());
else
eperson.setPasswordHash(null);
// Do not update eperson! Let subsequent problems roll it back.
}
// Now ingest the Groups
NodeList groups = document.getElementsByTagName(RoleDisseminator.GROUP);
// Create the groups and add their EPerson members
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
// int groupID = Integer.valueOf(group.getAttribute("ID")); // FIXME
// no way to set ID!
Group groupObj; // The group to restore
Group collider = Group.findByName(context, name); // Existing group?
if (null != collider)
{ // Group already exists, so empty it
if (params.replaceModeEnabled()) // -r -f
{
for (Group member : collider.getMemberGroups())
collider.removeMember(member);
for (EPerson member : collider.getMembers())
collider.removeMember(member);
log.info("Existing Group {} was cleared.", name);
groupObj = collider;
}
else if (params.keepExistingModeEnabled()) // -r -k
{
log.warn("Existing Group {} was not replaced from the package.",
name);
continue;
}
else
throw new PackageException("Group " + name
+ " already exists");
}
else
{ // No such group exists
groupObj = Group.create(context);
groupObj.setName(name);
log.info("Created Group {}.", name);
}
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
EPerson memberEPerson = EPerson.findByEmail(context, memberName);
groupObj.addMember(memberEPerson);
}
// Do not groupObj.update! We want to roll back on subsequent
// failures.
}
// Go back and add Group members, now that all groups exist
for (int groupx = 0; groupx < groups.getLength(); groupx++)
{
Element group = (Element) groups.item(groupx);
String name = group.getAttribute(RoleDisseminator.NAME);
Group groupObj = Group.findByName(context, name);
NodeList members = group
.getElementsByTagName(RoleDisseminator.MEMBER_GROUP);
for (int memberx = 0; memberx < members.getLength(); memberx++)
{
Element member = (Element) members.item(memberx);
String memberName = member.getAttribute(RoleDisseminator.NAME);
Group memberGroup = Group.findByName(context, memberName);
groupObj.addMember(memberGroup);
}
// Do not groupObj.update!
}
}
|
diff --git a/src/org/bombusim/xmpp/handlers/IqFallback.java b/src/org/bombusim/xmpp/handlers/IqFallback.java
index 7c22b71..f480a7e 100644
--- a/src/org/bombusim/xmpp/handlers/IqFallback.java
+++ b/src/org/bombusim/xmpp/handlers/IqFallback.java
@@ -1,63 +1,64 @@
/*
* Copyright (c) 2005-2011, Eugene Stahov ([email protected]),
* http://bombus-im.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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 software; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.bombusim.xmpp.handlers;
import java.io.IOException;
import org.bombusim.xmpp.XmppError;
import org.bombusim.xmpp.XmppObject;
import org.bombusim.xmpp.XmppObjectListener;
import org.bombusim.xmpp.XmppStream;
import org.bombusim.xmpp.exception.XmppException;
import org.bombusim.xmpp.stanza.Iq;
public class IqFallback extends XmppObjectListener {
@Override
public int blockArrived(XmppObject data, XmppStream stream)
throws IOException, XmppException {
try {
Iq f = (Iq)data;
String from = f.getAttribute("from");
String type = f.getTypeAttribute();
if (type.equals("result")) { return BLOCK_REJECTED; }
if (type.equals("error")) { return BLOCK_REJECTED; }
XmppError err = new XmppError(XmppError.FEATURE_NOT_IMPLEMENTED, null);
f.setAttribute("to", from);
f.setAttribute("from", null);
f.setAttribute("type", "error");
+ f.setAttribute("xml:lang", null);
f.addChild(err.construct());
stream.send(f);
} catch (Exception e) {};
return BLOCK_PROCESSED;
}
@Override
public int priority() { return PRIORITY_IQUNKNOWN_FALLBACK; }
}
| true | true | public int blockArrived(XmppObject data, XmppStream stream)
throws IOException, XmppException {
try {
Iq f = (Iq)data;
String from = f.getAttribute("from");
String type = f.getTypeAttribute();
if (type.equals("result")) { return BLOCK_REJECTED; }
if (type.equals("error")) { return BLOCK_REJECTED; }
XmppError err = new XmppError(XmppError.FEATURE_NOT_IMPLEMENTED, null);
f.setAttribute("to", from);
f.setAttribute("from", null);
f.setAttribute("type", "error");
f.addChild(err.construct());
stream.send(f);
} catch (Exception e) {};
return BLOCK_PROCESSED;
}
| public int blockArrived(XmppObject data, XmppStream stream)
throws IOException, XmppException {
try {
Iq f = (Iq)data;
String from = f.getAttribute("from");
String type = f.getTypeAttribute();
if (type.equals("result")) { return BLOCK_REJECTED; }
if (type.equals("error")) { return BLOCK_REJECTED; }
XmppError err = new XmppError(XmppError.FEATURE_NOT_IMPLEMENTED, null);
f.setAttribute("to", from);
f.setAttribute("from", null);
f.setAttribute("type", "error");
f.setAttribute("xml:lang", null);
f.addChild(err.construct());
stream.send(f);
} catch (Exception e) {};
return BLOCK_PROCESSED;
}
|
diff --git a/container/src/main/java/org/jboss/forge/container/ForgeImpl.java b/container/src/main/java/org/jboss/forge/container/ForgeImpl.java
index d4629e2cf..db6e5c518 100644
--- a/container/src/main/java/org/jboss/forge/container/ForgeImpl.java
+++ b/container/src/main/java/org/jboss/forge/container/ForgeImpl.java
@@ -1,304 +1,303 @@
package org.jboss.forge.container;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.forge.container.addons.Addon;
import org.jboss.forge.container.addons.AddonRegistry;
import org.jboss.forge.container.impl.AddonRegistryImpl;
import org.jboss.forge.container.impl.AddonRepositoryImpl;
import org.jboss.forge.container.lock.LockManager;
import org.jboss.forge.container.repositories.AddonRepository;
import org.jboss.forge.container.repositories.AddonRepositoryMode;
import org.jboss.forge.container.repositories.ImmutableAddonRepository;
import org.jboss.forge.container.spi.ContainerLifecycleListener;
import org.jboss.forge.container.spi.ListenerRegistration;
import org.jboss.forge.container.util.Assert;
import org.jboss.forge.container.versions.SingleVersion;
import org.jboss.forge.container.versions.Version;
import org.jboss.modules.Module;
import org.jboss.modules.log.StreamModuleLogger;
public class ForgeImpl implements Forge
{
private static Logger logger = Logger.getLogger(ForgeImpl.class.getName());
private volatile boolean alive = false;
private volatile ContainerStatus status = ContainerStatus.STOPPED;
private boolean serverMode = true;
private AddonRegistryImpl registry;
private List<ContainerLifecycleListener> registeredListeners = new ArrayList<ContainerLifecycleListener>();
private ClassLoader loader;
private List<AddonRepository> repositories = new ArrayList<AddonRepository>();
private Date lastCheckCompleted;
private final LockManager lock = new LockManagerImpl();
public ForgeImpl()
{
if (!AddonRepositoryImpl.hasRuntimeAPIVersion())
logger.warning("Could not detect Forge runtime version - " +
"loading all addons, but failures may occur if versions are not compatible.");
repositories.add(AddonRepositoryImpl.forDefaultDirectory(this));
registry = new AddonRegistryImpl(this, lock);
}
@Override
public LockManager getLockManager()
{
return lock;
}
@Override
public ClassLoader getRuntimeClassLoader()
{
return loader;
}
public Forge enableLogging()
{
assertNotAlive();
Module.setModuleLogger(new StreamModuleLogger(System.err));
return this;
}
@Override
public Forge startAsync()
{
return startAsync(Thread.currentThread().getContextClassLoader());
}
@Override
public Forge startAsync(final ClassLoader loader)
{
new Thread()
{
@Override
public void run()
{
Thread.currentThread().setName("Forge Container " + ForgeImpl.this);
ForgeImpl.this.start(loader);
};
}.start();
return this;
}
@Override
public Forge start()
{
return start(Thread.currentThread().getContextClassLoader());
}
@Override
public Forge start(ClassLoader loader)
{
assertNotAlive();
this.loader = loader;
fireBeforeContainerStartedEvent(loader);
if (!alive)
{
try
{
alive = true;
do
{
boolean dirty = false;
if (!isStartingAddons())
{
Date nextCheck = new Date();
for (AddonRepository repository : repositories)
{
if (lastCheckCompleted == null || repository.isModifiedSince(lastCheckCompleted))
{
dirty = true;
for (Addon addon : registry.getAddons())
{
boolean enabled = false;
if (repository.isEnabled(addon.getId()))
{
enabled = true;
- break;
}
if (!enabled && addon.getStatus().isStarted())
{
try
{
registry.stop(addon);
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
+ lastCheckCompleted = nextCheck;
}
}
- lastCheckCompleted = nextCheck;
if (dirty)
{
try
{
registry.startAll();
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
Thread.sleep(100);
}
while (alive && serverMode);
while (alive && isStartingAddons())
{
Thread.sleep(100);
}
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
finally
{
fireBeforeContainerStoppedEvent(loader);
registry.stopAll();
}
}
fireAfterContainerStoppedEvent(loader);
return this;
}
private boolean isStartingAddons()
{
return registry.isStartingAddons();
}
private void fireBeforeContainerStartedEvent(ClassLoader loader)
{
for (ContainerLifecycleListener listener : registeredListeners)
{
listener.beforeStart(this);
}
for (ContainerLifecycleListener listener : ServiceLoader.load(ContainerLifecycleListener.class, loader))
{
listener.beforeStart(this);
}
status = ContainerStatus.STARTED;
}
private void fireBeforeContainerStoppedEvent(ClassLoader loader)
{
for (ContainerLifecycleListener listener : registeredListeners)
{
listener.beforeStop(this);
}
for (ContainerLifecycleListener listener : ServiceLoader.load(ContainerLifecycleListener.class, loader))
{
listener.beforeStop(this);
}
status = ContainerStatus.STOPPED;
}
private void fireAfterContainerStoppedEvent(ClassLoader loader)
{
for (ContainerLifecycleListener listener : registeredListeners)
{
listener.afterStop(this);
}
for (ContainerLifecycleListener listener : ServiceLoader.load(ContainerLifecycleListener.class, loader))
{
listener.afterStop(this);
}
}
@Override
public Forge stop()
{
alive = false;
return this;
}
@Override
public Forge setServerMode(boolean server)
{
assertNotAlive();
this.serverMode = server;
return this;
}
@Override
public AddonRegistry getAddonRegistry()
{
return registry;
}
@Override
public Version getVersion()
{
return new SingleVersion(AddonRepositoryImpl.getRuntimeAPIVersion());
}
@Override
public ListenerRegistration<ContainerLifecycleListener> addContainerLifecycleListener(
final ContainerLifecycleListener listener)
{
registeredListeners.add(listener);
return new ListenerRegistration<ContainerLifecycleListener>()
{
@Override
public ContainerLifecycleListener removeListener()
{
registeredListeners.remove(listener);
return listener;
}
};
}
@Override
public List<AddonRepository> getRepositories()
{
return Collections.unmodifiableList(repositories);
}
@Override
public Forge addRepository(AddonRepositoryMode mode, File directory)
{
Assert.notNull(mode, "Addon repository mode must not be null.");
Assert.notNull(mode, "Addon repository directory must not be null.");
assertNotAlive();
if (mode.isMutable())
this.repositories.add(AddonRepositoryImpl.forDirectory(this, directory));
else if (mode.isImmutable())
this.repositories.add(new ImmutableAddonRepository(AddonRepositoryImpl.forDirectory(this, directory)));
return this;
}
public void assertNotAlive()
{
if (alive)
throw new IllegalStateException("Cannot modify a running Forge instance. Call .stop() first.");
}
@Override
public ContainerStatus getStatus()
{
return isStartingAddons() ? ContainerStatus.STARTING : status;
}
}
| false | true | public Forge start(ClassLoader loader)
{
assertNotAlive();
this.loader = loader;
fireBeforeContainerStartedEvent(loader);
if (!alive)
{
try
{
alive = true;
do
{
boolean dirty = false;
if (!isStartingAddons())
{
Date nextCheck = new Date();
for (AddonRepository repository : repositories)
{
if (lastCheckCompleted == null || repository.isModifiedSince(lastCheckCompleted))
{
dirty = true;
for (Addon addon : registry.getAddons())
{
boolean enabled = false;
if (repository.isEnabled(addon.getId()))
{
enabled = true;
break;
}
if (!enabled && addon.getStatus().isStarted())
{
try
{
registry.stop(addon);
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
}
}
lastCheckCompleted = nextCheck;
if (dirty)
{
try
{
registry.startAll();
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
Thread.sleep(100);
}
while (alive && serverMode);
while (alive && isStartingAddons())
{
Thread.sleep(100);
}
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
finally
{
fireBeforeContainerStoppedEvent(loader);
registry.stopAll();
}
}
fireAfterContainerStoppedEvent(loader);
return this;
}
| public Forge start(ClassLoader loader)
{
assertNotAlive();
this.loader = loader;
fireBeforeContainerStartedEvent(loader);
if (!alive)
{
try
{
alive = true;
do
{
boolean dirty = false;
if (!isStartingAddons())
{
Date nextCheck = new Date();
for (AddonRepository repository : repositories)
{
if (lastCheckCompleted == null || repository.isModifiedSince(lastCheckCompleted))
{
dirty = true;
for (Addon addon : registry.getAddons())
{
boolean enabled = false;
if (repository.isEnabled(addon.getId()))
{
enabled = true;
}
if (!enabled && addon.getStatus().isStarted())
{
try
{
registry.stop(addon);
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
lastCheckCompleted = nextCheck;
}
}
if (dirty)
{
try
{
registry.startAll();
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
}
}
Thread.sleep(100);
}
while (alive && serverMode);
while (alive && isStartingAddons())
{
Thread.sleep(100);
}
}
catch (Exception e)
{
logger.log(Level.SEVERE, "Error occurred.", e);
}
finally
{
fireBeforeContainerStoppedEvent(loader);
registry.stopAll();
}
}
fireAfterContainerStoppedEvent(loader);
return this;
}
|
diff --git a/src/test/java/org/nohope/spring/app/SpringAsyncModularAppTest.java b/src/test/java/org/nohope/spring/app/SpringAsyncModularAppTest.java
index ac9924c..a95ac98 100644
--- a/src/test/java/org/nohope/spring/app/SpringAsyncModularAppTest.java
+++ b/src/test/java/org/nohope/spring/app/SpringAsyncModularAppTest.java
@@ -1,181 +1,182 @@
package org.nohope.spring.app;
import org.junit.Test;
import org.nohope.spring.app.module.IModule;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:[email protected]">ketoth xupack</a>
* @since 7/27/12 5:29 PM
*/
public class SpringAsyncModularAppTest {
@Test
public void appIsAnonymousClass() throws Exception {
final AppWithContainer app = new AppWithContainer(null, "", "/") {
};
assertEquals("springAsyncModularAppTest", app.getAppName());
assertEquals("/", app.getAppMetaInfNamespace());
assertEquals("/", app.getModuleMetaInfNamespace());
}
@Test
public void appDefaultContextOverriding() throws Exception {
final AppWithContainer app = new AppWithContainer("appo", "appContextOverriding");
probe(app);
assertNotNull(app.getContext());
assertEquals("appBeanOverridden", app.getContext().getBean("appBean"));
}
@Test
public void moduleDefaultContextOverriding() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "", "moduleContextOverriding");
probe(app);
assertEquals(1, app.getModules().size());
final InjectModuleWithContextValue m = getModule(app, 0);
assertEquals("overridden", m.getValue());
assertEquals("moduleo", m.getName());
assertEquals("appBean", m.getContext().getBean("appBean"));
}
@Test
public void searchPathsDetermining() throws Exception {
final AppWithContainer app = new AppWithContainer();
assertEquals("appWithContainer", app.getAppName());
assertEquals("org.nohope.spring.app/", app.getAppMetaInfNamespace());
assertEquals("org.nohope.spring.app/module/", app.getModuleMetaInfNamespace());
assertEquals(IModule.class, app.getTargetModuleClass());
}
@Test
public void concatTest() {
assertEquals("test1" + File.separator + "test2" + File.separator +"test3" , AppWithContainer.concat("test1", "test2/", "/test3"));
}
@Test
public void illegalModuleDescriptor() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "", "illegalDescriptor") {
};
probe(app);
assertEquals(0, app.getModules().size());
}
@Test
public void nonexistentModuleClass() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "", "nonexistentClass") {
};
probe(app);
assertEquals(0, app.getModules().size());
}
@Test
public void notAModuleClass() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "", "notAModule") {
};
probe(app);
assertEquals(0, app.getModules().size());
}
/* all beans in contexts should be constructed ONCE! */
@Test
public void multipleConstructing() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "once", "once/module");
probe(app);
assertEquals(2, app.get(OnceConstructable.class).getId());
}
@Test
public void legalModuleDefaultContext() throws Exception {
final AppWithContainer app = new AppWithContainer("app", "", "legalModuleDefaultContext") {
};
probe(app);
assertEquals(1, app.getModules().size());
final InjectModuleWithContextValue m = getModule(app, 0);
assertEquals("123", m.getValue());
assertEquals("legal", m.getName());
final Properties p = m.getProperties();
assertEquals(2, p.size());
assertEquals("\"fuck yeah!\"", p.getProperty("property"));
// check for app beans inheritance
assertEquals("appBean", m.getContext().getBean("appBean"));
}
public static class UtilsBean {
// http://stackoverflow.com/a/1363435
@Resource(name = "testList")
private List<String> list;
public List<String> getList() {
return list;
}
}
@Test
public void utilsSupport() throws InterruptedException {
final AppWithContainer app = new AppWithContainer(
"utils",
"utils",
"legalModuleDefaultContext") {
};
probe(app);
assertNotNull(app.get("testList", List.class));
final UtilsBean bean = app.getOrInstantiate(UtilsBean.class);
final List<String> list = bean.getList();
assertNotNull(list);
assertEquals("one", list.get(0));
assertEquals("two", list.get(1));
assertEquals("three", list.get(2));
}
@SuppressWarnings("unchecked")
private static <T extends IModule> T getModule(final AppWithContainer app,
final int index) {
assertTrue(app.getModules().size() >= index);
final IModule module = app.getModules().get(index);
assertNotNull(module);
try {
return (T) module;
} catch (ClassCastException e) {
fail();
return null;
}
}
private static void probe(final AppWithContainer app) throws InterruptedException {
final AtomicReference<Throwable> ref = new AtomicReference<>();
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
app.start();
} catch (final Exception e) {
ref.set(e);
}
}
});
t.start();
app.stop();
t.join();
- if (ref.get() != null) {
- throw new IllegalStateException(ref.get());
+ final Throwable throwable = ref.get();
+ if (throwable != null) {
+ throw new IllegalStateException(throwable);
}
}
}
| true | true | private static void probe(final AppWithContainer app) throws InterruptedException {
final AtomicReference<Throwable> ref = new AtomicReference<>();
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
app.start();
} catch (final Exception e) {
ref.set(e);
}
}
});
t.start();
app.stop();
t.join();
if (ref.get() != null) {
throw new IllegalStateException(ref.get());
}
}
| private static void probe(final AppWithContainer app) throws InterruptedException {
final AtomicReference<Throwable> ref = new AtomicReference<>();
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
app.start();
} catch (final Exception e) {
ref.set(e);
}
}
});
t.start();
app.stop();
t.join();
final Throwable throwable = ref.get();
if (throwable != null) {
throw new IllegalStateException(throwable);
}
}
|
diff --git a/src/main/java/com/ning/metrics/action/binder/listeners/ActionCoreGuiceListener.java b/src/main/java/com/ning/metrics/action/binder/listeners/ActionCoreGuiceListener.java
index 0cf6bdb..d3dcff1 100644
--- a/src/main/java/com/ning/metrics/action/binder/listeners/ActionCoreGuiceListener.java
+++ b/src/main/java/com/ning/metrics/action/binder/listeners/ActionCoreGuiceListener.java
@@ -1,48 +1,47 @@
/*
* Copyright 2010-2011 Ning, Inc.
*
* Ning 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 com.ning.metrics.action.binder.listeners;
import com.ning.jetty.base.modules.ServerModuleBuilder;
import com.ning.jetty.core.listeners.SetupServer;
import com.ning.metrics.action.binder.config.ActionCoreConfig;
import com.ning.metrics.action.binder.modules.ActionCoreServicesModule;
import com.ning.metrics.action.binder.modules.HdfsModule;
import com.ning.metrics.action.healthchecks.HDFSHealthCheck;
import javax.servlet.ServletContextEvent;
public class ActionCoreGuiceListener extends SetupServer
{
@Override
public void contextInitialized(ServletContextEvent event)
{
final ServerModuleBuilder builder = new ServerModuleBuilder()
.addConfig(ActionCoreConfig.class)
.addHealthCheck(HDFSHealthCheck.class)
.addJMXExport(HDFSHealthCheck.class)
.setAreciboProfile(System.getProperty("action.arecibo.profile", "ning.jmx:name=MonitoringProfile"))
.addModule(new HdfsModule())
.addModule(new ActionCoreServicesModule())
.enableLog4J()
- .trackRequests()
.addResource("com.ning.metrics.action.endpoint");
guiceModule = builder.build();
super.contextInitialized(event);
}
}
| true | true | public void contextInitialized(ServletContextEvent event)
{
final ServerModuleBuilder builder = new ServerModuleBuilder()
.addConfig(ActionCoreConfig.class)
.addHealthCheck(HDFSHealthCheck.class)
.addJMXExport(HDFSHealthCheck.class)
.setAreciboProfile(System.getProperty("action.arecibo.profile", "ning.jmx:name=MonitoringProfile"))
.addModule(new HdfsModule())
.addModule(new ActionCoreServicesModule())
.enableLog4J()
.trackRequests()
.addResource("com.ning.metrics.action.endpoint");
guiceModule = builder.build();
super.contextInitialized(event);
}
| public void contextInitialized(ServletContextEvent event)
{
final ServerModuleBuilder builder = new ServerModuleBuilder()
.addConfig(ActionCoreConfig.class)
.addHealthCheck(HDFSHealthCheck.class)
.addJMXExport(HDFSHealthCheck.class)
.setAreciboProfile(System.getProperty("action.arecibo.profile", "ning.jmx:name=MonitoringProfile"))
.addModule(new HdfsModule())
.addModule(new ActionCoreServicesModule())
.enableLog4J()
.addResource("com.ning.metrics.action.endpoint");
guiceModule = builder.build();
super.contextInitialized(event);
}
|
diff --git a/FFMine_Common/net/digidownloads/FFmine/item/GrindStone.java b/FFMine_Common/net/digidownloads/FFmine/item/GrindStone.java
index ab9c065..510b6fc 100644
--- a/FFMine_Common/net/digidownloads/FFmine/item/GrindStone.java
+++ b/FFMine_Common/net/digidownloads/FFmine/item/GrindStone.java
@@ -1,32 +1,32 @@
package net.digidownloads.FFmine.item;
import cpw.mods.fml.common.registry.GameRegistry;
import net.digidownloads.FFmine.lib.Reference;
import net.digidownloads.FFmine.lib.Strings;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class GrindStone {
public static void Item() {
//Grinding wheels
final Item StoneGrindWheel = new Item((Reference.StoneGrindWheelID)-256).setUnlocalizedName(Strings.StoneGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item IronGrindWheel = new Item((Reference.IronGrindWheelID)-256).setUnlocalizedName(Strings.IronGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item GoldGrindWheel = new Item((Reference.GoldGrindWheelID)-256).setUnlocalizedName(Strings.GoldGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item DiamondGrindWheel = new Item((Reference.DiamondGrindWheelID)-256).setUnlocalizedName(Strings.DiamondGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
GameRegistry.addShapedRecipe(new ItemStack(StoneGrindWheel),new Object[] {"SSS","S S","SSS",Character.valueOf('S'),net.minecraft.block.Block.stone});
- //GameRegistry.addShapedRecipe(new ItemStack(IronGrindWheel),new Object[] {"III","S","III",Character.valueOf('I'),net.minecraft.item.Item.ingotIron,Character.valueOf('S'),StoneGrindWheel});
- //GameRegistry.addShapedRecipe(new ItemStack(GoldGrindWheel),new Object[] {"GGG","GIG","GGG",Character.valueOf('G'),net.minecraft.item.Item.ingotGold,Character.valueOf('I'),IronGrindWheel});
- //GameRegistry.addShapedRecipe(new ItemStack(DiamondGrindWheel),new Object[] {"DDD","DGD","DDD",Character.valueOf('D'),net.minecraft.item.Item.diamond,Character.valueOf('G'),GoldGrindWheel});
+ GameRegistry.addShapedRecipe(new ItemStack(IronGrindWheel),new Object[] {"III","ISI","III",Character.valueOf('I'),net.minecraft.item.Item.ingotIron,Character.valueOf('S'),StoneGrindWheel});
+ GameRegistry.addShapedRecipe(new ItemStack(GoldGrindWheel),new Object[] {"GGG","GIG","GGG",Character.valueOf('G'),net.minecraft.item.Item.ingotGold,Character.valueOf('I'),IronGrindWheel});
+ GameRegistry.addShapedRecipe(new ItemStack(DiamondGrindWheel),new Object[] {"DDD","DGD","DDD",Character.valueOf('D'),net.minecraft.item.Item.diamond,Character.valueOf('G'),GoldGrindWheel});
}
}
| true | true | public static void Item() {
//Grinding wheels
final Item StoneGrindWheel = new Item((Reference.StoneGrindWheelID)-256).setUnlocalizedName(Strings.StoneGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item IronGrindWheel = new Item((Reference.IronGrindWheelID)-256).setUnlocalizedName(Strings.IronGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item GoldGrindWheel = new Item((Reference.GoldGrindWheelID)-256).setUnlocalizedName(Strings.GoldGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item DiamondGrindWheel = new Item((Reference.DiamondGrindWheelID)-256).setUnlocalizedName(Strings.DiamondGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
GameRegistry.addShapedRecipe(new ItemStack(StoneGrindWheel),new Object[] {"SSS","S S","SSS",Character.valueOf('S'),net.minecraft.block.Block.stone});
//GameRegistry.addShapedRecipe(new ItemStack(IronGrindWheel),new Object[] {"III","S","III",Character.valueOf('I'),net.minecraft.item.Item.ingotIron,Character.valueOf('S'),StoneGrindWheel});
//GameRegistry.addShapedRecipe(new ItemStack(GoldGrindWheel),new Object[] {"GGG","GIG","GGG",Character.valueOf('G'),net.minecraft.item.Item.ingotGold,Character.valueOf('I'),IronGrindWheel});
//GameRegistry.addShapedRecipe(new ItemStack(DiamondGrindWheel),new Object[] {"DDD","DGD","DDD",Character.valueOf('D'),net.minecraft.item.Item.diamond,Character.valueOf('G'),GoldGrindWheel});
}
| public static void Item() {
//Grinding wheels
final Item StoneGrindWheel = new Item((Reference.StoneGrindWheelID)-256).setUnlocalizedName(Strings.StoneGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item IronGrindWheel = new Item((Reference.IronGrindWheelID)-256).setUnlocalizedName(Strings.IronGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item GoldGrindWheel = new Item((Reference.GoldGrindWheelID)-256).setUnlocalizedName(Strings.GoldGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
final Item DiamondGrindWheel = new Item((Reference.DiamondGrindWheelID)-256).setUnlocalizedName(Strings.DiamondGrindWheelName).setCreativeTab(CreativeTabs.tabMaterials);
GameRegistry.addShapedRecipe(new ItemStack(StoneGrindWheel),new Object[] {"SSS","S S","SSS",Character.valueOf('S'),net.minecraft.block.Block.stone});
GameRegistry.addShapedRecipe(new ItemStack(IronGrindWheel),new Object[] {"III","ISI","III",Character.valueOf('I'),net.minecraft.item.Item.ingotIron,Character.valueOf('S'),StoneGrindWheel});
GameRegistry.addShapedRecipe(new ItemStack(GoldGrindWheel),new Object[] {"GGG","GIG","GGG",Character.valueOf('G'),net.minecraft.item.Item.ingotGold,Character.valueOf('I'),IronGrindWheel});
GameRegistry.addShapedRecipe(new ItemStack(DiamondGrindWheel),new Object[] {"DDD","DGD","DDD",Character.valueOf('D'),net.minecraft.item.Item.diamond,Character.valueOf('G'),GoldGrindWheel});
}
|
diff --git a/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java b/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java
index 304ce5d..0fec984 100644
--- a/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java
+++ b/src/main/java/org/zeroturnaround/zip/ZipEntryUtil.java
@@ -1,106 +1,105 @@
package org.zeroturnaround.zip;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
/**
* Util class for static methods shared between ZipUtil and Zips.
*
* @author shelajev
*
*/
class ZipEntryUtil {
/**
* Copy entry
*
* @param original - zipEntry to copy
* @return copy of the original entry
*/
static ZipEntry copy(ZipEntry original) {
return copy(original, null);
}
/**
* Copy entry with another name.
*
* @param original - zipEntry to copy
* @param newName - new entry name, optional, if null, ogirinal's entry
* @return copy of the original entry, but with the given name
*/
static ZipEntry copy(ZipEntry original, String newName) {
ZipEntry copy = new ZipEntry(newName == null ? original.getName() : newName);
if (original.getCrc() != -1) {
copy.setCrc(original.getCrc());
}
if (original.getMethod() != -1) {
copy.setMethod(original.getMethod());
}
if (original.getSize() >= 0) {
copy.setSize(original.getSize());
}
if (original.getExtra() != null) {
copy.setExtra(original.getExtra());
}
copy.setComment(original.getComment());
- copy.setCompressedSize(original.getCompressedSize());
copy.setTime(original.getTime());
return copy;
}
/**
* Copies a given ZIP entry to a ZIP file.
*
* @param zipEntry
* a ZIP entry from existing ZIP file.
* @param in
* contents of the ZIP entry.
* @param out
* target ZIP stream.
*/
static void copyEntry(ZipEntry zipEntry, InputStream in, ZipOutputStream out) throws IOException {
copyEntry(zipEntry, in, out, true);
}
/**
* Copies a given ZIP entry to a ZIP file. If this.preserveTimestamps is true, original timestamp
* is carried over, otherwise uses current time.
*
* @param zipEntry
* a ZIP entry from existing ZIP file.
* @param in
* contents of the ZIP entry.
* @param out
* target ZIP stream.
*/
static void copyEntry(ZipEntry zipEntry, InputStream in, ZipOutputStream out, boolean preserveTimestamps) throws IOException {
ZipEntry copy = copy(zipEntry);
copy.setTime(preserveTimestamps ? zipEntry.getTime() : System.currentTimeMillis());
addEntry(copy, new BufferedInputStream(in), out);
}
/**
* Adds a given ZIP entry to a ZIP file.
*
* @param zipEntry
* new ZIP entry.
* @param in
* contents of the ZIP entry.
* @param out
* target ZIP stream.
*/
static void addEntry(ZipEntry zipEntry, InputStream in, ZipOutputStream out) throws IOException {
out.putNextEntry(zipEntry);
if (in != null) {
IOUtils.copy(in, out);
}
out.closeEntry();
}
}
| true | true | static ZipEntry copy(ZipEntry original, String newName) {
ZipEntry copy = new ZipEntry(newName == null ? original.getName() : newName);
if (original.getCrc() != -1) {
copy.setCrc(original.getCrc());
}
if (original.getMethod() != -1) {
copy.setMethod(original.getMethod());
}
if (original.getSize() >= 0) {
copy.setSize(original.getSize());
}
if (original.getExtra() != null) {
copy.setExtra(original.getExtra());
}
copy.setComment(original.getComment());
copy.setCompressedSize(original.getCompressedSize());
copy.setTime(original.getTime());
return copy;
}
| static ZipEntry copy(ZipEntry original, String newName) {
ZipEntry copy = new ZipEntry(newName == null ? original.getName() : newName);
if (original.getCrc() != -1) {
copy.setCrc(original.getCrc());
}
if (original.getMethod() != -1) {
copy.setMethod(original.getMethod());
}
if (original.getSize() >= 0) {
copy.setSize(original.getSize());
}
if (original.getExtra() != null) {
copy.setExtra(original.getExtra());
}
copy.setComment(original.getComment());
copy.setTime(original.getTime());
return copy;
}
|
diff --git a/org.eclipse.epp.mpc.ui/src/org/eclipse/epp/internal/mpc/ui/catalog/MarketplaceDiscoveryStrategy.java b/org.eclipse.epp.mpc.ui/src/org/eclipse/epp/internal/mpc/ui/catalog/MarketplaceDiscoveryStrategy.java
index 40b629e..4823bb9 100644
--- a/org.eclipse.epp.mpc.ui/src/org/eclipse/epp/internal/mpc/ui/catalog/MarketplaceDiscoveryStrategy.java
+++ b/org.eclipse.epp.mpc.ui/src/org/eclipse/epp/internal/mpc/ui/catalog/MarketplaceDiscoveryStrategy.java
@@ -1,369 +1,369 @@
/*******************************************************************************
* Copyright (c) 2010 The Eclipse Foundation 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:
* The Eclipse Foundation - initial API and implementation
*******************************************************************************/
package org.eclipse.epp.internal.mpc.ui.catalog;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.epp.internal.mpc.core.MarketplaceClientCore;
import org.eclipse.epp.internal.mpc.core.service.Categories;
import org.eclipse.epp.internal.mpc.core.service.Category;
import org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService;
import org.eclipse.epp.internal.mpc.core.service.Ius;
import org.eclipse.epp.internal.mpc.core.service.Market;
import org.eclipse.epp.internal.mpc.core.service.MarketplaceService;
import org.eclipse.epp.internal.mpc.core.service.Node;
import org.eclipse.epp.internal.mpc.core.service.SearchResult;
import org.eclipse.epp.internal.mpc.ui.MarketplaceClientUi;
import org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCategory.Contents;
import org.eclipse.epp.internal.mpc.ui.util.ConcurrentTaskManager;
import org.eclipse.epp.mpc.ui.CatalogDescriptor;
import org.eclipse.equinox.internal.p2.discovery.AbstractDiscoveryStrategy;
import org.eclipse.equinox.internal.p2.discovery.model.CatalogCategory;
import org.eclipse.equinox.internal.p2.discovery.model.CatalogItem;
import org.eclipse.equinox.internal.p2.discovery.model.Icon;
import org.eclipse.equinox.internal.p2.discovery.model.Overview;
import org.eclipse.equinox.internal.p2.discovery.model.Tag;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
/**
* @author David Green
*/
public class MarketplaceDiscoveryStrategy extends AbstractDiscoveryStrategy {
private static final String DOT_FEATURE_DOT_GROUP = ".feature.group"; //$NON-NLS-1$
private static final Pattern BREAK_PATTERN = Pattern.compile("<!--\\s*break\\s*-->"); //$NON-NLS-1$
private final CatalogDescriptor catalogDescriptor;
private final MarketplaceService marketplaceService;
private MarketplaceCatalogSource source;
private MarketplaceInfo marketplaceInfo;
private Map<String, IInstallableUnit> featureIUById;
public MarketplaceDiscoveryStrategy(CatalogDescriptor catalogDescriptor) {
if (catalogDescriptor == null) {
throw new IllegalArgumentException();
}
this.catalogDescriptor = catalogDescriptor;
marketplaceService = createMarketplaceService();
source = new MarketplaceCatalogSource(marketplaceService);
marketplaceInfo = MarketplaceInfo.getInstance();
}
public MarketplaceService createMarketplaceService() {
DefaultMarketplaceService service = new DefaultMarketplaceService(this.catalogDescriptor.getUrl());
Map<String, String> requestMetaParameters = new HashMap<String, String>();
requestMetaParameters.put(DefaultMarketplaceService.META_PARAM_CLIENT, MarketplaceClientCore.BUNDLE_ID);
service.setRequestMetaParameters(requestMetaParameters);
return service;
}
@Override
public void dispose() {
if (source != null) {
source.dispose();
source = null;
}
if (marketplaceInfo != null) {
marketplaceInfo.save();
marketplaceInfo = null;
}
super.dispose();
}
@Override
public void performDiscovery(IProgressMonitor monitor) throws CoreException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
final int totalWork = 10000000;
final int workSegment = totalWork / 3;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_loadingMarketplace, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, workSegment));
catalogCategory.setContents(Contents.FEATURED);
SearchResult featured = marketplaceService.featured(new SubProgressMonitor(monitor, workSegment));
handleSearchResult(catalogCategory, featured, new SubProgressMonitor(monitor, workSegment));
} finally {
monitor.done();
}
}
protected void handleSearchResult(MarketplaceCategory catalogCategory, SearchResult result,
final IProgressMonitor monitor) {
if (!result.getNodes().isEmpty()) {
int totalWork = 10000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_loadingResources, totalWork);
ConcurrentTaskManager executor = new ConcurrentTaskManager(result.getNodes().size(),
Messages.MarketplaceDiscoveryStrategy_loadingResources);
try {
for (final Node node : result.getNodes()) {
final MarketplaceNodeCatalogItem catalogItem = new MarketplaceNodeCatalogItem();
catalogItem.setMarketplaceUrl(catalogDescriptor.getUrl());
catalogItem.setId(node.getId());
catalogItem.setName(node.getName());
catalogItem.setCategoryId(catalogCategory.getId());
Categories categories = node.getCategories();
if (categories != null) {
for (Category category : categories.getCategory()) {
catalogItem.addTag(new Tag(Category.class, category.getId(), category.getName()));
}
}
catalogItem.setData(node);
catalogItem.setSource(source);
catalogItem.setLicense(node.getLicense());
Ius ius = node.getIus();
if (ius != null) {
List<String> discoveryIus = new ArrayList<String>(ius.getIu());
for (int x = 0; x < discoveryIus.size(); ++x) {
String iu = discoveryIus.get(x);
if (!iu.endsWith(DOT_FEATURE_DOT_GROUP)) {
discoveryIus.set(x, iu + DOT_FEATURE_DOT_GROUP);
}
}
catalogItem.setInstallableUnits(discoveryIus);
}
if (node.getShortdescription() == null && node.getBody() != null) {
// bug 306653 <!--break--> marks the end of the short description.
String descriptionText = node.getBody();
Matcher matcher = BREAK_PATTERN.matcher(node.getBody());
if (matcher.find()) {
int start = matcher.start();
if (start > 0) {
String shortDescriptionText = descriptionText.substring(0, start).trim();
if (shortDescriptionText.length() > 0) {
descriptionText = shortDescriptionText;
}
}
}
catalogItem.setDescription(descriptionText);
} else {
catalogItem.setDescription(node.getShortdescription());
}
catalogItem.setProvider(node.getCompanyname());
catalogItem.setSiteUrl(node.getUpdateurl());
if (node.getBody() != null || node.getScreenshot() != null) {
final Overview overview = new Overview();
overview.setItem(catalogItem);
overview.setSummary(node.getBody());
- overview.setUrl(node.getHomepageurl());
+ overview.setUrl(node.getUrl());
catalogItem.setOverview(overview);
if (node.getScreenshot() != null) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getScreenshot()) {
@Override
protected void resourceRetrieved() {
overview.setScreenshot(node.getScreenshot());
}
});
}
}
if (node.getImage() != null) {
// FIXME: icon sizing
if (!source.getResourceProvider().containsResource(node.getImage())) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getImage()) {
@Override
protected void resourceRetrieved() {
createIcon(catalogItem, node);
}
});
} else {
createIcon(catalogItem, node);
}
}
items.add(catalogItem);
marketplaceInfo.map(catalogItem.getMarketplaceUrl(), node);
catalogItem.setInstalled(marketplaceInfo.computeInstalled(computeInstalledFeatures(monitor), node));
}
try {
executor.waitUntilFinished(new SubProgressMonitor(monitor, totalWork - 10));
} catch (CoreException e) {
// just log, since this is expected to occur frequently
MarketplaceClientUi.error(e);
}
} finally {
executor.shutdownNow();
monitor.done();
}
if (result.getMatchCount() != null) {
catalogCategory.setMatchCount(result.getMatchCount());
if (result.getMatchCount() > result.getNodes().size()) {
// add an item here to indicate that the search matched more items than were returned by the server
CatalogItem catalogItem = new CatalogItem();
catalogItem.setSource(source);
catalogItem.setData(catalogDescriptor);
catalogItem.setId(catalogDescriptor.getUrl().toString());
catalogItem.setCategoryId(catalogCategory.getId());
items.add(catalogItem);
}
}
}
}
private void createIcon(CatalogItem catalogItem, final Node node) {
Icon icon = new Icon();
// don't know the size
icon.setImage32(node.getImage());
icon.setImage48(node.getImage());
icon.setImage64(node.getImage());
catalogItem.setIcon(icon);
}
public void performQuery(Market market, Category category, String queryText, IProgressMonitor monitor)
throws CoreException {
final int totalWork = 1000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_searchingMarketplace, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, 1));
catalogCategory.setContents(Contents.QUERY);
SearchResult result = marketplaceService.search(market, category, queryText, new SubProgressMonitor(
monitor, totalWork / 2));
handleSearchResult(catalogCategory, result, new SubProgressMonitor(monitor, totalWork / 2));
} finally {
monitor.done();
}
}
public void recent(IProgressMonitor monitor) throws CoreException {
final int totalWork = 1000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_searchingMarketplace, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, 1));
catalogCategory.setContents(Contents.RECENT);
SearchResult result = marketplaceService.recent(new SubProgressMonitor(monitor, totalWork / 2));
handleSearchResult(catalogCategory, result, new SubProgressMonitor(monitor, totalWork / 2));
} finally {
monitor.done();
}
}
public void featured(IProgressMonitor monitor, final Market market, final Category category) throws CoreException {
final int totalWork = 1000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_searchingMarketplace, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, 1));
catalogCategory.setContents(Contents.FEATURED);
SearchResult result = marketplaceService.featured(new SubProgressMonitor(monitor, totalWork / 2), market,
category);
handleSearchResult(catalogCategory, result, new SubProgressMonitor(monitor, totalWork / 2));
} finally {
monitor.done();
}
}
public void popular(IProgressMonitor monitor) throws CoreException {
// FIXME: do we want popular or favorites?
final int totalWork = 1000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_searchingMarketplace, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, 1));
catalogCategory.setContents(Contents.POPULAR);
SearchResult result = marketplaceService.favorites(new SubProgressMonitor(monitor, totalWork / 2));
handleSearchResult(catalogCategory, result, new SubProgressMonitor(monitor, totalWork / 2));
} finally {
monitor.done();
}
}
public void installed(IProgressMonitor monitor) throws CoreException {
final int totalWork = 1000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_findingInstalled, totalWork);
try {
MarketplaceCategory catalogCategory = findMarketplaceCategory(new SubProgressMonitor(monitor, 1));
catalogCategory.setContents(Contents.INSTALLED);
SearchResult result = new SearchResult();
result.setNodes(new ArrayList<Node>());
Set<String> installedFeatures = computeInstalledFeatures(monitor);
if (!monitor.isCanceled()) {
Set<Node> catalogNodes = marketplaceInfo.computeInstalledNodes(catalogDescriptor.getUrl(),
installedFeatures);
if (!catalogNodes.isEmpty()) {
int unitWork = totalWork / (2 * catalogNodes.size());
for (Node node : catalogNodes) {
node = marketplaceService.getNode(node, monitor);
result.getNodes().add(node);
monitor.worked(unitWork);
}
} else {
monitor.worked(totalWork / 2);
}
handleSearchResult(catalogCategory, result, new SubProgressMonitor(monitor, totalWork / 2));
}
} finally {
monitor.done();
}
}
protected Set<String> computeInstalledFeatures(IProgressMonitor monitor) {
return computeInstalledIUs(monitor).keySet();
}
protected synchronized Map<String, IInstallableUnit> computeInstalledIUs(IProgressMonitor monitor) {
if (featureIUById == null) {
featureIUById = MarketplaceClientUi.computeInstalledIUsById(monitor);
}
return featureIUById;
}
protected MarketplaceCategory findMarketplaceCategory(IProgressMonitor monitor) throws CoreException {
MarketplaceCategory catalogCategory = null;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_catalogCategory, 10000);
try {
for (CatalogCategory candidate : getCategories()) {
if (candidate.getSource() == source) {
catalogCategory = (MarketplaceCategory) candidate;
}
}
if (catalogCategory == null) {
List<Market> markets = marketplaceService.listMarkets(new SubProgressMonitor(monitor, 10000));
// marketplace has markets and categories, however a node and/or category can appear in multiple
// markets. This doesn't match well with discovery's concept of a category. Discovery requires all
// items to be in a category, so we use a single root category and tagging.
catalogCategory = new MarketplaceCategory();
catalogCategory.setId("<root>"); //$NON-NLS-1$
catalogCategory.setName("<root>"); //$NON-NLS-1$
catalogCategory.setSource(source);
catalogCategory.setMarkets(markets);
categories.add(catalogCategory);
}
} finally {
monitor.done();
}
return catalogCategory;
}
}
| true | true | protected void handleSearchResult(MarketplaceCategory catalogCategory, SearchResult result,
final IProgressMonitor monitor) {
if (!result.getNodes().isEmpty()) {
int totalWork = 10000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_loadingResources, totalWork);
ConcurrentTaskManager executor = new ConcurrentTaskManager(result.getNodes().size(),
Messages.MarketplaceDiscoveryStrategy_loadingResources);
try {
for (final Node node : result.getNodes()) {
final MarketplaceNodeCatalogItem catalogItem = new MarketplaceNodeCatalogItem();
catalogItem.setMarketplaceUrl(catalogDescriptor.getUrl());
catalogItem.setId(node.getId());
catalogItem.setName(node.getName());
catalogItem.setCategoryId(catalogCategory.getId());
Categories categories = node.getCategories();
if (categories != null) {
for (Category category : categories.getCategory()) {
catalogItem.addTag(new Tag(Category.class, category.getId(), category.getName()));
}
}
catalogItem.setData(node);
catalogItem.setSource(source);
catalogItem.setLicense(node.getLicense());
Ius ius = node.getIus();
if (ius != null) {
List<String> discoveryIus = new ArrayList<String>(ius.getIu());
for (int x = 0; x < discoveryIus.size(); ++x) {
String iu = discoveryIus.get(x);
if (!iu.endsWith(DOT_FEATURE_DOT_GROUP)) {
discoveryIus.set(x, iu + DOT_FEATURE_DOT_GROUP);
}
}
catalogItem.setInstallableUnits(discoveryIus);
}
if (node.getShortdescription() == null && node.getBody() != null) {
// bug 306653 <!--break--> marks the end of the short description.
String descriptionText = node.getBody();
Matcher matcher = BREAK_PATTERN.matcher(node.getBody());
if (matcher.find()) {
int start = matcher.start();
if (start > 0) {
String shortDescriptionText = descriptionText.substring(0, start).trim();
if (shortDescriptionText.length() > 0) {
descriptionText = shortDescriptionText;
}
}
}
catalogItem.setDescription(descriptionText);
} else {
catalogItem.setDescription(node.getShortdescription());
}
catalogItem.setProvider(node.getCompanyname());
catalogItem.setSiteUrl(node.getUpdateurl());
if (node.getBody() != null || node.getScreenshot() != null) {
final Overview overview = new Overview();
overview.setItem(catalogItem);
overview.setSummary(node.getBody());
overview.setUrl(node.getHomepageurl());
catalogItem.setOverview(overview);
if (node.getScreenshot() != null) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getScreenshot()) {
@Override
protected void resourceRetrieved() {
overview.setScreenshot(node.getScreenshot());
}
});
}
}
if (node.getImage() != null) {
// FIXME: icon sizing
if (!source.getResourceProvider().containsResource(node.getImage())) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getImage()) {
@Override
protected void resourceRetrieved() {
createIcon(catalogItem, node);
}
});
} else {
createIcon(catalogItem, node);
}
}
items.add(catalogItem);
marketplaceInfo.map(catalogItem.getMarketplaceUrl(), node);
catalogItem.setInstalled(marketplaceInfo.computeInstalled(computeInstalledFeatures(monitor), node));
}
try {
executor.waitUntilFinished(new SubProgressMonitor(monitor, totalWork - 10));
} catch (CoreException e) {
// just log, since this is expected to occur frequently
MarketplaceClientUi.error(e);
}
} finally {
executor.shutdownNow();
monitor.done();
}
if (result.getMatchCount() != null) {
catalogCategory.setMatchCount(result.getMatchCount());
if (result.getMatchCount() > result.getNodes().size()) {
// add an item here to indicate that the search matched more items than were returned by the server
CatalogItem catalogItem = new CatalogItem();
catalogItem.setSource(source);
catalogItem.setData(catalogDescriptor);
catalogItem.setId(catalogDescriptor.getUrl().toString());
catalogItem.setCategoryId(catalogCategory.getId());
items.add(catalogItem);
}
}
}
}
| protected void handleSearchResult(MarketplaceCategory catalogCategory, SearchResult result,
final IProgressMonitor monitor) {
if (!result.getNodes().isEmpty()) {
int totalWork = 10000000;
monitor.beginTask(Messages.MarketplaceDiscoveryStrategy_loadingResources, totalWork);
ConcurrentTaskManager executor = new ConcurrentTaskManager(result.getNodes().size(),
Messages.MarketplaceDiscoveryStrategy_loadingResources);
try {
for (final Node node : result.getNodes()) {
final MarketplaceNodeCatalogItem catalogItem = new MarketplaceNodeCatalogItem();
catalogItem.setMarketplaceUrl(catalogDescriptor.getUrl());
catalogItem.setId(node.getId());
catalogItem.setName(node.getName());
catalogItem.setCategoryId(catalogCategory.getId());
Categories categories = node.getCategories();
if (categories != null) {
for (Category category : categories.getCategory()) {
catalogItem.addTag(new Tag(Category.class, category.getId(), category.getName()));
}
}
catalogItem.setData(node);
catalogItem.setSource(source);
catalogItem.setLicense(node.getLicense());
Ius ius = node.getIus();
if (ius != null) {
List<String> discoveryIus = new ArrayList<String>(ius.getIu());
for (int x = 0; x < discoveryIus.size(); ++x) {
String iu = discoveryIus.get(x);
if (!iu.endsWith(DOT_FEATURE_DOT_GROUP)) {
discoveryIus.set(x, iu + DOT_FEATURE_DOT_GROUP);
}
}
catalogItem.setInstallableUnits(discoveryIus);
}
if (node.getShortdescription() == null && node.getBody() != null) {
// bug 306653 <!--break--> marks the end of the short description.
String descriptionText = node.getBody();
Matcher matcher = BREAK_PATTERN.matcher(node.getBody());
if (matcher.find()) {
int start = matcher.start();
if (start > 0) {
String shortDescriptionText = descriptionText.substring(0, start).trim();
if (shortDescriptionText.length() > 0) {
descriptionText = shortDescriptionText;
}
}
}
catalogItem.setDescription(descriptionText);
} else {
catalogItem.setDescription(node.getShortdescription());
}
catalogItem.setProvider(node.getCompanyname());
catalogItem.setSiteUrl(node.getUpdateurl());
if (node.getBody() != null || node.getScreenshot() != null) {
final Overview overview = new Overview();
overview.setItem(catalogItem);
overview.setSummary(node.getBody());
overview.setUrl(node.getUrl());
catalogItem.setOverview(overview);
if (node.getScreenshot() != null) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getScreenshot()) {
@Override
protected void resourceRetrieved() {
overview.setScreenshot(node.getScreenshot());
}
});
}
}
if (node.getImage() != null) {
// FIXME: icon sizing
if (!source.getResourceProvider().containsResource(node.getImage())) {
executor.submit(new AbstractResourceRunnable(monitor, source.getResourceProvider(),
node.getImage()) {
@Override
protected void resourceRetrieved() {
createIcon(catalogItem, node);
}
});
} else {
createIcon(catalogItem, node);
}
}
items.add(catalogItem);
marketplaceInfo.map(catalogItem.getMarketplaceUrl(), node);
catalogItem.setInstalled(marketplaceInfo.computeInstalled(computeInstalledFeatures(monitor), node));
}
try {
executor.waitUntilFinished(new SubProgressMonitor(monitor, totalWork - 10));
} catch (CoreException e) {
// just log, since this is expected to occur frequently
MarketplaceClientUi.error(e);
}
} finally {
executor.shutdownNow();
monitor.done();
}
if (result.getMatchCount() != null) {
catalogCategory.setMatchCount(result.getMatchCount());
if (result.getMatchCount() > result.getNodes().size()) {
// add an item here to indicate that the search matched more items than were returned by the server
CatalogItem catalogItem = new CatalogItem();
catalogItem.setSource(source);
catalogItem.setData(catalogDescriptor);
catalogItem.setId(catalogDescriptor.getUrl().toString());
catalogItem.setCategoryId(catalogCategory.getId());
items.add(catalogItem);
}
}
}
}
|
diff --git a/src/main/java/com/wabbit/silly/SpringSender.java b/src/main/java/com/wabbit/silly/SpringSender.java
index 1f09447..6365a9f 100644
--- a/src/main/java/com/wabbit/silly/SpringSender.java
+++ b/src/main/java/com/wabbit/silly/SpringSender.java
@@ -1,30 +1,31 @@
package com.wabbit.silly;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.UnsupportedEncodingException;
/**
* Created by IntelliJ IDEA.
* User: sclasen
* Date: 6/5/11
* Time: 10:59 AM
* To change this template use File | Settings | File Templates.
*/
public class SpringSender {
public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:context.xml");
RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
while(true){
String msg = "Spring Sent at:" + System.currentTimeMillis();
+ System.out.println(msg);
byte[] body = msg.getBytes("UTF-8");
rabbitTemplate.send(new Message(body, new MessageProperties()));
Thread.sleep(1000);
}
}
}
| true | true | public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:context.xml");
RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
while(true){
String msg = "Spring Sent at:" + System.currentTimeMillis();
byte[] body = msg.getBytes("UTF-8");
rabbitTemplate.send(new Message(body, new MessageProperties()));
Thread.sleep(1000);
}
}
| public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:context.xml");
RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
while(true){
String msg = "Spring Sent at:" + System.currentTimeMillis();
System.out.println(msg);
byte[] body = msg.getBytes("UTF-8");
rabbitTemplate.send(new Message(body, new MessageProperties()));
Thread.sleep(1000);
}
}
|
diff --git a/freeplane/src/org/freeplane/view/swing/map/mindmapmode/EditNodeTextField.java b/freeplane/src/org/freeplane/view/swing/map/mindmapmode/EditNodeTextField.java
index ec0de5162..d8a288af6 100644
--- a/freeplane/src/org/freeplane/view/swing/map/mindmapmode/EditNodeTextField.java
+++ b/freeplane/src/org/freeplane/view/swing/map/mindmapmode/EditNodeTextField.java
@@ -1,538 +1,540 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.map.mindmapmode;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.MatteBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.StyledEditorKit.BoldAction;
import javax.swing.text.StyledEditorKit.ForegroundAction;
import javax.swing.text.StyledEditorKit.ItalicAction;
import javax.swing.text.StyledEditorKit.StyledTextAction;
import javax.swing.text.StyledEditorKit.UnderlineAction;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.StyleSheet;
import org.freeplane.core.controller.Controller;
import org.freeplane.core.frame.ViewController;
import org.freeplane.core.resources.ResourceController;
import org.freeplane.core.util.ColorUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.common.map.ModeController;
import org.freeplane.features.common.map.NodeModel;
import org.freeplane.features.common.styles.MapStyleModel;
import org.freeplane.features.common.text.TextController;
import org.freeplane.features.mindmapmode.ortho.SpellCheckerController;
import org.freeplane.features.mindmapmode.text.AbstractEditNodeTextField;
import org.freeplane.view.swing.map.MainView;
import org.freeplane.view.swing.map.MapView;
import org.freeplane.view.swing.map.NodeView;
/**
* @author foltin
*/
class EditNodeTextField extends AbstractEditNodeTextField {
private int extraWidth;
private final class MyDocumentListener implements DocumentListener {
private boolean updateRunning = false;
public void changedUpdate(final DocumentEvent e) {
onUpdate();
}
private void onUpdate() {
if(updateRunning){
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
updateRunning = true;
layout();
updateRunning = false;
}
});
}
public void insertUpdate(final DocumentEvent e) {
onUpdate();
}
public void removeUpdate(final DocumentEvent e) {
onUpdate();
}
}
private void layout() {
if (textfield == null) {
return;
}
final int lastWidth = textfield.getWidth();
final int lastHeight = textfield.getHeight();
final boolean lineWrap = lastWidth == maxWidth;
Dimension preferredSize = textfield.getPreferredSize();
if (!lineWrap) {
preferredSize.width ++;
if (preferredSize.width > maxWidth) {
setLineWrap();
preferredSize = textfield.getPreferredSize();
}
else {
if (preferredSize.width < lastWidth) {
preferredSize.width = lastWidth;
}
else {
preferredSize.width = Math.min(preferredSize.width + extraWidth, maxWidth);
if (preferredSize.width == maxWidth) {
setLineWrap();
}
}
}
}
else {
preferredSize.width = Math.max(maxWidth, preferredSize.width);
}
if(preferredSize.width != lastWidth){
preferredSize.height = lastHeight;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
layout();
}
});
}
else{
preferredSize.height = Math.max(preferredSize.height, lastHeight);
}
if (preferredSize.width == lastWidth && preferredSize.height == lastHeight) {
textfield.repaint();
return;
}
textfield.setSize(preferredSize);
final JComponent mainView = (JComponent) textfield.getParent();
mainView.setPreferredSize(new Dimension(preferredSize.width + horizontalSpace + iconWidth, preferredSize.height
+ verticalSpace));
textfield.revalidate();
final NodeView nodeView = (NodeView) SwingUtilities.getAncestorOfClass(NodeView.class, mainView);
final MapView mapView = (MapView) SwingUtilities.getAncestorOfClass(MapView.class, nodeView);
mapView.scrollNodeToVisible(nodeView);
}
private void setLineWrap() {
if(null != textfield.getClientProperty("EditNodeTextField.linewrap")){
return;
}
final HTMLDocument document = (HTMLDocument) textfield.getDocument();
document.getStyleSheet().addRule("body { width: " + (maxWidth - 1) + "}");
textfield.setText(textfield.getText());
textfield.putClientProperty("EditNodeTextField.linewrap", true);
}
class TextFieldListener implements KeyListener, FocusListener, MouseListener {
final int CANCEL = 2;
final int EDIT = 1;
Integer eventSource = EDIT;
private boolean popupShown;
public TextFieldListener() {
}
private void conditionallyShowPopup(final MouseEvent e) {
if (e.isPopupTrigger()) {
final JPopupMenu popupMenu = createPopupMenu();
popupShown = true;
popupMenu.show(e.getComponent(), e.getX(), e.getY());
e.consume();
}
}
public void focusGained(final FocusEvent e) {
popupShown = false;
}
public void focusLost(final FocusEvent e) {
if (textfield == null || !textfield.isVisible() || eventSource == CANCEL || popupShown) {
return;
}
if (e == null) {
submitText();
hideMe();
eventSource = CANCEL;
return;
}
if (e.isTemporary() && e.getOppositeComponent() == null) {
return;
}
submitText();
hideMe();
}
private void submitText() {
submitText(textfield.getText());
}
private void submitText(final String output) {
getEditControl().ok(output);
}
public void keyPressed(final KeyEvent e) {
if (e.isControlDown() || e.isMetaDown() || eventSource == CANCEL) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
eventSource = CANCEL;
hideMe();
getEditControl().cancel();
nodeView.requestFocus();
e.consume();
break;
case KeyEvent.VK_ENTER: {
final boolean enterConfirms = ResourceController.getResourceController().getBooleanProperty(
"il__enter_confirms_by_default");
if (enterConfirms == e.isAltDown() || e.isShiftDown()) {
e.consume();
final Component component = e.getComponent();
final KeyEvent keyEvent = new KeyEvent(component, e.getID(), e.getWhen(), 0, e.getKeyCode(), e
.getKeyChar(), e.getKeyLocation());
SwingUtilities.processKeyBindings(keyEvent);
break;
}
}
final String output = textfield.getText();
e.consume();
eventSource = CANCEL;
hideMe();
submitText(output);
nodeView.requestFocus();
break;
case KeyEvent.VK_TAB:
textfield.replaceSelection(" ");
case KeyEvent.VK_SPACE:
e.consume();
break;
}
}
public void keyReleased(final KeyEvent e) {
}
public void keyTyped(final KeyEvent e) {
}
public void mouseClicked(final MouseEvent e) {
}
public void mouseEntered(final MouseEvent e) {
}
public void mouseExited(final MouseEvent e) {
}
public void mousePressed(final MouseEvent e) {
conditionallyShowPopup(e);
}
public void mouseReleased(final MouseEvent e) {
conditionallyShowPopup(e);
}
}
final private KeyEvent firstEvent;
private JEditorPane textfield;
private final DocumentListener documentListener;
private int maxWidth;
public EditNodeTextField(final NodeModel node, final String text, final KeyEvent firstEvent,
final IEditControl editControl) {
super(node, text, editControl);
this.firstEvent = firstEvent;
documentListener = new MyDocumentListener();
boldAction = new StyledEditorKit.BoldAction();
boldAction.putValue(Action.NAME, TextUtils.getText("BoldAction.text"));
boldAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control B"));
italicAction = new StyledEditorKit.ItalicAction();
italicAction.putValue(Action.NAME, TextUtils.getText("ItalicAction.text"));
italicAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control I"));
underlineAction = new StyledEditorKit.UnderlineAction();
underlineAction.putValue(Action.NAME, TextUtils.getText("UnderlineAction.text"));
underlineAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control U"));
redAction = new ForegroundAction(TextUtils.getText("red"), Color.RED);
redAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control R"));
greenAction = new ForegroundAction(TextUtils.getText("green"), Color.GREEN);
greenAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control G"));
blueAction = new ForegroundAction(TextUtils.getText("blue"), Color.BLUE);
blueAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control E"));
blackAction = new ForegroundAction(TextUtils.getText("black"), Color.BLACK);
blackAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control K"));
defaultColorAction = new ExtendedEditorKit.RemoveStyleAttributeAction(StyleConstants.Foreground, TextUtils.getText("DefaultColorAction.text"));
defaultColorAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control D"));
removeFormattingAction = new ExtendedEditorKit.RemoveStyleAttributeAction(null, TextUtils.getText("simplyhtml.clearFormatLabel"));
removeFormattingAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control T"));
}
private void hideMe() {
if (textfield == null) {
return;
}
textfield.getDocument().removeDocumentListener(documentListener);
final MainView mainView = (MainView) textfield.getParent();
textfield = null;
mainView.setPreferredSize(null);
mainView.updateText(getNode());
mainView.setHorizontalAlignment(JLabel.CENTER);
mainView.remove(0);
mainView.revalidate();
mainView.repaint();
}
private NodeView nodeView;
private Font font;
private float zoom;
private int iconWidth;
private int horizontalSpace;
private int verticalSpace;
private final BoldAction boldAction;
private final ItalicAction italicAction;
private final UnderlineAction underlineAction;
private final ForegroundAction redAction;
private final ForegroundAction greenAction;
private final ForegroundAction blueAction;
private final ForegroundAction blackAction;
private StyledTextAction defaultColorAction;
private StyledTextAction removeFormattingAction;
@Override
protected JPopupMenu createPopupMenu() {
JPopupMenu menu = super.createPopupMenu();
JMenu formatMenu = new JMenu(TextUtils.getText("simplyhtml.formatLabel"));
menu.add(formatMenu);
if (textfield.getSelectionStart() == textfield.getSelectionEnd()){
formatMenu.setEnabled(false);
return menu;
}
formatMenu.add(boldAction);
formatMenu.add(italicAction);
formatMenu.add(underlineAction);
formatMenu.add(redAction);
formatMenu.add(greenAction);
formatMenu.add(blueAction);
formatMenu.add(blackAction);
formatMenu.add(defaultColorAction);
formatMenu.add(removeFormattingAction);
return menu;
}
/* (non-Javadoc)
* @see org.freeplane.view.swing.map.INodeTextField#show()
*/
@Override
public void show(final Frame frame) {
final ModeController modeController = Controller.getCurrentModeController();
final ViewController viewController = modeController.getController().getViewController();
final TextController textController = TextController.getController(modeController);
final Component component = viewController.getComponent(getNode());
nodeView = (NodeView) SwingUtilities.getAncestorOfClass(NodeView.class, component);
font = nodeView.getTextFont();
zoom = viewController.getZoom();
if (zoom != 1F) {
final float fontSize = (int) (Math.rint(font.getSize() * zoom));
font = font.deriveFont(fontSize);
}
textfield = new JEditorPane(){
@Override
public void paste() {
final Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
if(contents.isDataFlavorSupported(DataFlavor.stringFlavor)){
try {
String text = (String) contents.getTransferData(DataFlavor.stringFlavor);
replaceSelection(text);
}
catch (Exception e) {
}
}
}
};
textfield.setContentType("text/html");
final InputMap inputMap = textfield.getInputMap();
final ActionMap actionMap = textfield.getActionMap();
inputMap.put((KeyStroke) boldAction.getValue(Action.ACCELERATOR_KEY), "boldAction");
actionMap.put("boldAction",boldAction);
inputMap.put((KeyStroke) italicAction.getValue(Action.ACCELERATOR_KEY), "italicAction");
actionMap.put("italicAction", italicAction);
inputMap.put((KeyStroke) underlineAction.getValue(Action.ACCELERATOR_KEY), "underlineAction");
actionMap.put("underlineAction", underlineAction);
inputMap.put((KeyStroke) redAction.getValue(Action.ACCELERATOR_KEY), "redAction");
actionMap.put("redAction", redAction);
inputMap.put((KeyStroke) greenAction.getValue(Action.ACCELERATOR_KEY), "greenAction");
actionMap.put("greenAction", greenAction);
inputMap.put((KeyStroke) blueAction.getValue(Action.ACCELERATOR_KEY), "blueAction");
actionMap.put("blueAction", blueAction);
inputMap.put((KeyStroke) blackAction.getValue(Action.ACCELERATOR_KEY), "blackAction");
actionMap.put("blackAction", blackAction);
inputMap.put((KeyStroke) defaultColorAction.getValue(Action.ACCELERATOR_KEY), "defaultColorAction");
actionMap.put("defaultColorAction", defaultColorAction);
inputMap.put((KeyStroke) removeFormattingAction.getValue(Action.ACCELERATOR_KEY), "removeFormattingAction");
actionMap.put("removeFormattingAction", removeFormattingAction);
final Color nodeTextColor = nodeView.getTextColor();
final Color nodeTextBackground = nodeView.getTextBackground();
textfield.setCaretColor(nodeTextColor);
textfield.setBackground(nodeTextBackground);
final StringBuilder ruleBuilder = new StringBuilder(100);
ruleBuilder.append("body {");
ruleBuilder.append("font-family: ").append(font.getFamily()).append(";");
ruleBuilder.append("font-size: ").append(font.getSize()).append("pt;");
if (font.isItalic()) {
ruleBuilder.append("font-style: italic; ");
}
if (font.isBold()) {
ruleBuilder.append("font-weight: bold; ");
}
ruleBuilder.append("color: ").append(ColorUtils.colorToString(nodeTextColor)).append(";");
ruleBuilder.append("}\n");
ruleBuilder.append("p {margin-top:0;}\n");
final HTMLDocument document = (HTMLDocument) textfield.getDocument();
final StyleSheet styleSheet = document.getStyleSheet();
styleSheet.removeStyle("p");
styleSheet.removeStyle("body");
styleSheet.addRule(ruleBuilder.toString());
textfield.setText(text);
final MapView mapView = (MapView) viewController.getMapView();
maxWidth = MapStyleModel.getExtension(mapView.getModel()).getMaxNodeWidth();
maxWidth = mapView.getZoomed(maxWidth) + 1;
extraWidth = ResourceController.getResourceController().getIntProperty("editor_extra_width", 80);
extraWidth = mapView.getZoomed(extraWidth);
final TextFieldListener textFieldListener = new TextFieldListener();
this.textFieldListener = textFieldListener;
textfield.addFocusListener(textFieldListener);
textfield.addKeyListener(textFieldListener);
textfield.addMouseListener(textFieldListener);
SpellCheckerController.getController().enableAutoSpell(textfield, true);
mapView.scrollNodeToVisible(nodeView);
final MainView mainView = nodeView.getMainView();
final int nodeWidth = mainView.getWidth();
final int nodeHeight = mainView.getHeight();
final Dimension textFieldSize;
textfield.setBorder(new MatteBorder(2, 2, 2, 2, nodeView.getSelectedColor()));
textFieldSize = textfield.getPreferredSize();
textFieldSize.width += 1;
if (textFieldSize.width > maxWidth) {
textFieldSize.width = maxWidth;
setLineWrap();
textFieldSize.height = textfield.getPreferredSize().height;
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
else {
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
if (horizontalSpace < 0) {
horizontalSpace = 0;
}
if (verticalSpace < 0) {
verticalSpace = 0;
}
textfield.setSize(textFieldSize.width, textFieldSize.height);
mainView.setPreferredSize(new Dimension(textFieldSize.width + horizontalSpace, textFieldSize.height
+ verticalSpace));
iconWidth = mainView.getIconWidth();
if (iconWidth != 0) {
iconWidth += mapView.getZoomed(mainView.getIconTextGap());
horizontalSpace -= iconWidth;
}
final int x = (horizontalSpace + 1) / 2;
final int y = (verticalSpace + 1) / 2;
if (nodeView.isLeft() && !nodeView.isRoot()) {
textfield.setBounds(x, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.RIGHT);
}
else {
textfield.setBounds(x + iconWidth, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.LEFT);
}
mainView.add(textfield, 0);
textfield.setCaretPosition(document.getLength());
if (firstEvent != null) {
redispatchKeyEvents(textfield, firstEvent);
}
document.addDocumentListener(documentListener);
if(textController.getIsShortened(node)){
layout();
}
textfield.repaint();
EventQueue.invokeLater(new Runnable() {
public void run() {
- textfield.requestFocus();
+ if(textfield != null){
+ textfield.requestFocus();
+ }
}
});
}
}
| true | true | public void show(final Frame frame) {
final ModeController modeController = Controller.getCurrentModeController();
final ViewController viewController = modeController.getController().getViewController();
final TextController textController = TextController.getController(modeController);
final Component component = viewController.getComponent(getNode());
nodeView = (NodeView) SwingUtilities.getAncestorOfClass(NodeView.class, component);
font = nodeView.getTextFont();
zoom = viewController.getZoom();
if (zoom != 1F) {
final float fontSize = (int) (Math.rint(font.getSize() * zoom));
font = font.deriveFont(fontSize);
}
textfield = new JEditorPane(){
@Override
public void paste() {
final Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
if(contents.isDataFlavorSupported(DataFlavor.stringFlavor)){
try {
String text = (String) contents.getTransferData(DataFlavor.stringFlavor);
replaceSelection(text);
}
catch (Exception e) {
}
}
}
};
textfield.setContentType("text/html");
final InputMap inputMap = textfield.getInputMap();
final ActionMap actionMap = textfield.getActionMap();
inputMap.put((KeyStroke) boldAction.getValue(Action.ACCELERATOR_KEY), "boldAction");
actionMap.put("boldAction",boldAction);
inputMap.put((KeyStroke) italicAction.getValue(Action.ACCELERATOR_KEY), "italicAction");
actionMap.put("italicAction", italicAction);
inputMap.put((KeyStroke) underlineAction.getValue(Action.ACCELERATOR_KEY), "underlineAction");
actionMap.put("underlineAction", underlineAction);
inputMap.put((KeyStroke) redAction.getValue(Action.ACCELERATOR_KEY), "redAction");
actionMap.put("redAction", redAction);
inputMap.put((KeyStroke) greenAction.getValue(Action.ACCELERATOR_KEY), "greenAction");
actionMap.put("greenAction", greenAction);
inputMap.put((KeyStroke) blueAction.getValue(Action.ACCELERATOR_KEY), "blueAction");
actionMap.put("blueAction", blueAction);
inputMap.put((KeyStroke) blackAction.getValue(Action.ACCELERATOR_KEY), "blackAction");
actionMap.put("blackAction", blackAction);
inputMap.put((KeyStroke) defaultColorAction.getValue(Action.ACCELERATOR_KEY), "defaultColorAction");
actionMap.put("defaultColorAction", defaultColorAction);
inputMap.put((KeyStroke) removeFormattingAction.getValue(Action.ACCELERATOR_KEY), "removeFormattingAction");
actionMap.put("removeFormattingAction", removeFormattingAction);
final Color nodeTextColor = nodeView.getTextColor();
final Color nodeTextBackground = nodeView.getTextBackground();
textfield.setCaretColor(nodeTextColor);
textfield.setBackground(nodeTextBackground);
final StringBuilder ruleBuilder = new StringBuilder(100);
ruleBuilder.append("body {");
ruleBuilder.append("font-family: ").append(font.getFamily()).append(";");
ruleBuilder.append("font-size: ").append(font.getSize()).append("pt;");
if (font.isItalic()) {
ruleBuilder.append("font-style: italic; ");
}
if (font.isBold()) {
ruleBuilder.append("font-weight: bold; ");
}
ruleBuilder.append("color: ").append(ColorUtils.colorToString(nodeTextColor)).append(";");
ruleBuilder.append("}\n");
ruleBuilder.append("p {margin-top:0;}\n");
final HTMLDocument document = (HTMLDocument) textfield.getDocument();
final StyleSheet styleSheet = document.getStyleSheet();
styleSheet.removeStyle("p");
styleSheet.removeStyle("body");
styleSheet.addRule(ruleBuilder.toString());
textfield.setText(text);
final MapView mapView = (MapView) viewController.getMapView();
maxWidth = MapStyleModel.getExtension(mapView.getModel()).getMaxNodeWidth();
maxWidth = mapView.getZoomed(maxWidth) + 1;
extraWidth = ResourceController.getResourceController().getIntProperty("editor_extra_width", 80);
extraWidth = mapView.getZoomed(extraWidth);
final TextFieldListener textFieldListener = new TextFieldListener();
this.textFieldListener = textFieldListener;
textfield.addFocusListener(textFieldListener);
textfield.addKeyListener(textFieldListener);
textfield.addMouseListener(textFieldListener);
SpellCheckerController.getController().enableAutoSpell(textfield, true);
mapView.scrollNodeToVisible(nodeView);
final MainView mainView = nodeView.getMainView();
final int nodeWidth = mainView.getWidth();
final int nodeHeight = mainView.getHeight();
final Dimension textFieldSize;
textfield.setBorder(new MatteBorder(2, 2, 2, 2, nodeView.getSelectedColor()));
textFieldSize = textfield.getPreferredSize();
textFieldSize.width += 1;
if (textFieldSize.width > maxWidth) {
textFieldSize.width = maxWidth;
setLineWrap();
textFieldSize.height = textfield.getPreferredSize().height;
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
else {
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
if (horizontalSpace < 0) {
horizontalSpace = 0;
}
if (verticalSpace < 0) {
verticalSpace = 0;
}
textfield.setSize(textFieldSize.width, textFieldSize.height);
mainView.setPreferredSize(new Dimension(textFieldSize.width + horizontalSpace, textFieldSize.height
+ verticalSpace));
iconWidth = mainView.getIconWidth();
if (iconWidth != 0) {
iconWidth += mapView.getZoomed(mainView.getIconTextGap());
horizontalSpace -= iconWidth;
}
final int x = (horizontalSpace + 1) / 2;
final int y = (verticalSpace + 1) / 2;
if (nodeView.isLeft() && !nodeView.isRoot()) {
textfield.setBounds(x, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.RIGHT);
}
else {
textfield.setBounds(x + iconWidth, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.LEFT);
}
mainView.add(textfield, 0);
textfield.setCaretPosition(document.getLength());
if (firstEvent != null) {
redispatchKeyEvents(textfield, firstEvent);
}
document.addDocumentListener(documentListener);
if(textController.getIsShortened(node)){
layout();
}
textfield.repaint();
EventQueue.invokeLater(new Runnable() {
public void run() {
textfield.requestFocus();
}
});
}
| public void show(final Frame frame) {
final ModeController modeController = Controller.getCurrentModeController();
final ViewController viewController = modeController.getController().getViewController();
final TextController textController = TextController.getController(modeController);
final Component component = viewController.getComponent(getNode());
nodeView = (NodeView) SwingUtilities.getAncestorOfClass(NodeView.class, component);
font = nodeView.getTextFont();
zoom = viewController.getZoom();
if (zoom != 1F) {
final float fontSize = (int) (Math.rint(font.getSize() * zoom));
font = font.deriveFont(fontSize);
}
textfield = new JEditorPane(){
@Override
public void paste() {
final Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
if(contents.isDataFlavorSupported(DataFlavor.stringFlavor)){
try {
String text = (String) contents.getTransferData(DataFlavor.stringFlavor);
replaceSelection(text);
}
catch (Exception e) {
}
}
}
};
textfield.setContentType("text/html");
final InputMap inputMap = textfield.getInputMap();
final ActionMap actionMap = textfield.getActionMap();
inputMap.put((KeyStroke) boldAction.getValue(Action.ACCELERATOR_KEY), "boldAction");
actionMap.put("boldAction",boldAction);
inputMap.put((KeyStroke) italicAction.getValue(Action.ACCELERATOR_KEY), "italicAction");
actionMap.put("italicAction", italicAction);
inputMap.put((KeyStroke) underlineAction.getValue(Action.ACCELERATOR_KEY), "underlineAction");
actionMap.put("underlineAction", underlineAction);
inputMap.put((KeyStroke) redAction.getValue(Action.ACCELERATOR_KEY), "redAction");
actionMap.put("redAction", redAction);
inputMap.put((KeyStroke) greenAction.getValue(Action.ACCELERATOR_KEY), "greenAction");
actionMap.put("greenAction", greenAction);
inputMap.put((KeyStroke) blueAction.getValue(Action.ACCELERATOR_KEY), "blueAction");
actionMap.put("blueAction", blueAction);
inputMap.put((KeyStroke) blackAction.getValue(Action.ACCELERATOR_KEY), "blackAction");
actionMap.put("blackAction", blackAction);
inputMap.put((KeyStroke) defaultColorAction.getValue(Action.ACCELERATOR_KEY), "defaultColorAction");
actionMap.put("defaultColorAction", defaultColorAction);
inputMap.put((KeyStroke) removeFormattingAction.getValue(Action.ACCELERATOR_KEY), "removeFormattingAction");
actionMap.put("removeFormattingAction", removeFormattingAction);
final Color nodeTextColor = nodeView.getTextColor();
final Color nodeTextBackground = nodeView.getTextBackground();
textfield.setCaretColor(nodeTextColor);
textfield.setBackground(nodeTextBackground);
final StringBuilder ruleBuilder = new StringBuilder(100);
ruleBuilder.append("body {");
ruleBuilder.append("font-family: ").append(font.getFamily()).append(";");
ruleBuilder.append("font-size: ").append(font.getSize()).append("pt;");
if (font.isItalic()) {
ruleBuilder.append("font-style: italic; ");
}
if (font.isBold()) {
ruleBuilder.append("font-weight: bold; ");
}
ruleBuilder.append("color: ").append(ColorUtils.colorToString(nodeTextColor)).append(";");
ruleBuilder.append("}\n");
ruleBuilder.append("p {margin-top:0;}\n");
final HTMLDocument document = (HTMLDocument) textfield.getDocument();
final StyleSheet styleSheet = document.getStyleSheet();
styleSheet.removeStyle("p");
styleSheet.removeStyle("body");
styleSheet.addRule(ruleBuilder.toString());
textfield.setText(text);
final MapView mapView = (MapView) viewController.getMapView();
maxWidth = MapStyleModel.getExtension(mapView.getModel()).getMaxNodeWidth();
maxWidth = mapView.getZoomed(maxWidth) + 1;
extraWidth = ResourceController.getResourceController().getIntProperty("editor_extra_width", 80);
extraWidth = mapView.getZoomed(extraWidth);
final TextFieldListener textFieldListener = new TextFieldListener();
this.textFieldListener = textFieldListener;
textfield.addFocusListener(textFieldListener);
textfield.addKeyListener(textFieldListener);
textfield.addMouseListener(textFieldListener);
SpellCheckerController.getController().enableAutoSpell(textfield, true);
mapView.scrollNodeToVisible(nodeView);
final MainView mainView = nodeView.getMainView();
final int nodeWidth = mainView.getWidth();
final int nodeHeight = mainView.getHeight();
final Dimension textFieldSize;
textfield.setBorder(new MatteBorder(2, 2, 2, 2, nodeView.getSelectedColor()));
textFieldSize = textfield.getPreferredSize();
textFieldSize.width += 1;
if (textFieldSize.width > maxWidth) {
textFieldSize.width = maxWidth;
setLineWrap();
textFieldSize.height = textfield.getPreferredSize().height;
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
else {
horizontalSpace = nodeWidth - textFieldSize.width;
verticalSpace = nodeHeight - textFieldSize.height;
}
if (horizontalSpace < 0) {
horizontalSpace = 0;
}
if (verticalSpace < 0) {
verticalSpace = 0;
}
textfield.setSize(textFieldSize.width, textFieldSize.height);
mainView.setPreferredSize(new Dimension(textFieldSize.width + horizontalSpace, textFieldSize.height
+ verticalSpace));
iconWidth = mainView.getIconWidth();
if (iconWidth != 0) {
iconWidth += mapView.getZoomed(mainView.getIconTextGap());
horizontalSpace -= iconWidth;
}
final int x = (horizontalSpace + 1) / 2;
final int y = (verticalSpace + 1) / 2;
if (nodeView.isLeft() && !nodeView.isRoot()) {
textfield.setBounds(x, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.RIGHT);
}
else {
textfield.setBounds(x + iconWidth, y, textFieldSize.width, textFieldSize.height);
mainView.setText("");
mainView.setHorizontalAlignment(JLabel.LEFT);
}
mainView.add(textfield, 0);
textfield.setCaretPosition(document.getLength());
if (firstEvent != null) {
redispatchKeyEvents(textfield, firstEvent);
}
document.addDocumentListener(documentListener);
if(textController.getIsShortened(node)){
layout();
}
textfield.repaint();
EventQueue.invokeLater(new Runnable() {
public void run() {
if(textfield != null){
textfield.requestFocus();
}
}
});
}
|
diff --git a/lib/src/java/org/j2free/jsp/tags/FragmentCacheTag.java b/lib/src/java/org/j2free/jsp/tags/FragmentCacheTag.java
index f59cbba..20a2577 100644
--- a/lib/src/java/org/j2free/jsp/tags/FragmentCacheTag.java
+++ b/lib/src/java/org/j2free/jsp/tags/FragmentCacheTag.java
@@ -1,424 +1,425 @@
/*
* FragmentCacheTag.java
*
* Created on April 2nd, 2009
*
* 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.j2free.jsp.tags;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.j2free.cache.Fragment;
import org.j2free.cache.FragmentCache;
import static org.j2free.util.ServletUtils.*;
/**
* Implementation of a fragment cache as a custom tag. This fragment cache
* guarantees that only a single thread may trigger an update
*
* @author Ryan Wilson
*/
public class FragmentCacheTag extends BodyTagSupport {
private final Log log = LogFactory.getLog(getClass());
/***********************************************************************
* Static Implementation
*/
private static final String ATTRIBUTE_FORCE_REFRESH = "nocache";
// The possible FragmentCaches
private static final ConcurrentHashMap<String, FragmentCache> caches
= new ConcurrentHashMap<String, FragmentCache>(5, 1.0f, 5);
// The default FragmentCache
private static final AtomicReference<FragmentCache> defaultCache
= new AtomicReference<FragmentCache>(null);
/**
* @return The underlying {@link FragmentCache} associated with the specified
* strategy name; useful for code looking to evict a cache {@link Fragment}
* outside of the FragmentCacheTag.
*/
public static FragmentCache getCache(String strategy) {
return caches.get(strategy);
}
/**
* @return The underlying default {@link FragmentCache}, useful for code looking
* to evict a cache {@link Fragment} outside of the FragmentCacheTag.
*/
public static FragmentCache getDefaultCache() {
return defaultCache.get();
}
/**
* Registers the specified cache under the specified cache strategy name.
* If this is the first cache strategy to be registered, it will also
* become the default.
*
* @param name The name by which to reference this cache strategy
* @param cache An instance of FragmentCache
*/
public static void registerStrategy(String name, FragmentCache cache) {
caches.put(name, cache);
if (defaultCache.get() == null) {
defaultCache.compareAndSet(null, cache);
}
}
/**
* Globally turn the cache on or off (off by default)
*/
private static final AtomicBoolean enabled = new AtomicBoolean(false);
/**
* Enables fragment caching
*/
public static void enable() {
enabled.set(true);
}
/**
* Disables fragment caching, clears any cached fragments
*/
public static void disable() {
enabled.set(false);
for (FragmentCache fc : caches.values()) {
fc.destroy();
}
caches.clear();
}
// This is the max amount of time a thread will wait() on another thread
// that is currently updating the Fragment. If the updating thread does
// not complete the update within REQUEST_TIMEOUT, the waiting thread
// will print a message to refresh the page.
private static final AtomicLong REQUEST_TIMEOUT = new AtomicLong(20);
public static void setRequestTimeout(long timeout) {
REQUEST_TIMEOUT.set(timeout);
}
private static final AtomicLong WARNING_COMPUTE_DURATION = new AtomicLong(10000);
public static void setWarningComputeDuration(long duration) {
WARNING_COMPUTE_DURATION.set(duration);
}
/***********************************************************************
* Tag Instance Implementation
*/
// Used to hold a reference to a particular fragment b/t start and end tags
private FragmentCache cache;
// Used to hold a reference to a particular fragment b/t start and end tags
private Fragment fragment;
// Cache Timeout
private long timeout;
// Cache Key
private String key;
// Cache Condition, used to specify a value to monitor for a change
private String condition;
// Cache strategy, if there are multiple registered, this is used
// to specify which to use
private String strategy;
// If true, the cache will be ignored for this request
private boolean disable;
// The time the page entered the tag
private long start;
// The time unit of the expiration
private String unit;
public FragmentCacheTag() {
super();
disable = false;
}
public void setKey(String key) {
this.key = key;
}
public void setCondition(String condition) {
this.condition = condition;
}
public void setTimeout(long timeout) {
this.timeout = timeout;
}
public void setDisable(boolean disable) {
this.disable = disable;
}
public void setStrategy(String strategy) {
this.strategy = strategy;
}
public void setUnit(String unit) {
this.unit = unit;
}
/**
* To evaluate the BODY and have control passed to doAfterBody, return EVAL_BODY_BUFFERED
* To use the cached content, writed the fragment content to the page, then return SKIP_BODY
*
* Rules:
*
* - Conditionts under which the body should be evaluated:
* - Caching is disabled
* - Caching is enabled, but no cached fragment exists
* - Caching is enabled, but the cache has expired and no other thread is currently refreshing the cache
* - Caching is enabled, but the condition has changed, and no other thread is currently refreshing the cache
*
* - Conditions under which the body should NOT be evaluated:
* - Caching is enabled and a cached version exists
* - Caching is enabled, the cache has expired, but another thread is refreshing the cache
* - Caching is enabled, the condition has changed, but another thread is refreshing the cache
*
*/
@Override
public int doStartTag() throws JspException {
start = System.currentTimeMillis();
// If the cache isn't enabled, make sure disable is set
disable |= !enabled.get();
// If disable is set, either by the tag, the request attribute, or the global flag, then ignore the cache
if (disable) {
if (log.isTraceEnabled()) log.trace(key + ": DISABLED");
return EVAL_BODY_BUFFERED;
}
if (log.isTraceEnabled()) log.trace(key + ": START");
// timeout is assumed to be on milliseconds, but there
// is the additional parameter
if (!empty(unit)) {
try {
TimeUnit timeUnit = TimeUnit.valueOf(unit.toUpperCase());
if (timeUnit != TimeUnit.MILLISECONDS) {
log.trace(key + ": Converting " + timeout + " " + timeUnit.name() + " to ms");
timeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
}
} catch (Exception e) {
log.warn(key + ": Unable to interpret timeout unit, assuming MILLISECONDS");
}
}
cache = defaultCache.get();
// If the user specified a cache, try to get that one
if (!StringUtils.isEmpty(strategy)) {
cache = caches.get(strategy);
if (cache == null) {
log.warn(key + ": NO CACHE for strategy: " + strategy);
cache = defaultCache.get();
}
}
if (cache == null) {
log.error(key + ": NO CACHE");
return EVAL_BODY_BUFFERED;
}
// See if there is a cached Fragment already
fragment = cache.get(key);
// If not ...
if (fragment == null) {
if (log.isTraceEnabled()) log.trace(key + ": NOT FOUND, creating...");
// If the fragment didn't exist, store a new one...
// Necessary to use putIfAbset, because the map could have changed
// since calling cache.get(key) above. In either case, the implementation
// of FragmentCache guarantees that the retruned value of this function will
// be the current Fragment stored in the cache by this key.
fragment = cache.putIfAbsent(key, cache.createFragment(condition, timeout));
} else if (fragment != null && fragment.isLockAbandoned()) {
// Or if it exists but is abandoned (lock-for-update has been held > lock wait timeout).
// If we're here, it probably means that a thread hit an exception while updating the old fragment and was never
// able to unlock the fragment. So, remove the old fragment, then create a new one starting with the old content
log.warn(key + ": DIRTY, replacing");
fragment = cache.replace(key, fragment, cache.createFragment(fragment, condition, timeout));
} else if (log.isTraceEnabled()) {
log.trace(key + ": FOUND");
}
// Try to acquire the lock for update. If successful, then
// the Fragment needs to be updated and this Thread has taken
// the responsibility to do so.
if (log.isTraceEnabled()) log.trace(key + ": TRY CONDITION lock-for-udpate: " + condition);
if (fragment.tryLockForUpdate(condition)) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
- boolean forceRefresh = pageContext.getAttribute(ATTRIBUTE_FORCE_REFRESH) != null;
+ boolean forceRefresh = pageContext.getAttribute(ATTRIBUTE_FORCE_REFRESH) != null ||
+ pageContext.getRequest().getAttribute(ATTRIBUTE_FORCE_REFRESH) != null;
// If the force-refresh attribute is set, then try to acquire
// the lock regardless of condition of expiration. Doing so
// only return false if another thread is already refreshing it
// which is fine.
if (forceRefresh) {
if (log.isTraceEnabled()) log.trace(key + ": TRY FORCE lock-for-update");
if (fragment.tryLockForUpdate()) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
}
if (log.isTraceEnabled()) log.trace(key + ": DENIED");
// Try to get the content, cached.get() will block if
// the content of the fragment is not yet set, so catch an
// InterruptedException.
String response = null;
try {
// if trace is on, we do a little more benchmarking, so we have
// a distinct branch here to save a branch at the second log call
// and save benchmarking when we're not tracing
if (log.isTraceEnabled()) {
log.trace(key + ": GET content");
final long getTime = System.currentTimeMillis();
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
log.trace(key + ": GOT content [waitTime:" + (System.currentTimeMillis() - getTime) + "]");
} else {
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
log.warn(key + ": INTERRUPTED while waiting for content");
}
// response will be null if the call to get timed out
if (response == null)
response = "Sorry, our cache did not respond in time. Try refreshing the page.";
// Write the response to the page
try {
if (log.isTraceEnabled()) log.trace(key + ": WRITE OUTPUT");
pageContext.getOut().write(response);
} catch (IOException e) {
log.error(key, e);
}
long duration = System.currentTimeMillis() - start;
if (duration > WARNING_COMPUTE_DURATION.get()) {
log.warn(key + ": SLOW FETCH, " + duration + "ms");
} else if (log.isTraceEnabled()) {
log.trace(key + ": COMPLETE, " + duration + "ms");
}
return SKIP_BODY;
}
/**
* Write the content to the apge, try to acquire lock and update, release lock,
* then return SKIP_BODY when complete
*/
@Override
public int doAfterBody() throws JspException {
// Get the BodyContent, the result of the processing of the body of the tag
BodyContent body = getBodyContent();
String content = body.getString();
// Make sure we had a cache
if (fragment != null) {
// Update the Fragment, doing this before writing to the page will release waiting threads sooner.
if (!disable) {
if (fragment.tryUpdateAndRelease(content, condition)) {
log.trace(key + ": UPDATE and RELEASED");
} else if (log.isTraceEnabled()) {
log.error(key + ": UPDATE FAILED [cache.contains(\"" + key + "\")=" + cache.contains(key) + "]");
}
} else if (log.isTraceEnabled()) {
log.trace(key + ": DISABLED, not caching");
}
}
// Attempt to write the body to the page
try {
if (log.isTraceEnabled()) log.trace(key + ": WRITE OUTPUT");
body.getEnclosingWriter().write(content);
} catch (IOException e) {
log.error(key, e);
}
long duration = System.currentTimeMillis() - start;
if (duration > WARNING_COMPUTE_DURATION.get()) {
log.warn(key + ": SLOW COMPUTE, " + duration + "ms");
} else if (log.isTraceEnabled()) {
log.trace(key + ": COMPLETE, " + duration + "ms");
}
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
if (fragment != null) { // Don't try to release a fragment we didn't have
fragment.tryRelease();
}
return EVAL_PAGE;
}
@Override
public void release() {
super.release();
disable = false; // Clear out instance props
cache = null;
fragment = null;
key = strategy = condition = unit = null;
}
}
| true | true | public int doStartTag() throws JspException {
start = System.currentTimeMillis();
// If the cache isn't enabled, make sure disable is set
disable |= !enabled.get();
// If disable is set, either by the tag, the request attribute, or the global flag, then ignore the cache
if (disable) {
if (log.isTraceEnabled()) log.trace(key + ": DISABLED");
return EVAL_BODY_BUFFERED;
}
if (log.isTraceEnabled()) log.trace(key + ": START");
// timeout is assumed to be on milliseconds, but there
// is the additional parameter
if (!empty(unit)) {
try {
TimeUnit timeUnit = TimeUnit.valueOf(unit.toUpperCase());
if (timeUnit != TimeUnit.MILLISECONDS) {
log.trace(key + ": Converting " + timeout + " " + timeUnit.name() + " to ms");
timeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
}
} catch (Exception e) {
log.warn(key + ": Unable to interpret timeout unit, assuming MILLISECONDS");
}
}
cache = defaultCache.get();
// If the user specified a cache, try to get that one
if (!StringUtils.isEmpty(strategy)) {
cache = caches.get(strategy);
if (cache == null) {
log.warn(key + ": NO CACHE for strategy: " + strategy);
cache = defaultCache.get();
}
}
if (cache == null) {
log.error(key + ": NO CACHE");
return EVAL_BODY_BUFFERED;
}
// See if there is a cached Fragment already
fragment = cache.get(key);
// If not ...
if (fragment == null) {
if (log.isTraceEnabled()) log.trace(key + ": NOT FOUND, creating...");
// If the fragment didn't exist, store a new one...
// Necessary to use putIfAbset, because the map could have changed
// since calling cache.get(key) above. In either case, the implementation
// of FragmentCache guarantees that the retruned value of this function will
// be the current Fragment stored in the cache by this key.
fragment = cache.putIfAbsent(key, cache.createFragment(condition, timeout));
} else if (fragment != null && fragment.isLockAbandoned()) {
// Or if it exists but is abandoned (lock-for-update has been held > lock wait timeout).
// If we're here, it probably means that a thread hit an exception while updating the old fragment and was never
// able to unlock the fragment. So, remove the old fragment, then create a new one starting with the old content
log.warn(key + ": DIRTY, replacing");
fragment = cache.replace(key, fragment, cache.createFragment(fragment, condition, timeout));
} else if (log.isTraceEnabled()) {
log.trace(key + ": FOUND");
}
// Try to acquire the lock for update. If successful, then
// the Fragment needs to be updated and this Thread has taken
// the responsibility to do so.
if (log.isTraceEnabled()) log.trace(key + ": TRY CONDITION lock-for-udpate: " + condition);
if (fragment.tryLockForUpdate(condition)) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
boolean forceRefresh = pageContext.getAttribute(ATTRIBUTE_FORCE_REFRESH) != null;
// If the force-refresh attribute is set, then try to acquire
// the lock regardless of condition of expiration. Doing so
// only return false if another thread is already refreshing it
// which is fine.
if (forceRefresh) {
if (log.isTraceEnabled()) log.trace(key + ": TRY FORCE lock-for-update");
if (fragment.tryLockForUpdate()) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
}
if (log.isTraceEnabled()) log.trace(key + ": DENIED");
// Try to get the content, cached.get() will block if
// the content of the fragment is not yet set, so catch an
// InterruptedException.
String response = null;
try {
// if trace is on, we do a little more benchmarking, so we have
// a distinct branch here to save a branch at the second log call
// and save benchmarking when we're not tracing
if (log.isTraceEnabled()) {
log.trace(key + ": GET content");
final long getTime = System.currentTimeMillis();
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
log.trace(key + ": GOT content [waitTime:" + (System.currentTimeMillis() - getTime) + "]");
} else {
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
log.warn(key + ": INTERRUPTED while waiting for content");
}
// response will be null if the call to get timed out
if (response == null)
response = "Sorry, our cache did not respond in time. Try refreshing the page.";
// Write the response to the page
try {
if (log.isTraceEnabled()) log.trace(key + ": WRITE OUTPUT");
pageContext.getOut().write(response);
} catch (IOException e) {
log.error(key, e);
}
long duration = System.currentTimeMillis() - start;
if (duration > WARNING_COMPUTE_DURATION.get()) {
log.warn(key + ": SLOW FETCH, " + duration + "ms");
} else if (log.isTraceEnabled()) {
log.trace(key + ": COMPLETE, " + duration + "ms");
}
return SKIP_BODY;
}
| public int doStartTag() throws JspException {
start = System.currentTimeMillis();
// If the cache isn't enabled, make sure disable is set
disable |= !enabled.get();
// If disable is set, either by the tag, the request attribute, or the global flag, then ignore the cache
if (disable) {
if (log.isTraceEnabled()) log.trace(key + ": DISABLED");
return EVAL_BODY_BUFFERED;
}
if (log.isTraceEnabled()) log.trace(key + ": START");
// timeout is assumed to be on milliseconds, but there
// is the additional parameter
if (!empty(unit)) {
try {
TimeUnit timeUnit = TimeUnit.valueOf(unit.toUpperCase());
if (timeUnit != TimeUnit.MILLISECONDS) {
log.trace(key + ": Converting " + timeout + " " + timeUnit.name() + " to ms");
timeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
}
} catch (Exception e) {
log.warn(key + ": Unable to interpret timeout unit, assuming MILLISECONDS");
}
}
cache = defaultCache.get();
// If the user specified a cache, try to get that one
if (!StringUtils.isEmpty(strategy)) {
cache = caches.get(strategy);
if (cache == null) {
log.warn(key + ": NO CACHE for strategy: " + strategy);
cache = defaultCache.get();
}
}
if (cache == null) {
log.error(key + ": NO CACHE");
return EVAL_BODY_BUFFERED;
}
// See if there is a cached Fragment already
fragment = cache.get(key);
// If not ...
if (fragment == null) {
if (log.isTraceEnabled()) log.trace(key + ": NOT FOUND, creating...");
// If the fragment didn't exist, store a new one...
// Necessary to use putIfAbset, because the map could have changed
// since calling cache.get(key) above. In either case, the implementation
// of FragmentCache guarantees that the retruned value of this function will
// be the current Fragment stored in the cache by this key.
fragment = cache.putIfAbsent(key, cache.createFragment(condition, timeout));
} else if (fragment != null && fragment.isLockAbandoned()) {
// Or if it exists but is abandoned (lock-for-update has been held > lock wait timeout).
// If we're here, it probably means that a thread hit an exception while updating the old fragment and was never
// able to unlock the fragment. So, remove the old fragment, then create a new one starting with the old content
log.warn(key + ": DIRTY, replacing");
fragment = cache.replace(key, fragment, cache.createFragment(fragment, condition, timeout));
} else if (log.isTraceEnabled()) {
log.trace(key + ": FOUND");
}
// Try to acquire the lock for update. If successful, then
// the Fragment needs to be updated and this Thread has taken
// the responsibility to do so.
if (log.isTraceEnabled()) log.trace(key + ": TRY CONDITION lock-for-udpate: " + condition);
if (fragment.tryLockForUpdate(condition)) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
boolean forceRefresh = pageContext.getAttribute(ATTRIBUTE_FORCE_REFRESH) != null ||
pageContext.getRequest().getAttribute(ATTRIBUTE_FORCE_REFRESH) != null;
// If the force-refresh attribute is set, then try to acquire
// the lock regardless of condition of expiration. Doing so
// only return false if another thread is already refreshing it
// which is fine.
if (forceRefresh) {
if (log.isTraceEnabled()) log.trace(key + ": TRY FORCE lock-for-update");
if (fragment.tryLockForUpdate()) {
if (log.isTraceEnabled()) log.trace(key + ": ACQUIRED, evaluating body...");
return EVAL_BODY_BUFFERED;
}
}
if (log.isTraceEnabled()) log.trace(key + ": DENIED");
// Try to get the content, cached.get() will block if
// the content of the fragment is not yet set, so catch an
// InterruptedException.
String response = null;
try {
// if trace is on, we do a little more benchmarking, so we have
// a distinct branch here to save a branch at the second log call
// and save benchmarking when we're not tracing
if (log.isTraceEnabled()) {
log.trace(key + ": GET content");
final long getTime = System.currentTimeMillis();
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
log.trace(key + ": GOT content [waitTime:" + (System.currentTimeMillis() - getTime) + "]");
} else {
response = fragment.get(REQUEST_TIMEOUT.get(), TimeUnit.SECONDS);
}
} catch (InterruptedException e) {
log.warn(key + ": INTERRUPTED while waiting for content");
}
// response will be null if the call to get timed out
if (response == null)
response = "Sorry, our cache did not respond in time. Try refreshing the page.";
// Write the response to the page
try {
if (log.isTraceEnabled()) log.trace(key + ": WRITE OUTPUT");
pageContext.getOut().write(response);
} catch (IOException e) {
log.error(key, e);
}
long duration = System.currentTimeMillis() - start;
if (duration > WARNING_COMPUTE_DURATION.get()) {
log.warn(key + ": SLOW FETCH, " + duration + "ms");
} else if (log.isTraceEnabled()) {
log.trace(key + ": COMPLETE, " + duration + "ms");
}
return SKIP_BODY;
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/failover/AbstractKillManagementTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/failover/AbstractKillManagementTest.java
index ef34781b..886a0122 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/failover/AbstractKillManagementTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/byon/failover/AbstractKillManagementTest.java
@@ -1,173 +1,173 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.failover;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import iTests.framework.utils.*;
import org.cloudifysource.dsl.utils.ServiceUtils;
import org.cloudifysource.quality.iTests.framework.utils.*;
import iTests.framework.utils.AssertUtils.RepetitiveConditionProvider;
import org.cloudifysource.quality.iTests.test.AbstractTestSupport;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.byon.AbstractByonCloudTest;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.CloudService;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.byon.ByonCloudService;
import org.openspaces.admin.gsm.GridServiceManager;
import org.openspaces.admin.machine.Machine;
import org.openspaces.admin.pu.ProcessingUnit;
import com.gigaspaces.log.LogEntries;
import com.gigaspaces.log.LogEntryMatcher;
import com.gigaspaces.log.LogEntryMatchers;
public abstract class AbstractKillManagementTest extends AbstractByonCloudTest {
private static final String GSM_BACKUP_RECOVERED_PU = "Completed recovery of processing units from GSM";
private int numOManagementMachines = 2;
private GridServiceManager[] managers;
private ProcessingUnit tomcat;
private ProcessingUnit mongod;
private static final long TEN_SECONDS = 10 * 1000;
protected abstract Machine getMachineToKill();
public void installApplication() throws IOException, InterruptedException {
LogUtils.log("installing application petclinic on byon");
installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic");
admin.getGridServiceManagers().waitFor(2, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS);
managers = admin.getGridServiceManagers().getManagers();
tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS);
mongod = admin.getProcessingUnits().waitFor("petclinic.tomcat", AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS);
}
public void testKillMachine() throws Exception {
LogUtils.log("Before restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
Machine machine = getMachineToKill();
String machineAddress = machine.getHostAddress();
GridServiceManager otherManager = getManagerInOtherHostThen(machineAddress);
LogUtils.log("Restarting machine with ip " + machine.getHostAddress());
restartMachineAndWait(machineAddress, getService());
LogUtils.log("Restart was successfully");
LogUtils.log("waiting for backup GSM to manage the tomcat processing unit");
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(tomcat, otherManager));
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(mongod, otherManager));
LogUtils.log("Managing gsm of tomcat pu is now " + otherManager);
LogUtils.log("After restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
LogUtils.log("Petclinic application is alive.");
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " gsm's after failover",
admin.getGridServiceManagers().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
- AssertUtils.assertTrue("Could not find " + numOManagementMachines + " gsm's after failover",
+ AssertUtils.assertTrue("Could not find " + numOManagementMachines + " lus's after failover",
admin.getLookupServices().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " webui instances after failover",
admin.getProcessingUnits().getProcessingUnit("webui").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " rest after failover",
admin.getProcessingUnits().getProcessingUnit("rest").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " space after failover",
admin.getProcessingUnits().getProcessingUnit("cloudifyManagementSpace").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
repetitiveAssertBackupGsmRecoveredPu(tomcat); // see CLOUDIFY-1585
repetitiveAssertBackupGsmRecoveredPu(mongod); // see CLOUDIFY-1585
uninstallApplicationAndWait("petclinic");
}
protected void repetitiveAssertPetclinicUrlIsAvailable() {
RepetitiveConditionProvider condition = new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
String spec = null;
try {
String hostAddress = tomcat.getInstances()[0].getGridServiceContainer().getMachine().getHostAddress();
spec = "http://" + hostAddress + ":8080/petclinic/";
return ServiceUtils.isHttpURLAvailable(spec);
} catch (final Exception e) {
throw new RuntimeException("Error polling to URL : " + spec + " . Reason --> " + e.getMessage());
}
}
};
AssertUtils.repetitiveAssertTrue("petclinic url is not available! waited for 5 minutes", condition,
OPERATION_TIMEOUT);
}
private void repetitiveAssertBackupGsmRecoveredPu(final ProcessingUnit pu) {
final GridServiceManager[] backupGridServiceManagers = pu.getBackupGridServiceManagers();
assertEquals(1,backupGridServiceManagers.length);
LogUtils.log("Waiting for 1 "+ GSM_BACKUP_RECOVERED_PU + " log entry before undeploying PU");
final LogEntryMatcher logMatcher = LogEntryMatchers.containsString(GSM_BACKUP_RECOVERED_PU);
repetitiveAssertTrue("Expected " + GSM_BACKUP_RECOVERED_PU +" log", new RepetitiveConditionProvider() {
@Override
public boolean getCondition() {
final LogEntries logEntries = backupGridServiceManagers[0].logEntries(logMatcher);
final int count = logEntries.logEntries().size();
LogUtils.log("Exepcted at least one "+ GSM_BACKUP_RECOVERED_PU + " log entries. Actual :" + count);
return count > 0;
}
} , OPERATION_TIMEOUT);
}
/**
* this method accepts a host address and return a GridServiceManager that is not located at the given address.
* @param esmMachineAddress
* @return
*/
private GridServiceManager getManagerInOtherHostThen(
String esmMachineAddress) {
GridServiceManager result = null;
for (GridServiceManager manager : managers) {
if (!manager.getMachine().getHostAddress().equals(esmMachineAddress)) {
result = manager;
break;
}
}
return result;
}
protected Machine[] getGridServiceManagerMachines() {
GridServiceManager[] griServiceManagers = admin.getGridServiceManagers().getManagers();
Machine[] gsmMachines = new Machine[griServiceManagers.length];
for (int i = 0 ; i < griServiceManagers.length ; i++) {
gsmMachines[i] = griServiceManagers[i].getMachine();
}
return gsmMachines;
}
//TODO: add support for windows machines (BYON doesn't support windows right now)
protected void startManagement(String machine1) throws Exception {
for (int i = 0 ; i < 3 ; i++) {
try {
String managementMachineTemplate = getService().getCloud().getConfiguration().getManagementMachineTemplate();
String cloudFile = getService().getCloud().getCloudCompute().getTemplates().get(managementMachineTemplate).getRemoteDirectory() + "/byon-cloud.groovy";
SSHUtils.runCommand(machine1, AbstractTestSupport.DEFAULT_TEST_TIMEOUT, ByonCloudService.BYON_HOME_FOLDER + "/gigaspaces/tools/cli/cloudify.sh start-management --verbose -timeout 10 -cloud-file " + cloudFile, getService().getUser(), getService().getApiKey());
return;
} catch (Throwable t) {
LogUtils.log("Failed to start management on machine " + machine1 + " restarting machine before attempting again. attempt number " + (i + 1), t);
restartMachineAndWait(machine1, getService());
}
}
AssertUtils.assertFail("Failed starting management on host " + machine1);
}
public void restartMachineAndWait(final String machine, final CloudService service) throws Exception {
DisconnectionUtils.restartMachineAndWait(machine, service);
}
}
| true | true | public void testKillMachine() throws Exception {
LogUtils.log("Before restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
Machine machine = getMachineToKill();
String machineAddress = machine.getHostAddress();
GridServiceManager otherManager = getManagerInOtherHostThen(machineAddress);
LogUtils.log("Restarting machine with ip " + machine.getHostAddress());
restartMachineAndWait(machineAddress, getService());
LogUtils.log("Restart was successfully");
LogUtils.log("waiting for backup GSM to manage the tomcat processing unit");
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(tomcat, otherManager));
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(mongod, otherManager));
LogUtils.log("Managing gsm of tomcat pu is now " + otherManager);
LogUtils.log("After restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
LogUtils.log("Petclinic application is alive.");
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " gsm's after failover",
admin.getGridServiceManagers().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " gsm's after failover",
admin.getLookupServices().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " webui instances after failover",
admin.getProcessingUnits().getProcessingUnit("webui").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " rest after failover",
admin.getProcessingUnits().getProcessingUnit("rest").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " space after failover",
admin.getProcessingUnits().getProcessingUnit("cloudifyManagementSpace").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
repetitiveAssertBackupGsmRecoveredPu(tomcat); // see CLOUDIFY-1585
repetitiveAssertBackupGsmRecoveredPu(mongod); // see CLOUDIFY-1585
uninstallApplicationAndWait("petclinic");
}
| public void testKillMachine() throws Exception {
LogUtils.log("Before restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
Machine machine = getMachineToKill();
String machineAddress = machine.getHostAddress();
GridServiceManager otherManager = getManagerInOtherHostThen(machineAddress);
LogUtils.log("Restarting machine with ip " + machine.getHostAddress());
restartMachineAndWait(machineAddress, getService());
LogUtils.log("Restart was successfully");
LogUtils.log("waiting for backup GSM to manage the tomcat processing unit");
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(tomcat, otherManager));
AssertUtils.assertEquals("Wrong managing gsm for tomcat pu", otherManager, ProcessingUnitUtils.waitForManaged(mongod, otherManager));
LogUtils.log("Managing gsm of tomcat pu is now " + otherManager);
LogUtils.log("After restart, checking for liveness of petclinic application");
repetitiveAssertPetclinicUrlIsAvailable();
LogUtils.log("Petclinic application is alive.");
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " gsm's after failover",
admin.getGridServiceManagers().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " lus's after failover",
admin.getLookupServices().waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " webui instances after failover",
admin.getProcessingUnits().getProcessingUnit("webui").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " rest after failover",
admin.getProcessingUnits().getProcessingUnit("rest").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
AssertUtils.assertTrue("Could not find " + numOManagementMachines + " space after failover",
admin.getProcessingUnits().getProcessingUnit("cloudifyManagementSpace").waitFor(numOManagementMachines, AbstractTestSupport.OPERATION_TIMEOUT, TimeUnit.MILLISECONDS));
repetitiveAssertBackupGsmRecoveredPu(tomcat); // see CLOUDIFY-1585
repetitiveAssertBackupGsmRecoveredPu(mongod); // see CLOUDIFY-1585
uninstallApplicationAndWait("petclinic");
}
|
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchSettings.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchSettings.java
index 9d9821048..8ecbec9a5 100644
--- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchSettings.java
+++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchSettings.java
@@ -1,196 +1,196 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.keywordsearch;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ModuleSettings;
import org.sleuthkit.autopsy.coreutils.StringExtract;
import org.sleuthkit.autopsy.coreutils.StringExtract.StringExtractUnicodeTable.SCRIPT;
import org.sleuthkit.autopsy.keywordsearch.KeywordSearchIngestModule.UpdateFrequency;
//This file contains constants and settings for KeywordSearch
public class KeywordSearchSettings {
public static final String MODULE_NAME = "KeywordSearch";
static final String PROPERTIES_OPTIONS = MODULE_NAME+"_Options";
static final String PROPERTIES_NSRL = MODULE_NAME+"_NSRL";
static final String PROPERTIES_SCRIPTS = MODULE_NAME+"_Scripts";
private static boolean skipKnown = true;
private static final Logger logger = Logger.getLogger(KeywordSearchSettings.class.getName());
private static UpdateFrequency UpdateFreq = UpdateFrequency.AVG;
static List<StringExtract.StringExtractUnicodeTable.SCRIPT> stringExtractScripts = new ArrayList<StringExtract.StringExtractUnicodeTable.SCRIPT>();
static Map<String,String> stringExtractOptions = new HashMap<String,String>();
/**
* Gets the update Frequency from KeywordSearch_Options.properties
* @return KeywordSearchIngestModule's update frequency
*/
static UpdateFrequency getUpdateFrequency(){
if(ModuleSettings.getConfigSetting(PROPERTIES_OPTIONS, "UpdateFrequency") != null){
return UpdateFrequency.valueOf(ModuleSettings.getConfigSetting(PROPERTIES_OPTIONS, "UpdateFrequency"));
}
//if it failed, return the default/last known value
logger.log(Level.WARNING, "Could not read property for UpdateFrequency, returning backup value.");
return UpdateFreq;
}
/**
* Sets the update frequency and writes to KeywordSearch_Options.properties
* @param freq Sets KeywordSearchIngestModule to this value.
*/
static void setUpdateFrequency(UpdateFrequency freq){
ModuleSettings.setConfigSetting(PROPERTIES_OPTIONS, "UpdateFrequency", freq.name());
UpdateFreq = freq;
}
/**
* Sets whether or not to skip adding known good files to the search during index.
* @param skip
*/
static void setSkipKnown(boolean skip) {
ModuleSettings.setConfigSetting(PROPERTIES_NSRL, "SkipKnown", Boolean.toString(skip));
skipKnown = skip;
}
/**
* Gets the setting for whether or not this ingest is skipping adding known good files to the index.
* @return skip setting
*/
static boolean getSkipKnown() {
if(ModuleSettings.getConfigSetting(PROPERTIES_NSRL, "SkipKnown") != null){
return Boolean.parseBoolean(ModuleSettings.getConfigSetting(PROPERTIES_NSRL, "SkipKnown"));
}
//if it fails, return the default/last known value
logger.log(Level.WARNING, "Could not read property for SkipKnown, returning backup value.");
return skipKnown;
}
/**
* Sets what scripts to extract during ingest
* @param scripts List of scripts to extract
*/
static void setStringExtractScripts(List<StringExtract.StringExtractUnicodeTable.SCRIPT> scripts) {
stringExtractScripts.clear();
stringExtractScripts.addAll(scripts);
for(String s : ModuleSettings.getConfigSettings(PROPERTIES_SCRIPTS).keySet()){
if (! scripts.contains(StringExtract.StringExtractUnicodeTable.SCRIPT.valueOf(s))){
ModuleSettings.setConfigSetting(PROPERTIES_SCRIPTS, s, "false");
}
}
for(StringExtract.StringExtractUnicodeTable.SCRIPT s : stringExtractScripts){
ModuleSettings.setConfigSetting(PROPERTIES_SCRIPTS, s.name(), "true");
}
}
/**
* Set / override string extract option
* @param key option name to set
* @param val option value to set
*/
static void setStringExtractOption(String key, String val) {
stringExtractOptions.put(key, val);
ModuleSettings.setConfigSetting(PROPERTIES_OPTIONS, key, val);
}
/**
* gets the currently set scripts to use
*
* @return the list of currently used script
*/
static List<SCRIPT> getStringExtractScripts(){
if(ModuleSettings.getConfigSettings(PROPERTIES_SCRIPTS) != null && !ModuleSettings.getConfigSettings(PROPERTIES_SCRIPTS).isEmpty()){
List<SCRIPT> scripts = new ArrayList<SCRIPT>();
for(Map.Entry<String,String> kvp : ModuleSettings.getConfigSettings(PROPERTIES_SCRIPTS).entrySet()){
if(kvp.getValue().equals("true")){
scripts.add(SCRIPT.valueOf(kvp.getKey()));
}
}
return scripts;
}
//if it failed, try to return the built-in list maintained by the singleton.
logger.log(Level.WARNING, "Could not read properties for extracting scripts, returning backup values.");
return new ArrayList<SCRIPT>(stringExtractScripts);
}
/**
* get string extract option for the key
* @param key option name
* @return option string value, or empty string if the option is not set
*/
static String getStringExtractOption(String key) {
if (ModuleSettings.getConfigSetting(PROPERTIES_OPTIONS, key) != null){
return ModuleSettings.getConfigSetting(PROPERTIES_OPTIONS, key);
}
else {
logger.log(Level.WARNING, "Could not read property for Key "+ key + ", returning backup value.");
return stringExtractOptions.get(key);
}
}
/**
* Sets the default values of the KeywordSearch properties files if none already exist.
*/
static void setDefaults(){
logger.log(Level.INFO, "Detecting default settings.");
//setting default NSRL
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_NSRL, "SkipKnown")){
- logger.log(Level.INFO, "No configuration for NSRL not found, generating default...");
+ logger.log(Level.INFO, "No configuration for NSRL found, generating default...");
KeywordSearchSettings.setSkipKnown(true);
}
//setting default Update Frequency
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, "UpdateFrequency")){
- logger.log(Level.INFO, "No configuration for Update Frequency not found, generating default...");
+ logger.log(Level.INFO, "No configuration for Update Frequency found, generating default...");
KeywordSearchSettings.setUpdateFrequency(UpdateFrequency.AVG);
}
//setting default Extract UTF8
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString())){
- logger.log(Level.INFO, "No configuration for UTF8 not found, generating default...");
+ logger.log(Level.INFO, "No configuration for UTF8 found, generating default...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString(), Boolean.TRUE.toString());
}
//setting default Extract UTF16
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString())){
- logger.log(Level.INFO, "No configuration for UTF16 not found, generating defaults...");
+ logger.log(Level.INFO, "No configuration for UTF16 found, generating defaults...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString(), Boolean.TRUE.toString());
}
//setting default Latin-1 Script
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name())){
- logger.log(Level.INFO, "No configuration for Scripts not found, generating defaults...");
+ logger.log(Level.INFO, "No configuration for Scripts found, generating defaults...");
ModuleSettings.setConfigSetting(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name(), Boolean.toString(true));
}
}
}
| false | true | static void setDefaults(){
logger.log(Level.INFO, "Detecting default settings.");
//setting default NSRL
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_NSRL, "SkipKnown")){
logger.log(Level.INFO, "No configuration for NSRL not found, generating default...");
KeywordSearchSettings.setSkipKnown(true);
}
//setting default Update Frequency
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, "UpdateFrequency")){
logger.log(Level.INFO, "No configuration for Update Frequency not found, generating default...");
KeywordSearchSettings.setUpdateFrequency(UpdateFrequency.AVG);
}
//setting default Extract UTF8
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString())){
logger.log(Level.INFO, "No configuration for UTF8 not found, generating default...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString(), Boolean.TRUE.toString());
}
//setting default Extract UTF16
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString())){
logger.log(Level.INFO, "No configuration for UTF16 not found, generating defaults...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString(), Boolean.TRUE.toString());
}
//setting default Latin-1 Script
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name())){
logger.log(Level.INFO, "No configuration for Scripts not found, generating defaults...");
ModuleSettings.setConfigSetting(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name(), Boolean.toString(true));
}
}
| static void setDefaults(){
logger.log(Level.INFO, "Detecting default settings.");
//setting default NSRL
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_NSRL, "SkipKnown")){
logger.log(Level.INFO, "No configuration for NSRL found, generating default...");
KeywordSearchSettings.setSkipKnown(true);
}
//setting default Update Frequency
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, "UpdateFrequency")){
logger.log(Level.INFO, "No configuration for Update Frequency found, generating default...");
KeywordSearchSettings.setUpdateFrequency(UpdateFrequency.AVG);
}
//setting default Extract UTF8
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString())){
logger.log(Level.INFO, "No configuration for UTF8 found, generating default...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF8.toString(), Boolean.TRUE.toString());
}
//setting default Extract UTF16
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_OPTIONS, AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString())){
logger.log(Level.INFO, "No configuration for UTF16 found, generating defaults...");
KeywordSearchSettings.setStringExtractOption(AbstractFileExtract.ExtractOptions.EXTRACT_UTF16.toString(), Boolean.TRUE.toString());
}
//setting default Latin-1 Script
if(!ModuleSettings.settingExists(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name())){
logger.log(Level.INFO, "No configuration for Scripts found, generating defaults...");
ModuleSettings.setConfigSetting(KeywordSearchSettings.PROPERTIES_SCRIPTS, SCRIPT.LATIN_1.name(), Boolean.toString(true));
}
}
|
diff --git a/rmt/src/test/java/de/flower/rmt/ui/page/user/manager/PlayerTeamsPanelTest.java b/rmt/src/test/java/de/flower/rmt/ui/page/user/manager/PlayerTeamsPanelTest.java
index 13e967cd..e9890ee9 100644
--- a/rmt/src/test/java/de/flower/rmt/ui/page/user/manager/PlayerTeamsPanelTest.java
+++ b/rmt/src/test/java/de/flower/rmt/ui/page/user/manager/PlayerTeamsPanelTest.java
@@ -1,56 +1,57 @@
package de.flower.rmt.ui.page.user.manager;
import de.flower.rmt.model.db.entity.Player_;
import de.flower.rmt.model.db.entity.User;
import de.flower.rmt.service.IPlayerManager;
import de.flower.rmt.test.AbstractRMTWicketMockitoTests;
import org.apache.wicket.Component;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.tester.FormTester;
import org.testng.annotations.Test;
import java.util.ArrayList;
import static org.mockito.Mockito.*;
/**
* @author flowerrrr
*/
public class PlayerTeamsPanelTest extends AbstractRMTWicketMockitoTests {
@SpringBean
private IPlayerManager playerManager;
@Test
public void testRender() {
final User user = testData.newUserWithTeams();
user.setId(1L); // make it act persisted
when(playerManager.findAllByUser(user, Player_.team)).thenReturn(user.getPlayers());
+ when(playerManager.sortByTeam(user.getPlayers())).thenReturn(user.getPlayers());
wicketTester.startComponentInPage(new PlayerTeamsPanel("panel", Model.of(user)));
wicketTester.dumpComponentWithPage();
wicketTester.assertVisible("list");
wicketTester.assertInvisible("noTeam");
// trigger onChange event
FormTester formTester = wicketTester.newFormTester("0:form"); // select first form of list of forms.
Component c = formTester.getForm().get("notification:input");
formTester.setValue(c, new ResourceModel("choice.player.notification.false").getObject());
wicketTester.executeAjaxEvent(c, "onchange");
// verify does complain about springbean injected mocks. must get mock directly from appContext
verify(playerManager, times(1)).save(user.getPlayers().get(0));
wicketTester.dumpAjaxResponse();
}
@Test
public void testNoTeam() {
final User user = testData.newUser();
when(playerManager.findAllByUser(user)).thenReturn(new ArrayList());
wicketTester.startComponentInPage(new PlayerTeamsPanel("panel", Model.of(user)));
wicketTester.dumpComponentWithPage();
wicketTester.assertVisible("noTeam");
wicketTester.assertInvisible("list");
}
}
| true | true | public void testRender() {
final User user = testData.newUserWithTeams();
user.setId(1L); // make it act persisted
when(playerManager.findAllByUser(user, Player_.team)).thenReturn(user.getPlayers());
wicketTester.startComponentInPage(new PlayerTeamsPanel("panel", Model.of(user)));
wicketTester.dumpComponentWithPage();
wicketTester.assertVisible("list");
wicketTester.assertInvisible("noTeam");
// trigger onChange event
FormTester formTester = wicketTester.newFormTester("0:form"); // select first form of list of forms.
Component c = formTester.getForm().get("notification:input");
formTester.setValue(c, new ResourceModel("choice.player.notification.false").getObject());
wicketTester.executeAjaxEvent(c, "onchange");
// verify does complain about springbean injected mocks. must get mock directly from appContext
verify(playerManager, times(1)).save(user.getPlayers().get(0));
wicketTester.dumpAjaxResponse();
}
| public void testRender() {
final User user = testData.newUserWithTeams();
user.setId(1L); // make it act persisted
when(playerManager.findAllByUser(user, Player_.team)).thenReturn(user.getPlayers());
when(playerManager.sortByTeam(user.getPlayers())).thenReturn(user.getPlayers());
wicketTester.startComponentInPage(new PlayerTeamsPanel("panel", Model.of(user)));
wicketTester.dumpComponentWithPage();
wicketTester.assertVisible("list");
wicketTester.assertInvisible("noTeam");
// trigger onChange event
FormTester formTester = wicketTester.newFormTester("0:form"); // select first form of list of forms.
Component c = formTester.getForm().get("notification:input");
formTester.setValue(c, new ResourceModel("choice.player.notification.false").getObject());
wicketTester.executeAjaxEvent(c, "onchange");
// verify does complain about springbean injected mocks. must get mock directly from appContext
verify(playerManager, times(1)).save(user.getPlayers().get(0));
wicketTester.dumpAjaxResponse();
}
|
diff --git a/src/main/java/net/pterodactylus/reactor/states/HttpState.java b/src/main/java/net/pterodactylus/reactor/states/HttpState.java
index 38ca80c..442106b 100644
--- a/src/main/java/net/pterodactylus/reactor/states/HttpState.java
+++ b/src/main/java/net/pterodactylus/reactor/states/HttpState.java
@@ -1,154 +1,154 @@
/*
* Reactor - HttpState.java - Copyright © 2013 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.pterodactylus.reactor.states;
import java.io.UnsupportedEncodingException;
import net.pterodactylus.reactor.State;
import net.pterodactylus.reactor.queries.HttpQuery;
import org.apache.http.HeaderElement;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicHeaderValueParser;
/**
* {@link State} that contains the results of an {@link HttpQuery}.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class HttpState extends AbstractState {
/** The URI that was requested. */
private final String uri;
/** The protocol code. */
private final int protocolCode;
/** The content type. */
private final String contentType;
/** The result. */
private final byte[] rawResult;
/**
* Creates a new HTTP state.
*
* @param uri
* The URI that was requested
* @param protocolCode
* The code of the reply
* @param contentType
* The content type of the reply
* @param rawResult
* The raw result
*/
public HttpState(String uri, int protocolCode, String contentType, byte[] rawResult) {
this.uri = uri;
this.protocolCode = protocolCode;
this.contentType = contentType;
this.rawResult = rawResult;
}
//
// ACCESSORS
//
/**
* Returns the URI that was requested.
*
* @return The URI that was request
*/
public String uri() {
return uri;
}
/**
* Returns the protocol code of the reply.
*
* @return The protocol code of the reply
*/
public int protocolCode() {
return protocolCode;
}
/**
* Returns the content type of the reply.
*
* @return The content type of the reply
*/
public String contentType() {
return contentType;
}
/**
* Returns the raw result of the reply.
*
* @return The raw result of the reply
*/
public byte[] rawResult() {
return rawResult;
}
/**
* Returns the decoded content of the reply. This method uses the charset
* information from the {@link #contentType()}, if present, or UTF-8 if no
* content type is present.
*
* @return The decoded content
*/
public String content() {
try {
return new String(rawResult(), extractCharset(contentType()));
} catch (UnsupportedEncodingException uee1) {
throw new RuntimeException(String.format("Could not decode content as %s.", extractCharset(contentType())), uee1);
}
}
//
// STATIC METHODS
//
/**
* Extracts charset information from the given content type.
*
* @param contentType
* The content type response header
* @return The extracted charset, or UTF-8 if no charset could be extracted
*/
private static String extractCharset(String contentType) {
if (contentType == null) {
- return "UTF-8";
+ return "ISO-8859-1";
}
HeaderElement headerElement = BasicHeaderValueParser.parseHeaderElement(contentType, new BasicHeaderValueParser());
NameValuePair charset = headerElement.getParameterByName("charset");
- return (charset != null) ? charset.getValue() : "UTF-8";
+ return (charset != null) ? charset.getValue() : "ISO-8859-1";
}
//
// OBJECT METHODS
//
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("%s[uri=%s,protocolCode=%d,contentType=%s,rawResult=(%s bytes)]", getClass().getSimpleName(), uri(), protocolCode(), contentType(), rawResult().length);
}
}
| false | true | private static String extractCharset(String contentType) {
if (contentType == null) {
return "UTF-8";
}
HeaderElement headerElement = BasicHeaderValueParser.parseHeaderElement(contentType, new BasicHeaderValueParser());
NameValuePair charset = headerElement.getParameterByName("charset");
return (charset != null) ? charset.getValue() : "UTF-8";
}
| private static String extractCharset(String contentType) {
if (contentType == null) {
return "ISO-8859-1";
}
HeaderElement headerElement = BasicHeaderValueParser.parseHeaderElement(contentType, new BasicHeaderValueParser());
NameValuePair charset = headerElement.getParameterByName("charset");
return (charset != null) ? charset.getValue() : "ISO-8859-1";
}
|
diff --git a/src/main/java/uk/co/revthefox/foxbot/Utils.java b/src/main/java/uk/co/revthefox/foxbot/Utils.java
index d489bb2..a2f5c81 100644
--- a/src/main/java/uk/co/revthefox/foxbot/Utils.java
+++ b/src/main/java/uk/co/revthefox/foxbot/Utils.java
@@ -1,77 +1,77 @@
package uk.co.revthefox.foxbot;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import org.pircbotx.Channel;
import org.pircbotx.Colors;
import org.pircbotx.User;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils
{
private FoxBot foxbot;
private AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
private Response response;
public Utils(FoxBot foxbot)
{
this.foxbot = foxbot;
}
public String parseChatUrl(String stringToParse, User sender, Channel channel)
{
- String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
+ String pattern = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(stringToParse);
if (!matcher.matches())
{
return "";
}
stringToParse = matcher.group();
try
{
Future<Response> future = asyncHttpClient.prepareGet(stringToParse).execute();
response = future.get();
}
catch (IOException ex)
{
ex.printStackTrace();
return "";
}
catch (InterruptedException ex)
{
ex.printStackTrace();
return "";
}
catch (ExecutionException ex)
{
System.out.println("That last URL appeared to be invalid...");
return "";
}
try
{
stringToParse = response.getResponseBody().toString();
}
catch (IOException ex)
{
ex.printStackTrace();
}
Pattern titlePattern = Pattern.compile("<head>.*?<title>(.*?)</title>.*?</head>", Pattern.DOTALL);
Matcher m = titlePattern.matcher(stringToParse);
while (m.find()) {
stringToParse = m.group(1);
}
return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("'", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType());
}
}
| true | true | public String parseChatUrl(String stringToParse, User sender, Channel channel)
{
String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(stringToParse);
if (!matcher.matches())
{
return "";
}
stringToParse = matcher.group();
try
{
Future<Response> future = asyncHttpClient.prepareGet(stringToParse).execute();
response = future.get();
}
catch (IOException ex)
{
ex.printStackTrace();
return "";
}
catch (InterruptedException ex)
{
ex.printStackTrace();
return "";
}
catch (ExecutionException ex)
{
System.out.println("That last URL appeared to be invalid...");
return "";
}
try
{
stringToParse = response.getResponseBody().toString();
}
catch (IOException ex)
{
ex.printStackTrace();
}
Pattern titlePattern = Pattern.compile("<head>.*?<title>(.*?)</title>.*?</head>", Pattern.DOTALL);
Matcher m = titlePattern.matcher(stringToParse);
while (m.find()) {
stringToParse = m.group(1);
}
return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("'", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType());
}
| public String parseChatUrl(String stringToParse, User sender, Channel channel)
{
String pattern = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(stringToParse);
if (!matcher.matches())
{
return "";
}
stringToParse = matcher.group();
try
{
Future<Response> future = asyncHttpClient.prepareGet(stringToParse).execute();
response = future.get();
}
catch (IOException ex)
{
ex.printStackTrace();
return "";
}
catch (InterruptedException ex)
{
ex.printStackTrace();
return "";
}
catch (ExecutionException ex)
{
System.out.println("That last URL appeared to be invalid...");
return "";
}
try
{
stringToParse = response.getResponseBody().toString();
}
catch (IOException ex)
{
ex.printStackTrace();
}
Pattern titlePattern = Pattern.compile("<head>.*?<title>(.*?)</title>.*?</head>", Pattern.DOTALL);
Matcher m = titlePattern.matcher(stringToParse);
while (m.find()) {
stringToParse = m.group(1);
}
return String.format("(%s's URL) %sTitle: %s%s %sContent type: %s%s", sender.getNick(), Colors.GREEN, Colors.NORMAL, stringToParse.replace("'", "'"), Colors.GREEN, Colors.NORMAL, response.getContentType());
}
|
diff --git a/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java b/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
index f6f5654cf..289eb105b 100644
--- a/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
+++ b/modules/DesktopImport/src/main/java/org/gephi/desktop/importer/ReportPanel.java
@@ -1,843 +1,844 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2011 Gephi Consortium. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s):
Portions Copyrighted 2011 Gephi Consortium.
*/
package org.gephi.desktop.importer;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JRootPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.gephi.io.importer.api.Container;
import org.gephi.io.importer.api.ContainerUnloader;
import org.gephi.io.importer.api.EdgeDirectionDefault;
import org.gephi.io.importer.api.EdgeWeightMergeStrategy;
import org.gephi.io.importer.api.Issue;
import org.gephi.io.importer.api.Report;
import org.gephi.io.processor.spi.Processor;
import org.gephi.io.processor.spi.ProcessorUI;
import org.gephi.ui.components.BusyUtils;
import org.netbeans.swing.outline.DefaultOutlineModel;
import org.netbeans.swing.outline.OutlineModel;
import org.netbeans.swing.outline.RenderDataProvider;
import org.netbeans.swing.outline.RowModel;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
/**
*
* @author Mathieu Bastian
*/
public class ReportPanel extends javax.swing.JPanel {
//Preferences
private final static String SHOW_ISSUES = "ReportPanel_Show_Issues";
private final static String SHOW_REPORT = "ReportPanel_Show_Report";
private final static int ISSUES_LIMIT = 5000;
private ThreadGroup fillingThreads;
//Icons
private ImageIcon infoIcon;
private ImageIcon warningIcon;
private ImageIcon severeIcon;
private ImageIcon criticalIcon;
//Container
private Container container;
//UI
private ButtonGroup processorGroup = new ButtonGroup();
public ReportPanel() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
initComponents();
initIcons();
initProcessors();
initProcessorsUI();
initMoreOptionsPanel();
initMergeStrategyCombo();
}
});
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (InvocationTargetException ex) {
Exceptions.printStackTrace(ex);
}
fillingThreads = new ThreadGroup("Report Panel Issues");
graphTypeCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int g = graphTypeCombo.getSelectedIndex();
switch (g) {
case 0:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.DIRECTED);
break;
case 1:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.UNDIRECTED);
break;
case 2:
container.getLoader().setEdgeDefault(EdgeDirectionDefault.MIXED);
break;
}
}
});
autoscaleCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (autoscaleCheckbox.isSelected() != container.getUnloader().isAutoScale()) {
container.getLoader().setAutoScale(autoscaleCheckbox.isSelected());
}
}
});
createMissingNodesCheckbox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (createMissingNodesCheckbox.isSelected() != container.getUnloader().allowAutoNode()) {
container.getLoader().setAllowAutoNode(createMissingNodesCheckbox.isSelected());
}
}
});
moreOptionsLink.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
moreOptionsPanel.setVisible(!moreOptionsPanel.isVisible());
JRootPane rootPane = SwingUtilities.getRootPane(ReportPanel.this);
((JDialog) rootPane.getParent()).pack();
}
});
edgesMergeStrategyCombo.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int g = edgesMergeStrategyCombo.getSelectedIndex();
switch (g) {
case 0:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.SUM);
break;
case 1:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.AVG);
break;
case 2:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.MIN);
break;
case 3:
container.getLoader().setEdgesMergeStrategy(EdgeWeightMergeStrategy.MAX);
break;
}
}
});
selfLoopCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (selfLoopCheckBox.isSelected() != container.getUnloader().allowSelfLoop()) {
container.getLoader().setAllowSelfLoop(selfLoopCheckBox.isSelected());
}
}
});
}
public void initIcons() {
infoIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/info.png"));
warningIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/warning.gif"));
severeIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/severe.png"));
criticalIcon = new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/importer/resources/critical.png"));
}
public void setData(Report report, Container container) {
this.container = container;
initGraphTypeCombo(container);
report.pruneReport(ISSUES_LIMIT);
fillIssues(report);
fillReport(report);
fillStats(container);
fillParameters(container);
}
private void removeTabbedPane() {
tabbedPane.setVisible(false);
}
private void initMergeStrategyCombo() {
DefaultComboBoxModel mergeStrategryModel = new DefaultComboBoxModel(new String[]{
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.sum"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.avg"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.min"),
NbBundle.getMessage(ReportPanel.class, "ReportPanel.mergeStrategy.max")});
edgesMergeStrategyCombo.setModel(mergeStrategryModel);
}
private void initMoreOptionsPanel() {
moreOptionsPanel.setVisible(false);
}
private void initGraphTypeCombo(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
String directedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.directed");
String undirectedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.undirected");
String mixedStr = NbBundle.getMessage(ReportPanel.class, "ReportPanel.graphType.mixed");
DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
EdgeDirectionDefault dir = container.getUnloader().getEdgeDefault();
switch (dir) {
case DIRECTED:
comboModel.addElement(directedStr);
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
case UNDIRECTED:
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
case MIXED:
comboModel.addElement(directedStr);
comboModel.addElement(undirectedStr);
comboModel.addElement(mixedStr);
break;
}
graphTypeCombo.setModel(comboModel);
}
});
}
private void fillIssues(Report report) {
final List<Issue> issues = report.getIssues();
if (issues.isEmpty()) {
JLabel label = new JLabel(NbBundle.getMessage(getClass(), "ReportPanel.noIssues"));
label.setHorizontalAlignment(SwingConstants.CENTER);
tab1ScrollPane.setViewportView(label);
} else {
//Busy label
final BusyUtils.BusyLabel busyLabel = BusyUtils.createCenteredBusyLabel(tab1ScrollPane, "Retrieving issues...", issuesOutline);
//Thread
Thread thread = new Thread(fillingThreads, new Runnable() {
@Override
public void run() {
busyLabel.setBusy(true);
final TreeModel treeMdl = new IssueTreeModel(issues);
final OutlineModel mdl = DefaultOutlineModel.createOutlineModel(treeMdl, new IssueRowModel(), true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
issuesOutline.setRootVisible(false);
issuesOutline.setRenderDataProvider(new IssueRenderer());
issuesOutline.setModel(mdl);
busyLabel.setBusy(false);
}
});
}
}, "Report Panel Issues Outline");
if (NbPreferences.forModule(ReportPanel.class).getBoolean(SHOW_ISSUES, true)) {
thread.start();
}
}
}
private void fillReport(final Report report) {
Thread thread = new Thread(fillingThreads, new Runnable() {
@Override
public void run() {
final String str = report.getText();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
reportEditor.setText(str);
}
});
}
}, "Report Panel Issues Report");
if (NbPreferences.forModule(ReportPanel.class).getBoolean(SHOW_REPORT, true)) {
thread.start();
}
}
private void fillParameters(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//Autoscale
autoscaleCheckbox.setSelected(container.getUnloader().isAutoScale());
selfLoopCheckBox.setSelected(container.getUnloader().allowSelfLoop());
createMissingNodesCheckbox.setSelected(container.getUnloader().allowAutoNode());
switch (container.getUnloader().getEdgeDefault()) {
case DIRECTED:
graphTypeCombo.setSelectedIndex(0);
break;
case UNDIRECTED:
graphTypeCombo.setSelectedIndex(1);
break;
case MIXED:
graphTypeCombo.setSelectedIndex(2);
break;
}
switch (container.getUnloader().getEdgesMergeStrategy()) {
case SUM:
edgesMergeStrategyCombo.setSelectedIndex(0);
break;
case AVG:
edgesMergeStrategyCombo.setSelectedIndex(1);
break;
case MIN:
edgesMergeStrategyCombo.setSelectedIndex(2);
break;
case MAX:
edgesMergeStrategyCombo.setSelectedIndex(3);
break;
}
}
});
}
private void fillStats(final Container container) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//Source
String source = container.getSource();
String[] label = source.split("\\.");
if (label.length > 2 && label[label.length - 2].matches("\\d+")) { //case of temp file
source = source.replaceFirst("." + label[label.length - 2], "");
}
sourceLabel.setText(source);
ContainerUnloader unloader = container.getUnloader();
//Node & Edge count
int nodeCount = unloader.getNodeCount();
int edgeCount = unloader.getEdgeCount();
nodeCountLabel.setText("" + nodeCount);
edgeCountLabel.setText("" + edgeCount);
//Dynamic & Hierarchical graph
String yes = NbBundle.getMessage(getClass(), "ReportPanel.yes");
String no = NbBundle.getMessage(getClass(), "ReportPanel.no");
dynamicLabel.setText(container.isDynamicGraph() ? yes : no);
multigraphLabel.setText(container.isMultiGraph() ? yes : no);
}
});
}
private static final Object PROCESSOR_KEY = new Object();
private void initProcessors() {
int i = 0;
for (Processor processor : Lookup.getDefault().lookupAll(Processor.class)) {
JRadioButton radio = new JRadioButton(processor.getDisplayName());
radio.setSelected(i == 0);
radio.putClientProperty(PROCESSOR_KEY, processor);
processorGroup.add(radio);
GridBagConstraints constraints = new GridBagConstraints(0, i++, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
processorPanel.add(radio, constraints);
}
}
private void initProcessorsUI() {
for (Enumeration<AbstractButton> enumeration = processorGroup.getElements(); enumeration.hasMoreElements();) {
AbstractButton radioButton = enumeration.nextElement();
Processor p = (Processor) radioButton.getClientProperty(PROCESSOR_KEY);
//Enabled
ProcessorUI pui = getProcessorUI(p);
if (pui != null) {
radioButton.setEnabled(pui.isValid(container));
}
}
}
public void destroy() {
fillingThreads.interrupt();
}
public Processor getProcessor() {
for (Enumeration<AbstractButton> enumeration = processorGroup.getElements(); enumeration.hasMoreElements();) {
AbstractButton radioButton = enumeration.nextElement();
if (radioButton.isSelected()) {
return (Processor) radioButton.getClientProperty(PROCESSOR_KEY);
}
}
return null;
}
private ProcessorUI getProcessorUI(Processor processor) {
for (ProcessorUI pui : Lookup.getDefault().lookupAll(ProcessorUI.class)) {
if (pui.isUIFoProcessor(processor)) {
return pui;
}
}
return null;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
+ moreOptionsLink.setClickedColor(new java.awt.Color(0, 51, 255));
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(processorPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JCheckBox autoscaleCheckbox;
private javax.swing.JCheckBox createMissingNodesCheckbox;
private javax.swing.JLabel dynamicLabel;
private javax.swing.JLabel edgeCountLabel;
private javax.swing.JComboBox edgesMergeStrategyCombo;
private javax.swing.JComboBox graphTypeCombo;
private org.netbeans.swing.outline.Outline issuesOutline;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel labelDynamic;
private javax.swing.JLabel labelEdgeCount;
private javax.swing.JLabel labelGraphType;
private javax.swing.JLabel labelMultiGraph;
private javax.swing.JLabel labelNodeCount;
private javax.swing.JLabel labelParallelEdgesMergeStrategy;
private javax.swing.JLabel labelSrc;
private org.jdesktop.swingx.JXHyperlink moreOptionsLink;
private javax.swing.JPanel moreOptionsPanel;
private javax.swing.JLabel multigraphLabel;
private javax.swing.JLabel nodeCountLabel;
private javax.swing.JPanel processorPanel;
private javax.swing.ButtonGroup processorStrategyRadio;
private javax.swing.JEditorPane reportEditor;
private javax.swing.JCheckBox selfLoopCheckBox;
private javax.swing.JLabel sourceLabel;
private javax.swing.JPanel statsPanel;
private javax.swing.JScrollPane tab1ScrollPane;
private javax.swing.JScrollPane tab2ScrollPane;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration//GEN-END:variables
private class IssueTreeModel implements TreeModel {
private List<Issue> issues;
public IssueTreeModel(List<Issue> issues) {
this.issues = issues;
}
@Override
public Object getRoot() {
return "root";
}
@Override
public Object getChild(Object parent, int index) {
return issues.get(index);
}
@Override
public int getChildCount(Object parent) {
return issues.size();
}
@Override
public boolean isLeaf(Object node) {
if (node instanceof Issue) {
return true;
}
return false;
}
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
}
@Override
public int getIndexOfChild(Object parent, Object child) {
return issues.indexOf(child);
}
@Override
public void addTreeModelListener(TreeModelListener l) {
}
@Override
public void removeTreeModelListener(TreeModelListener l) {
}
}
private class IssueRowModel implements RowModel {
@Override
public int getColumnCount() {
return 1;
}
@Override
public Object getValueFor(Object node, int column) {
if (node instanceof Issue) {
Issue issue = (Issue) node;
return issue.getLevel().toString();
}
return "";
}
@Override
public Class getColumnClass(int column) {
return String.class;
}
@Override
public boolean isCellEditable(Object node, int column) {
return false;
}
@Override
public void setValueFor(Object node, int column, Object value) {
}
@Override
public String getColumnName(int column) {
return NbBundle.getMessage(ReportPanel.class, "ReportPanel.issueTable.issues");
}
}
private class IssueRenderer implements RenderDataProvider {
@Override
public String getDisplayName(Object o) {
Issue issue = (Issue) o;
return issue.getMessage();
}
@Override
public boolean isHtmlDisplayName(Object o) {
return false;
}
@Override
public Color getBackground(Object o) {
return null;
}
@Override
public Color getForeground(Object o) {
return null;
}
@Override
public String getTooltipText(Object o) {
return "";
}
@Override
public Icon getIcon(Object o) {
Issue issue = (Issue) o;
switch (issue.getLevel()) {
case INFO:
return infoIcon;
case WARNING:
return warningIcon;
case SEVERE:
return severeIcon;
case CRITICAL:
return criticalIcon;
}
return null;
}
}
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(processorPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
processorStrategyRadio = new javax.swing.ButtonGroup();
labelSrc = new javax.swing.JLabel();
sourceLabel = new javax.swing.JLabel();
tabbedPane = new javax.swing.JTabbedPane();
tab1ScrollPane = new javax.swing.JScrollPane();
issuesOutline = new org.netbeans.swing.outline.Outline();
tab2ScrollPane = new javax.swing.JScrollPane();
reportEditor = new javax.swing.JEditorPane();
labelGraphType = new javax.swing.JLabel();
graphTypeCombo = new javax.swing.JComboBox();
processorPanel = new javax.swing.JPanel();
statsPanel = new javax.swing.JPanel();
labelNodeCount = new javax.swing.JLabel();
labelEdgeCount = new javax.swing.JLabel();
nodeCountLabel = new javax.swing.JLabel();
edgeCountLabel = new javax.swing.JLabel();
dynamicLabel = new javax.swing.JLabel();
labelDynamic = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
labelMultiGraph = new javax.swing.JLabel();
multigraphLabel = new javax.swing.JLabel();
moreOptionsLink = new org.jdesktop.swingx.JXHyperlink();
moreOptionsPanel = new javax.swing.JPanel();
autoscaleCheckbox = new javax.swing.JCheckBox();
createMissingNodesCheckbox = new javax.swing.JCheckBox();
selfLoopCheckBox = new javax.swing.JCheckBox();
labelParallelEdgesMergeStrategy = new javax.swing.JLabel();
edgesMergeStrategyCombo = new javax.swing.JComboBox();
labelSrc.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelSrc.text")); // NOI18N
sourceLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.sourceLabel.text")); // NOI18N
tab1ScrollPane.setViewportView(issuesOutline);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab1ScrollPane.TabConstraints.tabTitle"), tab1ScrollPane); // NOI18N
tab2ScrollPane.setViewportView(reportEditor);
tabbedPane.addTab(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.tab2ScrollPane.TabConstraints.tabTitle"), tab2ScrollPane); // NOI18N
labelGraphType.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelGraphType.text")); // NOI18N
processorPanel.setLayout(new java.awt.GridBagLayout());
statsPanel.setLayout(new java.awt.GridBagLayout());
labelNodeCount.setFont(labelNodeCount.getFont().deriveFont(labelNodeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelNodeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelNodeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 6, 0);
statsPanel.add(labelNodeCount, gridBagConstraints);
labelEdgeCount.setFont(labelEdgeCount.getFont().deriveFont(labelEdgeCount.getFont().getStyle() | java.awt.Font.BOLD));
labelEdgeCount.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelEdgeCount.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
statsPanel.add(labelEdgeCount, gridBagConstraints);
nodeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
nodeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.nodeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 6, 0);
statsPanel.add(nodeCountLabel, gridBagConstraints);
edgeCountLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
edgeCountLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.edgeCountLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 0);
statsPanel.add(edgeCountLabel, gridBagConstraints);
dynamicLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.dynamicLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(dynamicLabel, gridBagConstraints);
labelDynamic.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelDynamic.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelDynamic, gridBagConstraints);
jLabel1.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.jLabel1.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
statsPanel.add(jLabel1, gridBagConstraints);
labelMultiGraph.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelMultiGraph.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 6, 0);
statsPanel.add(labelMultiGraph, gridBagConstraints);
multigraphLabel.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.multigraphLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 6, 0);
statsPanel.add(multigraphLabel, gridBagConstraints);
moreOptionsLink.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.moreOptionsLink.text")); // NOI18N
moreOptionsLink.setClickedColor(new java.awt.Color(0, 51, 255));
moreOptionsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
autoscaleCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.text")); // NOI18N
autoscaleCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.autoscaleCheckbox.toolTipText")); // NOI18N
createMissingNodesCheckbox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.text")); // NOI18N
createMissingNodesCheckbox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.createMissingNodesCheckbox.toolTipText")); // NOI18N
selfLoopCheckBox.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.text")); // NOI18N
selfLoopCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.selfLoopCheckBox.toolTipText")); // NOI18N
selfLoopCheckBox.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
labelParallelEdgesMergeStrategy.setText(org.openide.util.NbBundle.getMessage(ReportPanel.class, "ReportPanel.labelParallelEdgesMergeStrategy.text")); // NOI18N
javax.swing.GroupLayout moreOptionsPanelLayout = new javax.swing.GroupLayout(moreOptionsPanel);
moreOptionsPanel.setLayout(moreOptionsPanelLayout);
moreOptionsPanelLayout.setHorizontalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addComponent(autoscaleCheckbox, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(labelParallelEdgesMergeStrategy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(createMissingNodesCheckbox)
.addComponent(selfLoopCheckBox))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
moreOptionsPanelLayout.setVerticalGroup(
moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(moreOptionsPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(moreOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelParallelEdgesMergeStrategy)
.addComponent(edgesMergeStrategyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(autoscaleCheckbox))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(createMissingNodesCheckbox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selfLoopCheckBox)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabbedPane)
.addGroup(layout.createSequentialGroup()
.addComponent(labelSrc)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sourceLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(labelGraphType)
.addGap(18, 18, 18)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(processorPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8))))
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelSrc)
.addComponent(sourceLabel))
.addGap(18, 18, 18)
.addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(labelGraphType)
.addComponent(graphTypeCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(moreOptionsLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(moreOptionsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(processorPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/sql12/app/src/test/java/net/sourceforge/squirrel_sql/client/update/gui/installer/PreLaunchHelperImplIntegrationTest.java b/sql12/app/src/test/java/net/sourceforge/squirrel_sql/client/update/gui/installer/PreLaunchHelperImplIntegrationTest.java
index b57ad9de1..41c27d0bf 100644
--- a/sql12/app/src/test/java/net/sourceforge/squirrel_sql/client/update/gui/installer/PreLaunchHelperImplIntegrationTest.java
+++ b/sql12/app/src/test/java/net/sourceforge/squirrel_sql/client/update/gui/installer/PreLaunchHelperImplIntegrationTest.java
@@ -1,113 +1,113 @@
/*
* Copyright (C) 2007 Rob Manning
* [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
*/
package net.sourceforge.squirrel_sql.client.update.gui.installer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import net.sourceforge.squirrel_sql.client.ApplicationArguments;
import net.sourceforge.squirrel_sql.fw.util.FileWrapper;
import net.sourceforge.squirrel_sql.fw.util.FileWrapperFactory;
import net.sourceforge.squirrel_sql.fw.util.IOUtilities;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {})
@ContextConfiguration(locations = {
"/net/sourceforge/squirrel_sql/fw/util/net.sourceforge.squirrel_sql.fw.util.applicationContext.xml",
"/net/sourceforge/squirrel_sql/client/update/gui/installer/net.sourceforge.squirrel_sql.client.update.gui.installer.applicationContext.xml",
"/net/sourceforge/squirrel_sql/client/update/gui/installer/event/net.sourceforge.squirrel_sql.client.update.gui.installer.event.applicationContext.xml",
"/net/sourceforge/squirrel_sql/client/update/gui/installer/util/net.sourceforge.squirrel_sql.client.update.gui.installer.util.applicationContext.xml",
"/net/sourceforge/squirrel_sql/client/update/util/net.sourceforge.squirrel_sql.client.update.util.applicationContext.xml" })
public class PreLaunchHelperImplIntegrationTest extends AbstractJUnit4SpringContextTests
{
static
{
ApplicationArguments.initialize(new String[] { "-home", "./target" });
}
public static final String beanIdToTest =
"net.sourceforge.squirrel_sql.client.update.gui.installer.PreLaunchHelper";
private static final String SOURCE_SCRIPT_FILE_TO_TEST = "src/test/resources/squirrel-sql.sh";
private static final String TARGET_SCRIPT_FILE_TO_TEST = "target/squirrel-sql-copy.sh";
@Autowired
private IOUtilities ioutils;
@Autowired
private FileWrapperFactory _fileWrapperFactory;
/**
* This test confirms that the launch script can be updated to include the new Splash screen icon
* configuration.
*
* @throws IOException
*/
@Test
public void testUpdateLaunchScript() throws IOException
{
FileWrapper sourceScriptFile = _fileWrapperFactory.create(SOURCE_SCRIPT_FILE_TO_TEST);
FileWrapper targetScriptFile = _fileWrapperFactory.create(TARGET_SCRIPT_FILE_TO_TEST);
ioutils.copyFile(sourceScriptFile, targetScriptFile);
// Confirm that the script doesn't contain the splash screen icon setting.
checkScriptFile(false);
PreLaunchHelperImpl beanToTest = (PreLaunchHelperImpl) applicationContext.getBean(beanIdToTest);
beanToTest.setScriptLocation(TARGET_SCRIPT_FILE_TO_TEST);
beanToTest.updateLaunchScript();
// Confirm that the script now contain the splash screen icon setting.
checkScriptFile(true);
}
private void checkScriptFile(boolean containsSplashIconArgument) throws IOException
{
List<String> linesFromScriptFile = ioutils.getLinesFromFile(TARGET_SCRIPT_FILE_TO_TEST, null);
boolean foundMainClassLine = false;
for (String line : linesFromScriptFile)
{
if (line.contains(SplashScreenFixer.CLIENT_MAIN_CLASS))
{
foundMainClassLine = true;
if (!containsSplashIconArgument) {
- assertFalse(line.contains(SplashScreenFixer.SPLASH_ICON_ARGUMENT));
+ assertFalse(line.contains(SplashScreenFixer.SPLASH_ICON));
} else {
- assertTrue(line.contains(SplashScreenFixer.SPLASH_ICON_ARGUMENT));
+ assertTrue(line.contains(SplashScreenFixer.SPLASH_ICON));
}
}
}
Assert.assertTrue(foundMainClassLine);
}
}
| false | true | private void checkScriptFile(boolean containsSplashIconArgument) throws IOException
{
List<String> linesFromScriptFile = ioutils.getLinesFromFile(TARGET_SCRIPT_FILE_TO_TEST, null);
boolean foundMainClassLine = false;
for (String line : linesFromScriptFile)
{
if (line.contains(SplashScreenFixer.CLIENT_MAIN_CLASS))
{
foundMainClassLine = true;
if (!containsSplashIconArgument) {
assertFalse(line.contains(SplashScreenFixer.SPLASH_ICON_ARGUMENT));
} else {
assertTrue(line.contains(SplashScreenFixer.SPLASH_ICON_ARGUMENT));
}
}
}
Assert.assertTrue(foundMainClassLine);
}
| private void checkScriptFile(boolean containsSplashIconArgument) throws IOException
{
List<String> linesFromScriptFile = ioutils.getLinesFromFile(TARGET_SCRIPT_FILE_TO_TEST, null);
boolean foundMainClassLine = false;
for (String line : linesFromScriptFile)
{
if (line.contains(SplashScreenFixer.CLIENT_MAIN_CLASS))
{
foundMainClassLine = true;
if (!containsSplashIconArgument) {
assertFalse(line.contains(SplashScreenFixer.SPLASH_ICON));
} else {
assertTrue(line.contains(SplashScreenFixer.SPLASH_ICON));
}
}
}
Assert.assertTrue(foundMainClassLine);
}
|
diff --git a/src/uk/org/ponder/htmlutil/HTMLUtil.java b/src/uk/org/ponder/htmlutil/HTMLUtil.java
index c7e5d4c..0f3f435 100644
--- a/src/uk/org/ponder/htmlutil/HTMLUtil.java
+++ b/src/uk/org/ponder/htmlutil/HTMLUtil.java
@@ -1,125 +1,125 @@
/*
* Created on May 17, 2006
*/
package uk.org.ponder.htmlutil;
import java.util.Iterator;
import java.util.Map;
import uk.org.ponder.stringutil.CharWrap;
public class HTMLUtil {
public static void appendStyle(String style, String value, Map attrmap) {
String oldstyle = (String) attrmap.get("style");
if (oldstyle == null)
oldstyle = "";
oldstyle = oldstyle + " " + style + ": " + value + ";";
attrmap.put("style", oldstyle);
}
/**
* Parses a CSS string (separated by ; with keys named with :) into a
* key/value map of Strings to Strings
*/
public static void parseStyle(String style, Map toreceive) {
String[] styles = style.split(";");
for (int i = 0; i < styles.length; ++i) {
int colpos = styles[i].indexOf(':');
if (colpos == -1) {
throw new IllegalArgumentException("Style string " + styles[i]
+ " does not contain a colon character");
}
String key = styles[i].substring(0, colpos).trim();
String value = styles[i].substring(colpos + 1).trim();
toreceive.put(key, value);
}
}
public static String renderStyle(Map torender) {
CharWrap togo = new CharWrap();
for (Iterator sit = torender.keySet().iterator(); sit.hasNext();) {
String key = (String) sit.next();
String value = (String) torender.get(key);
if (togo.size != 0) {
togo.append(' ');
}
togo.append(key).append(": ").append(value).append(';');
}
return togo.toString();
}
/**
* Constructs the String representing a Javascript array declaration.
*
* @param name The Javascript name of the required array
* @param elements The values of the elements to be rendered.
* @deprecated Use the JSON encoder directly
*/
public static String emitJavascriptArray(String name, String[] elements) {
CharWrap togo = new CharWrap();
togo.append(" ").append(name).append(" = ").append("[\"");
for (int i = 0; i < elements.length; ++i) {
togo.append(elements[i]);
if (i != elements.length - 1) {
togo.append("\", \"");
}
}
togo.append("\"];\n");
return togo.toString();
}
/** Emits the text for a single Javascript call taking a single argument
* @see #emitJavascriptCall(String, String[])
* **/
public static String emitJavascriptCall(String name, String argument, boolean quote) {
return emitJavascriptCall(name, new String[] {argument});
}
/** Emits the text for a single Javascript call taking a single argument
* @see #emitJavascriptCall(String, String[])
* **/
public static String emitJavascriptCall(String name, String argument) {
return emitJavascriptCall(name, new String[] {argument}, true);
}
/** Emits the text for a single Javascript call, that is
* <code>name(arguments[0], arguments[1]) ...)</code>
* @param name The name of the JS function to be invoked
* @param arguments The function arguments to be applied.
*/
public static String emitJavascriptCall(String name, String[] arguments) {
return emitJavascriptCall(name, arguments, true);
}
/** Emits the text for a single Javascript call, that is
* <code>name(arguments[0], arguments[1]) ...)</code>
* @param name The name of the JS function to be invoked
* @param arguments The function arguments to be applied.
* @param quote <code>true</code> if the arguments are to be quoted as Javascript strings
*/
public static String emitJavascriptCall(String name, String[] arguments, boolean quote) {
CharWrap togo = new CharWrap();
togo.append(" ").append(name).append('(');
for (int i = 0; i < arguments.length; ++i) {
if (quote) togo.append('"');
togo.append(arguments[i]);
+ if (quote) togo.append('"');
if (i != arguments.length - 1) {
togo.append(", ");
}
- if (quote) togo.append('"');
}
togo.append(");\n");
return togo.toString();
}
/** The "natural" format accepted by Javascript's Date.parse() method **/
public static String JS_DATE_FORMAT = "MMMM, d yyyy HH:mm:ss";
public static String emitJavascriptVar(String name, String value) {
return " " + name + " = \"" + value + "\";\n";
}
}
| false | true | public static String emitJavascriptCall(String name, String[] arguments, boolean quote) {
CharWrap togo = new CharWrap();
togo.append(" ").append(name).append('(');
for (int i = 0; i < arguments.length; ++i) {
if (quote) togo.append('"');
togo.append(arguments[i]);
if (i != arguments.length - 1) {
togo.append(", ");
}
if (quote) togo.append('"');
}
togo.append(");\n");
return togo.toString();
}
| public static String emitJavascriptCall(String name, String[] arguments, boolean quote) {
CharWrap togo = new CharWrap();
togo.append(" ").append(name).append('(');
for (int i = 0; i < arguments.length; ++i) {
if (quote) togo.append('"');
togo.append(arguments[i]);
if (quote) togo.append('"');
if (i != arguments.length - 1) {
togo.append(", ");
}
}
togo.append(");\n");
return togo.toString();
}
|
diff --git a/net/rymate/SimpleWarp/WarpCommand.java b/net/rymate/SimpleWarp/WarpCommand.java
index e26dd43..1d5361c 100644
--- a/net/rymate/SimpleWarp/WarpCommand.java
+++ b/net/rymate/SimpleWarp/WarpCommand.java
@@ -1,80 +1,79 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.rymate.SimpleWarp;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.iConomy.*;
import com.iConomy.system.Account;
import com.iConomy.system.Holdings;
import org.bukkit.block.Block;
/**
*
* @author Ryan
*/
class WarpCommand implements CommandExecutor {
private final SimpleWarpPlugin plugin;
private iConomy iConomy;
public WarpCommand(SimpleWarpPlugin plugin) {
this.plugin = plugin;
plugin.iConomy = iConomy;
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
if ((plugin).permissionHandler.has(player, "warp.go")) {
if (args.length < 1) {
return false;
} else if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Location loc = (Location) plugin.m_warps.get(args[0]);
if ((loc != null) && (plugin.useEconomy = true) && (iConomy != null)) {
Account account = iConomy.getAccount(player.getName());
Holdings balance = iConomy.getAccount(player.getName()).getHoldings();
if ((account != null) && balance.hasEnough(plugin.warpPrice)) {
balance.subtract(plugin.warpPrice);
- //player.teleportTo(loc);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination! " + plugin.warpPrice + "was deducted from your money.");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough money :(");
}
} else if (loc != null) {
//player.teleportTo(loc);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination!");
} else {
player.sendMessage(ChatColor.RED + "There is no warp with that name!");
}
} else {
player.sendMessage(ChatColor.RED + "You do not have the permissions to use this command.");
}
return true;
}
private void warpPlayer(Player player, Location loc){
Block block = loc.getBlock();
while (block.getRelative(0, 1, 0).getTypeId() != 0 && block.getY() < 126) {
if (block.getRelative(0, 2, 0).getTypeId() != 0) {
block = block.getRelative(0, 3, 0);
} else {
block = block.getRelative(0, 2, 0);
}
}
player.teleport(new Location(block.getWorld(), block.getX(), block.getY(), block.getZ(), loc.getYaw(), loc.getPitch()));
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
if ((plugin).permissionHandler.has(player, "warp.go")) {
if (args.length < 1) {
return false;
} else if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Location loc = (Location) plugin.m_warps.get(args[0]);
if ((loc != null) && (plugin.useEconomy = true) && (iConomy != null)) {
Account account = iConomy.getAccount(player.getName());
Holdings balance = iConomy.getAccount(player.getName()).getHoldings();
if ((account != null) && balance.hasEnough(plugin.warpPrice)) {
balance.subtract(plugin.warpPrice);
//player.teleportTo(loc);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination! " + plugin.warpPrice + "was deducted from your money.");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough money :(");
}
} else if (loc != null) {
//player.teleportTo(loc);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination!");
} else {
player.sendMessage(ChatColor.RED + "There is no warp with that name!");
}
} else {
player.sendMessage(ChatColor.RED + "You do not have the permissions to use this command.");
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
if ((plugin).permissionHandler.has(player, "warp.go")) {
if (args.length < 1) {
return false;
} else if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You are not an in-game player!");
return true;
}
Location loc = (Location) plugin.m_warps.get(args[0]);
if ((loc != null) && (plugin.useEconomy = true) && (iConomy != null)) {
Account account = iConomy.getAccount(player.getName());
Holdings balance = iConomy.getAccount(player.getName()).getHoldings();
if ((account != null) && balance.hasEnough(plugin.warpPrice)) {
balance.subtract(plugin.warpPrice);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination! " + plugin.warpPrice + "was deducted from your money.");
} else {
player.sendMessage(ChatColor.RED + "You do not have enough money :(");
}
} else if (loc != null) {
//player.teleportTo(loc);
warpPlayer(player, loc);
player.sendMessage(ChatColor.GREEN + "You have arrived at your destination!");
} else {
player.sendMessage(ChatColor.RED + "There is no warp with that name!");
}
} else {
player.sendMessage(ChatColor.RED + "You do not have the permissions to use this command.");
}
return true;
}
|
diff --git a/core/src/main/java/org/mobicents/ha/javax/sip/LoadBalancerHeartBeatingServiceImpl.java b/core/src/main/java/org/mobicents/ha/javax/sip/LoadBalancerHeartBeatingServiceImpl.java
index b101022..73915d2 100644
--- a/core/src/main/java/org/mobicents/ha/javax/sip/LoadBalancerHeartBeatingServiceImpl.java
+++ b/core/src/main/java/org/mobicents/ha/javax/sip/LoadBalancerHeartBeatingServiceImpl.java
@@ -1,683 +1,687 @@
/*
* TeleStax, Open Source Cloud Communications.
* Copyright 2011-2013 and individual contributors by the @authors tag.
*
* 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.mobicents.ha.javax.sip;
import gov.nist.core.CommonLogger;
import gov.nist.core.StackLogger;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.management.ObjectName;
import javax.sip.ListeningPoint;
import org.mobicents.ha.javax.sip.util.Inet6Util;
import org.mobicents.tools.sip.balancer.NodeRegisterRMIStub;
import org.mobicents.tools.sip.balancer.SIPNode;
/**
* <p>implementation of the <code>LoadBalancerHeartBeatingService</code> interface.</p>
*
* <p>
* It sends heartbeats and health information to the sip balancers configured through the stack property org.mobicents.ha.javax.sip.BALANCERS
* </p>
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class LoadBalancerHeartBeatingServiceImpl implements LoadBalancerHeartBeatingService, LoadBalancerHeartBeatingServiceImplMBean {
private static StackLogger logger = CommonLogger.getLogger(LoadBalancerHeartBeatingServiceImpl.class);
public static String LB_HB_SERVICE_MBEAN_NAME = "org.mobicents.jain.sip:type=load-balancer-heartbeat-service,name=";
public static final int DEFAULT_RMI_PORT = 2000;
public static final String BALANCER_SIP_PORT_CHAR_SEPARATOR = ":";
public static final String BALANCERS_CHAR_SEPARATOR = ";";
public static final int DEFAULT_LB_SIP_PORT = 5065;
ClusteredSipStack sipStack = null;
//the logger
//the balancers to send heartbeat to and our health info
protected String balancers;
//the jvmRoute for this node
protected String jvmRoute;
//the balancers names to send heartbeat to and our health info
protected Map<String, SipLoadBalancer> register = new ConcurrentHashMap<String, SipLoadBalancer>();
//heartbeat interval, can be modified through JMX
protected long heartBeatInterval = 5000;
protected Timer heartBeatTimer = new Timer();
protected TimerTask hearBeatTaskToRun = null;
protected List<String> cachedAnyLocalAddresses = new ArrayList<String>();
protected boolean started = false;
protected Set<LoadBalancerHeartBeatingListener> loadBalancerHeartBeatingListeners;
ObjectName oname = null;
public LoadBalancerHeartBeatingServiceImpl() {
loadBalancerHeartBeatingListeners = new CopyOnWriteArraySet<LoadBalancerHeartBeatingListener>();
}
public void init(ClusteredSipStack clusteredSipStack,
Properties stackProperties) {
sipStack = clusteredSipStack;
balancers = stackProperties.getProperty(BALANCERS);
heartBeatInterval = Integer.parseInt(stackProperties.getProperty(HEARTBEAT_INTERVAL, "5000"));
}
public void stopBalancer() {
stop();
}
public void start() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
stopBalancer();
logger.logInfo("Shutting down the Load Balancer Link");}
});
if (!started) {
if (balancers != null && balancers.length() > 0) {
String[] balancerDescriptions = balancers.split(BALANCERS_CHAR_SEPARATOR);
for (String balancerDescription : balancerDescriptions) {
String balancerAddress = balancerDescription;
int sipPort = DEFAULT_LB_SIP_PORT;
int rmiPort = DEFAULT_RMI_PORT;
if(balancerDescription.indexOf(BALANCER_SIP_PORT_CHAR_SEPARATOR) != -1) {
String[] balancerDescriptionSplitted = balancerDescription.split(BALANCER_SIP_PORT_CHAR_SEPARATOR);
balancerAddress = balancerDescriptionSplitted[0];
try {
sipPort = Integer.parseInt(balancerDescriptionSplitted[1]);
if(balancerDescriptionSplitted.length>2) {
rmiPort = Integer.parseInt(balancerDescriptionSplitted[2]);
}
} catch (NumberFormatException e) {
logger.logError("Impossible to parse the following sip balancer port " + balancerDescriptionSplitted[1], e);
}
}
if(Inet6Util.isValidIP6Address(balancerAddress) || Inet6Util.isValidIPV4Address(balancerAddress)) {
try {
this.addBalancer(InetAddress.getByName(balancerAddress).getHostAddress(), sipPort, rmiPort);
} catch (UnknownHostException e) {
logger.logError("Impossible to parse the following sip balancer address " + balancerAddress, e);
}
} else {
this.addBalancer(balancerAddress, sipPort, 0, rmiPort);
}
}
}
started = true;
}
this.hearBeatTaskToRun = new BalancerPingTimerTask();
// Delay the start with 2 seconds so nodes joining under load are really ready to serve requests
// Otherwise one of the listeneing points comes a bit later and results in errors.
this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 2000,
this.heartBeatInterval);
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("Created and scheduled tasks for sending heartbeats to the sip balancer.");
}
registerMBean();
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("Load Balancer Heart Beating Service has been started");
}
}
public void stop() {
// Force removal from load balancer upon shutdown
// added for Issue 308 (http://code.google.com/p/mobicents/issues/detail?id=308)
ArrayList<SIPNode> info = getConnectorsAsSIPNode();
removeNodesFromBalancers(info);
//cleaning
// balancerNames.clear();
register.clear();
if(hearBeatTaskToRun != null) {
this.hearBeatTaskToRun.cancel();
}
this.hearBeatTaskToRun = null;
loadBalancerHeartBeatingListeners.clear();
started = false;
heartBeatTimer.cancel();
unRegisterMBean();
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("Load Balancer Heart Beating Service has been stopped");
}
}
protected void registerMBean() {
String mBeanName = LB_HB_SERVICE_MBEAN_NAME + sipStack.getStackName();
try {
oname = new ObjectName(mBeanName);
if (sipStack.getMBeanServer() != null && !sipStack.getMBeanServer().isRegistered(oname)) {
sipStack.getMBeanServer().registerMBean(this, oname);
}
} catch (Exception e) {
logger.logError("Could not register the Load Balancer Service as an MBean under the following name " + mBeanName, e);
}
}
protected void unRegisterMBean() {
String mBeanName = LB_HB_SERVICE_MBEAN_NAME + sipStack.getStackName();
try {
if (oname != null && sipStack.getMBeanServer() != null && sipStack.getMBeanServer().isRegistered(oname)) {
sipStack.getMBeanServer().unregisterMBean(oname);
}
} catch (Exception e) {
logger.logError("Could not unregister the stack as an MBean under the following name" + mBeanName);
}
}
/**
* {@inheritDoc}
*/
public long getHeartBeatInterval() {
return heartBeatInterval;
}
/**
* {@inheritDoc}
*/
public void setHeartBeatInterval(long heartBeatInterval) {
if (heartBeatInterval < 100)
return;
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("Setting HeartBeatInterval from " + this.heartBeatInterval + " to " + heartBeatInterval);
}
this.heartBeatInterval = heartBeatInterval;
this.hearBeatTaskToRun.cancel();
this.hearBeatTaskToRun = new BalancerPingTimerTask();
this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 0,
this.heartBeatInterval);
}
/**
*
* @param hostName
* @param index
* @return
*/
private InetAddress fetchHostAddress(String hostName, int index) {
if (hostName == null)
throw new NullPointerException("Host name cant be null!!!");
InetAddress[] hostAddr = null;
try {
hostAddr = InetAddress.getAllByName(hostName);
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException(
"HostName is not a valid host name or it doesnt exists in DNS",
uhe);
}
if (index < 0 || index >= hostAddr.length) {
throw new IllegalArgumentException(
"Index in host address array is wrong, it should be [0]<x<["
+ hostAddr.length + "] and it is [" + index + "]");
}
InetAddress address = hostAddr[index];
return address;
}
/**
* {@inheritDoc}
*/
public String[] getBalancers() {
return this.register.keySet().toArray(new String[register.keySet().size()]);
}
/**
* {@inheritDoc}
*/
public boolean addBalancer(String addr, int sipPort, int rmiPort) {
if (addr == null)
throw new NullPointerException("addr cant be null!!!");
InetAddress address = null;
try {
address = InetAddress.getByName(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException(
"Something wrong with host creation.", e);
}
String balancerName = address.getCanonicalHostName() + ":" + rmiPort;
if (register.get(balancerName) != null) {
logger.logInfo("Sip balancer " + balancerName + " already present, not added");
return false;
}
SipLoadBalancer sipLoadBalancer = new SipLoadBalancer(this, address, sipPort, rmiPort);
register.put(balancerName, sipLoadBalancer);
// notify the listeners
for (LoadBalancerHeartBeatingListener loadBalancerHeartBeatingListener : loadBalancerHeartBeatingListeners) {
loadBalancerHeartBeatingListener.loadBalancerAdded(sipLoadBalancer);
}
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("following balancer name : " + balancerName +"/address:"+ addr + " added");
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean addBalancer(String hostName, int sipPort, int index, int rmiPort) {
return this.addBalancer(fetchHostAddress(hostName, index)
.getHostAddress(), sipPort, rmiPort);
}
/**
* {@inheritDoc}
*/
public boolean removeBalancer(String addr, int sipPort, int rmiPort) {
if (addr == null)
throw new NullPointerException("addr cant be null!!!");
InetAddress address = null;
try {
address = InetAddress.getByName(addr);
} catch (UnknownHostException e) {
throw new IllegalArgumentException(
"Something wrong with host creation.", e);
}
SipLoadBalancer sipLoadBalancer = new SipLoadBalancer(this, address, sipPort, rmiPort);
String keyToRemove = null;
Iterator<String> keyIterator = register.keySet().iterator();
while (keyIterator.hasNext() && keyToRemove ==null) {
String key = keyIterator.next();
if(register.get(key).equals(sipLoadBalancer)) {
keyToRemove = key;
}
}
if(keyToRemove !=null ) {
register.remove(keyToRemove);
// notify the listeners
for (LoadBalancerHeartBeatingListener loadBalancerHeartBeatingListener : loadBalancerHeartBeatingListeners) {
loadBalancerHeartBeatingListener.loadBalancerRemoved(sipLoadBalancer);
}
if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("following balancer name : " + keyToRemove +"/address:"+ addr + " removed");
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public boolean removeBalancer(String hostName, int sipPort, int index, int rmiPort) {
InetAddress[] hostAddr = null;
try {
hostAddr = InetAddress.getAllByName(hostName);
} catch (UnknownHostException uhe) {
throw new IllegalArgumentException(
"HostName is not a valid host name or it doesnt exists in DNS",
uhe);
}
if (index < 0 || index >= hostAddr.length) {
throw new IllegalArgumentException(
"Index in host address array is wrong, it should be [0]<x<["
+ hostAddr.length + "] and it is [" + index + "]");
}
InetAddress address = hostAddr[index];
return this.removeBalancer(address.getHostAddress(), sipPort, rmiPort);
}
protected ArrayList<SIPNode> getConnectorsAsSIPNode() {
ArrayList<SIPNode> info = new ArrayList<SIPNode>();
Integer sipTcpPort = null;
Integer sipUdpPort = null;
+ Integer sipWsPort = null;
String address = null;
String hostName = null;
// Gathering info about server' sip listening points
Iterator<ListeningPoint> listeningPointIterator = sipStack.getListeningPoints();
while (listeningPointIterator.hasNext()) {
ListeningPoint listeningPoint = listeningPointIterator.next();
address = listeningPoint.getIPAddress();
// From Vladimir: for some reason I get "localhost" here instead of IP and this confiuses the LB
if(address.equals("localhost")) address = "127.0.0.1";
int port = listeningPoint.getPort();
String transport = listeningPoint.getTransport();
if(transport.equalsIgnoreCase("tcp")) {
sipTcpPort = port;
- } else if(transport.equals("udp")) {
+ } else if(transport.equalsIgnoreCase("udp")) {
sipUdpPort = port;
+ } else if(transport.equalsIgnoreCase("ws")) {
+ sipWsPort = port;
}
try {
InetAddress[] aArray = InetAddress
.getAllByName(address);
if (aArray != null && aArray.length > 0) {
// Damn it, which one we should pick?
hostName = aArray[0].getCanonicalHostName();
}
} catch (UnknownHostException e) {
logger.logError("An exception occurred while trying to retrieve the hostname of a sip connector", e);
}
}
List<String> ipAddresses = new ArrayList<String>();
boolean isAnyLocalAddress = false;
try {
isAnyLocalAddress = InetAddress.getByName(address).isAnyLocalAddress();
} catch (UnknownHostException e) {
logger.logWarning("Unable to enumerate mapped interfaces. Binding to 0.0.0.0 may not work.");
isAnyLocalAddress = false;
}
if(isAnyLocalAddress) {
if(cachedAnyLocalAddresses.isEmpty()) {
try{
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> bindings = networkInterface.getInetAddresses();
while(bindings.hasMoreElements()) {
InetAddress addr = bindings.nextElement();
String networkInterfaceIpAddress = addr.getHostAddress();
// we cache the look up to speed up the next time
cachedAnyLocalAddresses.add(networkInterfaceIpAddress);
}
}
} catch (SocketException e) {
logger.logWarning("Unable to enumerate network interfaces. Binding to 0.0.0.0 may not work.");
}
} else {
ipAddresses.addAll(cachedAnyLocalAddresses);
}
} else {
ipAddresses.add(address);
}
String httpPortString = System.getProperty("org.mobicents.properties.httpPort");
String sslPortString = System.getProperty("org.mobicents.properties.sslPort");
for (String ipAddress : ipAddresses) {
SIPNode node = new SIPNode(hostName, ipAddress);
int httpPort = 0;
int sslPort = 0;
if(httpPortString != null) {
httpPort = Integer.parseInt(httpPortString);
node.getProperties().put("httpPort", httpPort);
}
if(sslPortString != null) {
sslPort = Integer.parseInt(sslPortString);
node.getProperties().put("sslPort", sslPort);
}
if(sipTcpPort != null) node.getProperties().put("tcpPort", sipTcpPort);
if(sipUdpPort != null) node.getProperties().put("udpPort", sipUdpPort);
+ if(sipWsPort != null) node.getProperties().put("wsPort", sipWsPort);
if(jvmRoute != null) node.getProperties().put("jvmRoute", jvmRoute);
//, port,
// transports, jvmRoute, httpPort, sslPort, null);
node.getProperties().put("version", System.getProperty("org.mobicents.server.version", "0"));
info.add(node);
}
return info;
}
/**
* @param info
*/
protected void sendKeepAliveToBalancers(ArrayList<SIPNode> info) {
Thread.currentThread().setContextClassLoader(NodeRegisterRMIStub.class.getClassLoader());
for(SipLoadBalancer balancerDescription:new HashSet<SipLoadBalancer>(register.values())) {
try {
long startTime = System.currentTimeMillis();
Registry registry = LocateRegistry.getRegistry(balancerDescription.getAddress().getHostAddress(), balancerDescription.getRmiPort());
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
ArrayList<SIPNode> reachableInfo = getReachableSIPNodeInfo(balancerDescription.getAddress(), info);
if(reachableInfo.isEmpty()) {
logger.logWarning("All connectors are unreachable from the balancer");
}
reg.handlePing(reachableInfo);
balancerDescription.setDisplayWarning(true);
if(!balancerDescription.isAvailable()) {
logger.logInfo("Keepalive: SIP Load Balancer Found! " + balancerDescription);
}
balancerDescription.setAvailable(true);
startTime = System.currentTimeMillis() - startTime;
if(startTime>200)
logger.logWarning("Heartbeat sent too slow in " + startTime + " millis at " + System.currentTimeMillis());
} catch (IOException e) {
balancerDescription.setAvailable(false);
if(balancerDescription.isDisplayWarning()) {
logger.logWarning("sendKeepAlive: Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running. Host " + balancerDescription.toString());
}
balancerDescription.setDisplayWarning(false);
} catch (Exception e) {
balancerDescription.setAvailable(false);
if(balancerDescription.isDisplayWarning()) {
logger.logError("sendKeepAlive: Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running. Host " + balancerDescription.toString(), e);
}
balancerDescription.setDisplayWarning(false);
}
}
if(logger.isLoggingEnabled(StackLogger.TRACE_TRACE)) {
logger.logTrace("Finished gathering, Gathered info[" + info + "]");
}
}
/**
* Contribution from Naoki Nishihara from OKI for Issue 1806 (SIP LB can not forward when node is listening on 0.0.0.0)
* Useful for a multi homed address, tries to reach a given load balancer from the list of ip addresses given in param
* @param balancerAddr the load balancer to try to reach
* @param info the list of node info from which we try to access the load balancer
* @return the list stripped from the nodes not able to reach the load balancer
*/
protected ArrayList<SIPNode> getReachableSIPNodeInfo(InetAddress balancerAddr, ArrayList<SIPNode> info) {
if (balancerAddr.isLoopbackAddress()) {
return info;
}
ArrayList<SIPNode> rv = new ArrayList<SIPNode>();
for(SIPNode node: info) {
try {
NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getByName(node.getIp()));
// FIXME How can I determine the ttl?
boolean b = balancerAddr.isReachable(ni, 5, 900);
if(b) {
rv.add(node);
}
} catch (IOException e) {
logger.logError("IOException", e);
}
}
if(logger.isLoggingEnabled(StackLogger.TRACE_TRACE)) {
logger.logTrace("Reachable SIP Node:[balancer=" + balancerAddr + "],[node info=" + rv + "]");
}
return rv;
}
/**
* @param info
*/
protected void removeNodesFromBalancers(ArrayList<SIPNode> info) {
Thread.currentThread().setContextClassLoader(NodeRegisterRMIStub.class.getClassLoader());
for(SipLoadBalancer balancerDescription:new HashSet<SipLoadBalancer>(register.values())) {
try {
Registry registry = LocateRegistry.getRegistry(balancerDescription.getAddress().getHostAddress(),balancerDescription.getRmiPort());
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
reg.forceRemoval(info);
if(!balancerDescription.isAvailable()) {
logger.logInfo("Remove: SIP Load Balancer Found! " + balancerDescription);
balancerDescription.setDisplayWarning(true);
}
balancerDescription.setAvailable(true);
} catch (IOException e) {
if(balancerDescription.isDisplayWarning()) {
logger.logWarning("remove: Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.");
balancerDescription.setDisplayWarning(false);
}
balancerDescription.setAvailable(true);
} catch (Exception e) {
if(balancerDescription.isDisplayWarning()) {
logger.logError("remove: Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.", e);
balancerDescription.setDisplayWarning(false);
}
balancerDescription.setAvailable(true);
}
}
if(logger.isLoggingEnabled(StackLogger.TRACE_TRACE)) {
logger.logTrace("Finished gathering, Gathered info[" + info + "]");
}
}
/**
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
protected class BalancerPingTimerTask extends TimerTask {
@SuppressWarnings("unchecked")
@Override
public void run() {
ArrayList<SIPNode> info = getConnectorsAsSIPNode();
sendKeepAliveToBalancers(info);
}
}
/**
* @param balancers the balancers to set
*/
public void setBalancers(String balancers) {
this.balancers = balancers;
}
/**
* @return the jvmRoute
*/
public String getJvmRoute() {
return jvmRoute;
}
/**
* @param jvmRoute the jvmRoute to set
*/
public void setJvmRoute(String jvmRoute) {
this.jvmRoute = jvmRoute;
}
public void addLoadBalancerHeartBeatingListener(
LoadBalancerHeartBeatingListener loadBalancerHeartBeatingListener) {
loadBalancerHeartBeatingListeners.add(loadBalancerHeartBeatingListener);
}
public void removeLoadBalancerHeartBeatingListener(
LoadBalancerHeartBeatingListener loadBalancerHeartBeatingListener) {
loadBalancerHeartBeatingListeners.remove(loadBalancerHeartBeatingListener);
}
/**
* @param info
*/
public void sendSwitchoverInstruction(SipLoadBalancer sipLoadBalancer, String fromJvmRoute, String toJvmRoute) {
logger.logInfo("switching over from " + fromJvmRoute + " to " + toJvmRoute);
if(fromJvmRoute == null || toJvmRoute == null) {
return;
}
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(NodeRegisterRMIStub.class.getClassLoader());
Registry registry = LocateRegistry.getRegistry(sipLoadBalancer.getAddress().getHostAddress(),sipLoadBalancer.getRmiPort());
NodeRegisterRMIStub reg=(NodeRegisterRMIStub) registry.lookup("SIPBalancer");
reg.switchover(fromJvmRoute, toJvmRoute);
sipLoadBalancer.setDisplayWarning(true);
if(!sipLoadBalancer.isAvailable()) {
logger.logInfo("Switchover: SIP Load Balancer Found! " + sipLoadBalancer);
}
} catch (IOException e) {
sipLoadBalancer.setAvailable(false);
if(sipLoadBalancer.isDisplayWarning()) {
logger.logWarning("Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.");
sipLoadBalancer.setDisplayWarning(false);
}
} catch (Exception e) {
sipLoadBalancer.setAvailable(false);
if(sipLoadBalancer.isDisplayWarning()) {
logger.logError("Cannot access the SIP load balancer RMI registry: " + e.getMessage() +
"\nIf you need a cluster configuration make sure the SIP load balancer is running.", e);
sipLoadBalancer.setDisplayWarning(false);
}
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
}
public SipLoadBalancer[] getLoadBalancers() {
// This is slow, but it is called rarely, so no prob
return register.values().toArray(new SipLoadBalancer[] {});
}
}
| false | true | protected ArrayList<SIPNode> getConnectorsAsSIPNode() {
ArrayList<SIPNode> info = new ArrayList<SIPNode>();
Integer sipTcpPort = null;
Integer sipUdpPort = null;
String address = null;
String hostName = null;
// Gathering info about server' sip listening points
Iterator<ListeningPoint> listeningPointIterator = sipStack.getListeningPoints();
while (listeningPointIterator.hasNext()) {
ListeningPoint listeningPoint = listeningPointIterator.next();
address = listeningPoint.getIPAddress();
// From Vladimir: for some reason I get "localhost" here instead of IP and this confiuses the LB
if(address.equals("localhost")) address = "127.0.0.1";
int port = listeningPoint.getPort();
String transport = listeningPoint.getTransport();
if(transport.equalsIgnoreCase("tcp")) {
sipTcpPort = port;
} else if(transport.equals("udp")) {
sipUdpPort = port;
}
try {
InetAddress[] aArray = InetAddress
.getAllByName(address);
if (aArray != null && aArray.length > 0) {
// Damn it, which one we should pick?
hostName = aArray[0].getCanonicalHostName();
}
} catch (UnknownHostException e) {
logger.logError("An exception occurred while trying to retrieve the hostname of a sip connector", e);
}
}
List<String> ipAddresses = new ArrayList<String>();
boolean isAnyLocalAddress = false;
try {
isAnyLocalAddress = InetAddress.getByName(address).isAnyLocalAddress();
} catch (UnknownHostException e) {
logger.logWarning("Unable to enumerate mapped interfaces. Binding to 0.0.0.0 may not work.");
isAnyLocalAddress = false;
}
if(isAnyLocalAddress) {
if(cachedAnyLocalAddresses.isEmpty()) {
try{
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> bindings = networkInterface.getInetAddresses();
while(bindings.hasMoreElements()) {
InetAddress addr = bindings.nextElement();
String networkInterfaceIpAddress = addr.getHostAddress();
// we cache the look up to speed up the next time
cachedAnyLocalAddresses.add(networkInterfaceIpAddress);
}
}
} catch (SocketException e) {
logger.logWarning("Unable to enumerate network interfaces. Binding to 0.0.0.0 may not work.");
}
} else {
ipAddresses.addAll(cachedAnyLocalAddresses);
}
} else {
ipAddresses.add(address);
}
String httpPortString = System.getProperty("org.mobicents.properties.httpPort");
String sslPortString = System.getProperty("org.mobicents.properties.sslPort");
for (String ipAddress : ipAddresses) {
SIPNode node = new SIPNode(hostName, ipAddress);
int httpPort = 0;
int sslPort = 0;
if(httpPortString != null) {
httpPort = Integer.parseInt(httpPortString);
node.getProperties().put("httpPort", httpPort);
}
if(sslPortString != null) {
sslPort = Integer.parseInt(sslPortString);
node.getProperties().put("sslPort", sslPort);
}
if(sipTcpPort != null) node.getProperties().put("tcpPort", sipTcpPort);
if(sipUdpPort != null) node.getProperties().put("udpPort", sipUdpPort);
if(jvmRoute != null) node.getProperties().put("jvmRoute", jvmRoute);
//, port,
// transports, jvmRoute, httpPort, sslPort, null);
node.getProperties().put("version", System.getProperty("org.mobicents.server.version", "0"));
info.add(node);
}
return info;
}
| protected ArrayList<SIPNode> getConnectorsAsSIPNode() {
ArrayList<SIPNode> info = new ArrayList<SIPNode>();
Integer sipTcpPort = null;
Integer sipUdpPort = null;
Integer sipWsPort = null;
String address = null;
String hostName = null;
// Gathering info about server' sip listening points
Iterator<ListeningPoint> listeningPointIterator = sipStack.getListeningPoints();
while (listeningPointIterator.hasNext()) {
ListeningPoint listeningPoint = listeningPointIterator.next();
address = listeningPoint.getIPAddress();
// From Vladimir: for some reason I get "localhost" here instead of IP and this confiuses the LB
if(address.equals("localhost")) address = "127.0.0.1";
int port = listeningPoint.getPort();
String transport = listeningPoint.getTransport();
if(transport.equalsIgnoreCase("tcp")) {
sipTcpPort = port;
} else if(transport.equalsIgnoreCase("udp")) {
sipUdpPort = port;
} else if(transport.equalsIgnoreCase("ws")) {
sipWsPort = port;
}
try {
InetAddress[] aArray = InetAddress
.getAllByName(address);
if (aArray != null && aArray.length > 0) {
// Damn it, which one we should pick?
hostName = aArray[0].getCanonicalHostName();
}
} catch (UnknownHostException e) {
logger.logError("An exception occurred while trying to retrieve the hostname of a sip connector", e);
}
}
List<String> ipAddresses = new ArrayList<String>();
boolean isAnyLocalAddress = false;
try {
isAnyLocalAddress = InetAddress.getByName(address).isAnyLocalAddress();
} catch (UnknownHostException e) {
logger.logWarning("Unable to enumerate mapped interfaces. Binding to 0.0.0.0 may not work.");
isAnyLocalAddress = false;
}
if(isAnyLocalAddress) {
if(cachedAnyLocalAddresses.isEmpty()) {
try{
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while(networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> bindings = networkInterface.getInetAddresses();
while(bindings.hasMoreElements()) {
InetAddress addr = bindings.nextElement();
String networkInterfaceIpAddress = addr.getHostAddress();
// we cache the look up to speed up the next time
cachedAnyLocalAddresses.add(networkInterfaceIpAddress);
}
}
} catch (SocketException e) {
logger.logWarning("Unable to enumerate network interfaces. Binding to 0.0.0.0 may not work.");
}
} else {
ipAddresses.addAll(cachedAnyLocalAddresses);
}
} else {
ipAddresses.add(address);
}
String httpPortString = System.getProperty("org.mobicents.properties.httpPort");
String sslPortString = System.getProperty("org.mobicents.properties.sslPort");
for (String ipAddress : ipAddresses) {
SIPNode node = new SIPNode(hostName, ipAddress);
int httpPort = 0;
int sslPort = 0;
if(httpPortString != null) {
httpPort = Integer.parseInt(httpPortString);
node.getProperties().put("httpPort", httpPort);
}
if(sslPortString != null) {
sslPort = Integer.parseInt(sslPortString);
node.getProperties().put("sslPort", sslPort);
}
if(sipTcpPort != null) node.getProperties().put("tcpPort", sipTcpPort);
if(sipUdpPort != null) node.getProperties().put("udpPort", sipUdpPort);
if(sipWsPort != null) node.getProperties().put("wsPort", sipWsPort);
if(jvmRoute != null) node.getProperties().put("jvmRoute", jvmRoute);
//, port,
// transports, jvmRoute, httpPort, sslPort, null);
node.getProperties().put("version", System.getProperty("org.mobicents.server.version", "0"));
info.add(node);
}
return info;
}
|
diff --git a/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java b/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
index 206f9f8..b67c727 100644
--- a/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
+++ b/src/main/java/nz/org/nesi/goldwrap/impl/GoldWrapServiceImpl.java
@@ -1,663 +1,664 @@
package nz.org.nesi.goldwrap.impl;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;
import javax.ws.rs.Path;
import nz.org.nesi.goldwrap.Config;
import nz.org.nesi.goldwrap.api.GoldWrapService;
import nz.org.nesi.goldwrap.domain.Allocation;
import nz.org.nesi.goldwrap.domain.ExternalCommand;
import nz.org.nesi.goldwrap.domain.Machine;
import nz.org.nesi.goldwrap.domain.Project;
import nz.org.nesi.goldwrap.domain.User;
import nz.org.nesi.goldwrap.errors.MachineFault;
import nz.org.nesi.goldwrap.errors.ProjectFault;
import nz.org.nesi.goldwrap.errors.ServiceException;
import nz.org.nesi.goldwrap.errors.UserFault;
import nz.org.nesi.goldwrap.util.GoldHelper;
import nz.org.nesi.goldwrap.utils.BeanHelpers;
import nz.org.nesi.goldwrap.utils.JSONHelpers;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
@WebService(endpointInterface = "nz.org.nesi.goldwrap.api.GoldWrapService", name = "GoldWrapService")
@Path("/goldwrap")
public class GoldWrapServiceImpl implements GoldWrapService {
public static Logger myLogger = LoggerFactory
.getLogger(GoldWrapServiceImpl.class);
private static ExternalCommand executeGoldCommand(String command) {
ExternalCommand gc = new ExternalCommand(command);
gc.execute();
gc.verify();
return gc;
}
private static ExternalCommand executeGoldCommand(List<String> command) {
ExternalCommand gc = new ExternalCommand(command);
gc.execute();
gc.verify();
return gc;
}
private static volatile boolean initialized = false;
public GoldWrapServiceImpl() {
initialize();
}
public synchronized void initialize() {
if (!initialized) {
try {
File configDir = Config.getConfigDir();
myLogger.debug("Running init commands...");
File initFile = new File(configDir, "init.config");
if (initFile.exists()) {
List<String> lines = null;
try {
lines = Files.readLines(initFile, Charsets.UTF_8);
} catch (IOException e1) {
throw new RuntimeException("Can't read file: "
+ initFile.toString());
}
for (String line : lines) {
line = line.trim();
if (StringUtils.isEmpty(line) || line.startsWith("#")) {
continue;
}
myLogger.debug("Executing: " + line);
ExternalCommand ec = executeGoldCommand(line);
myLogger.debug("StdOut:\n\n{}\n\n", Joiner.on("\n")
.join(ec.getStdOut()));
myLogger.debug("StdErr:\n\n{}\n\n", Joiner.on("\n")
.join(ec.getStdErr()));
}
}
myLogger.debug("Trying to initialize static values...");
File machinesFile = new File(configDir, "machines.json");
if (machinesFile.exists()) {
try {
List<Machine> machines = JSONHelpers.readJSONfile(
machinesFile, Machine.class);
for (Machine m : machines) {
Machine mInGold = null;
try {
mInGold = getMachine(m.getName());
myLogger.debug("Machine " + m.getName()
+ " in Gold, modifying it...");
modifyMachine(m.getName(), m);
} catch (MachineFault mf) {
myLogger.debug("Machine " + m.getName()
+ " not in Gold, creating it...");
createMachine(m);
}
}
} catch (Exception e) {
throw new RuntimeException("Can't parse json file: "
+ machinesFile.toString(), e);
}
}
} finally {
initialized = true;
}
}
}
public Project addUserToProject(String projName, String userId) {
return GoldHelper.addUserToProject(projName, userId);
}
private void checkProjectname(String projectname) {
if (StringUtils.isBlank(projectname)) {
throw new ServiceException("Can't execute operation.",
"Projectname blank or not specified.");
}
}
private void checkUsername(String username) {
if (StringUtils.isBlank(username)) {
throw new ServiceException("Can't execute operation.",
"Username blank or not specified.");
}
}
public void checkMachineName(String machineName) {
if (StringUtils.isBlank(machineName)) {
throw new ServiceException("Can't execute operation.",
"Machine name blank or not specified.");
}
}
public void createMachine(Machine mach) {
String machName = mach.getName();
mach.validate(true);
if (GoldHelper.machineExists(machName)) {
throw new MachineFault(mach, "Can't create machine " + machName,
"Machine name '" + machName + "' already exists in Gold.");
}
StringBuffer command = new StringBuffer("gmkmachine ");
String desc = mach.getDescription();
if (StringUtils.isNotBlank(desc)) {
command.append("-d '" + desc + "' ");
}
String arch = mach.getArch();
if (StringUtils.isNotBlank(arch)) {
command.append("--arch '" + arch + "' ");
}
String opsys = mach.getOpsys();
if (StringUtils.isNotBlank(opsys)) {
command.append("--opsys '" + opsys + "' ");
}
command.append(machName);
ExternalCommand ec = executeGoldCommand(command.toString());
if (!GoldHelper.machineExists(machName)) {
throw new MachineFault(mach, "Can't create machine.",
"Unknow reason");
}
}
public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
desc = "{\"projectId\":\"" + projName + "\"}";
command.add("-d");
- command.add("'" + desc + "'");
+ command.add(desc);
+ // command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
private void createOrModifyUsers(List<User> users) {
for (User user : users) {
if (GoldHelper.isRegistered(user.getUserId())) {
myLogger.debug("Potentially modifying user " + user.getUserId());
modifyUser(user.getUserId(), user);
} else {
myLogger.debug("Creating user: " + user.getUserId());
createUser(user);
}
}
}
public void createUser(User user) {
user.validate(false);
String username = user.getUserId();
String phone = user.getPhone();
String email = user.getEmail();
String middlename = user.getMiddleName();
String fullname = user.getFirstName();
if (StringUtils.isNotBlank(middlename)) {
fullname = fullname + " " + middlename;
}
fullname = fullname + " " + user.getLastName();
String institution = user.getInstitution();
if (GoldHelper.isRegistered(username)) {
throw new UserFault("Can't create user.", "User " + username
+ " already in Gold database.", 409);
}
String desc = JSONHelpers.convertToJSONString(user);
String command = "gmkuser ";
if (StringUtils.isNotBlank(fullname)) {
command = command + "-n \"" + fullname + "\" ";
}
if (StringUtils.isNotBlank(email)) {
command = command + "-E " + email + " ";
}
if (StringUtils.isNotBlank(phone)) {
command = command + "-F " + phone + " ";
}
command = command + " -d '" + desc + "' " + username;
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.isRegistered(username)) {
throw new UserFault(user, "Can't create user.", "Unknown reason");
}
}
public void deleteProject(String projName) {
checkProjectname(projName);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault("Can't delete project " + projName + ".",
"Project " + projName + " not in Gold database.", 404);
}
String command = "grmproject " + projName;
ExternalCommand ec = executeGoldCommand(command);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(
"Could not delete project " + projName + ".",
"Unknown reason.", 500);
}
}
public void deleteUser(String username) {
if (StringUtils.isBlank(username)) {
throw new ServiceException("Can't delete user.",
"Username blank or not specified.");
}
if (!GoldHelper.isRegistered(username)) {
throw new UserFault("Can't delete user.", "User " + username
+ " not in Gold database.", 404);
}
String command = "grmuser " + username;
ExternalCommand ec = executeGoldCommand(command);
if (GoldHelper.isRegistered(username)) {
throw new UserFault("Could not delete user.", "Unknown reason.",
500);
}
}
public Machine getMachine(String machineName) {
checkMachineName(machineName);
return GoldHelper.getMachine(machineName);
}
public List<Machine> getMachines() {
return GoldHelper.getAllMachines();
}
public Project getProject(String projName) {
checkProjectname(projName);
return GoldHelper.getProject(projName);
}
public List<Project> getProjects() {
return GoldHelper.getAllProjects();
}
public List<Project> getProjectsForUser(String username) {
return GoldHelper.getProjectsForUser(username);
}
public User getUser(String username) {
checkUsername(username);
User u = GoldHelper.getUser(username);
return u;
}
public List<User> getUsers() {
return GoldHelper.getAllUsers();
}
public List<User> getUsersForProject(String projName) {
return GoldHelper.getUsersForProject(projName);
}
public boolean isRegistered(String user) {
return GoldHelper.isRegistered(user);
}
public Project modifyProject(String projName, Project project) {
checkProjectname(projName);
if (StringUtils.isNotBlank(project.getProjectId())
&& !projName.equals(project.getProjectId())) {
throw new ProjectFault(project, "Can't modify project.",
"Project name can't be changed.");
}
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault("Can't modify project.", "Project "
+ projName + " not in Gold database.", 404);
}
String principal = project.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(project, "Can't create project "
+ projName, "Principal '" + principal
+ "' does not exist in Gold.");
}
}
List<User> users = project.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(project, "Can't modify project "
+ projName, "Userid not specified.");
}
}
project.validate(false);
Project goldProject = getProject(projName);
try {
BeanHelpers.merge(goldProject, project);
} catch (Exception e) {
e.printStackTrace();
throw new ProjectFault(project, "Can't modify project " + projName,
"Can't merge new properties: " + e.getLocalizedMessage());
}
// we don't want to store userdata in the description
goldProject.setUsers(new ArrayList<User>());
StringBuffer command = new StringBuffer("gchproject ");
String desc = JSONHelpers.convertToJSONString(goldProject);
command.append("-d '" + desc + "' ");
command.append(projName);
ExternalCommand ec = executeGoldCommand(command.toString());
// ensuring users are present
createOrModifyUsers(users);
addUsersToProject(projName, users);
Project p = getProject(projName);
return p;
}
public void addUsersToProject(String projectName, List<User> users) {
for (User user : users) {
addUserToProject(projectName, user.getUserId());
}
}
public Machine modifyMachine(String machName, Machine machine) {
checkMachineName(machName);
machine.validate(true);
Machine mach = null;
try {
mach = getMachine(machName);
} catch (Exception e) {
myLogger.debug("Can't load machine {}", machName, e);
}
if (mach == null) {
throw new MachineFault("Can't modify machine " + machName + ".",
"Machine " + machName + " not in Gold database", 404);
}
String newArch = machine.getArch();
String newOs = machine.getOpsys();
String newDesc = machine.getDescription();
StringBuffer command = new StringBuffer("gchmachine ");
if (StringUtils.isNotBlank(newDesc)) {
command.append("-d '" + newDesc + "' ");
}
if (StringUtils.isNotBlank(newArch)) {
command.append("--arch '" + newArch + "' ");
}
if (StringUtils.isNotBlank(newOs)) {
command.append("--opsys '" + newOs + "' ");
}
command.append(machName);
ExternalCommand ec = executeGoldCommand(command.toString());
return getMachine(machName);
}
public void modifyUser(String username, User user) {
if (StringUtils.isBlank(username)) {
throw new UserFault(user, "Can't modify user.",
"Username field can't be blank.");
}
if (StringUtils.isNotBlank(user.getUserId())
&& !username.equals(user.getUserId())) {
throw new UserFault(user, "Can't modify user.",
"Username can't be changed.");
}
if (!GoldHelper.isRegistered(username)) {
throw new UserFault("Can't modify user.", "User " + username
+ " not in Gold database.", 404);
}
User goldUser = getUser(username);
try {
BeanHelpers.merge(goldUser, user);
} catch (Exception e) {
throw new UserFault(goldUser, "Can't merge new user into old one.",
e.getLocalizedMessage());
}
goldUser.validate(false);
String middlename = goldUser.getMiddleName();
String fullname = goldUser.getFirstName();
if (StringUtils.isNotBlank(middlename)) {
fullname = fullname + " " + middlename;
}
fullname = fullname + " " + goldUser.getLastName();
String phone = goldUser.getPhone();
String institution = goldUser.getInstitution();
String email = goldUser.getEmail();
String desc = JSONHelpers.convertToJSONString(goldUser);
String command = "gchuser ";
if (StringUtils.isNotBlank(fullname)) {
command = command + "-n \"" + fullname + "\" ";
}
if (StringUtils.isNotBlank(email)) {
command = command + "-E " + email + " ";
}
if (StringUtils.isNotBlank(phone)) {
command = command + "-F " + phone + " ";
}
command = command + " -d '" + desc + "' " + username;
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.isRegistered(username)) {
throw new UserFault(goldUser, "Can't create user.",
"Unknown reason");
}
}
}
| true | true | public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
desc = "{\"projectId\":\"" + projName + "\"}";
command.add("-d");
command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
| public void createProject(Project proj) {
String projName = proj.getProjectId();
proj.validate(true);
if (GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project " + projName,
"Project name '" + projName + "' already exists in Gold.");
}
String principal = proj.getPrincipal();
if (StringUtils.isNotBlank(principal)) {
try {
User princ = getUser(principal);
} catch (Exception e) {
throw new ProjectFault(proj,
"Can't create project " + projName, "Principal '"
+ principal + "' does not exist in Gold.");
}
}
List<User> users = proj.getUsers();
if (users != null) {
users = Lists.newArrayList(users);
} else {
users = Lists.newArrayList();
}
for (User user : users) {
String userId = user.getUserId();
if (StringUtils.isBlank(userId)) {
throw new ProjectFault(proj,
"Can't create project " + projName,
"Userid not specified.");
}
// if (!GoldHelper.isRegistered(userId)) {
// throw new ProjectFault(proj,
// "Can't create project " + projName, "User '" + userId
// + "' does not exist in Gold yet.");
// }
}
List<String> command = Lists.newArrayList("gmkproject");
proj.setUsers(new ArrayList<User>());
proj.setAllocations(new ArrayList<Allocation>());
String desc = JSONHelpers.convertToJSONString(proj);
desc = "{\"projectId\":\"" + projName + "\"}";
command.add("-d");
command.add(desc);
// command.add("'" + desc + "'");
// String users = Joiner.on(",").join(proj.getUsers());
//
// if (StringUtils.isNotBlank(users)) {
// command.append("-u '" + users + "' ");
// }
command.add("--createAccount=False");
if (proj.isFunded()) {
command.add("-X");
command.add("Funded=True");
} else {
command.add("-X");
command.add("Funded=False");
}
command.add(projName);
ExternalCommand ec = executeGoldCommand(command);
if (!GoldHelper.projectExists(projName)) {
throw new ProjectFault(proj, "Can't create project.",
"Unknow reason");
}
myLogger.debug("Creating account...");
String command2 = "gmkaccount ";
command2 = command2 + "-p " + projName + " ";
command2 = command2 + "-n " + "acc_" + projName;
ExternalCommand ec2 = executeGoldCommand(command2);
int exitCode = ec2.getExitCode();
if (exitCode != 0) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e) {
myLogger.debug("Deleting project failed: {}",
e.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not create associated account for some reason.");
}
myLogger.debug("Parsing output to find out account number.");
try {
String stdout = ec2.getStdOut().get(0);
Iterable<String> tokens = Splitter.on(' ').split(stdout);
Integer accNr = Integer.parseInt(Iterables.getLast(tokens));
Project tempProj = new Project(projName);
tempProj.setAccountId(accNr);
// remove ANY user
myLogger.debug("Removeing ANY user from account {}", accNr);
String removeAnyCommand = "gchaccount --delUsers ANY " + accNr;
ExternalCommand removeCommand = executeGoldCommand(removeAnyCommand);
modifyProject(projName, tempProj);
} catch (Exception e) {
try {
myLogger.debug("Trying to delete project {}...", projName);
deleteProject(projName);
} catch (Exception e2) {
myLogger.debug("Deleting project failed: {}",
e2.getLocalizedMessage());
}
throw new ProjectFault(proj, "Could not create project.",
"Could not parse account nr for project.");
}
myLogger.debug("Account created. Now adding users...");
createOrModifyUsers(users);
addUsersToProject(projName, users);
}
|
diff --git a/src/com/android/exchange/adapter/CalendarSyncAdapter.java b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
index aa38e05..1d1059f 100644
--- a/src/com/android/exchange/adapter/CalendarSyncAdapter.java
+++ b/src/com/android/exchange/adapter/CalendarSyncAdapter.java
@@ -1,2169 +1,2172 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to 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.exchange.adapter;
import android.content.ContentProviderClient;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Entity;
import android.content.Entity.NamedContentValues;
import android.content.EntityIterator;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.EventsEntity;
import android.provider.CalendarContract.ExtendedProperties;
import android.provider.CalendarContract.Reminders;
import android.provider.CalendarContract.SyncState;
import android.provider.ContactsContract.RawContacts;
import android.provider.SyncStateContract;
import android.text.TextUtils;
import android.util.Log;
import com.android.emailcommon.AccountManagerTypes;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Message;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.CommandStatusException;
import com.android.exchange.Eas;
import com.android.exchange.EasOutboxService;
import com.android.exchange.EasSyncService;
import com.android.exchange.ExchangeService;
import com.android.exchange.utility.CalendarUtilities;
import com.android.exchange.utility.Duration;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
/**
* Sync adapter class for EAS calendars
*
*/
public class CalendarSyncAdapter extends AbstractSyncAdapter {
private static final String TAG = "EasCalendarSyncAdapter";
private static final String EVENT_SAVED_TIMEZONE_COLUMN = Events.SYNC_DATA1;
/**
* Used to keep track of exception vs parent event dirtiness.
*/
private static final String EVENT_SYNC_MARK = Events.SYNC_DATA8;
private static final String EVENT_SYNC_VERSION = Events.SYNC_DATA4;
// Since exceptions will have the same _SYNC_ID as the original event we have to check that
// there's no original event when finding an item by _SYNC_ID
private static final String SERVER_ID_AND_CALENDAR_ID = Events._SYNC_ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String EVENT_ID_AND_CALENDAR_ID = Events._ID + "=? AND " +
Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR = "(" + Events.DIRTY
+ "=1 OR " + EVENT_SYNC_MARK + "= 1) AND " +
Events.ORIGINAL_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?";
private static final String DIRTY_EXCEPTION_IN_CALENDAR =
Events.DIRTY + "=1 AND " + Events.ORIGINAL_ID + " NOTNULL AND " +
Events.CALENDAR_ID + "=?";
private static final String CLIENT_ID_SELECTION = Events.SYNC_DATA2 + "=?";
private static final String ORIGINAL_EVENT_AND_CALENDAR =
Events.ORIGINAL_SYNC_ID + "=? AND " + Events.CALENDAR_ID + "=?";
private static final String ATTENDEES_EXCEPT_ORGANIZER = Attendees.EVENT_ID + "=? AND " +
Attendees.ATTENDEE_RELATIONSHIP + "!=" + Attendees.RELATIONSHIP_ORGANIZER;
private static final String[] ID_PROJECTION = new String[] {Events._ID};
private static final String[] ORIGINAL_EVENT_PROJECTION =
new String[] {Events.ORIGINAL_ID, Events._ID};
private static final String EVENT_ID_AND_NAME =
ExtendedProperties.EVENT_ID + "=? AND " + ExtendedProperties.NAME + "=?";
// Note that we use LIKE below for its case insensitivity
private static final String EVENT_AND_EMAIL =
Attendees.EVENT_ID + "=? AND "+ Attendees.ATTENDEE_EMAIL + " LIKE ?";
private static final int ATTENDEE_STATUS_COLUMN_STATUS = 0;
private static final String[] ATTENDEE_STATUS_PROJECTION =
new String[] {Attendees.ATTENDEE_STATUS};
public static final String CALENDAR_SELECTION =
Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?";
private static final int CALENDAR_SELECTION_ID = 0;
private static final String[] EXTENDED_PROPERTY_PROJECTION =
new String[] {ExtendedProperties._ID};
private static final int EXTENDED_PROPERTY_ID = 0;
private static final String CATEGORY_TOKENIZER_DELIMITER = "\\";
private static final String ATTENDEE_TOKENIZER_DELIMITER = CATEGORY_TOKENIZER_DELIMITER;
private static final String EXTENDED_PROPERTY_USER_ATTENDEE_STATUS = "userAttendeeStatus";
private static final String EXTENDED_PROPERTY_ATTENDEES = "attendees";
private static final String EXTENDED_PROPERTY_DTSTAMP = "dtstamp";
private static final String EXTENDED_PROPERTY_MEETING_STATUS = "meeting_status";
private static final String EXTENDED_PROPERTY_CATEGORIES = "categories";
// Used to indicate that we removed the attendee list because it was too large
private static final String EXTENDED_PROPERTY_ATTENDEES_REDACTED = "attendeesRedacted";
// Used to indicate that upsyncs aren't allowed (we catch this in sendLocalChanges)
private static final String EXTENDED_PROPERTY_UPSYNC_PROHIBITED = "upsyncProhibited";
private static final ContentProviderOperation PLACEHOLDER_OPERATION =
ContentProviderOperation.newInsert(Uri.EMPTY).build();
private static final Object sSyncKeyLock = new Object();
private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC");
private final TimeZone mLocalTimeZone = TimeZone.getDefault();
// Maximum number of allowed attendees; above this number, we mark the Event with the
// attendeesRedacted extended property and don't allow the event to be upsynced to the server
private static final int MAX_SYNCED_ATTENDEES = 50;
// We set the organizer to this when the user is the organizer and we've redacted the
// attendee list. By making the meeting organizer OTHER than the user, we cause the UI to
// prevent edits to this event (except local changes like reminder).
private static final String BOGUS_ORGANIZER_EMAIL = "[email protected]";
// Maximum number of CPO's before we start redacting attendees in exceptions
// The number 500 has been determined empirically; 1500 CPOs appears to be the limit before
// binder failures occur, but we need room at any point for additional events/exceptions so
// we set our limit at 1/3 of the apparent maximum for extra safety
// TODO Find a better solution to this workaround
private static final int MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION = 500;
private long mCalendarId = -1;
private String mCalendarIdString;
private String[] mCalendarIdArgument;
/*package*/ String mEmailAddress;
private ArrayList<Long> mDeletedIdList = new ArrayList<Long>();
private ArrayList<Long> mUploadedIdList = new ArrayList<Long>();
private ArrayList<Long> mSendCancelIdList = new ArrayList<Long>();
private ArrayList<Message> mOutgoingMailList = new ArrayList<Message>();
public CalendarSyncAdapter(EasSyncService service) {
super(service);
mEmailAddress = mAccount.mEmailAddress;
Cursor c = mService.mContentResolver.query(Calendars.CONTENT_URI,
new String[] {Calendars._ID}, CALENDAR_SELECTION,
new String[] {mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE}, null);
if (c == null) return;
try {
if (c.moveToFirst()) {
mCalendarId = c.getLong(CALENDAR_SELECTION_ID);
} else {
mCalendarId = CalendarUtilities.createCalendar(mService, mAccount, mMailbox);
}
mCalendarIdString = Long.toString(mCalendarId);
mCalendarIdArgument = new String[] {mCalendarIdString};
} finally {
c.close();
}
}
@Override
public String getCollectionName() {
return "Calendar";
}
@Override
public void cleanup() {
}
@Override
public void wipe() {
// Delete the calendar associated with this account
// CalendarProvider2 does NOT handle selection arguments in deletions
mContentResolver.delete(
asSyncAdapter(Calendars.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
Calendars.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(mEmailAddress)
+ " AND " + Calendars.ACCOUNT_TYPE + "="
+ DatabaseUtils.sqlEscapeString(AccountManagerTypes.TYPE_EXCHANGE), null);
// Invalidate our calendar observers
ExchangeService.unregisterCalendarObservers();
}
@Override
public void sendSyncOptions(Double protocolVersion, Serializer s) throws IOException {
setPimSyncOptions(protocolVersion, Eas.FILTER_2_WEEKS, s);
}
@Override
public boolean isSyncable() {
return ContentResolver.getSyncAutomatically(mAccountManagerAccount,
CalendarContract.AUTHORITY);
}
@Override
public boolean parse(InputStream is) throws IOException, CommandStatusException {
EasCalendarSyncParser p = new EasCalendarSyncParser(is, this);
return p.parse();
}
public static Uri asSyncAdapter(Uri uri, String account, String accountType) {
return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
.appendQueryParameter(Calendars.ACCOUNT_NAME, account)
.appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
}
/**
* Generate the uri for the data row associated with this NamedContentValues object
* @param ncv the NamedContentValues object
* @return a uri that can be used to refer to this row
*/
public Uri dataUriFromNamedContentValues(NamedContentValues ncv) {
long id = ncv.values.getAsLong(RawContacts._ID);
Uri dataUri = ContentUris.withAppendedId(ncv.uri, id);
return dataUri;
}
/**
* We get our SyncKey from CalendarProvider. If there's not one, we set it to "0" (the reset
* state) and save that away.
*/
@Override
public String getSyncKey() throws IOException {
synchronized (sSyncKeyLock) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
byte[] data = SyncStateContract.Helpers.get(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount);
if (data == null || data.length == 0) {
// Initialize the SyncKey
setSyncKey("0", false);
return "0";
} else {
String syncKey = new String(data);
userLog("SyncKey retrieved as ", syncKey, " from CalendarProvider");
return syncKey;
}
} catch (RemoteException e) {
throw new IOException("Can't get SyncKey from CalendarProvider");
}
}
}
/**
* We only need to set this when we're forced to make the SyncKey "0" (a reset). In all other
* cases, the SyncKey is set within Calendar
*/
@Override
public void setSyncKey(String syncKey, boolean inCommands) throws IOException {
synchronized (sSyncKeyLock) {
if ("0".equals(syncKey) || !inCommands) {
ContentProviderClient client = mService.mContentResolver
.acquireContentProviderClient(CalendarContract.CONTENT_URI);
try {
SyncStateContract.Helpers.set(
client,
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount,
syncKey.getBytes());
userLog("SyncKey set to ", syncKey, " in CalendarProvider");
} catch (RemoteException e) {
throw new IOException("Can't set SyncKey in CalendarProvider");
}
}
mMailbox.mSyncKey = syncKey;
}
}
public class EasCalendarSyncParser extends AbstractSyncParser {
String[] mBindArgument = new String[1];
Uri mAccountUri;
CalendarOperations mOps = new CalendarOperations();
public EasCalendarSyncParser(InputStream in, CalendarSyncAdapter adapter)
throws IOException {
super(in, adapter);
setLoggingTag("CalendarParser");
mAccountUri = Events.CONTENT_URI;
}
private void addOrganizerToAttendees(CalendarOperations ops, long eventId,
String organizerName, String organizerEmail) {
// Handle the organizer (who IS an attendee on device, but NOT in EAS)
if (organizerName != null || organizerEmail != null) {
ContentValues attendeeCv = new ContentValues();
if (organizerName != null) {
attendeeCv.put(Attendees.ATTENDEE_NAME, organizerName);
}
if (organizerEmail != null) {
attendeeCv.put(Attendees.ATTENDEE_EMAIL, organizerEmail);
}
attendeeCv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER);
attendeeCv.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED);
attendeeCv.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED);
if (eventId < 0) {
ops.newAttendee(attendeeCv);
} else {
ops.updatedAttendee(attendeeCv, eventId);
}
}
}
/**
* Set DTSTART, DTEND, DURATION and EVENT_TIMEZONE as appropriate for the given Event
* The follow rules are enforced by CalendarProvider2:
* Events that aren't exceptions MUST have either 1) a DTEND or 2) a DURATION
* Recurring events (i.e. events with RRULE) must have a DURATION
* All-day recurring events MUST have a DURATION that is in the form P<n>D
* Other events MAY have a DURATION in any valid form (we use P<n>M)
* All-day events MUST have hour, minute, and second = 0; in addition, they must have
* the EVENT_TIMEZONE set to UTC
* Also, exceptions to all-day events need to have an ORIGINAL_INSTANCE_TIME that has
* hour, minute, and second = 0 and be set in UTC
* @param cv the ContentValues for the Event
* @param startTime the start time for the Event
* @param endTime the end time for the Event
* @param allDayEvent whether this is an all day event (1) or not (0)
*/
/*package*/ void setTimeRelatedValues(ContentValues cv, long startTime, long endTime,
int allDayEvent) {
// If there's no startTime, the event will be found to be invalid, so return
if (startTime < 0) return;
// EAS events can arrive without an end time, but CalendarProvider requires them
// so we'll default to 30 minutes; this will be superceded if this is an all-day event
if (endTime < 0) endTime = startTime + (30*MINUTES);
// If this is an all-day event, set hour, minute, and second to zero, and use UTC
if (allDayEvent != 0) {
startTime = CalendarUtilities.getUtcAllDayCalendarTime(startTime, mLocalTimeZone);
endTime = CalendarUtilities.getUtcAllDayCalendarTime(endTime, mLocalTimeZone);
String originalTimeZone = cv.getAsString(Events.EVENT_TIMEZONE);
cv.put(EVENT_SAVED_TIMEZONE_COLUMN, originalTimeZone);
cv.put(Events.EVENT_TIMEZONE, UTC_TIMEZONE.getID());
}
// If this is an exception, and the original was an all-day event, make sure the
// original instance time has hour, minute, and second set to zero, and is in UTC
if (cv.containsKey(Events.ORIGINAL_INSTANCE_TIME) &&
cv.containsKey(Events.ORIGINAL_ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ORIGINAL_ALL_DAY);
if (ade != null && ade != 0) {
long exceptionTime = cv.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
GregorianCalendar cal = new GregorianCalendar(UTC_TIMEZONE);
cal.setTimeInMillis(exceptionTime);
cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
cal.set(GregorianCalendar.MINUTE, 0);
cal.set(GregorianCalendar.SECOND, 0);
cv.put(Events.ORIGINAL_INSTANCE_TIME, cal.getTimeInMillis());
}
}
// Always set DTSTART
cv.put(Events.DTSTART, startTime);
// For recurring events, set DURATION. Use P<n>D format for all day events
if (cv.containsKey(Events.RRULE)) {
if (allDayEvent != 0) {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / DAYS) + "D");
}
else {
cv.put(Events.DURATION, "P" + ((endTime - startTime) / MINUTES) + "M");
}
// For other events, set DTEND and LAST_DATE
} else {
cv.put(Events.DTEND, endTime);
cv.put(Events.LAST_DATE, endTime);
}
}
public void addEvent(CalendarOperations ops, String serverId, boolean update)
throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.HAS_ATTENDEE_DATA, 1);
cv.put(Events.SYNC_DATA2, "0");
int allDayEvent = 0;
String organizerName = null;
String organizerEmail = null;
int eventOffset = -1;
int deleteOffset = -1;
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
int responseType = CalendarUtilities.RESPONSE_TYPE_NONE;
boolean firstTag = true;
long eventId = -1;
long startTime = -1;
long endTime = -1;
TimeZone timeZone = null;
// Keep track of the attendees; exceptions will need them
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
int reminderMins = -1;
String dtStamp = null;
boolean organizerAdded = false;
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
if (update && firstTag) {
// Find the event that's being updated
Cursor c = getServerIdCursor(serverId);
long id = -1;
try {
if (c != null && c.moveToFirst()) {
id = c.getLong(0);
}
} finally {
if (c != null) c.close();
}
if (id > 0) {
// DTSTAMP can come first, and we simply need to track it
if (tag == Tags.CALENDAR_DTSTAMP) {
dtStamp = getValue();
continue;
} else if (tag == Tags.CALENDAR_ATTENDEES) {
// This is an attendees-only update; just
// delete/re-add attendees
mBindArgument[0] = Long.toString(id);
ops.add(ContentProviderOperation
.newDelete(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(ATTENDEES_EXCEPT_ORGANIZER, mBindArgument)
.build());
eventId = id;
} else {
// Otherwise, delete the original event and recreate it
userLog("Changing (delete/add) event ", serverId);
deleteOffset = ops.newDelete(id, serverId);
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
} else {
// The changed item isn't found. We'll treat this as a new item
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
userLog(TAG, "Changed item not found; treating as new.");
}
} else if (firstTag) {
// Add a placeholder event so that associated tables can reference
// this as a back reference. We add the event at the end of the method
eventOffset = ops.newEvent(PLACEHOLDER_OPERATION);
}
firstTag = false;
switch (tag) {
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
if (allDayEvent != 0 && timeZone != null) {
// If the event doesn't start at midnight local time, we won't consider
// this an all-day event in the local time zone (this is what OWA does)
GregorianCalendar cal = new GregorianCalendar(mLocalTimeZone);
cal.setTimeInMillis(startTime);
userLog("All-day event arrived in: " + timeZone.getID());
if (cal.get(GregorianCalendar.HOUR_OF_DAY) != 0 ||
cal.get(GregorianCalendar.MINUTE) != 0) {
allDayEvent = 0;
userLog("Not an all-day event locally: " + mLocalTimeZone.getID());
}
}
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_ATTENDEES:
// If eventId >= 0, this is an update; otherwise, a new Event
attendeeValues = attendeesParser(ops, eventId);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_TIME_ZONE:
timeZone = CalendarUtilities.tziStringToTimeZone(getValue());
if (timeZone == null) {
timeZone = mLocalTimeZone;
}
cv.put(Events.EVENT_TIMEZONE, timeZone.getID());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_EXCEPTIONS:
// For exceptions to show the organizer, the organizer must be added before
// we call exceptionsParser
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
organizerAdded = true;
exceptionsParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_ORGANIZER_EMAIL:
organizerEmail = getValue();
cv.put(Events.ORGANIZER, organizerEmail);
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_ORGANIZER_NAME:
organizerName = getValue();
break;
case Tags.CALENDAR_REMINDER_MINS_BEFORE:
reminderMins = getValueInt();
ops.newReminder(reminderMins);
cv.put(Events.HAS_ALARM, 1);
break;
// The following are fields we should save (for changes), though they don't
// relate to data used by CalendarProvider at this point
case Tags.CALENDAR_UID:
cv.put(Events.SYNC_DATA2, getValue());
break;
case Tags.CALENDAR_DTSTAMP:
dtStamp = getValue();
break;
case Tags.CALENDAR_MEETING_STATUS:
ops.newExtendedProperty(EXTENDED_PROPERTY_MEETING_STATUS, getValue());
break;
case Tags.CALENDAR_BUSY_STATUS:
// We'll set the user's status in the Attendees table below
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
busyStatus = getValueInt();
break;
case Tags.CALENDAR_RESPONSE_TYPE:
// EAS 14+ uses this for the user's response status; we'll use this instead
// of busy status, if it appears
responseType = getValueInt();
break;
case Tags.CALENDAR_CATEGORIES:
String categories = categoriesParser(ops);
if (categories.length() > 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_CATEGORIES, categories);
}
break;
default:
skipTag();
}
}
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// If we haven't added the organizer to attendees, do it now
if (!organizerAdded) {
addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail);
}
// Note that organizerEmail can be null with a DTSTAMP only change from the server
boolean selfOrganizer = (mEmailAddress.equals(organizerEmail));
// Store email addresses of attendees (in a tokenizable string) in ExtendedProperties
// If the user is an attendee, set the attendee status using busyStatus (note that the
// busyStatus is inherited from the parent unless it's specified in the exception)
// Add the insert/update operation for each attendee (based on whether it's add/change)
int numAttendees = attendeeValues.size();
if (numAttendees > MAX_SYNCED_ATTENDEES) {
// Indicate that we've redacted attendees. If we're the organizer, disable edit
// by setting organizerEmail to a bogus value and by setting the upsync prohibited
// extended properly.
// Note that we don't set ANY attendees if we're in this branch; however, the
// organizer has already been included above, and WILL show up (which is good)
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1");
if (selfOrganizer) {
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1");
}
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1", eventId);
if (selfOrganizer) {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1",
eventId);
}
}
if (selfOrganizer) {
organizerEmail = BOGUS_ORGANIZER_EMAIL;
cv.put(Events.ORGANIZER, organizerEmail);
}
// Tell UI that we don't have any attendees
cv.put(Events.HAS_ATTENDEE_DATA, "0");
mService.userLog("Maximum number of attendees exceeded; redacting");
} else if (numAttendees > 0) {
StringBuilder sb = new StringBuilder();
for (ContentValues attendee: attendeeValues) {
String attendeeEmail = attendee.getAsString(Attendees.ATTENDEE_EMAIL);
sb.append(attendeeEmail);
sb.append(ATTENDEE_TOKENIZER_DELIMITER);
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
int attendeeStatus;
// We'll use the response type (EAS 14), if we've got one; otherwise, we'll
// try to infer it from busy status
if (responseType != CalendarUtilities.RESPONSE_TYPE_NONE) {
attendeeStatus =
CalendarUtilities.attendeeStatusFromResponseType(responseType);
} else if (!update) {
// For new events in EAS < 14, we have no idea what the busy status
// means, so we show "none", allowing the user to select an option.
attendeeStatus = Attendees.ATTENDEE_STATUS_NONE;
} else {
// For updated events, we'll try to infer the attendee status from the
// busy status
attendeeStatus =
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus);
}
attendee.put(Attendees.ATTENDEE_STATUS, attendeeStatus);
// If we're an attendee, save away our initial attendee status in the
// event's ExtendedProperties (we look for differences between this and
// the user's current attendee status to determine whether an email needs
// to be sent to the organizer)
// organizerEmail will be null in the case that this is an attendees-only
// change from the server
if (organizerEmail == null ||
!organizerEmail.equalsIgnoreCase(attendeeEmail)) {
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus));
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS,
Integer.toString(attendeeStatus), eventId);
}
}
}
if (eventId < 0) {
ops.newAttendee(attendee);
} else {
ops.updatedAttendee(attendee, eventId);
}
}
if (eventId < 0) {
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString());
ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0");
ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0");
} else {
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString(),
eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0", eventId);
ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0", eventId);
}
}
// Put the real event in the proper place in the ops ArrayList
if (eventOffset >= 0) {
// Store away the DTSTAMP here
if (dtStamp != null) {
ops.newExtendedProperty(EXTENDED_PROPERTY_DTSTAMP, dtStamp);
}
if (isValidEventValues(cv)) {
ops.set(eventOffset,
ContentProviderOperation
.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
} else {
// If we can't add this event (it's invalid), remove all of the inserts
// we've built for it
int cnt = ops.mCount - eventOffset;
userLog(TAG, "Removing " + cnt + " inserts from mOps");
for (int i = 0; i < cnt; i++) {
ops.remove(eventOffset);
}
ops.mCount = eventOffset;
// If this is a change, we need to also remove the deletion that comes
// before the addition
if (deleteOffset >= 0) {
// Remove the deletion
ops.remove(deleteOffset);
// And the deletion of exceptions
ops.remove(deleteOffset);
userLog(TAG, "Removing deletion ops from mOps");
ops.mCount = deleteOffset;
}
}
}
}
private void logEventColumns(ContentValues cv, String reason) {
if (Eas.USER_LOG) {
StringBuilder sb =
new StringBuilder("Event invalid, " + reason + ", skipping: Columns = ");
for (Entry<String, Object> entry: cv.valueSet()) {
sb.append(entry.getKey());
sb.append('/');
}
userLog(TAG, sb.toString());
}
}
/*package*/ boolean isValidEventValues(ContentValues cv) {
boolean isException = cv.containsKey(Events.ORIGINAL_INSTANCE_TIME);
// All events require DTSTART
if (!cv.containsKey(Events.DTSTART)) {
logEventColumns(cv, "DTSTART missing");
return false;
// If we're a top-level event, we must have _SYNC_DATA (uid)
} else if (!isException && !cv.containsKey(Events.SYNC_DATA2)) {
logEventColumns(cv, "_SYNC_DATA missing");
return false;
// We must also have DTEND or DURATION if we're not an exception
} else if (!isException && !cv.containsKey(Events.DTEND) &&
!cv.containsKey(Events.DURATION)) {
logEventColumns(cv, "DTEND/DURATION missing");
return false;
// Exceptions require DTEND
} else if (isException && !cv.containsKey(Events.DTEND)) {
logEventColumns(cv, "Exception missing DTEND");
return false;
// If this is a recurrence, we need a DURATION (in days if an all-day event)
} else if (cv.containsKey(Events.RRULE)) {
String duration = cv.getAsString(Events.DURATION);
if (duration == null) return false;
if (cv.containsKey(Events.ALL_DAY)) {
Integer ade = cv.getAsInteger(Events.ALL_DAY);
if (ade != null && ade != 0 && !duration.endsWith("D")) {
return false;
}
}
}
return true;
}
public String recurrenceParser() throws IOException {
// Turn this information into an RRULE
int type = -1;
int occurrences = -1;
int interval = -1;
int dow = -1;
int dom = -1;
int wom = -1;
int moy = -1;
String until = null;
while (nextTag(Tags.CALENDAR_RECURRENCE) != END) {
switch (tag) {
case Tags.CALENDAR_RECURRENCE_TYPE:
type = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_INTERVAL:
interval = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_OCCURRENCES:
occurrences = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFWEEK:
dow = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_DAYOFMONTH:
dom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_WEEKOFMONTH:
wom = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_MONTHOFYEAR:
moy = getValueInt();
break;
case Tags.CALENDAR_RECURRENCE_UNTIL:
until = getValue();
break;
default:
skipTag();
}
}
return CalendarUtilities.rruleFromRecurrence(type, occurrences, interval,
dow, dom, wom, moy, until);
}
private void exceptionParser(CalendarOperations ops, ContentValues parentCv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
ContentValues cv = new ContentValues();
cv.put(Events.CALENDAR_ID, mCalendarId);
// It appears that these values have to be copied from the parent if they are to appear
// Note that they can be overridden below
cv.put(Events.ORGANIZER, parentCv.getAsString(Events.ORGANIZER));
cv.put(Events.TITLE, parentCv.getAsString(Events.TITLE));
cv.put(Events.DESCRIPTION, parentCv.getAsString(Events.DESCRIPTION));
cv.put(Events.ORIGINAL_ALL_DAY, parentCv.getAsInteger(Events.ALL_DAY));
cv.put(Events.EVENT_LOCATION, parentCv.getAsString(Events.EVENT_LOCATION));
cv.put(Events.ACCESS_LEVEL, parentCv.getAsString(Events.ACCESS_LEVEL));
cv.put(Events.EVENT_TIMEZONE, parentCv.getAsString(Events.EVENT_TIMEZONE));
// Exceptions should always have this set to zero, since EAS has no concept of
// separate attendee lists for exceptions; if we fail to do this, then the UI will
// allow the user to change attendee data, and this change would never get reflected
// on the server.
cv.put(Events.HAS_ATTENDEE_DATA, 0);
int allDayEvent = 0;
// This column is the key that links the exception to the serverId
cv.put(Events.ORIGINAL_SYNC_ID, parentCv.getAsString(Events._SYNC_ID));
String exceptionStartTime = "_noStartTime";
while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENTS:
attachmentsParser();
break;
case Tags.CALENDAR_EXCEPTION_START_TIME:
exceptionStartTime = getValue();
cv.put(Events.ORIGINAL_INSTANCE_TIME,
Utility.parseDateTimeToMillis(exceptionStartTime));
break;
case Tags.CALENDAR_EXCEPTION_IS_DELETED:
if (getValueInt() == 1) {
cv.put(Events.STATUS, Events.STATUS_CANCELED);
}
break;
case Tags.CALENDAR_ALL_DAY_EVENT:
allDayEvent = getValueInt();
cv.put(Events.ALL_DAY, allDayEvent);
break;
case Tags.BASE_BODY:
cv.put(Events.DESCRIPTION, bodyParser());
break;
case Tags.CALENDAR_BODY:
cv.put(Events.DESCRIPTION, getValue());
break;
case Tags.CALENDAR_START_TIME:
startTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_END_TIME:
endTime = Utility.parseDateTimeToMillis(getValue());
break;
case Tags.CALENDAR_LOCATION:
cv.put(Events.EVENT_LOCATION, getValue());
break;
case Tags.CALENDAR_RECURRENCE:
String rrule = recurrenceParser();
if (rrule != null) {
cv.put(Events.RRULE, rrule);
}
break;
case Tags.CALENDAR_SUBJECT:
cv.put(Events.TITLE, getValue());
break;
case Tags.CALENDAR_SENSITIVITY:
cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt()));
break;
case Tags.CALENDAR_BUSY_STATUS:
busyStatus = getValueInt();
// Don't set selfAttendeeStatus or CalendarProvider will create a duplicate
// attendee!
break;
// TODO How to handle these items that are linked to event id!
// case Tags.CALENDAR_DTSTAMP:
// ops.newExtendedProperty("dtstamp", getValue());
// break;
// case Tags.CALENDAR_REMINDER_MINS_BEFORE:
// ops.newReminder(getValueInt());
// break;
default:
skipTag();
}
}
// We need a _sync_id, but it can't be the parent's id, so we generate one
cv.put(Events._SYNC_ID, parentCv.getAsString(Events._SYNC_ID) + '_' +
exceptionStartTime);
// Enforce CalendarProvider required properties
setTimeRelatedValues(cv, startTime, endTime, allDayEvent);
// Don't insert an invalid exception event
if (!isValidEventValues(cv)) return;
// Add the exception insert
int exceptionStart = ops.mCount;
ops.newException(cv);
// Also add the attendees, because they need to be copied over from the parent event
boolean attendeesRedacted = false;
if (attendeeValues != null) {
for (ContentValues attValues: attendeeValues) {
// If this is the user, use his busy status for attendee status
String attendeeEmail = attValues.getAsString(Attendees.ATTENDEE_EMAIL);
// Note that the exception at which we surpass the redaction limit might have
// any number of attendees shown; since this is an edge case and a workaround,
// it seems to be an acceptable implementation
if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) {
attValues.put(Attendees.ATTENDEE_STATUS,
CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus));
ops.newAttendee(attValues, exceptionStart);
} else if (ops.size() < MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION) {
ops.newAttendee(attValues, exceptionStart);
} else {
attendeesRedacted = true;
}
}
}
// And add the parent's reminder value
if (reminderMins > 0) {
ops.newReminder(reminderMins, exceptionStart);
}
if (attendeesRedacted) {
mService.userLog("Attendees redacted in this exception");
}
}
private int encodeVisibility(int easVisibility) {
int visibility = 0;
switch(easVisibility) {
case 0:
visibility = Events.ACCESS_DEFAULT;
break;
case 1:
visibility = Events.ACCESS_PUBLIC;
break;
case 2:
visibility = Events.ACCESS_PRIVATE;
break;
case 3:
visibility = Events.ACCESS_CONFIDENTIAL;
break;
}
return visibility;
}
private void exceptionsParser(CalendarOperations ops, ContentValues cv,
ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus,
long startTime, long endTime) throws IOException {
while (nextTag(Tags.CALENDAR_EXCEPTIONS) != END) {
switch (tag) {
case Tags.CALENDAR_EXCEPTION:
exceptionParser(ops, cv, attendeeValues, reminderMins, busyStatus,
startTime, endTime);
break;
default:
skipTag();
}
}
}
private String categoriesParser(CalendarOperations ops) throws IOException {
StringBuilder categories = new StringBuilder();
while (nextTag(Tags.CALENDAR_CATEGORIES) != END) {
switch (tag) {
case Tags.CALENDAR_CATEGORY:
// TODO Handle categories (there's no similar concept for gdata AFAIK)
// We need to save them and spit them back when we update the event
categories.append(getValue());
categories.append(CATEGORY_TOKENIZER_DELIMITER);
break;
default:
skipTag();
}
}
return categories.toString();
}
/**
* For now, we ignore (but still have to parse) event attachments; these are new in EAS 14
*/
private void attachmentsParser() throws IOException {
while (nextTag(Tags.CALENDAR_ATTACHMENTS) != END) {
switch (tag) {
case Tags.CALENDAR_ATTACHMENT:
skipParser(Tags.CALENDAR_ATTACHMENT);
break;
default:
skipTag();
}
}
}
private ArrayList<ContentValues> attendeesParser(CalendarOperations ops, long eventId)
throws IOException {
int attendeeCount = 0;
ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>();
while (nextTag(Tags.CALENDAR_ATTENDEES) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE:
ContentValues cv = attendeeParser(ops, eventId);
// If we're going to redact these attendees anyway, let's avoid unnecessary
// memory pressure, and not keep them around
// We still need to parse them all, however
attendeeCount++;
// Allow one more than MAX_ATTENDEES, so that the check for "too many" will
// succeed in addEvent
if (attendeeCount <= (MAX_SYNCED_ATTENDEES+1)) {
attendeeValues.add(cv);
}
break;
default:
skipTag();
}
}
return attendeeValues;
}
private ContentValues attendeeParser(CalendarOperations ops, long eventId)
throws IOException {
ContentValues cv = new ContentValues();
while (nextTag(Tags.CALENDAR_ATTENDEE) != END) {
switch (tag) {
case Tags.CALENDAR_ATTENDEE_EMAIL:
cv.put(Attendees.ATTENDEE_EMAIL, getValue());
break;
case Tags.CALENDAR_ATTENDEE_NAME:
cv.put(Attendees.ATTENDEE_NAME, getValue());
break;
case Tags.CALENDAR_ATTENDEE_STATUS:
int status = getValueInt();
cv.put(Attendees.ATTENDEE_STATUS,
(status == 2) ? Attendees.ATTENDEE_STATUS_TENTATIVE :
(status == 3) ? Attendees.ATTENDEE_STATUS_ACCEPTED :
(status == 4) ? Attendees.ATTENDEE_STATUS_DECLINED :
(status == 5) ? Attendees.ATTENDEE_STATUS_INVITED :
Attendees.ATTENDEE_STATUS_NONE);
break;
case Tags.CALENDAR_ATTENDEE_TYPE:
int type = Attendees.TYPE_NONE;
// EAS types: 1 = req'd, 2 = opt, 3 = resource
switch (getValueInt()) {
case 1:
type = Attendees.TYPE_REQUIRED;
break;
case 2:
type = Attendees.TYPE_OPTIONAL;
break;
}
cv.put(Attendees.ATTENDEE_TYPE, type);
break;
default:
skipTag();
}
}
cv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE);
return cv;
}
private String bodyParser() throws IOException {
String body = null;
while (nextTag(Tags.BASE_BODY) != END) {
switch (tag) {
case Tags.BASE_DATA:
body = getValue();
break;
default:
skipTag();
}
}
// Handle null data without error
if (body == null) return "";
// Remove \r's from any body text
return body.replace("\r\n", "\n");
}
public void addParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID: // same as
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
addEvent(ops, serverId, false);
break;
default:
skipTag();
}
}
}
private Cursor getServerIdCursor(String serverId) {
return mContentResolver.query(mAccountUri, ID_PROJECTION, SERVER_ID_AND_CALENDAR_ID,
new String[] {serverId, mCalendarIdString}, null);
}
private Cursor getClientIdCursor(String clientId) {
mBindArgument[0] = clientId;
return mContentResolver.query(mAccountUri, ID_PROJECTION, CLIENT_ID_SELECTION,
mBindArgument, null);
}
public void deleteParser(CalendarOperations ops) throws IOException {
while (nextTag(Tags.SYNC_DELETE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
String serverId = getValue();
// Find the event with the given serverId
Cursor c = getServerIdCursor(serverId);
try {
if (c.moveToFirst()) {
userLog("Deleting ", serverId);
ops.delete(c.getLong(0), serverId);
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
/**
* A change is handled as a delete (including all exceptions) and an add
* This isn't as efficient as attempting to traverse the original and all of its exceptions,
* but changes happen infrequently and this code is both simpler and easier to maintain
* @param ops the array of pending ContactProviderOperations.
* @throws IOException
*/
public void changeParser(CalendarOperations ops) throws IOException {
String serverId = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_APPLICATION_DATA:
userLog("Changing " + serverId);
addEvent(ops, serverId, true);
break;
default:
skipTag();
}
}
}
@Override
public void commandsParser() throws IOException {
while (nextTag(Tags.SYNC_COMMANDS) != END) {
if (tag == Tags.SYNC_ADD) {
addParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_DELETE) {
deleteParser(mOps);
incrementChangeCount();
} else if (tag == Tags.SYNC_CHANGE) {
changeParser(mOps);
incrementChangeCount();
} else
skipTag();
}
}
@Override
public void commit() throws IOException {
userLog("Calendar SyncKey saved as: ", mMailbox.mSyncKey);
// Save the syncKey here, using the Helper provider by Calendar provider
mOps.add(SyncStateContract.Helpers.newSetOperation(
asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
mAccountManagerAccount,
mMailbox.mSyncKey.getBytes()));
// We need to send cancellations now, because the Event won't exist after the commit
for (long eventId: mSendCancelIdList) {
EmailContent.Message msg;
try {
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_CANCEL, null,
mAccount);
} catch (RemoteException e) {
// Nothing to do here; the Event may no longer exist
continue;
}
if (msg != null) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
// Execute these all at once...
mOps.execute();
if (mOps.mResults != null) {
// Clear dirty and mark flags for updates sent to server
if (!mUploadedIdList.isEmpty()) {
ContentValues cv = new ContentValues();
cv.put(Events.DIRTY, 0);
cv.put(EVENT_SYNC_MARK, "0");
for (long eventId : mUploadedIdList) {
mContentResolver.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
null, null);
}
}
// Delete events marked for deletion
if (!mDeletedIdList.isEmpty()) {
for (long eventId : mDeletedIdList) {
mContentResolver.delete(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
null);
}
}
// Send any queued up email (invitations replies, etc.)
for (Message msg: mOutgoingMailList) {
EasOutboxService.sendMessage(mContext, mAccount.mId, msg);
}
}
}
public void addResponsesParser() throws IOException {
String serverId = null;
String clientId = null;
int status = -1;
ContentValues cv = new ContentValues();
while (nextTag(Tags.SYNC_ADD) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_CLIENT_ID:
clientId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValueInt();
if (status != 1) {
userLog("Attempt to add event failed with status: " + status);
}
break;
default:
skipTag();
}
}
if (clientId == null) return;
if (serverId == null) {
// TODO Reconsider how to handle this
serverId = "FAIL:" + status;
}
Cursor c = getClientIdCursor(clientId);
try {
if (c.moveToFirst()) {
cv.put(Events._SYNC_ID, serverId);
cv.put(Events.SYNC_DATA2, clientId);
long id = c.getLong(0);
// Write the serverId into the Event
mOps.add(ContentProviderOperation
.newUpdate(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValues(cv).build());
userLog("New event " + clientId + " was given serverId: " + serverId);
}
} finally {
c.close();
}
}
public void changeResponsesParser() throws IOException {
String serverId = null;
String status = null;
while (nextTag(Tags.SYNC_CHANGE) != END) {
switch (tag) {
case Tags.SYNC_SERVER_ID:
serverId = getValue();
break;
case Tags.SYNC_STATUS:
status = getValue();
break;
default:
skipTag();
}
}
if (serverId != null && status != null) {
userLog("Changed event " + serverId + " failed with status: " + status);
}
}
@Override
public void responsesParser() throws IOException {
// Handle server responses here (for Add and Change)
while (nextTag(Tags.SYNC_RESPONSES) != END) {
if (tag == Tags.SYNC_ADD) {
addResponsesParser();
} else if (tag == Tags.SYNC_CHANGE) {
changeResponsesParser();
} else
skipTag();
}
}
}
protected class CalendarOperations extends ArrayList<ContentProviderOperation> {
private static final long serialVersionUID = 1L;
public int mCount = 0;
private ContentProviderResult[] mResults = null;
private int mEventStart = 0;
@Override
public boolean add(ContentProviderOperation op) {
super.add(op);
mCount++;
return true;
}
public int newEvent(ContentProviderOperation op) {
mEventStart = mCount;
add(op);
return mEventStart;
}
public int newDelete(long id, String serverId) {
int offset = mCount;
delete(id, serverId);
return offset;
}
public void newAttendee(ContentValues cv) {
newAttendee(cv, mEventStart);
}
public void newAttendee(ContentValues cv, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv)
.withValueBackReference(Attendees.EVENT_ID, eventStart).build());
}
public void updatedAttendee(ContentValues cv, long id) {
cv.put(Attendees.EVENT_ID, id);
add(ContentProviderOperation.newInsert(asSyncAdapter(Attendees.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newException(ContentValues cv) {
add(ContentProviderOperation.newInsert(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build());
}
public void newExtendedProperty(String name, String value) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(ExtendedProperties.NAME, name)
.withValue(ExtendedProperties.VALUE, value)
.withValueBackReference(ExtendedProperties.EVENT_ID, mEventStart).build());
}
public void updatedExtendedProperty(String name, String value, long id) {
// Find an existing ExtendedProperties row for this event and property name
Cursor c = mService.mContentResolver.query(ExtendedProperties.CONTENT_URI,
EXTENDED_PROPERTY_PROJECTION, EVENT_ID_AND_NAME,
new String[] {Long.toString(id), name}, null);
long extendedPropertyId = -1;
// If there is one, capture its _id
if (c != null) {
try {
if (c.moveToFirst()) {
extendedPropertyId = c.getLong(EXTENDED_PROPERTY_ID);
}
} finally {
c.close();
}
}
// Either do an update or an insert, depending on whether one
// already exists
if (extendedPropertyId >= 0) {
add(ContentProviderOperation
.newUpdate(
ContentUris.withAppendedId(
asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
extendedPropertyId))
.withValue(ExtendedProperties.VALUE, value).build());
} else {
newExtendedProperty(name, value);
}
}
public void newReminder(int mins, int eventStart) {
add(ContentProviderOperation
.newInsert(asSyncAdapter(Reminders.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withValue(Reminders.MINUTES, mins)
.withValue(Reminders.METHOD, Reminders.METHOD_ALERT)
.withValueBackReference(ExtendedProperties.EVENT_ID, eventStart).build());
}
public void newReminder(int mins) {
newReminder(mins, mEventStart);
}
public void delete(long id, String syncId) {
add(ContentProviderOperation.newDelete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, id),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).build());
// Delete the exceptions for this Event (CalendarProvider doesn't do
// this)
add(ContentProviderOperation
.newDelete(asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE))
.withSelection(Events.ORIGINAL_SYNC_ID + "=?", new String[] {syncId}).build());
}
public void execute() {
synchronized (mService.getSynchronizer()) {
if (!mService.isStopped()) {
try {
if (!isEmpty()) {
mService.userLog("Executing ", size(), " CPO's");
mResults = mContext.getContentResolver().applyBatch(
CalendarContract.AUTHORITY, this);
}
} catch (RemoteException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
} catch (OperationApplicationException e) {
// There is nothing sensible to be done here
Log.e(TAG, "problem inserting event during server update", e);
}
}
}
}
}
private String decodeVisibility(int visibility) {
int easVisibility = 0;
switch(visibility) {
case Events.ACCESS_DEFAULT:
easVisibility = 0;
break;
case Events.ACCESS_PUBLIC:
easVisibility = 1;
break;
case Events.ACCESS_PRIVATE:
easVisibility = 2;
break;
case Events.ACCESS_CONFIDENTIAL:
easVisibility = 3;
break;
}
return Integer.toString(easVisibility);
}
private int getInt(ContentValues cv, String column) {
Integer i = cv.getAsInteger(column);
if (i == null) return 0;
return i;
}
private void sendEvent(Entity entity, String clientId, Serializer s)
throws IOException {
// Serialize for EAS here
// Set uid with the client id we created
// 1) Serialize the top-level event
// 2) Serialize attendees and reminders from subvalues
// 3) Look for exceptions and serialize with the top-level event
ContentValues entityValues = entity.getEntityValues();
final boolean isException = (clientId == null);
boolean hasAttendees = false;
final boolean isChange = entityValues.containsKey(Events._SYNC_ID);
final Double version = mService.mProtocolVersionDouble;
final boolean allDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ALL_DAY);
// NOTE: Exchange 2003 (EAS 2.5) seems to require the "exception deleted" and "exception
// start time" data before other data in exceptions. Failure to do so results in a
// status 6 error during sync
if (isException) {
// Send exception deleted flag if necessary
Integer deleted = entityValues.getAsInteger(Events.DELETED);
boolean isDeleted = deleted != null && deleted == 1;
Integer eventStatus = entityValues.getAsInteger(Events.STATUS);
boolean isCanceled = eventStatus != null && eventStatus.equals(Events.STATUS_CANCELED);
if (isDeleted || isCanceled) {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "1");
// If we're deleted, the UI will continue to show this exception until we mark
// it canceled, so we'll do that here...
if (isDeleted && !isCanceled) {
final long eventId = entityValues.getAsLong(Events._ID);
ContentValues cv = new ContentValues();
cv.put(Events.STATUS, Events.STATUS_CANCELED);
mService.mContentResolver.update(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null,
null);
}
} else {
s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "0");
}
// TODO Add reminders to exceptions (allow them to be specified!)
Long originalTime = entityValues.getAsLong(Events.ORIGINAL_INSTANCE_TIME);
if (originalTime != null) {
final boolean originalAllDay =
CalendarUtilities.getIntegerValueAsBoolean(entityValues,
Events.ORIGINAL_ALL_DAY);
if (originalAllDay) {
// For all day events, we need our local all-day time
originalTime =
CalendarUtilities.getLocalAllDayCalendarTime(originalTime, mLocalTimeZone);
}
s.data(Tags.CALENDAR_EXCEPTION_START_TIME,
CalendarUtilities.millisToEasDateTime(originalTime));
} else {
// Illegal; what should we do?
}
}
// Get the event's time zone
String timeZoneName =
entityValues.getAsString(allDay ? EVENT_SAVED_TIMEZONE_COLUMN : Events.EVENT_TIMEZONE);
if (timeZoneName == null) {
timeZoneName = mLocalTimeZone.getID();
}
TimeZone eventTimeZone = TimeZone.getTimeZone(timeZoneName);
if (!isException) {
// A time zone is required in all EAS events; we'll use the default if none is set
// Exchange 2003 seems to require this first... :-)
String timeZone = CalendarUtilities.timeZoneToTziString(eventTimeZone);
s.data(Tags.CALENDAR_TIME_ZONE, timeZone);
}
s.data(Tags.CALENDAR_ALL_DAY_EVENT, allDay ? "1" : "0");
// DTSTART is always supplied
long startTime = entityValues.getAsLong(Events.DTSTART);
// Determine endTime; it's either provided as DTEND or we calculate using DURATION
// If no DURATION is provided, we default to one hour
long endTime;
if (entityValues.containsKey(Events.DTEND)) {
endTime = entityValues.getAsLong(Events.DTEND);
} else {
long durationMillis = HOURS;
if (entityValues.containsKey(Events.DURATION)) {
Duration duration = new Duration();
try {
duration.parse(entityValues.getAsString(Events.DURATION));
durationMillis = duration.getMillis();
} catch (ParseException e) {
// Can't do much about this; use the default (1 hour)
}
}
endTime = startTime + durationMillis;
}
if (allDay) {
TimeZone tz = mLocalTimeZone;
startTime = CalendarUtilities.getLocalAllDayCalendarTime(startTime, tz);
endTime = CalendarUtilities.getLocalAllDayCalendarTime(endTime, tz);
}
s.data(Tags.CALENDAR_START_TIME, CalendarUtilities.millisToEasDateTime(startTime));
s.data(Tags.CALENDAR_END_TIME, CalendarUtilities.millisToEasDateTime(endTime));
s.data(Tags.CALENDAR_DTSTAMP,
CalendarUtilities.millisToEasDateTime(System.currentTimeMillis()));
String loc = entityValues.getAsString(Events.EVENT_LOCATION);
if (!TextUtils.isEmpty(loc)) {
if (version < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
// EAS 2.5 doesn't like bare line feeds
loc = Utility.replaceBareLfWithCrlf(loc);
}
s.data(Tags.CALENDAR_LOCATION, loc);
}
s.writeStringValue(entityValues, Events.TITLE, Tags.CALENDAR_SUBJECT);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.start(Tags.BASE_BODY);
s.data(Tags.BASE_TYPE, "1");
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.BASE_DATA);
s.end();
} else {
// EAS 2.5 doesn't like bare line feeds
s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.CALENDAR_BODY);
}
if (!isException) {
// For Exchange 2003, only upsync if the event is new
if ((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) {
s.writeStringValue(entityValues, Events.ORGANIZER, Tags.CALENDAR_ORGANIZER_EMAIL);
}
String rrule = entityValues.getAsString(Events.RRULE);
if (rrule != null) {
CalendarUtilities.recurrenceFromRrule(rrule, startTime, s);
}
// Handle associated data EXCEPT for attendees, which have to be grouped
ArrayList<NamedContentValues> subValues = entity.getSubValues();
// The earliest of the reminders for this Event; we can only send one reminder...
int earliestReminder = -1;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(ExtendedProperties.CONTENT_URI)) {
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
String propertyValue =
ncvValues.getAsString(ExtendedProperties.VALUE);
if (TextUtils.isEmpty(propertyValue)) {
continue;
}
if (propertyName.equals(EXTENDED_PROPERTY_CATEGORIES)) {
// Send all the categories back to the server
// We've saved them as a String of delimited tokens
StringTokenizer st =
new StringTokenizer(propertyValue, CATEGORY_TOKENIZER_DELIMITER);
if (st.countTokens() > 0) {
s.start(Tags.CALENDAR_CATEGORIES);
while (st.hasMoreTokens()) {
String category = st.nextToken();
s.data(Tags.CALENDAR_CATEGORY, category);
}
s.end();
}
}
} else if (ncvUri.equals(Reminders.CONTENT_URI)) {
Integer mins = ncvValues.getAsInteger(Reminders.MINUTES);
if (mins != null) {
// -1 means "default", which for Exchange, is 30
if (mins < 0) {
mins = 30;
}
// Save this away if it's the earliest reminder (greatest minutes)
if (mins > earliestReminder) {
earliestReminder = mins;
}
}
}
}
// If we have a reminder, send it to the server
if (earliestReminder >= 0) {
s.data(Tags.CALENDAR_REMINDER_MINS_BEFORE, Integer.toString(earliestReminder));
}
// We've got to send a UID, unless this is an exception. If the event is new, we've
// generated one; if not, we should have gotten one from extended properties.
if (clientId != null) {
s.data(Tags.CALENDAR_UID, clientId);
}
// Handle attendee data here; keep track of organizer and stream it afterward
String organizerName = null;
String organizerEmail = null;
for (NamedContentValues ncv: subValues) {
Uri ncvUri = ncv.uri;
ContentValues ncvValues = ncv.values;
if (ncvUri.equals(Attendees.CONTENT_URI)) {
Integer relationship = ncvValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP);
// If there's no relationship, we can't create this for EAS
// Similarly, we need an attendee email for each invitee
if (relationship != null && ncvValues.containsKey(Attendees.ATTENDEE_EMAIL)) {
// Organizer isn't among attendees in EAS
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
organizerName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
organizerEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
continue;
}
if (!hasAttendees) {
s.start(Tags.CALENDAR_ATTENDEES);
hasAttendees = true;
}
s.start(Tags.CALENDAR_ATTENDEE);
String attendeeEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL);
String attendeeName = ncvValues.getAsString(Attendees.ATTENDEE_NAME);
if (attendeeName == null) {
attendeeName = attendeeEmail;
}
s.data(Tags.CALENDAR_ATTENDEE_NAME, attendeeName);
s.data(Tags.CALENDAR_ATTENDEE_EMAIL, attendeeEmail);
if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) {
s.data(Tags.CALENDAR_ATTENDEE_TYPE, "1"); // Required
}
s.end(); // Attendee
}
}
}
if (hasAttendees) {
s.end(); // Attendees
}
// Get busy status from Attendees table
long eventId = entityValues.getAsLong(Events._ID);
int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE;
Cursor c = mService.mContentResolver.query(
asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
ATTENDEE_STATUS_PROJECTION, EVENT_AND_EMAIL,
new String[] {Long.toString(eventId), mEmailAddress}, null);
if (c != null) {
try {
if (c.moveToFirst()) {
busyStatus = CalendarUtilities.busyStatusFromAttendeeStatus(
c.getInt(ATTENDEE_STATUS_COLUMN_STATUS));
}
} finally {
c.close();
}
}
s.data(Tags.CALENDAR_BUSY_STATUS, Integer.toString(busyStatus));
// Meeting status, 0 = appointment, 1 = meeting, 3 = attendee
if (mEmailAddress.equalsIgnoreCase(organizerEmail)) {
s.data(Tags.CALENDAR_MEETING_STATUS, hasAttendees ? "1" : "0");
} else {
s.data(Tags.CALENDAR_MEETING_STATUS, "3");
}
// For Exchange 2003, only upsync if the event is new
if (((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) &&
organizerName != null) {
s.data(Tags.CALENDAR_ORGANIZER_NAME, organizerName);
}
// NOTE: Sensitivity must NOT be sent to the server for exceptions in Exchange 2003
// The result will be a status 6 failure during sync
Integer visibility = entityValues.getAsInteger(Events.ACCESS_LEVEL);
if (visibility != null) {
s.data(Tags.CALENDAR_SENSITIVITY, decodeVisibility(visibility));
} else {
// Default to private if not set
s.data(Tags.CALENDAR_SENSITIVITY, "1");
}
}
}
/**
* Convenience method for sending an email to the organizer declining the meeting
* @param entity
* @param clientId
*/
private void sendDeclinedEmail(Entity entity, String clientId) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext, entity,
Message.FLAG_OUTGOING_MEETING_DECLINE, clientId, mAccount);
if (msg != null) {
userLog("Queueing declined response to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
@Override
public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
- cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
- attendeeStringId), cv, null, null);
+ cr.update(asSyncAdapter(ContentUris.withAppendedId(
+ ExtendedProperties.CONTENT_URI, attendeeStringId),
+ mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
+ cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
- cr.insert(ExtendedProperties.CONTENT_URI, cv);
+ cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
+ mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
}
| false | true | public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
attendeeStringId), cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(ExtendedProperties.CONTENT_URI, cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
| public boolean sendLocalChanges(Serializer s) throws IOException {
ContentResolver cr = mService.mContentResolver;
if (getSyncKey().equals("0")) {
return false;
}
try {
// We've got to handle exceptions as part of the parent when changes occur, so we need
// to find new/changed exceptions and mark the parent dirty
ArrayList<Long> orphanedExceptions = new ArrayList<Long>();
Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION,
DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null);
try {
ContentValues cv = new ContentValues();
// We use _sync_mark here to distinguish dirty parents from parents with dirty
// exceptions
cv.put(EVENT_SYNC_MARK, "1");
while (c.moveToNext()) {
// Mark the parents of dirty exceptions
long parentId = c.getLong(0);
int cnt = cr.update(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv,
EVENT_ID_AND_CALENDAR_ID, new String[] {
Long.toString(parentId), mCalendarIdString
});
// Keep track of any orphaned exceptions
if (cnt == 0) {
orphanedExceptions.add(c.getLong(1));
}
}
} finally {
c.close();
}
// Delete any orphaned exceptions
for (long orphan : orphanedExceptions) {
userLog(TAG, "Deleted orphaned exception: " + orphan);
cr.delete(
asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null);
}
orphanedExceptions.clear();
// Now we can go through dirty/marked top-level events and send them
// back to the server
EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr);
ContentValues cidValues = new ContentValues();
try {
boolean first = true;
while (eventIterator.hasNext()) {
Entity entity = eventIterator.next();
// For each of these entities, create the change commands
ContentValues entityValues = entity.getEntityValues();
String serverId = entityValues.getAsString(Events._SYNC_ID);
// We first need to check whether we can upsync this event; our test for this
// is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED
// If this is set to "1", we can't upsync the event
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
if (ncvValues.getAsString(ExtendedProperties.NAME).equals(
EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) {
if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) {
// Make sure we mark this to clear the dirty flag
mUploadedIdList.add(entityValues.getAsLong(Events._ID));
continue;
}
}
}
}
// Find our uid in the entity; otherwise create one
String clientId = entityValues.getAsString(Events.SYNC_DATA2);
if (clientId == null) {
clientId = UUID.randomUUID().toString();
}
// EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID
// We can generate all but what we're testing for below
String organizerEmail = entityValues.getAsString(Events.ORGANIZER);
boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress);
if (!entityValues.containsKey(Events.DTSTART)
|| (!entityValues.containsKey(Events.DURATION) &&
!entityValues.containsKey(Events.DTEND))
|| organizerEmail == null) {
continue;
}
if (first) {
s.start(Tags.SYNC_COMMANDS);
userLog("Sending Calendar changes to the server");
first = false;
}
long eventId = entityValues.getAsLong(Events._ID);
if (serverId == null) {
// This is a new event; create a clientId
userLog("Creating new event with clientId: ", clientId);
s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId);
// And save it in the Event as the local id
cidValues.put(Events.SYNC_DATA2, clientId);
cidValues.put(EVENT_SYNC_VERSION, "0");
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
} else {
if (entityValues.getAsInteger(Events.DELETED) == 1) {
userLog("Deleting event with serverId: ", serverId);
s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
mDeletedIdList.add(eventId);
if (selfOrganizer) {
mSendCancelIdList.add(eventId);
} else {
sendDeclinedEmail(entity, clientId);
}
continue;
}
userLog("Upsync change to event with serverId: " + serverId);
// Get the current version
String version = entityValues.getAsString(EVENT_SYNC_VERSION);
// This should never be null, but catch this error anyway
// Version should be "0" when we create the event, so use that
if (version == null) {
version = "0";
} else {
// Increment and save
try {
version = Integer.toString((Integer.parseInt(version) + 1));
} catch (Exception e) {
// Handle the case in which someone writes a non-integer here;
// shouldn't happen, but we don't want to kill the sync for his
version = "0";
}
}
cidValues.put(EVENT_SYNC_VERSION, version);
// Also save in entityValues so that we send it this time around
entityValues.put(EVENT_SYNC_VERSION, version);
cr.update(
asSyncAdapter(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cidValues, null, null);
s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId);
}
s.start(Tags.SYNC_APPLICATION_DATA);
sendEvent(entity, clientId, s);
// Now, the hard part; find exceptions for this event
if (serverId != null) {
EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query(
asSyncAdapter(Events.CONTENT_URI, mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null,
ORIGINAL_EVENT_AND_CALENDAR, new String[] {
serverId, mCalendarIdString
}, null), cr);
boolean exFirst = true;
while (exIterator.hasNext()) {
Entity exEntity = exIterator.next();
if (exFirst) {
s.start(Tags.CALENDAR_EXCEPTIONS);
exFirst = false;
}
s.start(Tags.CALENDAR_EXCEPTION);
sendEvent(exEntity, null, s);
ContentValues exValues = exEntity.getEntityValues();
if (getInt(exValues, Events.DIRTY) == 1) {
// This is a new/updated exception, so we've got to notify our
// attendees about it
long exEventId = exValues.getAsLong(Events._ID);
int flag;
// Copy subvalues into the exception; otherwise, we won't see the
// attendees when preparing the message
for (NamedContentValues ncv: entity.getSubValues()) {
exEntity.addSubValue(ncv.uri, ncv.values);
}
if ((getInt(exValues, Events.DELETED) == 1) ||
(getInt(exValues, Events.STATUS) ==
Events.STATUS_CANCELED)) {
flag = Message.FLAG_OUTGOING_MEETING_CANCEL;
if (!selfOrganizer) {
// Send a cancellation notice to the organizer
// Since CalendarProvider2 sets the organizer of exceptions
// to the user, we have to reset it first to the original
// organizer
exValues.put(Events.ORGANIZER,
entityValues.getAsString(Events.ORGANIZER));
sendDeclinedEmail(exEntity, clientId);
}
} else {
flag = Message.FLAG_OUTGOING_MEETING_INVITE;
}
// Add the eventId of the exception to the uploaded id list, so that
// the dirty/mark bits are cleared
mUploadedIdList.add(exEventId);
// Copy version so the ics attachment shows the proper sequence #
exValues.put(EVENT_SYNC_VERSION,
entityValues.getAsString(EVENT_SYNC_VERSION));
// Copy location so that it's included in the outgoing email
if (entityValues.containsKey(Events.EVENT_LOCATION)) {
exValues.put(Events.EVENT_LOCATION,
entityValues.getAsString(Events.EVENT_LOCATION));
}
if (selfOrganizer) {
Message msg =
CalendarUtilities.createMessageForEntity(mContext,
exEntity, flag, clientId, mAccount);
if (msg != null) {
userLog("Queueing exception update to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
s.end(); // EXCEPTION
}
if (!exFirst) {
s.end(); // EXCEPTIONS
}
}
s.end().end(); // ApplicationData & Change
mUploadedIdList.add(eventId);
// Go through the extended properties of this Event and pull out our tokenized
// attendees list and the user attendee status; we will need them later
String attendeeString = null;
long attendeeStringId = -1;
String userAttendeeStatus = null;
long userAttendeeStatusId = -1;
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) {
ContentValues ncvValues = ncv.values;
String propertyName =
ncvValues.getAsString(ExtendedProperties.NAME);
if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) {
attendeeString =
ncvValues.getAsString(ExtendedProperties.VALUE);
attendeeStringId =
ncvValues.getAsLong(ExtendedProperties._ID);
} else if (propertyName.equals(
EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) {
userAttendeeStatus =
ncvValues.getAsString(ExtendedProperties.VALUE);
userAttendeeStatusId =
ncvValues.getAsLong(ExtendedProperties._ID);
}
}
}
// Send the meeting invite if there are attendees and we're the organizer AND
// if the Event itself is dirty (we might be syncing only because an exception
// is dirty, in which case we DON'T send email about the Event)
if (selfOrganizer &&
(getInt(entityValues, Events.DIRTY) == 1)) {
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId,
mAccount);
if (msg != null) {
userLog("Queueing invitation to ", msg.mTo);
mOutgoingMailList.add(msg);
}
// Make a list out of our tokenized attendees, if we have any
ArrayList<String> originalAttendeeList = new ArrayList<String>();
if (attendeeString != null) {
StringTokenizer st =
new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER);
while (st.hasMoreTokens()) {
originalAttendeeList.add(st.nextToken());
}
}
StringBuilder newTokenizedAttendees = new StringBuilder();
// See if any attendees have been dropped and while we're at it, build
// an updated String with tokenized attendee addresses
for (NamedContentValues ncv: entity.getSubValues()) {
if (ncv.uri.equals(Attendees.CONTENT_URI)) {
String attendeeEmail =
ncv.values.getAsString(Attendees.ATTENDEE_EMAIL);
// Remove all found attendees
originalAttendeeList.remove(attendeeEmail);
newTokenizedAttendees.append(attendeeEmail);
newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER);
}
}
// Update extended properties with the new attendee list, if we have one
// Otherwise, create one (this would be the case for Events created on
// device or "legacy" events (before this code was added)
ContentValues cv = new ContentValues();
cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString());
if (attendeeString != null) {
cr.update(asSyncAdapter(ContentUris.withAppendedId(
ExtendedProperties.CONTENT_URI, attendeeStringId),
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE),
cv, null, null);
} else {
// If there wasn't an "attendees" property, insert one
cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES);
cv.put(ExtendedProperties.EVENT_ID, eventId);
cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI,
mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv);
}
// Whoever is left has been removed from the attendee list; send them
// a cancellation
for (String removedAttendee: originalAttendeeList) {
// Send a cancellation message to each of them
msg = CalendarUtilities.createMessageForEventId(mContext, eventId,
Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount,
removedAttendee);
if (msg != null) {
// Just send it to the removed attendee
userLog("Queueing cancellation to removed attendee " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
} else if (!selfOrganizer) {
// If we're not the organizer, see if we've changed our attendee status
// Our last synced attendee status is in ExtendedProperties, and we've
// retrieved it above as userAttendeeStatus
int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS);
int syncStatus = Attendees.ATTENDEE_STATUS_NONE;
if (userAttendeeStatus != null) {
try {
syncStatus = Integer.parseInt(userAttendeeStatus);
} catch (NumberFormatException e) {
// Just in case somebody else mucked with this and it's not Integer
}
}
if ((currentStatus != syncStatus) &&
(currentStatus != Attendees.ATTENDEE_STATUS_NONE)) {
// If so, send a meeting reply
int messageFlag = 0;
switch (currentStatus) {
case Attendees.ATTENDEE_STATUS_ACCEPTED:
messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT;
break;
case Attendees.ATTENDEE_STATUS_DECLINED:
messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE;
break;
case Attendees.ATTENDEE_STATUS_TENTATIVE:
messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE;
break;
}
// Make sure we have a valid status (messageFlag should never be zero)
if (messageFlag != 0 && userAttendeeStatusId >= 0) {
// Save away the new status
cidValues.clear();
cidValues.put(ExtendedProperties.VALUE,
Integer.toString(currentStatus));
cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI,
userAttendeeStatusId), cidValues, null, null);
// Send mail to the organizer advising of the new status
EmailContent.Message msg =
CalendarUtilities.createMessageForEventId(mContext, eventId,
messageFlag, clientId, mAccount);
if (msg != null) {
userLog("Queueing invitation reply to " + msg.mTo);
mOutgoingMailList.add(msg);
}
}
}
}
}
if (!first) {
s.end(); // Commands
}
} finally {
eventIterator.close();
}
} catch (RemoteException e) {
Log.e(TAG, "Could not read dirty events.");
}
return false;
}
|
diff --git a/benchmark/tests/threads-single/threads_001.java b/benchmark/tests/threads-single/threads_001.java
index 4216cfe2..bdfb03cc 100644
--- a/benchmark/tests/threads-single/threads_001.java
+++ b/benchmark/tests/threads-single/threads_001.java
@@ -1,14 +1,15 @@
public class threads_001 {
public static void main(String[] args) {
- double t0 = System.currentTimeMillis();
+ //double t0 = System.currentTimeMillis();
long acc = 0;
int L = 10000000;
int n = 2 * L;
for (int i = 0; i <= n; ++i) acc += i;
- double t1 = System.currentTimeMillis();
- System.out.println("Time elapsed single-thread version Java: " + (t1 - t0) / 1000);
- System.out.println("Result: " + acc);
+ //double t1 = System.currentTimeMillis();
+ //System.out.println("Time elapsed single-thread version Java: " + (t1 - t0) / 1000);
+ System.out.println("Java");
+ System.out.println(acc);
}
}
| false | true | public static void main(String[] args) {
double t0 = System.currentTimeMillis();
long acc = 0;
int L = 10000000;
int n = 2 * L;
for (int i = 0; i <= n; ++i) acc += i;
double t1 = System.currentTimeMillis();
System.out.println("Time elapsed single-thread version Java: " + (t1 - t0) / 1000);
System.out.println("Result: " + acc);
}
| public static void main(String[] args) {
//double t0 = System.currentTimeMillis();
long acc = 0;
int L = 10000000;
int n = 2 * L;
for (int i = 0; i <= n; ++i) acc += i;
//double t1 = System.currentTimeMillis();
//System.out.println("Time elapsed single-thread version Java: " + (t1 - t0) / 1000);
System.out.println("Java");
System.out.println(acc);
}
|
diff --git a/src/com/jgaap/JGAAP.java b/src/com/jgaap/JGAAP.java
index 4957fd9..6cf59e0 100644
--- a/src/com/jgaap/JGAAP.java
+++ b/src/com/jgaap/JGAAP.java
@@ -1,71 +1,75 @@
/*
* JGAAP -- a graphical program for stylometric authorship attribution
* Copyright (C) 2009,2011 by Patrick Juola
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
**/
package com.jgaap;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.jgaap.backend.CLI;
import com.jgaap.ui.JGAAP_UI_MainForm;
/**
* The jgaap main file.
*
* @author michael ryan
*/
public class JGAAP {
static Logger logger = Logger.getLogger("com.jgaap");
static Logger mainLogger = Logger.getLogger(JGAAP.class);
public static boolean commandline = false;
/**
* Launches the jgaap GUI.
*/
private static void createAndShowGUI() {
JGAAP_UI_MainForm gui = new JGAAP_UI_MainForm();
gui.setVisible(true);
}
/**
* launches either the CLI or the GUI based on the command line arguments
* @param args the command line arguments
*/
public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.INFO);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
- CLI.main(args);
+ try {
+ CLI.main(args);
+ } catch (Exception e) {
+ mainLogger.fatal("Command Line Failure", e);
+ }
}
}
}
| true | true | public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.INFO);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
CLI.main(args);
}
}
| public static void main(String[] args) {
BasicConfigurator.configure();
logger.setLevel(Level.INFO);
if (args.length == 0) {
mainLogger.info("Starting GUI");
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} else {
mainLogger.info("Starting CLI");
try {
CLI.main(args);
} catch (Exception e) {
mainLogger.fatal("Command Line Failure", e);
}
}
}
|
diff --git a/component/content/src/main/java/org/exoplatform/management/content/operations/site/contents/SiteContentsExportResource.java b/component/content/src/main/java/org/exoplatform/management/content/operations/site/contents/SiteContentsExportResource.java
index 3108c7f9..ae8a5e3d 100644
--- a/component/content/src/main/java/org/exoplatform/management/content/operations/site/contents/SiteContentsExportResource.java
+++ b/component/content/src/main/java/org/exoplatform/management/content/operations/site/contents/SiteContentsExportResource.java
@@ -1,389 +1,391 @@
package org.exoplatform.management.content.operations.site.contents;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import org.apache.commons.lang.StringUtils;
import org.exoplatform.portal.config.DataStorage;
import org.exoplatform.portal.config.model.Application;
import org.exoplatform.portal.config.model.Container;
import org.exoplatform.portal.config.model.ModelObject;
import org.exoplatform.portal.config.model.Page;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.portal.mop.SiteType;
import org.exoplatform.portal.mop.page.PageContext;
import org.exoplatform.portal.mop.page.PageService;
import org.exoplatform.portal.pom.spi.portlet.Portlet;
import org.exoplatform.services.jcr.RepositoryService;
import org.exoplatform.services.jcr.core.ManageableRepository;
import org.exoplatform.services.jcr.ext.common.SessionProvider;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.wcm.core.NodeLocation;
import org.exoplatform.services.wcm.core.WCMConfigurationService;
import org.exoplatform.services.wcm.core.WCMService;
import org.exoplatform.services.wcm.portal.PortalFolderSchemaHandler;
import org.exoplatform.wcm.webui.Utils;
import org.gatein.management.api.PathAddress;
import org.gatein.management.api.exceptions.OperationException;
import org.gatein.management.api.operation.OperationAttributes;
import org.gatein.management.api.operation.OperationContext;
import org.gatein.management.api.operation.OperationHandler;
import org.gatein.management.api.operation.OperationNames;
import org.gatein.management.api.operation.ResultHandler;
import org.gatein.management.api.operation.model.ExportResourceModel;
import org.gatein.management.api.operation.model.ExportTask;
/**
* @author <a href="mailto:[email protected]">Thomas
* Delhoménie</a>
* @version $Revision$
*/
public class SiteContentsExportResource implements OperationHandler {
private static final Log log = ExoLogger.getLogger(SiteContentsExportResource.class);
private static final String FOLDER_PATH = "folderPath";
private static final String WORKSPACE = "workspace";
private static final String IDENTIFIER = "nodeIdentifier";
public static final String FILTER_SEPARATOR = ":";
private WCMConfigurationService wcmConfigurationService = null;
private RepositoryService repositoryService = null;
private WCMService wcmService = null;
private DataStorage dataStorage = null;
private PageService pageService = null;
private SiteMetaData metaData = null;
@Override
public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException {
try {
metaData = new SiteMetaData();
String operationName = operationContext.getOperationName();
PathAddress address = operationContext.getAddress();
OperationAttributes attributes = operationContext.getAttributes();
String siteName = address.resolvePathTemplate("site-name");
if (siteName == null) {
throw new OperationException(operationName, "No site name specified.");
}
wcmConfigurationService = operationContext.getRuntimeContext().getRuntimeComponent(WCMConfigurationService.class);
repositoryService = operationContext.getRuntimeContext().getRuntimeComponent(RepositoryService.class);
dataStorage = operationContext.getRuntimeContext().getRuntimeComponent(DataStorage.class);
pageService = operationContext.getRuntimeContext().getRuntimeComponent(PageService.class);
wcmService = operationContext.getRuntimeContext().getRuntimeComponent(WCMService.class);
NodeLocation sitesLocation = wcmConfigurationService.getLivePortalsLocation();
String sitePath = sitesLocation.getPath();
if (!sitePath.endsWith("/")) {
sitePath += "/";
}
sitePath += siteName;
metaData.getOptions().put(SiteMetaData.SITE_PATH, sitePath);
metaData.getOptions().put(SiteMetaData.SITE_WORKSPACE, sitesLocation.getWorkspace());
metaData.getOptions().put(SiteMetaData.SITE_NAME, siteName);
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
List<String> filters = attributes.getValues("filter");
boolean exportSiteWithSkeleton = true;
String jcrQuery = null;
// no-skeleton as the priority over query
if(!filters.contains("no-skeleton:true") && !filters.contains("no-skeleton:false")) {
for (String filterValue : filters) {
if (filterValue.startsWith("query:")) {
jcrQuery = filterValue.replace("query:", "");
}
}
} else {
exportSiteWithSkeleton = !filters.contains("no-skeleton:true");
}
+ // "taxonomy" attribute. Defaults to true.
boolean exportSiteTaxonomy = !filters.contains("taxonomy:false");
+ // "no-history" attribute. Defaults to false.
boolean exportVersionHistory = !filters.contains("no-history:true");
// Validate Site Structure
validateSiteStructure(siteName);
// Site contents
if (!StringUtils.isEmpty(jcrQuery)) {
exportTasks.addAll(exportQueryResult(sitesLocation, sitePath, jcrQuery, exportVersionHistory));
} else if (exportSiteWithSkeleton) {
exportTasks.addAll(exportSite(sitesLocation, sitePath, exportVersionHistory));
} else {
exportTasks.addAll(exportSiteWithoutSkeleton(sitesLocation, sitePath, exportSiteTaxonomy, exportVersionHistory));
}
// Metadata
exportTasks.add(getMetaDataExportTask());
resultHandler.completed(new ExportResourceModel(exportTasks));
} catch (Exception e) {
throw new OperationException(OperationNames.EXPORT_RESOURCE, "Unable to retrieve the list of the contents sites : " + e.getMessage());
}
}
private void validateSiteStructure(String siteName) throws Exception {
if (siteName.equals(wcmConfigurationService.getSharedPortalName())) {
return;
}
// pages
Iterator<PageContext> pagesQueryResult = pageService.findPages(0, Integer.MAX_VALUE, SiteType.PORTAL, siteName, null, null).iterator();
Set<String> contentSet = new HashSet<String>();
while (pagesQueryResult.hasNext()) {
PageContext pageContext = (PageContext) pagesQueryResult.next();
Page page = dataStorage.getPage(pageContext.getKey().format());
contentSet.addAll(getSCVPaths(page.getChildren()));
contentSet.addAll(getCLVPaths(page.getChildren()));
}
// site layout
PortalConfig portalConfig = dataStorage.getPortalConfig(siteName);
if (portalConfig != null) {
Container portalLayout = portalConfig.getPortalLayout();
contentSet.addAll(getSCVPaths(portalLayout.getChildren()));
contentSet.addAll(getCLVPaths(portalLayout.getChildren()));
}
if (!contentSet.isEmpty()) {
log.warn("Site contents export: There are some contents used in pages that don't belong to <<" + siteName + ">> site's JCR structure: " + contentSet);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<String> getSCVPaths(ArrayList<ModelObject> children) throws Exception {
List<String> scvPaths = new ArrayList<String>();
if (children != null) {
for (ModelObject modelObject : children) {
if (modelObject instanceof Application) {
Portlet portlet = (Portlet) dataStorage.load(((Application) modelObject).getState(), ((Application) modelObject).getType());
if (portlet == null || portlet.getValue(IDENTIFIER) == null) {
continue;
}
String workspace = portlet.getPreference(WORKSPACE).getValue();
String nodeIdentifier = portlet.getPreference(IDENTIFIER) == null ? null : portlet.getPreference(IDENTIFIER).getValue();
if (nodeIdentifier == null || nodeIdentifier.isEmpty()) {
continue;
}
if (workspace.equals(metaData.getOptions().get(SiteMetaData.SITE_WORKSPACE)) && nodeIdentifier.startsWith(metaData.getOptions().get(SiteMetaData.SITE_PATH))) {
continue;
}
String path = nodeIdentifier;
if (!nodeIdentifier.startsWith("/")) {
Node node = wcmService.getReferencedContent(SessionProvider.createSystemProvider(), workspace, nodeIdentifier);
if (node != null) {
node = Utils.getRealNode(node);
}
path = node == null ? null : node.getPath();
}
if (path == null || path.isEmpty()) {
continue;
}
scvPaths.add(path);
} else if (modelObject instanceof Container) {
scvPaths.addAll(getSCVPaths(((Container) modelObject).getChildren()));
}
}
}
return scvPaths;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<String> getCLVPaths(ArrayList<ModelObject> children) throws Exception {
List<String> scvPaths = new ArrayList<String>();
if (children != null) {
for (ModelObject modelObject : children) {
if (modelObject instanceof Application) {
Portlet portlet = (Portlet) dataStorage.load(((Application) modelObject).getState(), ((Application) modelObject).getType());
if (portlet == null || portlet.getValue(FOLDER_PATH) == null) {
continue;
}
String[] folderPaths = portlet.getPreference(FOLDER_PATH).getValue().split(";");
for (String folderPath : folderPaths) {
String[] paths = folderPath.split(":");
String workspace = paths[1];
String path = paths[2];
if (workspace.equals(metaData.getOptions().get(SiteMetaData.SITE_WORKSPACE)) && path.startsWith(metaData.getOptions().get(SiteMetaData.SITE_PATH))) {
continue;
}
scvPaths.add(path);
}
} else if (modelObject instanceof Container) {
scvPaths.addAll(getCLVPaths(((Container) modelObject).getChildren()));
}
}
}
return scvPaths;
}
/**
*
* @param sitesLocation
* @param siteRootNodePath
* @param exportVersionHistory
* @return
*/
private List<ExportTask> exportSite(NodeLocation sitesLocation, String siteRootNodePath, boolean exportVersionHistory) {
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
SiteContentsExportTask siteContentExportTask = new SiteContentsExportTask(repositoryService, sitesLocation.getWorkspace(), metaData.getOptions().get(SiteMetaData.SITE_NAME), siteRootNodePath);
exportTasks.add(siteContentExportTask);
if (exportVersionHistory) {
SiteContentsVersionHistoryExportTask siteContentVersionHistoryExportTask = new SiteContentsVersionHistoryExportTask(repositoryService, sitesLocation.getWorkspace(), metaData.getOptions().get(
SiteMetaData.SITE_NAME), siteRootNodePath);
exportTasks.add(siteContentVersionHistoryExportTask);
metaData.getExportedHistoryFiles().put(siteContentExportTask.getEntry(), siteContentVersionHistoryExportTask.getEntry());
}
metaData.getExportedFiles().put(siteContentExportTask.getEntry(), sitesLocation.getPath());
return exportTasks;
}
/**
*
* @param sitesLocation
* @param siteRootNodePath
* @param exportVersionHistory
* @return
*/
private List<ExportTask> exportQueryResult(NodeLocation sitesLocation, String siteRootNodePath, String jcrQuery, boolean exportVersionHistory) throws Exception {
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
String queryPath = "jcr:path = '" + siteRootNodePath + "/%'";
queryPath.replace("//", "/");
if (jcrQuery.contains("where")) {
int startIndex = jcrQuery.indexOf("where");
int endIndex = startIndex + "where".length();
String condition = jcrQuery.substring(endIndex);
condition = queryPath + " AND (" + condition + ")";
jcrQuery = jcrQuery.substring(0, startIndex) + " where " + condition;
} else {
jcrQuery += " where " + queryPath;
}
SessionProvider provider = SessionProvider.createSystemProvider();
ManageableRepository repository = repositoryService.getCurrentRepository();
Session session = provider.getSession(sitesLocation.getWorkspace(), repository);
Query query = session.getWorkspace().getQueryManager().createQuery(jcrQuery, Query.SQL);
NodeIterator nodeIterator = query.execute().getNodes();
while (nodeIterator.hasNext()) {
Node node = nodeIterator.nextNode();
exportNode(sitesLocation.getWorkspace(), node.getParent(), null, exportVersionHistory, exportTasks, node);
}
return exportTasks;
}
/**
*
* @param sitesLocation
* @param path
* @param exportSiteTaxonomy
* @param exportVersionHistory
* @return
* @throws Exception
* @throws RepositoryException
*/
private List<ExportTask> exportSiteWithoutSkeleton(NodeLocation sitesLocation, String path, boolean exportSiteTaxonomy, boolean exportVersionHistory) throws Exception, RepositoryException {
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
NodeLocation nodeLocation = new NodeLocation("repository", sitesLocation.getWorkspace(), path, null, true);
Node portalNode = NodeLocation.getNodeByLocation(nodeLocation);
PortalFolderSchemaHandler portalFolderSchemaHandler = new PortalFolderSchemaHandler();
// CSS Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getCSSFolder(portalNode), null, exportVersionHistory));
// JS Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getJSFolder(portalNode), null, exportVersionHistory));
// Document Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getDocumentStorage(portalNode), null, exportVersionHistory));
// Images Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getImagesFolder(portalNode), null, exportVersionHistory));
// Audio Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getAudioFolder(portalNode), null, exportVersionHistory));
// Video Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getVideoFolder(portalNode), null, exportVersionHistory));
// Multimedia Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getMultimediaFolder(portalNode), Arrays.asList("images", "audio", "videos"), exportVersionHistory));
// Link Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getLinkFolder(portalNode), null, exportVersionHistory));
// WebContent Folder
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), portalFolderSchemaHandler.getWebContentStorage(portalNode), Arrays.asList("site artifacts"), exportVersionHistory));
// Site Artifacts Folder
Node webContentNode = portalFolderSchemaHandler.getWebContentStorage(portalNode);
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), webContentNode.getNode("site artifacts"), null, exportVersionHistory));
if (exportSiteTaxonomy) {
// Categories Folder
Node categoriesNode = portalNode.getNode("categories");
exportTasks.addAll(exportSubNodes(sitesLocation.getWorkspace(), categoriesNode, null, exportVersionHistory));
}
return exportTasks;
}
/**
* Export all sub-nodes of the given node
*
* @param repositoryService
* @param workspace
* @param parentNode
* @param excludedNodes
* @return
* @throws RepositoryException
*/
protected List<ExportTask> exportSubNodes(String workspace, Node parentNode, List<String> excludedNodes, boolean exportVersionHistory) throws RepositoryException {
List<ExportTask> subNodesExportTask = new ArrayList<ExportTask>();
NodeIterator childrenNodes = parentNode.getNodes();
while (childrenNodes.hasNext()) {
Node childNode = (Node) childrenNodes.next();
exportNode(workspace, parentNode, excludedNodes, exportVersionHistory, subNodesExportTask, childNode);
}
return subNodesExportTask;
}
private void exportNode(String workspace, Node parentNode, List<String> excludedNodes, boolean exportVersionHistory, List<ExportTask> subNodesExportTask, Node childNode) throws RepositoryException {
if (excludedNodes == null || !excludedNodes.contains(childNode.getName())) {
SiteContentsExportTask siteContentExportTask = new SiteContentsExportTask(repositoryService, workspace, metaData.getOptions().get(SiteMetaData.SITE_NAME), childNode.getPath());
subNodesExportTask.add(siteContentExportTask);
if (exportVersionHistory) {
SiteContentsVersionHistoryExportTask versionHistoryExportTask = new SiteContentsVersionHistoryExportTask(repositoryService, workspace, metaData.getOptions().get(SiteMetaData.SITE_NAME),
childNode.getPath());
subNodesExportTask.add(versionHistoryExportTask);
}
metaData.getExportedFiles().put(siteContentExportTask.getEntry(), parentNode.getPath());
}
}
private SiteMetaDataExportTask getMetaDataExportTask() {
return new SiteMetaDataExportTask(metaData);
}
}
| false | true | public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException {
try {
metaData = new SiteMetaData();
String operationName = operationContext.getOperationName();
PathAddress address = operationContext.getAddress();
OperationAttributes attributes = operationContext.getAttributes();
String siteName = address.resolvePathTemplate("site-name");
if (siteName == null) {
throw new OperationException(operationName, "No site name specified.");
}
wcmConfigurationService = operationContext.getRuntimeContext().getRuntimeComponent(WCMConfigurationService.class);
repositoryService = operationContext.getRuntimeContext().getRuntimeComponent(RepositoryService.class);
dataStorage = operationContext.getRuntimeContext().getRuntimeComponent(DataStorage.class);
pageService = operationContext.getRuntimeContext().getRuntimeComponent(PageService.class);
wcmService = operationContext.getRuntimeContext().getRuntimeComponent(WCMService.class);
NodeLocation sitesLocation = wcmConfigurationService.getLivePortalsLocation();
String sitePath = sitesLocation.getPath();
if (!sitePath.endsWith("/")) {
sitePath += "/";
}
sitePath += siteName;
metaData.getOptions().put(SiteMetaData.SITE_PATH, sitePath);
metaData.getOptions().put(SiteMetaData.SITE_WORKSPACE, sitesLocation.getWorkspace());
metaData.getOptions().put(SiteMetaData.SITE_NAME, siteName);
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
List<String> filters = attributes.getValues("filter");
boolean exportSiteWithSkeleton = true;
String jcrQuery = null;
// no-skeleton as the priority over query
if(!filters.contains("no-skeleton:true") && !filters.contains("no-skeleton:false")) {
for (String filterValue : filters) {
if (filterValue.startsWith("query:")) {
jcrQuery = filterValue.replace("query:", "");
}
}
} else {
exportSiteWithSkeleton = !filters.contains("no-skeleton:true");
}
boolean exportSiteTaxonomy = !filters.contains("taxonomy:false");
boolean exportVersionHistory = !filters.contains("no-history:true");
// Validate Site Structure
validateSiteStructure(siteName);
// Site contents
if (!StringUtils.isEmpty(jcrQuery)) {
exportTasks.addAll(exportQueryResult(sitesLocation, sitePath, jcrQuery, exportVersionHistory));
} else if (exportSiteWithSkeleton) {
exportTasks.addAll(exportSite(sitesLocation, sitePath, exportVersionHistory));
} else {
exportTasks.addAll(exportSiteWithoutSkeleton(sitesLocation, sitePath, exportSiteTaxonomy, exportVersionHistory));
}
// Metadata
exportTasks.add(getMetaDataExportTask());
resultHandler.completed(new ExportResourceModel(exportTasks));
} catch (Exception e) {
throw new OperationException(OperationNames.EXPORT_RESOURCE, "Unable to retrieve the list of the contents sites : " + e.getMessage());
}
}
| public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException {
try {
metaData = new SiteMetaData();
String operationName = operationContext.getOperationName();
PathAddress address = operationContext.getAddress();
OperationAttributes attributes = operationContext.getAttributes();
String siteName = address.resolvePathTemplate("site-name");
if (siteName == null) {
throw new OperationException(operationName, "No site name specified.");
}
wcmConfigurationService = operationContext.getRuntimeContext().getRuntimeComponent(WCMConfigurationService.class);
repositoryService = operationContext.getRuntimeContext().getRuntimeComponent(RepositoryService.class);
dataStorage = operationContext.getRuntimeContext().getRuntimeComponent(DataStorage.class);
pageService = operationContext.getRuntimeContext().getRuntimeComponent(PageService.class);
wcmService = operationContext.getRuntimeContext().getRuntimeComponent(WCMService.class);
NodeLocation sitesLocation = wcmConfigurationService.getLivePortalsLocation();
String sitePath = sitesLocation.getPath();
if (!sitePath.endsWith("/")) {
sitePath += "/";
}
sitePath += siteName;
metaData.getOptions().put(SiteMetaData.SITE_PATH, sitePath);
metaData.getOptions().put(SiteMetaData.SITE_WORKSPACE, sitesLocation.getWorkspace());
metaData.getOptions().put(SiteMetaData.SITE_NAME, siteName);
List<ExportTask> exportTasks = new ArrayList<ExportTask>();
List<String> filters = attributes.getValues("filter");
boolean exportSiteWithSkeleton = true;
String jcrQuery = null;
// no-skeleton as the priority over query
if(!filters.contains("no-skeleton:true") && !filters.contains("no-skeleton:false")) {
for (String filterValue : filters) {
if (filterValue.startsWith("query:")) {
jcrQuery = filterValue.replace("query:", "");
}
}
} else {
exportSiteWithSkeleton = !filters.contains("no-skeleton:true");
}
// "taxonomy" attribute. Defaults to true.
boolean exportSiteTaxonomy = !filters.contains("taxonomy:false");
// "no-history" attribute. Defaults to false.
boolean exportVersionHistory = !filters.contains("no-history:true");
// Validate Site Structure
validateSiteStructure(siteName);
// Site contents
if (!StringUtils.isEmpty(jcrQuery)) {
exportTasks.addAll(exportQueryResult(sitesLocation, sitePath, jcrQuery, exportVersionHistory));
} else if (exportSiteWithSkeleton) {
exportTasks.addAll(exportSite(sitesLocation, sitePath, exportVersionHistory));
} else {
exportTasks.addAll(exportSiteWithoutSkeleton(sitesLocation, sitePath, exportSiteTaxonomy, exportVersionHistory));
}
// Metadata
exportTasks.add(getMetaDataExportTask());
resultHandler.completed(new ExportResourceModel(exportTasks));
} catch (Exception e) {
throw new OperationException(OperationNames.EXPORT_RESOURCE, "Unable to retrieve the list of the contents sites : " + e.getMessage());
}
}
|
diff --git a/asadmin-java/src/main/java/org/n0pe/asadmin/AsAdmin.java b/asadmin-java/src/main/java/org/n0pe/asadmin/AsAdmin.java
index 8eb2cb2..bc7ab7f 100644
--- a/asadmin-java/src/main/java/org/n0pe/asadmin/AsAdmin.java
+++ b/asadmin-java/src/main/java/org/n0pe/asadmin/AsAdmin.java
@@ -1,278 +1,278 @@
/**
* asadmin-glassfish-plugin : a maven plugin for glassfish administratives tasks
*
* Copyright (C) 2008 Paul Merlin
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.n0pe.asadmin;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.n0pe.asadmin.commands.Database;
import org.n0pe.asadmin.commands.Domain;
/**
* asadmin command execution facility built as a multipleton which discriminator is a configuration provider.
*
* TODO : allows AsAdminCommands to provide input lines for stdin, implements this command :
* echo y | asadmin generate-diagnostic-report --outputfile report-dosadi.jar domainName
*
* TODO : handle asadmin invocation return codes with exceptions
*
* @author Paul Merlin <[email protected]>
* @author Christophe Souvignier <[email protected]>
*/
public class AsAdmin {
private static final String ASADMIN_FAILED = "failed";
private static final String OUTPUT_PREFIX = "[ASADMIN] ";
private static Map instances;
public static final String HOST_OPT = "--host";
public static final String PORT_OPT = "--port";
public static final String SECURE_OPT = "--secure";
public static final String USER_OPT = "--user";
public static final String PASSWORDFILE_OPT = "--passwordfile";
public static String ASADMIN_COMMAND_NAME;
static {
ASADMIN_COMMAND_NAME = SystemUtils.IS_OS_WINDOWS
? "asadmin.bat"
: "asadmin";
}
private IAsAdminConfig config;
/**
* Get a asadmin instance configured with the given configuration provider.
*
* @param config
* @return
*/
public static AsAdmin getInstance(final IAsAdminConfig config) {
if (instances == null) {
instances = new HashMap(1);
}
AsAdmin instance = (AsAdmin) instances.get(config);
if (instance == null) {
instance = new AsAdmin(config);
instances.put(config, instance);
}
return instance;
}
private AsAdmin(final IAsAdminConfig config) {
this.config = config;
}
/**
* Run the given list of AsAdmin command.
*
* @param cmdList AsAdmin commands to be run
* @throws org.n0pe.asadmin.AsAdminException AsAdminException
*/
public void run(final AsAdminCmdList cmdList)
throws AsAdminException {
final Iterator it = cmdList.iterator();
IAsAdminCmd cmd;
while (it.hasNext()) {
cmd = (IAsAdminCmd) it.next();
run(cmd);
}
}
/**
* Run the given AsAdmin command.
*
* @param cmd AsAdmin command to be run
* @throws org.n0pe.asadmin.AsAdminException AsAdminException
*/
public void run(final IAsAdminCmd cmd)
throws AsAdminException {
try {
final File gfBinPath = new File(config.getGlassfishHome() + File.separator + "bin");
final String[] cmds = buildProcessParams(cmd, config);
cmds[0] = gfBinPath + File.separator + cmds[0];
int exitCode;
final Process proc;
if (SystemUtils.IS_OS_WINDOWS) {
// Windows
final String command = "\"" + StringUtils.join(cmds, "\" \"") + "\"";
final String[] windowsCommand;
if (SystemUtils.IS_OS_WINDOWS_95 || SystemUtils.IS_OS_WINDOWS_98 || SystemUtils.IS_OS_WINDOWS_ME) {
windowsCommand = new String[]{"command.com", "/C", command};
} else {
- windowsCommand = new String[]{"cmd.com", "/C", command};
+ windowsCommand = new String[]{"cmd.exe", "/C", command};
}
outPrintln("Will run the following command: " + StringUtils.join(windowsCommand, " "));
proc = Runtime.getRuntime().exec(windowsCommand);
} else {
// Non Windows
outPrintln("Will run the following command: " + StringUtils.join(cmds, " "));
proc = Runtime.getRuntime().exec(cmds);
}
final ProcessStreamGobbler errorGobbler = new ProcessStreamGobbler(proc.getErrorStream(),
ProcessStreamGobbler.ERROR);
final ProcessStreamGobbler outputGobbler = new ProcessStreamGobbler(proc.getInputStream(),
ProcessStreamGobbler.OUTPUT);
errorGobbler.start();
outputGobbler.start();
exitCode = proc.waitFor();
if (exitCode != 0) {
throw new AsAdminException("asadmin invocation failed and returned : " + String.valueOf(exitCode));
}
} catch (final InterruptedException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
} catch (final IOException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
}
}
public static String[] buildProcessParams(final IAsAdminCmd cmd, final IAsAdminConfig config) {
final List pbParams = new ArrayList();
pbParams.add(ASADMIN_COMMAND_NAME);
pbParams.add(cmd.getActionCommand());
if (!StringUtils.isEmpty(config.getHost()) &&
!Domain.START.equals(cmd.getActionCommand()) &&
!Domain.STOP.equals(cmd.getActionCommand()) &&
!Database.STOP.equals(cmd.getActionCommand()) &&
!Database.START.equals(cmd.getActionCommand())) {
pbParams.add(HOST_OPT);
pbParams.add(config.getHost());
}
if (!StringUtils.isEmpty(config.getPort()) &&
!Domain.START.equals(cmd.getActionCommand()) &&
!Domain.STOP.equals(cmd.getActionCommand()) &&
!Database.STOP.equals(cmd.getActionCommand()) &&
!Database.START.equals(cmd.getActionCommand())) {
pbParams.add(PORT_OPT);
pbParams.add(config.getPort());
}
if (config.isSecure()) {
pbParams.add(SECURE_OPT);
}
if (cmd.needCredentials()) {
pbParams.add(USER_OPT);
pbParams.add(config.getUser());
pbParams.add(PASSWORDFILE_OPT);
pbParams.add(config.getPasswordFile());
}
pbParams.addAll(Arrays.asList(cmd.getParameters()));
return (String[]) pbParams.toArray(new String[pbParams.size()]);
}
private static void outPrintln(final String message) {
System.out.print(OUTPUT_PREFIX);
System.out.println(message);
}
private static void errPrintln(final String message) {
System.out.print(OUTPUT_PREFIX);
System.out.println(message);
}
/**
* TODO : take a logger as constructor parameter and remove type
*/
private static class ProcessStreamGobbler
extends Thread {
private static final int OUTPUT = 0;
private static final int ERROR = 1;
private InputStream is;
private int type = OUTPUT;
private ProcessStreamGobbler(InputStream is, int type) {
this.is = is;
this.type = type;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
switch (type) {
case OUTPUT:
outPrintln("[OUTPUT] " + line);
break;
case ERROR:
errPrintln("[ERROR] " + line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
| true | true | public void run(final IAsAdminCmd cmd)
throws AsAdminException {
try {
final File gfBinPath = new File(config.getGlassfishHome() + File.separator + "bin");
final String[] cmds = buildProcessParams(cmd, config);
cmds[0] = gfBinPath + File.separator + cmds[0];
int exitCode;
final Process proc;
if (SystemUtils.IS_OS_WINDOWS) {
// Windows
final String command = "\"" + StringUtils.join(cmds, "\" \"") + "\"";
final String[] windowsCommand;
if (SystemUtils.IS_OS_WINDOWS_95 || SystemUtils.IS_OS_WINDOWS_98 || SystemUtils.IS_OS_WINDOWS_ME) {
windowsCommand = new String[]{"command.com", "/C", command};
} else {
windowsCommand = new String[]{"cmd.com", "/C", command};
}
outPrintln("Will run the following command: " + StringUtils.join(windowsCommand, " "));
proc = Runtime.getRuntime().exec(windowsCommand);
} else {
// Non Windows
outPrintln("Will run the following command: " + StringUtils.join(cmds, " "));
proc = Runtime.getRuntime().exec(cmds);
}
final ProcessStreamGobbler errorGobbler = new ProcessStreamGobbler(proc.getErrorStream(),
ProcessStreamGobbler.ERROR);
final ProcessStreamGobbler outputGobbler = new ProcessStreamGobbler(proc.getInputStream(),
ProcessStreamGobbler.OUTPUT);
errorGobbler.start();
outputGobbler.start();
exitCode = proc.waitFor();
if (exitCode != 0) {
throw new AsAdminException("asadmin invocation failed and returned : " + String.valueOf(exitCode));
}
} catch (final InterruptedException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
} catch (final IOException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
}
}
| public void run(final IAsAdminCmd cmd)
throws AsAdminException {
try {
final File gfBinPath = new File(config.getGlassfishHome() + File.separator + "bin");
final String[] cmds = buildProcessParams(cmd, config);
cmds[0] = gfBinPath + File.separator + cmds[0];
int exitCode;
final Process proc;
if (SystemUtils.IS_OS_WINDOWS) {
// Windows
final String command = "\"" + StringUtils.join(cmds, "\" \"") + "\"";
final String[] windowsCommand;
if (SystemUtils.IS_OS_WINDOWS_95 || SystemUtils.IS_OS_WINDOWS_98 || SystemUtils.IS_OS_WINDOWS_ME) {
windowsCommand = new String[]{"command.com", "/C", command};
} else {
windowsCommand = new String[]{"cmd.exe", "/C", command};
}
outPrintln("Will run the following command: " + StringUtils.join(windowsCommand, " "));
proc = Runtime.getRuntime().exec(windowsCommand);
} else {
// Non Windows
outPrintln("Will run the following command: " + StringUtils.join(cmds, " "));
proc = Runtime.getRuntime().exec(cmds);
}
final ProcessStreamGobbler errorGobbler = new ProcessStreamGobbler(proc.getErrorStream(),
ProcessStreamGobbler.ERROR);
final ProcessStreamGobbler outputGobbler = new ProcessStreamGobbler(proc.getInputStream(),
ProcessStreamGobbler.OUTPUT);
errorGobbler.start();
outputGobbler.start();
exitCode = proc.waitFor();
if (exitCode != 0) {
throw new AsAdminException("asadmin invocation failed and returned : " + String.valueOf(exitCode));
}
} catch (final InterruptedException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
} catch (final IOException ex) {
throw new AsAdminException("AsAdmin error occurred: " + ex.getMessage(), ex);
}
}
|
diff --git a/MODSRC/vazkii/tinkerer/common/item/kami/armor/ItemGemChest.java b/MODSRC/vazkii/tinkerer/common/item/kami/armor/ItemGemChest.java
index 2f10f534..e5891ea2 100644
--- a/MODSRC/vazkii/tinkerer/common/item/kami/armor/ItemGemChest.java
+++ b/MODSRC/vazkii/tinkerer/common/item/kami/armor/ItemGemChest.java
@@ -1,91 +1,91 @@
/**
* This class was created by <Vazkii>. It's distributed as
* part of the ThaumicTinkerer Mod.
*
* ThaumicTinkerer is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*
* ThaumicTinkerer is a Derivative Work on Thaumcraft 4.
* Thaumcraft 4 (c) Azanor 2012
* (http://www.minecraftforum.net/topic/1585216-)
*
* File Created @ [Dec 26, 2013, 4:18:27 PM (GMT)]
*/
package vazkii.tinkerer.common.item.kami.armor;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import vazkii.tinkerer.client.model.ModelWings;
import vazkii.tinkerer.common.item.ModItems;
import vazkii.tinkerer.common.item.foci.ItemFocusDeflect;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemGemChest extends ItemIchorclothArmorAdv {
public static List<String> playersWithFlight = new ArrayList();
public ItemGemChest(int par1, int par2) {
super(par1, par2);
}
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) {
return new ModelWings();
}
@Override
boolean ticks() {
return true;
}
@Override
void tickPlayer(EntityPlayer player) {
ItemFocusDeflect.protectFromProjectiles(player);
}
@ForgeSubscribe
public void updatePlayerFlyStatus(LivingUpdateEvent event) {
if(event.entityLiving instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) event.entityLiving;
ItemStack armor = player.getCurrentArmor(3 - armorType);
if(armor != null && armor.getItem() == this)
tickPlayer(player);
if(playersWithFlight.contains(playerStr(player)))
if(shouldPlayerHaveFlight(player))
player.capabilities.allowFlying = true;
else {
- player.capabilities.allowFlying = false;
- if(!player.capabilities.isCreativeMode)
+ if(!player.capabilities.isCreativeMode) {
player.capabilities.isFlying = false;
- player.capabilities.disableDamage = false;
+ player.capabilities.disableDamage = false;
+ }
playersWithFlight.remove(playerStr(player));
}
else if(shouldPlayerHaveFlight(player)) {
playersWithFlight.add(playerStr(player));
player.capabilities.allowFlying = true;
}
}
}
public static String playerStr(EntityPlayer player) {
return player.username + ":" + player.worldObj.isRemote;
}
private static boolean shouldPlayerHaveFlight(EntityPlayer player) {
ItemStack armor = player.getCurrentArmor(2);
return armor != null && armor.itemID == ModItems.ichorChestGem.itemID;
}
}
| false | true | public void updatePlayerFlyStatus(LivingUpdateEvent event) {
if(event.entityLiving instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) event.entityLiving;
ItemStack armor = player.getCurrentArmor(3 - armorType);
if(armor != null && armor.getItem() == this)
tickPlayer(player);
if(playersWithFlight.contains(playerStr(player)))
if(shouldPlayerHaveFlight(player))
player.capabilities.allowFlying = true;
else {
player.capabilities.allowFlying = false;
if(!player.capabilities.isCreativeMode)
player.capabilities.isFlying = false;
player.capabilities.disableDamage = false;
playersWithFlight.remove(playerStr(player));
}
else if(shouldPlayerHaveFlight(player)) {
playersWithFlight.add(playerStr(player));
player.capabilities.allowFlying = true;
}
}
}
| public void updatePlayerFlyStatus(LivingUpdateEvent event) {
if(event.entityLiving instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) event.entityLiving;
ItemStack armor = player.getCurrentArmor(3 - armorType);
if(armor != null && armor.getItem() == this)
tickPlayer(player);
if(playersWithFlight.contains(playerStr(player)))
if(shouldPlayerHaveFlight(player))
player.capabilities.allowFlying = true;
else {
if(!player.capabilities.isCreativeMode) {
player.capabilities.isFlying = false;
player.capabilities.disableDamage = false;
}
playersWithFlight.remove(playerStr(player));
}
else if(shouldPlayerHaveFlight(player)) {
playersWithFlight.add(playerStr(player));
player.capabilities.allowFlying = true;
}
}
}
|
diff --git a/src/java/com/eviware/soapui/security/actions/SecurityTestOptionsAction.java b/src/java/com/eviware/soapui/security/actions/SecurityTestOptionsAction.java
index da5388281..195e55d97 100644
--- a/src/java/com/eviware/soapui/security/actions/SecurityTestOptionsAction.java
+++ b/src/java/com/eviware/soapui/security/actions/SecurityTestOptionsAction.java
@@ -1,88 +1,88 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.security.actions;
import com.eviware.soapui.impl.wsdl.support.HelpUrls;
import com.eviware.soapui.security.SecurityTest;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.action.support.AbstractSoapUIAction;
import com.eviware.soapui.support.types.StringToStringMap;
import com.eviware.x.form.XForm;
import com.eviware.x.form.XFormDialog;
import com.eviware.x.form.XFormDialogBuilder;
import com.eviware.x.form.XFormFactory;
import com.eviware.x.form.XFormField;
import com.eviware.x.form.XFormFieldListener;
/**
* Options dialog for securitytests
*
* @author dragica.soldo
*/
public class SecurityTestOptionsAction extends AbstractSoapUIAction<SecurityTest>
{
private static final String FAIL_ON_ERROR = "Abort on Error";
private static final String FAIL_SECURITYTEST_ON_ERROR = "Fail SecurityTest on Error";
public static final String SOAPUI_ACTION_ID = "SecurityTestOptionsAction";
private XFormDialog dialog;
private XForm form;
public SecurityTestOptionsAction()
{
super( "Options", "Sets options for this SecurityTest" );
}
public void perform( SecurityTest securityTest, Object param )
{
if( dialog == null )
{
XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "SecurityTest Options" );
form = builder.createForm( "Basic" );
form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener()
{
public void valueChanged( XFormField sourceField, String newValue, String oldValue )
{
form.getFormField( FAIL_SECURITYTEST_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) );
}
} );
form.addCheckBox( FAIL_SECURITYTEST_ON_ERROR, "Fail SecurityTest if it has failed TestSteps" );
- dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.TESTCASEOPTIONS_HELP_URL ),
+ dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.SECURITYTESTEDITOR_HELP_URL ),
"Specify general options for this SecurityTest", UISupport.OPTIONS_ICON );
}
StringToStringMap values = new StringToStringMap();
values.put( FAIL_ON_ERROR, String.valueOf( securityTest.getFailOnError() ) );
values.put( FAIL_SECURITYTEST_ON_ERROR, String.valueOf( securityTest.getFailSecurityTestOnScanErrors() ) );
values = dialog.show( values );
if( dialog.getReturnValue() == XFormDialog.OK_OPTION )
{
try
{
securityTest.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) );
securityTest.setFailSecurityTestOnScanErrors( Boolean
.parseBoolean( values.get( FAIL_SECURITYTEST_ON_ERROR ) ) );
}
catch( Exception e1 )
{
UISupport.showErrorMessage( e1.getMessage() );
}
}
}
}
| true | true | public void perform( SecurityTest securityTest, Object param )
{
if( dialog == null )
{
XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "SecurityTest Options" );
form = builder.createForm( "Basic" );
form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener()
{
public void valueChanged( XFormField sourceField, String newValue, String oldValue )
{
form.getFormField( FAIL_SECURITYTEST_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) );
}
} );
form.addCheckBox( FAIL_SECURITYTEST_ON_ERROR, "Fail SecurityTest if it has failed TestSteps" );
dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.TESTCASEOPTIONS_HELP_URL ),
"Specify general options for this SecurityTest", UISupport.OPTIONS_ICON );
}
StringToStringMap values = new StringToStringMap();
values.put( FAIL_ON_ERROR, String.valueOf( securityTest.getFailOnError() ) );
values.put( FAIL_SECURITYTEST_ON_ERROR, String.valueOf( securityTest.getFailSecurityTestOnScanErrors() ) );
values = dialog.show( values );
if( dialog.getReturnValue() == XFormDialog.OK_OPTION )
{
try
{
securityTest.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) );
securityTest.setFailSecurityTestOnScanErrors( Boolean
.parseBoolean( values.get( FAIL_SECURITYTEST_ON_ERROR ) ) );
}
catch( Exception e1 )
{
UISupport.showErrorMessage( e1.getMessage() );
}
}
}
| public void perform( SecurityTest securityTest, Object param )
{
if( dialog == null )
{
XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "SecurityTest Options" );
form = builder.createForm( "Basic" );
form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener()
{
public void valueChanged( XFormField sourceField, String newValue, String oldValue )
{
form.getFormField( FAIL_SECURITYTEST_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) );
}
} );
form.addCheckBox( FAIL_SECURITYTEST_ON_ERROR, "Fail SecurityTest if it has failed TestSteps" );
dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.SECURITYTESTEDITOR_HELP_URL ),
"Specify general options for this SecurityTest", UISupport.OPTIONS_ICON );
}
StringToStringMap values = new StringToStringMap();
values.put( FAIL_ON_ERROR, String.valueOf( securityTest.getFailOnError() ) );
values.put( FAIL_SECURITYTEST_ON_ERROR, String.valueOf( securityTest.getFailSecurityTestOnScanErrors() ) );
values = dialog.show( values );
if( dialog.getReturnValue() == XFormDialog.OK_OPTION )
{
try
{
securityTest.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) );
securityTest.setFailSecurityTestOnScanErrors( Boolean
.parseBoolean( values.get( FAIL_SECURITYTEST_ON_ERROR ) ) );
}
catch( Exception e1 )
{
UISupport.showErrorMessage( e1.getMessage() );
}
}
}
|
diff --git a/zssapp/test/SS_117_Test.java b/zssapp/test/SS_117_Test.java
index de7a31d..563c560 100644
--- a/zssapp/test/SS_117_Test.java
+++ b/zssapp/test/SS_117_Test.java
@@ -1,38 +1,36 @@
/* order_test_1Test.java
Purpose:
Description:
History:
Sep, 7, 2010 17:30:59 PM
Copyright (C) 2010 Potix Corporation. All Rights Reserved.
This program is distributed under Apache License Version 2.0 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
*/
//change row 12 height to 40
public class SS_117_Test extends SSAbstractTestCase {
@Override
protected void executeTest() {
String f13value = getSpecifiedCell(5,12).text();
rightClickRowHeader(11);
click(jq("$rowHeight a.z-menu-item-cnt"));
waitResponse();
type(jq("$headerSize"), "40");
waitResponse();
click(jq("$okBtn td.z-button-cm"));
waitResponse();
- //verify, set height to 40, but expect 39 as result
- int height = getSpecifiedCell(5,11).height();
- verifyTrue(height == 39);
+ verifyTrue(getSpecifiedCell(5,11).height() == 40);
}
}
| true | true | protected void executeTest() {
String f13value = getSpecifiedCell(5,12).text();
rightClickRowHeader(11);
click(jq("$rowHeight a.z-menu-item-cnt"));
waitResponse();
type(jq("$headerSize"), "40");
waitResponse();
click(jq("$okBtn td.z-button-cm"));
waitResponse();
//verify, set height to 40, but expect 39 as result
int height = getSpecifiedCell(5,11).height();
verifyTrue(height == 39);
}
| protected void executeTest() {
String f13value = getSpecifiedCell(5,12).text();
rightClickRowHeader(11);
click(jq("$rowHeight a.z-menu-item-cnt"));
waitResponse();
type(jq("$headerSize"), "40");
waitResponse();
click(jq("$okBtn td.z-button-cm"));
waitResponse();
verifyTrue(getSpecifiedCell(5,11).height() == 40);
}
|
diff --git a/src/main/java/info/gomeow/chester/Chester.java b/src/main/java/info/gomeow/chester/Chester.java
index ffd1214..ad0be4d 100644
--- a/src/main/java/info/gomeow/chester/Chester.java
+++ b/src/main/java/info/gomeow/chester/Chester.java
@@ -1,199 +1,200 @@
package info.gomeow.chester;
import info.gomeow.chester.API.ChesterBroadcastEvent;
import info.gomeow.chester.API.ChesterLogEvent;
import info.gomeow.chester.util.Metrics;
import info.gomeow.chester.util.Updater;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.jibble.jmegahal.JMegaHal;
public class Chester extends JavaPlugin implements Listener {
public static String LINK;
public static boolean UPDATE;
public static String NEWVERSION;
JMegaHal hal = new JMegaHal();
List<String> triggerwords;
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
saveDefaultConfig();
if(getConfig().getString("chatcolor") == null) {
getConfig().set("chatcolor", "r");
}
if(getConfig().getString("check-update") == null) {
getConfig().set("check-update", true);
}
triggerwords = getConfig().getStringList("triggerwords");
if(triggerwords.size() == 0) {
triggerwords.add("chester");
}
System.out.println(triggerwords);
startChester();
startMetrics();
checkUpdate();
}
public void firstRun(File f) {
try {
f.createNewFile();
} catch(IOException ioe) {
ioe.printStackTrace();
}
hal.add("Hello World");
hal.add("Can I have some coffee?");
hal.add("Please slap me");
}
public void transfer(ObjectInputStream in) throws ClassNotFoundException, IOException {
hal = (JMegaHal) in.readObject();
if(in != null) {
in.close();
}
}
public void checkUpdate() {
new BukkitRunnable() {
public void run() {
if(getConfig().getBoolean("check-update", true)) {
try {
Updater u = new Updater(getDescription().getVersion());
if(UPDATE = u.getUpdate()) {
LINK = u.getLink();
NEWVERSION = u.getNewVersion();
}
} catch(Exception e) {
getLogger().log(Level.WARNING, "Failed to check for updates.");
getLogger().log(Level.WARNING, "Report this stack trace to gomeow.");
e.printStackTrace();
}
}
}
}.runTaskAsynchronously(this);
}
public void startMetrics() {
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch(IOException e) {
e.printStackTrace();
}
}
public void startChester() {
try {
File chesterFile = new File(this.getDataFolder(), "brain.chester");
File dir = new File("plugins" + File.separator + "Chester");
if(!dir.exists()) {
dir.mkdirs();
}
File old = new File(this.getDataFolder(), "chester.brain");
if(old.exists()) {
transfer(new ObjectInputStream(new FileInputStream(old)));
}
if(chesterFile.exists()) {
FileReader fr = new FileReader(chesterFile);
BufferedReader br = new BufferedReader(fr);
String line = null;
while((line = br.readLine()) != null) {
hal.add(line);
}
br.close();
} else {
firstRun(chesterFile);
}
} catch(IOException ioe) {
} catch(ClassNotFoundException cnfe) {
}
}
public String clean(String string) {
if(string != null && string.length() > 300) {
string = string.substring(0, 300);
}
String newstring = string.replaceAll("<.*?>", "").replaceAll("\\[.*?\\]", "");
return newstring;
}
public void write(String sentence) {
File chesterFile = new File(this.getDataFolder(), "brain.chester");
try {
FileWriter fw = new FileWriter(chesterFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(sentence + "\n");
bw.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if(player.isOp() && UPDATE) {
player.sendMessage(ChatColor.DARK_AQUA + "Version " + NEWVERSION + " of Chester is up for download!");
player.sendMessage(ChatColor.DARK_AQUA + LINK + " to view the changelog and download!");
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onChat(final PlayerChatEvent event) {
Player player = event.getPlayer();
final String message = event.getMessage();
- ChesterLogEvent logEvent = new ChesterLogEvent(player, message);
- getServer().getPluginManager().callEvent(logEvent);
- if(player.hasPermission("chester.log") || logEvent.isCancelled()) {
+ ChesterLogEvent cle = new ChesterLogEvent(player, message);
+ getServer().getPluginManager().callEvent(cle);
+ if(player.hasPermission("chester.log") && !cle.isCancelled()) {
write(clean(message));
}
if(player.hasPermission("chester.trigger")) {
boolean cancel = false;
for(String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
cancel = true;
break;
}
}
if(!cancel) {
hal.add(message);
}
}
for(final String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
String sentence = hal.getSentence();
while(sentence.matches("^.*(?i)" + trigger + ".*$")) {
sentence = hal.getSentence();
}
ChesterBroadcastEvent cbe = new ChesterBroadcastEvent(sentence);
+ getServer().getPluginManager().callEvent(cbe);
for(Player plyer:cbe.getRecipients()) {
plyer.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("nickname")) + ChatColor.getByChar(getConfig().getString("chatcolor")) + " " + ChatColor.translateAlternateColorCodes('&', sentence));
}
break;
}
}
}
}
| false | true | public void onChat(final PlayerChatEvent event) {
Player player = event.getPlayer();
final String message = event.getMessage();
ChesterLogEvent logEvent = new ChesterLogEvent(player, message);
getServer().getPluginManager().callEvent(logEvent);
if(player.hasPermission("chester.log") || logEvent.isCancelled()) {
write(clean(message));
}
if(player.hasPermission("chester.trigger")) {
boolean cancel = false;
for(String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
cancel = true;
break;
}
}
if(!cancel) {
hal.add(message);
}
}
for(final String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
String sentence = hal.getSentence();
while(sentence.matches("^.*(?i)" + trigger + ".*$")) {
sentence = hal.getSentence();
}
ChesterBroadcastEvent cbe = new ChesterBroadcastEvent(sentence);
for(Player plyer:cbe.getRecipients()) {
plyer.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("nickname")) + ChatColor.getByChar(getConfig().getString("chatcolor")) + " " + ChatColor.translateAlternateColorCodes('&', sentence));
}
break;
}
}
}
| public void onChat(final PlayerChatEvent event) {
Player player = event.getPlayer();
final String message = event.getMessage();
ChesterLogEvent cle = new ChesterLogEvent(player, message);
getServer().getPluginManager().callEvent(cle);
if(player.hasPermission("chester.log") && !cle.isCancelled()) {
write(clean(message));
}
if(player.hasPermission("chester.trigger")) {
boolean cancel = false;
for(String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
cancel = true;
break;
}
}
if(!cancel) {
hal.add(message);
}
}
for(final String trigger:triggerwords) {
if(message.matches("^.*(?i)" + trigger + ".*$")) {
String sentence = hal.getSentence();
while(sentence.matches("^.*(?i)" + trigger + ".*$")) {
sentence = hal.getSentence();
}
ChesterBroadcastEvent cbe = new ChesterBroadcastEvent(sentence);
getServer().getPluginManager().callEvent(cbe);
for(Player plyer:cbe.getRecipients()) {
plyer.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("nickname")) + ChatColor.getByChar(getConfig().getString("chatcolor")) + " " + ChatColor.translateAlternateColorCodes('&', sentence));
}
break;
}
}
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java
index 60b1f8a88..ba031c497 100755
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/indels/IndelRealigner.java
@@ -1,1619 +1,1620 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.picard.reference.IndexedFastaSequenceFile;
import net.sf.samtools.*;
import net.sf.samtools.util.RuntimeIOException;
import net.sf.samtools.util.SequenceUtil;
import net.sf.samtools.util.StringUtil;
import org.broad.tribble.Feature;
import org.broadinstitute.sting.commandline.*;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.io.StingSAMFileWriter;
import org.broadinstitute.sting.gatk.refdata.ReadMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.utils.GATKFeature;
import org.broadinstitute.sting.gatk.walkers.BAQMode;
import org.broadinstitute.sting.gatk.walkers.ReadWalker;
import org.broadinstitute.sting.utils.*;
import org.broadinstitute.sting.utils.baq.BAQ;
import org.broadinstitute.sting.utils.collections.Pair;
import org.broadinstitute.sting.utils.exceptions.ReviewedStingException;
import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.exceptions.UserException;
import org.broadinstitute.sting.utils.fasta.CachingIndexedFastaSequenceFile;
import org.broadinstitute.sting.utils.sam.AlignmentUtils;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;
import org.broadinstitute.sting.utils.sam.NWaySAMFileWriter;
import org.broadinstitute.sting.utils.sam.ReadUtils;
import org.broadinstitute.sting.utils.text.TextFormattingUtils;
import org.broadinstitute.sting.utils.text.XReadLines;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
/**
* Performs local realignment of reads based on misalignments due to the presence of indels.
*
* <p>
* The local realignment tool is designed to consume one or more BAM files and to locally realign reads such that the number of mismatching bases
* is minimized across all the reads. In general, a large percent of regions requiring local realignment are due to the presence of an insertion
* or deletion (indels) in the individual's genome with respect to the reference genome. Such alignment artifacts result in many bases mismatching
* the reference near the misalignment, which are easily mistaken as SNPs. Moreover, since read mapping algorithms operate on each read independently,
* it is impossible to place reads on the reference genome such at mismatches are minimized across all reads. Consequently, even when some reads are
* correctly mapped with indels, reads covering the indel near just the start or end of the read are often incorrectly mapped with respect the true indel,
* also requiring realignment. Local realignment serves to transform regions with misalignments due to indels into clean reads containing a consensus
* indel suitable for standard variant discovery approaches. Unlike most mappers, this walker uses the full alignment context to determine whether an
* appropriate alternate reference (i.e. indel) exists. Following local realignment, the GATK tool Unified Genotyper can be used to sensitively and
* specifically identify indels.
* <p>
* <ol>There are 2 steps to the realignment process:
* <li>Determining (small) suspicious intervals which are likely in need of realignment (see the RealignerTargetCreator tool)</li>
* <li>Running the realigner over those intervals (IndelRealigner)</li>
* </ol>
* <p>
* An important note: the input bam(s), reference, and known indel file(s) should be the same ones used for the RealignerTargetCreator step.
* <p>
* Another important note: because reads produced from the 454 technology inherently contain false indels, the realigner will not currently work with them
* (or with reads from similar technologies).
*
* <h2>Input</h2>
* <p>
* One or more aligned BAM files and optionally one or more lists of known indels.
* </p>
*
* <h2>Output</h2>
* <p>
* A realigned version of your input BAM file(s).
* </p>
*
* <h2>Examples</h2>
* <pre>
* java -Xmx4g -jar GenomeAnalysisTK.jar \
* -I input.bam \
* -R ref.fasta \
* -T IndelRealigner \
* -targetIntervals intervalListFromRTC.intervals \
* -o realignedBam.bam \
* [--known /path/to/indels.vcf] \
* [-compress 0] (this argument recommended to speed up the process *if* this is only a temporary file; otherwise, use the default value)
* </pre>
*
* @author ebanks
*/
@BAQMode(QualityMode = BAQ.QualityMode.ADD_TAG, ApplicationTime = BAQ.ApplicationTime.ON_OUTPUT)
public class IndelRealigner extends ReadWalker<Integer, Integer> {
public static final String ORIGINAL_CIGAR_TAG = "OC";
public static final String ORIGINAL_POSITION_TAG = "OP";
public static final String PROGRAM_RECORD_NAME = "GATK IndelRealigner";
public enum ConsensusDeterminationModel {
/**
* Uses only indels from a provided ROD of known indels.
*/
KNOWNS_ONLY,
/**
* Additionally uses indels already present in the original alignments of the reads.
*/
USE_READS,
/**
* Additionally uses 'Smith-Waterman' to generate alternate consenses.
*/
USE_SW
}
/**
* Any number of VCF files representing known indels to be used for constructing alternate consenses.
* Could be e.g. dbSNP and/or official 1000 Genomes indel calls. Non-indel variants in these files will be ignored.
*/
@Input(fullName="knownAlleles", shortName = "known", doc="Input VCF file(s) with known indels", required=false)
public List<RodBinding<VariantContext>> known = Collections.emptyList();
/**
* The interval list output from the RealignerTargetCreator tool using the same bam(s), reference, and known indel file(s).
*/
@Input(fullName="targetIntervals", shortName="targetIntervals", doc="intervals file output from RealignerTargetCreator", required=true)
protected IntervalBinding<Feature> intervalsFile = null;
/**
* This term is equivalent to "significance" - i.e. is the improvement significant enough to merit realignment? Note that this number
* should be adjusted based on your particular data set. For low coverage and/or when looking for indels with low allele frequency,
* this number should be smaller.
*/
@Argument(fullName="LODThresholdForCleaning", shortName="LOD", doc="LOD threshold above which the cleaner will clean", required=false)
protected double LOD_THRESHOLD = 5.0;
/**
* The realigned bam file.
*/
@Output(required=false, doc="Output bam")
protected StingSAMFileWriter writer = null;
protected ConstrainedMateFixingManager manager = null;
protected SAMFileWriter writerToUse = null;
/**
* We recommend that users run with USE_READS when trying to realign high quality longer read data mapped with a gapped aligner;
* Smith-Waterman is really only necessary when using an ungapped aligner (e.g. MAQ in the case of single-end read data).
*/
@Argument(fullName = "consensusDeterminationModel", shortName = "model", doc = "Determines how to compute the possible alternate consenses", required = false)
public ConsensusDeterminationModel consensusModel = ConsensusDeterminationModel.USE_READS;
// ADVANCED OPTIONS FOLLOW
/**
* For expert users only! This is similar to the argument in the RealignerTargetCreator walker. The point here is that the realigner
* will only proceed with the realignment (even above the given threshold) if it minimizes entropy among the reads (and doesn't simply
* push the mismatch column to another position). This parameter is just a heuristic and should be adjusted based on your particular data set.
*/
@Advanced
@Argument(fullName="entropyThreshold", shortName="entropy", doc="percentage of mismatches at a locus to be considered having high entropy", required=false)
protected double MISMATCH_THRESHOLD = 0.15;
/**
* For expert users only! To minimize memory consumption you can lower this number (but then the tool may skip realignment on regions with too much coverage;
* and if the number is too low, it may generate errors during realignment). Just make sure to give Java enough memory! 4Gb should be enough with the default value.
*/
@Advanced
@Argument(fullName="maxReadsInMemory", shortName="maxInMemory", doc="max reads allowed to be kept in memory at a time by the SAMFileWriter", required=false)
protected int MAX_RECORDS_IN_MEMORY = 150000;
/**
* For expert users only!
*/
@Advanced
@Argument(fullName="maxIsizeForMovement", shortName="maxIsize", doc="maximum insert size of read pairs that we attempt to realign", required=false)
protected int MAX_ISIZE_FOR_MOVEMENT = 3000;
/**
* For expert users only!
*/
@Advanced
@Argument(fullName="maxPositionalMoveAllowed", shortName="maxPosMove", doc="maximum positional move in basepairs that a read can be adjusted during realignment", required=false)
protected int MAX_POS_MOVE_ALLOWED = 200;
/**
* For expert users only! If you need to find the optimal solution regardless of running time, use a higher number.
*/
@Advanced
@Argument(fullName="maxConsensuses", shortName="maxConsensuses", doc="max alternate consensuses to try (necessary to improve performance in deep coverage)", required=false)
protected int MAX_CONSENSUSES = 30;
/**
* For expert users only! If you need to find the optimal solution regardless of running time, use a higher number.
*/
@Advanced
@Argument(fullName="maxReadsForConsensuses", shortName="greedy", doc="max reads used for finding the alternate consensuses (necessary to improve performance in deep coverage)", required=false)
protected int MAX_READS_FOR_CONSENSUSES = 120;
/**
* For expert users only! If this value is exceeded at a given interval, realignment is not attempted and the reads are passed to the output file(s) as-is.
* If you need to allow more reads (e.g. with very deep coverage) regardless of memory, use a higher number.
*/
@Advanced
@Argument(fullName="maxReadsForRealignment", shortName="maxReads", doc="max reads allowed at an interval for realignment", required=false)
protected int MAX_READS = 20000;
@Advanced
@Argument(fullName="noOriginalAlignmentTags", shortName="noTags", required=false, doc="Don't output the original cigar or alignment start tags for each realigned read in the output bam")
protected boolean NO_ORIGINAL_ALIGNMENT_TAGS = false;
/**
* Reads from all input files will be realigned together, but then each read will be saved in the output file corresponding to the input file that
* the read came from. There are two ways to generate output bam file names: 1) if the value of this argument is a general string (e.g. '.cleaned.bam'),
* then extensions (".bam" or ".sam") will be stripped from the input file names and the provided string value will be pasted on instead; 2) if the
* value ends with a '.map' (e.g. input_output.map), then the two-column tab-separated file with the specified name must exist and list unique output
* file name (2nd column) for each input file name (1st column).
*/
@Argument(fullName="nWayOut", shortName="nWayOut", required=false, doc="Generate one output file for each input (-I) bam file")
protected String N_WAY_OUT = null;
@Hidden
@Argument(fullName="generate_nWayOut_md5s",doc="Generate md5sums for BAMs")
protected boolean generateMD5s = false;
// DEBUGGING OPTIONS FOLLOW
@Hidden
@Argument(fullName="check_early",shortName="check_early",required=false,doc="Do early check of reads against existing consensuses")
protected boolean CHECKEARLY = false;
@Hidden
@Argument(fullName="noPGTag", shortName="noPG", required=false,
doc="Don't output the usual PG tag in the realigned bam file header. FOR DEBUGGING PURPOSES ONLY. This option is required in order to pass integration tests.")
protected boolean NO_PG_TAG = false;
@Hidden
@Argument(fullName="keepPGTags", shortName="keepPG", required=false,
doc="Keep older PG tags left in the bam header by previous runs of this tool (by default, all these "+
"historical tags will be replaced by the latest tag generated in the current run).")
protected boolean KEEP_ALL_PG_RECORDS = false;
@Hidden
@Output(fullName="indelsFileForDebugging", shortName="indels", required=false, doc="Output file (text) for the indels found; FOR DEBUGGING PURPOSES ONLY")
protected String OUT_INDELS = null;
@Hidden
@Output(fullName="statisticsFileForDebugging", shortName="stats", doc="print out statistics (what does or doesn't get cleaned); FOR DEBUGGING PURPOSES ONLY", required=false)
protected String OUT_STATS = null;
@Hidden
@Output(fullName="SNPsFileForDebugging", shortName="snps", doc="print out whether mismatching columns do or don't get cleaned out; FOR DEBUGGING PURPOSES ONLY", required=false)
protected String OUT_SNPS = null;
// fasta reference reader to supplement the edges of the reference sequence
private IndexedFastaSequenceFile referenceReader;
// the intervals input by the user
private Iterator<GenomeLoc> intervals = null;
// the current interval in the list
private GenomeLoc currentInterval = null;
private boolean sawReadInCurrentInterval = false;
// the reads and known indels that fall into the current interval
private final ReadBin readsToClean = new ReadBin();
private final ArrayList<GATKSAMRecord> readsNotToClean = new ArrayList<GATKSAMRecord>();
private final ArrayList<VariantContext> knownIndelsToTry = new ArrayList<VariantContext>();
private final HashSet<Object> indelRodsSeen = new HashSet<Object>();
private final HashSet<GATKSAMRecord> readsActuallyCleaned = new HashSet<GATKSAMRecord>();
private static final int MAX_QUAL = 99;
// fraction of mismatches that need to no longer mismatch for a column to be considered cleaned
private static final double MISMATCH_COLUMN_CLEANED_FRACTION = 0.75;
private static final double SW_MATCH = 30.0; // 1.0;
private static final double SW_MISMATCH = -10.0; //-1.0/3.0;
private static final double SW_GAP = -10.0; //-1.0-1.0/3.0;
private static final double SW_GAP_EXTEND = -2.0; //-1.0/.0;
// reference base padding size
// TODO -- make this a command-line argument if the need arises
private static final int REFERENCE_PADDING = 30;
// other output files
private FileWriter indelOutput = null;
private FileWriter statsOutput = null;
private FileWriter snpsOutput = null;
//###protected Map<SAMReaderID, ConstrainedMateFixingManager> nwayWriters = null;
// debug info for lazy SW evaluation:
private long exactMatchesFound = 0; // how many reads exactly matched a consensus we already had
private long SWalignmentRuns = 0; // how many times (=for how many reads) we ran SW alignment
private long SWalignmentSuccess = 0; // how many SW alignments were "successful" (i.e. found a workable indel and resulted in non-null consensus)
private Map<String,String> loadFileNameMap(String mapFile) {
Map<String,String> fname_map = new HashMap<String,String>();
try {
XReadLines reader = new XReadLines(new File(mapFile),true);
for ( String line : reader ) {
if ( line.length() == 0 ) continue;
String fields[] = line.split("\t");
if ( fields.length != 2 )
throw new UserException.BadInput("Input-output map file must have exactly two columns. Offending line:\n"+line);
if ( fields[0].length() == 0 || fields[1].length() == 0 )
throw new UserException.BadInput("Input-output map file can not have empty strings in either column. Offending line:\n"+line);
if ( fname_map.containsKey(fields[0]) )
throw new UserException.BadInput("Input-output map file contains duplicate entries for input name "+fields[0]);
if ( fname_map.containsValue(fields[1]) )
throw new UserException.BadInput("Input-output map file maps multiple entries onto single output name "+fields[1]);
fname_map.put(fields[0],fields[1]);
}
} catch (IOException e) {
throw new StingException("I/O Error while reading input-output map file "+N_WAY_OUT+": "+e.getMessage());
}
return fname_map;
}
public void initialize() {
if ( N_WAY_OUT == null && writer == null ) {
throw new UserException.CommandLineException("Either -o or -nWayOut must be specified");
}
if ( N_WAY_OUT != null && writer != null ) {
throw new UserException.CommandLineException("-o and -nWayOut can not be used simultaneously");
}
if ( LOD_THRESHOLD < 0.0 )
throw new RuntimeException("LOD threshold cannot be a negative number");
if ( MISMATCH_THRESHOLD <= 0.0 || MISMATCH_THRESHOLD > 1.0 )
throw new RuntimeException("Entropy threshold must be a fraction between 0 and 1");
try {
referenceReader = new CachingIndexedFastaSequenceFile(getToolkit().getArguments().referenceFile);
}
catch(FileNotFoundException ex) {
throw new UserException.CouldNotReadInputFile(getToolkit().getArguments().referenceFile,ex);
}
intervals = intervalsFile.getIntervals(getToolkit()).iterator();
currentInterval = intervals.hasNext() ? intervals.next() : null;
writerToUse = writer;
if ( N_WAY_OUT != null ) {
boolean createIndex = true;
if ( N_WAY_OUT.toUpperCase().endsWith(".MAP") ) {
writerToUse = new NWaySAMFileWriter(getToolkit(),loadFileNameMap(N_WAY_OUT),
SAMFileHeader.SortOrder.coordinate,true, createIndex, generateMD5s,createProgramRecord(),KEEP_ALL_PG_RECORDS);
} else {
writerToUse = new NWaySAMFileWriter(getToolkit(),N_WAY_OUT,SAMFileHeader.SortOrder.coordinate,true,
createIndex, generateMD5s,createProgramRecord(),KEEP_ALL_PG_RECORDS);
}
} else {
// set up the output writer
setupWriter(getToolkit().getSAMFileHeader());
}
manager = new ConstrainedMateFixingManager(writerToUse, getToolkit().getGenomeLocParser(), MAX_ISIZE_FOR_MOVEMENT, MAX_POS_MOVE_ALLOWED, MAX_RECORDS_IN_MEMORY);
if ( OUT_INDELS != null ) {
try {
indelOutput = new FileWriter(new File(OUT_INDELS));
} catch (Exception e) {
logger.error("Failed to create output file "+ OUT_INDELS+". Indel output will be suppressed");
logger.error(e.getMessage());
indelOutput = null;
}
}
if ( OUT_STATS != null ) {
try {
statsOutput = new FileWriter(new File(OUT_STATS));
} catch (Exception e) {
logger.error("Failed to create output file "+ OUT_STATS+". Cleaning stats output will be suppressed");
logger.error(e.getMessage());
statsOutput = null;
}
}
if ( OUT_SNPS != null ) {
try {
snpsOutput = new FileWriter(new File(OUT_SNPS));
} catch (Exception e) {
logger.error("Failed to create output file "+ OUT_SNPS+". Cleaning snps output will be suppressed");
logger.error(e.getMessage());
snpsOutput = null;
}
}
}
private void setupWriter(SAMFileHeader header) {
if ( !NO_PG_TAG ) {
final SAMProgramRecord programRecord = createProgramRecord();
List<SAMProgramRecord> oldRecords = header.getProgramRecords();
List<SAMProgramRecord> newRecords = new ArrayList<SAMProgramRecord>(oldRecords.size()+1);
for ( SAMProgramRecord record : oldRecords ) {
if ( !record.getId().startsWith(PROGRAM_RECORD_NAME) || KEEP_ALL_PG_RECORDS )
newRecords.add(record);
}
newRecords.add(programRecord);
header.setProgramRecords(newRecords);
}
writer.writeHeader(header);
writer.setPresorted(true);
}
private SAMProgramRecord createProgramRecord() {
if ( NO_PG_TAG ) return null;
final SAMProgramRecord programRecord = new SAMProgramRecord(PROGRAM_RECORD_NAME);
final ResourceBundle headerInfo = TextFormattingUtils.loadResourceBundle("StingText");
try {
final String version = headerInfo.getString("org.broadinstitute.sting.gatk.version");
programRecord.setProgramVersion(version);
} catch (MissingResourceException e) {}
programRecord.setCommandLine(getToolkit().createApproximateCommandLineArgumentString(getToolkit(), this));
return programRecord;
}
private void emit(final SAMRecord read) {
// check to see whether the read was modified by looking at the temporary tag
boolean wasModified = readsActuallyCleaned.contains(read);
try {
manager.addRead(read, wasModified);
} catch (RuntimeIOException e) {
throw new UserException.ErrorWritingBamFile(e.getMessage());
}
}
private void emitReadLists() {
// pre-merge lists to sort them in preparation for constrained SAMFileWriter
readsNotToClean.addAll(readsToClean.getReads());
ReadUtils.coordinateSortReads(readsNotToClean);
manager.addReads(readsNotToClean, readsActuallyCleaned);
readsToClean.clear();
readsNotToClean.clear();
readsActuallyCleaned.clear();
}
public Integer map(ReferenceContext ref, GATKSAMRecord read, ReadMetaDataTracker metaDataTracker) {
if ( currentInterval == null ) {
emit(read);
return 0;
}
// edge case: when the last target interval abuts the end of the genome, we'll get one of the
// unmapped reads while the currentInterval still isn't null. We need to trigger the cleaning
// at this point without trying to create a GenomeLoc.
if ( read.getReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX ) {
cleanAndCallMap(ref, read, metaDataTracker, null);
return 0;
}
GenomeLoc readLoc = getToolkit().getGenomeLocParser().createGenomeLoc(read);
// hack to get around unmapped reads having screwy locations
if ( readLoc.getStop() == 0 )
readLoc = getToolkit().getGenomeLocParser().createGenomeLoc(readLoc.getContig(), readLoc.getStart(), readLoc.getStart());
if ( readLoc.isBefore(currentInterval) ) {
if ( !sawReadInCurrentInterval )
emit(read);
else
readsNotToClean.add(read);
}
else if ( readLoc.overlapsP(currentInterval) ) {
sawReadInCurrentInterval = true;
if ( doNotTryToClean(read) ) {
readsNotToClean.add(read);
} else {
readsToClean.add(read);
// add the rods to the list of known variants
populateKnownIndels(metaDataTracker, ref);
}
if ( readsToClean.size() + readsNotToClean.size() >= MAX_READS ) {
logger.info("Not attempting realignment in interval " + currentInterval + " because there are too many reads.");
abortCleanForCurrentInterval();
}
}
else { // the read is past the current interval
cleanAndCallMap(ref, read, metaDataTracker, readLoc);
}
return 0;
}
private void abortCleanForCurrentInterval() {
emitReadLists();
currentInterval = intervals.hasNext() ? intervals.next() : null;
sawReadInCurrentInterval = false;
}
private boolean doNotTryToClean(SAMRecord read) {
return read.getReadUnmappedFlag() ||
read.getNotPrimaryAlignmentFlag() ||
read.getReadFailsVendorQualityCheckFlag() ||
read.getMappingQuality() == 0 ||
read.getAlignmentStart() == SAMRecord.NO_ALIGNMENT_START ||
ConstrainedMateFixingManager.iSizeTooBigToMove(read, MAX_ISIZE_FOR_MOVEMENT) ||
ReadUtils.is454Read(read);
// TODO -- it would be nice if we could use indels from 454 reads as alternate consenses
}
private void cleanAndCallMap(ReferenceContext ref, GATKSAMRecord read, ReadMetaDataTracker metaDataTracker, GenomeLoc readLoc) {
if ( readsToClean.size() > 0 ) {
GenomeLoc earliestPossibleMove = getToolkit().getGenomeLocParser().createGenomeLoc(readsToClean.getReads().get(0));
if ( manager.canMoveReads(earliestPossibleMove) )
clean(readsToClean);
}
knownIndelsToTry.clear();
indelRodsSeen.clear();
emitReadLists();
try {
do {
currentInterval = intervals.hasNext() ? intervals.next() : null;
} while ( currentInterval != null && (readLoc == null || currentInterval.isBefore(readLoc)) );
} catch (ReviewedStingException e) {
throw new UserException.MissortedFile(new File(intervalsFile.getSource()), " *** Are you sure that your interval file is sorted? If not, you must use the --targetIntervalsAreNotSorted argument. ***", e);
}
sawReadInCurrentInterval = false;
// call back into map now that the state has been updated
map(ref, read, metaDataTracker);
}
public Integer reduceInit() {
return 0;
}
public Integer reduce(Integer value, Integer sum) {
return sum + value;
}
public void onTraversalDone(Integer result) {
if ( readsToClean.size() > 0 ) {
GenomeLoc earliestPossibleMove = getToolkit().getGenomeLocParser().createGenomeLoc(readsToClean.getReads().get(0));
if ( manager.canMoveReads(earliestPossibleMove) )
clean(readsToClean);
emitReadLists();
} else if ( readsNotToClean.size() > 0 ) {
emitReadLists();
}
knownIndelsToTry.clear();
indelRodsSeen.clear();
if ( OUT_INDELS != null ) {
try {
indelOutput.close();
} catch (Exception e) {
logger.error("Failed to close "+OUT_INDELS+" gracefully. Data may be corrupt.");
}
}
if ( OUT_STATS != null ) {
try {
statsOutput.close();
} catch (Exception e) {
logger.error("Failed to close "+OUT_STATS+" gracefully. Data may be corrupt.");
}
}
if ( OUT_SNPS != null ) {
try {
snpsOutput.close();
} catch (Exception e) {
logger.error("Failed to close "+OUT_SNPS+" gracefully. Data may be corrupt.");
}
}
manager.close();
if ( N_WAY_OUT != null ) writerToUse.close();
if ( CHECKEARLY ) {
logger.info("SW alignments runs: "+SWalignmentRuns);
logger.info("SW alignments successfull: "+SWalignmentSuccess + " ("+SWalignmentSuccess/SWalignmentRuns+"% of SW runs)");
logger.info("SW alignments skipped (perfect match): "+exactMatchesFound);
logger.info("Total reads SW worked for: "+(SWalignmentSuccess + exactMatchesFound)+
" ("+(SWalignmentSuccess+exactMatchesFound)/(SWalignmentRuns+exactMatchesFound)+"% of all reads requiring SW)");
}
}
private void populateKnownIndels(ReadMetaDataTracker metaDataTracker, ReferenceContext ref) {
for ( Collection<GATKFeature> rods : metaDataTracker.getContigOffsetMapping().values() ) {
Iterator<GATKFeature> rodIter = rods.iterator();
while ( rodIter.hasNext() ) {
Object rod = rodIter.next().getUnderlyingObject();
if ( indelRodsSeen.contains(rod) )
continue;
indelRodsSeen.add(rod);
if ( rod instanceof VariantContext )
knownIndelsToTry.add((VariantContext)rod);
}
}
}
private static int mismatchQualitySumIgnoreCigar(final AlignedRead aRead, final byte[] refSeq, int refIndex, int quitAboveThisValue) {
final byte[] readSeq = aRead.getReadBases();
final byte[] quals = aRead.getBaseQualities();
int sum = 0;
for (int readIndex = 0 ; readIndex < readSeq.length ; refIndex++, readIndex++ ) {
if ( refIndex >= refSeq.length ) {
sum += MAX_QUAL;
// optimization: once we pass the threshold, stop calculating
if ( sum > quitAboveThisValue )
return sum;
} else {
byte refChr = refSeq[refIndex];
byte readChr = readSeq[readIndex];
if ( !BaseUtils.isRegularBase(readChr) || !BaseUtils.isRegularBase(refChr) )
continue; // do not count Ns/Xs/etc ?
if ( readChr != refChr ) {
sum += (int)quals[readIndex];
// optimization: once we pass the threshold, stop calculating
if ( sum > quitAboveThisValue )
return sum;
}
}
}
return sum;
}
private void clean(ReadBin readsToClean) {
final List<GATKSAMRecord> reads = readsToClean.getReads();
if ( reads.size() == 0 )
return;
byte[] reference = readsToClean.getReference(referenceReader);
int leftmostIndex = readsToClean.getLocation().getStart();
final ArrayList<GATKSAMRecord> refReads = new ArrayList<GATKSAMRecord>(); // reads that perfectly match ref
final ArrayList<AlignedRead> altReads = new ArrayList<AlignedRead>(); // reads that don't perfectly match
final LinkedList<AlignedRead> altAlignmentsToTest = new LinkedList<AlignedRead>(); // should we try to make an alt consensus from the read?
final Set<Consensus> altConsenses = new LinkedHashSet<Consensus>(); // list of alt consenses
// if there are any known indels for this region, get them and create alternate consenses
generateAlternateConsensesFromKnownIndels(altConsenses, leftmostIndex, reference);
// decide which reads potentially need to be cleaned;
// if there are reads with a single indel in them, add that indel to the list of alternate consenses
long totalRawMismatchSum = determineReadsThatNeedCleaning(reads, refReads, altReads, altAlignmentsToTest, altConsenses, leftmostIndex, reference);
// use 'Smith-Waterman' to create alternate consenses from reads that mismatch the reference, using totalRawMismatchSum as the random seed
if ( consensusModel == ConsensusDeterminationModel.USE_SW )
generateAlternateConsensesFromReads(altAlignmentsToTest, altConsenses, reference, leftmostIndex);
// if ( debugOn ) System.out.println("------\nChecking consenses...\n--------\n");
Consensus bestConsensus = null;
Iterator<Consensus> iter = altConsenses.iterator();
while ( iter.hasNext() ) {
Consensus consensus = iter.next();
//logger.debug("Trying new consensus: " + consensus.cigar + " " + new String(consensus.str));
// if ( DEBUG ) {
// System.out.println("Checking consensus with alignment at "+consensus.positionOnReference+" cigar "+consensus.cigar);
// System.out.println(new String(consensus.str));
// int z = 0;
// for ( ; z < consensus.positionOnReference; z++ ) System.out.print('.');
// for ( z=0 ; z < consensus.cigar.getCigarElement(0).getLength() ; z++ ) System.out.print('.');
// if ( consensus.cigar.getCigarElement(1).getOperator() == CigarOperator.I ) for ( z= 0; z < consensus.cigar.getCigarElement(1).getLength(); z++ ) System.out.print('I');
// System.out.println();
// }
// if ( debugOn ) System.out.println("Consensus: "+consensus.str);
for ( int j = 0; j < altReads.size(); j++ ) {
AlignedRead toTest = altReads.get(j);
Pair<Integer, Integer> altAlignment = findBestOffset(consensus.str, toTest, leftmostIndex);
// the mismatch score is the min of its alignment vs. the reference and vs. the alternate
int myScore = altAlignment.second;
if ( myScore > toTest.getAlignerMismatchScore() || myScore >= toTest.getMismatchScoreToReference() )
myScore = toTest.getMismatchScoreToReference();
// keep track of reads that align better to the alternate consensus.
// By pushing alignments with equal scores to the alternate, it means we'll over-call (het -> hom non ref) but are less likely to under-call (het -> ref, het non ref -> het)
else
consensus.readIndexes.add(new Pair<Integer, Integer>(j, altAlignment.first));
//logger.debug(consensus.cigar + " vs. " + toTest.getRead().getReadName() + "-" + toTest.getRead().getReadString() + " => " + myScore + " vs. " + toTest.getMismatchScoreToReference());
if ( !toTest.getRead().getDuplicateReadFlag() )
consensus.mismatchSum += myScore;
// optimization: once the mismatch sum is higher than the best consensus, quit since this one can't win
// THIS MUST BE DISABLED IF WE DECIDE TO ALLOW MORE THAN ONE ALTERNATE CONSENSUS!
if ( bestConsensus != null && consensus.mismatchSum > bestConsensus.mismatchSum )
break;
}
//logger.debug("Mismatch sum of new consensus: " + consensus.mismatchSum);
if ( bestConsensus == null || bestConsensus.mismatchSum > consensus.mismatchSum) {
// we do not need this alt consensus, release memory right away!!
if ( bestConsensus != null )
bestConsensus.readIndexes.clear();
bestConsensus = consensus;
//logger.debug("New consensus " + bestConsensus.cigar + " is now best consensus");
} else {
// we do not need this alt consensus, release memory right away!!
consensus.readIndexes.clear();
}
}
// if:
// 1) the best alternate consensus has a smaller sum of quality score mismatches than the aligned version of the reads,
// 2) beats the LOD threshold for the sum of quality score mismatches of the raw version of the reads,
// 3) didn't just move around the mismatching columns (i.e. it actually reduces entropy),
// then clean!
final double improvement = (bestConsensus == null ? -1 : ((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0);
if ( improvement >= LOD_THRESHOLD ) {
bestConsensus.cigar = AlignmentUtils.leftAlignIndel(bestConsensus.cigar, reference, bestConsensus.str, bestConsensus.positionOnReference, bestConsensus.positionOnReference);
// start cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
AlignedRead aRead = altReads.get(indexPair.first);
if ( !updateRead(bestConsensus.cigar, bestConsensus.positionOnReference, indexPair.second, aRead, leftmostIndex) )
return;
}
if ( consensusModel != ConsensusDeterminationModel.KNOWNS_ONLY && !alternateReducesEntropy(altReads, reference, leftmostIndex) ) {
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tFAIL (bad indel)\t"); // if improvement > LOD_THRESHOLD *BUT* entropy is not reduced (SNPs still exist)
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
} else {
//logger.debug("CLEAN: " + bestConsensus.cigar + " " + bestConsensus.str.toString() + " " + bestConsensus.cigar.numCigarElements() );
if ( indelOutput != null && bestConsensus.cigar.numCigarElements() > 1 ) {
// NOTE: indels are printed out in the format specified for the low-coverage pilot1
// indel calls (tab-delimited): chr position size type sequence
StringBuilder str = new StringBuilder();
str.append(reads.get(0).getReferenceName());
int position = bestConsensus.positionOnReference + bestConsensus.cigar.getCigarElement(0).getLength();
str.append("\t" + (leftmostIndex + position - 1));
CigarElement ce = bestConsensus.cigar.getCigarElement(1);
str.append("\t" + ce.getLength() + "\t" + ce.getOperator() + "\t");
int length = ce.getLength();
if ( ce.getOperator() == CigarOperator.D ) {
for ( int i = 0; i < length; i++)
str.append((char)reference[position+i]);
} else {
for ( int i = 0; i < length; i++)
str.append((char)bestConsensus.str[position+i]);
}
str.append("\t" + (((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0) + "\n");
try {
indelOutput.write(str.toString());
indelOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("indelOutput", "Failed to write indel output file", e);
}
}
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tCLEAN"); // if improvement > LOD_THRESHOLD *AND* entropy is reduced
if ( bestConsensus.cigar.numCigarElements() > 1 )
statsOutput.write(" (found indel)");
statsOutput.write("\t");
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
// finish cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
final AlignedRead aRead = altReads.get(indexPair.first);
if ( aRead.finalizeUpdate() ) {
// We need to update the mapping quality score of the cleaned reads;
// however we don't have enough info to use the proper MAQ scoring system.
// For now, we will just arbitrarily add 10 to the mapping quality. [EB, 6/7/2010].
// TODO -- we need a better solution here
GATKSAMRecord read = aRead.getRead();
- read.setMappingQuality(Math.min(aRead.getRead().getMappingQuality() + 10, 254));
+ if ( read.getMappingQuality() != 255 ) // 255 == Unknown, so don't modify it
+ read.setMappingQuality(Math.min(aRead.getRead().getMappingQuality() + 10, 254));
// before we fix the attribute tags we first need to make sure we have enough of the reference sequence
int neededBasesToLeft = leftmostIndex - read.getAlignmentStart();
int neededBasesToRight = read.getAlignmentEnd() - leftmostIndex - reference.length + 1;
int neededBases = Math.max(neededBasesToLeft, neededBasesToRight);
if ( neededBases > 0 ) {
int padLeft = Math.max(leftmostIndex-neededBases, 1);
int padRight = Math.min(leftmostIndex+reference.length+neededBases, referenceReader.getSequenceDictionary().getSequence(currentInterval.getContig()).getSequenceLength());
reference = referenceReader.getSubsequenceAt(currentInterval.getContig(), padLeft, padRight).getBases();
leftmostIndex = padLeft;
}
// now, fix the attribute tags
// TODO -- get rid of this try block when Picard does the right thing for reads aligned off the end of the reference
try {
if ( read.getAttribute(SAMTag.NM.name()) != null )
read.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(read, reference, leftmostIndex-1));
if ( read.getAttribute(SAMTag.UQ.name()) != null )
read.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(read, reference, leftmostIndex-1));
} catch (Exception e) {
// ignore it
}
// TODO -- this is only temporary until Tim adds code to recalculate this value
if ( read.getAttribute(SAMTag.MD.name()) != null )
read.setAttribute(SAMTag.MD.name(), null);
// mark that it was actually cleaned
readsActuallyCleaned.add(read);
}
}
}
// END IF ( improvement >= LOD_THRESHOLD )
} else if ( statsOutput != null ) {
try {
statsOutput.write(String.format("%s\tFAIL\t%.1f%n",
currentInterval.toString(), improvement));
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
}
private void generateAlternateConsensesFromKnownIndels(final Set<Consensus> altConsensesToPopulate, final int leftmostIndex, final byte[] reference) {
for ( VariantContext knownIndel : knownIndelsToTry ) {
if ( knownIndel == null || !knownIndel.isIndel() || knownIndel.isComplexIndel() )
continue;
byte[] indelStr = knownIndel.isSimpleInsertion() ? knownIndel.getAlternateAllele(0).getBases() : Utils.dupBytes((byte)'-', knownIndel.getReference().length());
int start = knownIndel.getStart() - leftmostIndex + 1;
Consensus c = createAlternateConsensus(start, reference, indelStr, knownIndel);
if ( c != null )
altConsensesToPopulate.add(c);
}
}
private long determineReadsThatNeedCleaning(final List<GATKSAMRecord> reads,
final ArrayList<GATKSAMRecord> refReadsToPopulate,
final ArrayList<AlignedRead> altReadsToPopulate,
final LinkedList<AlignedRead> altAlignmentsToTest,
final Set<Consensus> altConsenses,
final int leftmostIndex,
final byte[] reference) {
long totalRawMismatchSum = 0L;
for ( final GATKSAMRecord read : reads ) {
// we can not deal with screwy records
if ( read.getCigar().numCigarElements() == 0 ) {
refReadsToPopulate.add(read);
continue;
}
final AlignedRead aRead = new AlignedRead(read);
// first, move existing indels (for 1 indel reads only) to leftmost position within identical sequence
int numBlocks = AlignmentUtils.getNumAlignmentBlocks(read);
if ( numBlocks == 2 ) {
Cigar newCigar = AlignmentUtils.leftAlignIndel(unclipCigar(read.getCigar()), reference, read.getReadBases(), read.getAlignmentStart()-leftmostIndex, 0);
aRead.setCigar(newCigar, false);
}
final int startOnRef = read.getAlignmentStart()-leftmostIndex;
final int rawMismatchScore = mismatchQualitySumIgnoreCigar(aRead, reference, startOnRef, Integer.MAX_VALUE);
// if this doesn't match perfectly to the reference, let's try to clean it
if ( rawMismatchScore > 0 ) {
altReadsToPopulate.add(aRead);
//logger.debug("Adding " + read.getReadName() + " with raw mismatch score " + rawMismatchScore + " to non-ref reads");
if ( !read.getDuplicateReadFlag() )
totalRawMismatchSum += rawMismatchScore;
aRead.setMismatchScoreToReference(rawMismatchScore);
aRead.setAlignerMismatchScore(AlignmentUtils.mismatchingQualities(aRead.getRead(), reference, startOnRef));
// if it has an indel, let's see if that's the best consensus
if ( consensusModel != ConsensusDeterminationModel.KNOWNS_ONLY && numBlocks == 2 ) {
Consensus c = createAlternateConsensus(startOnRef, aRead.getCigar(), reference, aRead.getReadBases());
if ( c != null )
altConsenses.add(c);
} else {
altAlignmentsToTest.add(aRead);
}
}
// otherwise, we can emit it as is
else {
//logger.debug("Adding " + read.getReadName() + " with raw mismatch score " + rawMismatchScore + " to ref reads");
refReadsToPopulate.add(read);
}
}
return totalRawMismatchSum;
}
private void generateAlternateConsensesFromReads(final LinkedList<AlignedRead> altAlignmentsToTest,
final Set<Consensus> altConsensesToPopulate,
final byte[] reference,
final int leftmostIndex) {
// if we are under the limit, use all reads to generate alternate consenses
if ( altAlignmentsToTest.size() <= MAX_READS_FOR_CONSENSUSES ) {
for ( AlignedRead aRead : altAlignmentsToTest ) {
if ( CHECKEARLY ) createAndAddAlternateConsensus1(aRead, altConsensesToPopulate, reference,leftmostIndex);
else createAndAddAlternateConsensus(aRead.getReadBases(), altConsensesToPopulate, reference);
}
}
// otherwise, choose reads for alternate consenses randomly
else {
int readsSeen = 0;
while ( readsSeen++ < MAX_READS_FOR_CONSENSUSES && altConsensesToPopulate.size() <= MAX_CONSENSUSES) {
int index = GenomeAnalysisEngine.getRandomGenerator().nextInt(altAlignmentsToTest.size());
AlignedRead aRead = altAlignmentsToTest.remove(index);
if ( CHECKEARLY ) createAndAddAlternateConsensus1(aRead, altConsensesToPopulate, reference,leftmostIndex);
else createAndAddAlternateConsensus(aRead.getReadBases(), altConsensesToPopulate, reference);
}
}
}
private void createAndAddAlternateConsensus(final byte[] read, final Set<Consensus> altConsensesToPopulate, final byte[] reference) {
// do a pairwise alignment against the reference
SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read, SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND);
Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read);
if ( c != null )
altConsensesToPopulate.add(c);
}
private void createAndAddAlternateConsensus1(AlignedRead read, final Set<Consensus> altConsensesToPopulate,
final byte[] reference, final int leftmostIndex) {
for ( Consensus known : altConsensesToPopulate ) {
Pair<Integer, Integer> altAlignment = findBestOffset(known.str, read, leftmostIndex);
// the mismatch score is the min of its alignment vs. the reference and vs. the alternate
int myScore = altAlignment.second;
if ( myScore == 0 ) {exactMatchesFound++; return; }// read matches perfectly to a known alt consensus - no need to run SW, we already know the answer
}
// do a pairwise alignment against the reference
SWalignmentRuns++;
SWPairwiseAlignment swConsensus = new SWPairwiseAlignment(reference, read.getReadBases(), SW_MATCH, SW_MISMATCH, SW_GAP, SW_GAP_EXTEND);
Consensus c = createAlternateConsensus(swConsensus.getAlignmentStart2wrt1(), swConsensus.getCigar(), reference, read.getReadBases());
if ( c != null ) {
altConsensesToPopulate.add(c);
SWalignmentSuccess++;
}
}
// create a Consensus from cigar/read strings which originate somewhere on the reference
private Consensus createAlternateConsensus(final int indexOnRef, final Cigar c, final byte[] reference, final byte[] readStr) {
if ( indexOnRef < 0 )
return null;
// if there are no indels, we do not need this consensus, can abort early:
if ( c.numCigarElements() == 1 && c.getCigarElement(0).getOperator() == CigarOperator.M ) return null;
// create the new consensus
ArrayList<CigarElement> elements = new ArrayList<CigarElement>(c.numCigarElements()-1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indexOnRef; i++)
sb.append((char)reference[i]);
int indelCount = 0;
int altIdx = 0;
int refIdx = indexOnRef;
boolean ok_flag = true;
for ( int i = 0 ; i < c.numCigarElements() ; i++ ) {
CigarElement ce = c.getCigarElement(i);
int elementLength = ce.getLength();
switch( ce.getOperator() ) {
case D:
refIdx += elementLength;
indelCount++;
elements.add(ce);
break;
case M:
altIdx += elementLength;
case N:
if ( reference.length < refIdx + elementLength )
ok_flag = false;
else {
for (int j = 0; j < elementLength; j++)
sb.append((char)reference[refIdx+j]);
}
refIdx += elementLength;
elements.add(new CigarElement(elementLength, CigarOperator.M));
break;
case I:
for (int j = 0; j < elementLength; j++) {
if ( ! BaseUtils.isRegularBase(readStr[altIdx+j]) ) {
// Insertions with N's in them cause real problems sometimes; it's better to drop them altogether
ok_flag=false;
break;
}
sb.append((char)readStr[altIdx + j]);
}
altIdx += elementLength;
indelCount++;
elements.add(ce);
break;
case S:
default:
break;
}
}
// make sure that there is at most only a single indel and it aligns appropriately!
if ( !ok_flag || indelCount != 1 || reference.length < refIdx )
return null;
for (int i = refIdx; i < reference.length; i++)
sb.append((char)reference[i]);
byte[] altConsensus = StringUtil.stringToBytes(sb.toString()); // alternative consensus sequence we just built from the current read
return new Consensus(altConsensus, new Cigar(elements), indexOnRef);
}
// create a Consensus from just the indel string that falls on the reference
private Consensus createAlternateConsensus(final int indexOnRef, final byte[] reference, final byte[] indelStr, final VariantContext indel) {
if ( indexOnRef < 0 || indexOnRef >= reference.length )
return null;
// create the new consensus
StringBuilder sb = new StringBuilder();
Cigar cigar = new Cigar();
int refIdx;
for (refIdx = 0; refIdx < indexOnRef; refIdx++)
sb.append((char)reference[refIdx]);
if ( indexOnRef > 0 )
cigar.add(new CigarElement(indexOnRef, CigarOperator.M));
if ( indel.isSimpleDeletion() ) {
refIdx += indelStr.length;
cigar.add(new CigarElement(indelStr.length, CigarOperator.D));
}
else if ( indel.isSimpleInsertion() ) {
for ( byte b : indelStr )
sb.append((char)b);
cigar.add(new CigarElement(indelStr.length, CigarOperator.I));
} else {
throw new IllegalStateException("Creating an alternate consensus from a complex indel is not allows");
}
if ( reference.length - refIdx > 0 )
cigar.add(new CigarElement(reference.length - refIdx, CigarOperator.M));
for (; refIdx < reference.length; refIdx++)
sb.append((char)reference[refIdx]);
byte[] altConsensus = StringUtil.stringToBytes(sb.toString()); // alternative consensus sequence we just built from the current read
return new Consensus(altConsensus, cigar, 0);
}
private Pair<Integer, Integer> findBestOffset(final byte[] ref, final AlignedRead read, final int leftmostIndex) {
// optimization: try the most likely alignment first (to get a low score to beat)
int originalAlignment = read.getOriginalAlignmentStart() - leftmostIndex;
int bestScore = mismatchQualitySumIgnoreCigar(read, ref, originalAlignment, Integer.MAX_VALUE);
int bestIndex = originalAlignment;
// optimization: we can't get better than 0, so we can quit now
if ( bestScore == 0 )
return new Pair<Integer, Integer>(bestIndex, 0);
// optimization: the correct alignment shouldn't be too far from the original one (or else the read wouldn't have aligned in the first place)
for ( int i = 0; i < originalAlignment; i++ ) {
int score = mismatchQualitySumIgnoreCigar(read, ref, i, bestScore);
if ( score < bestScore ) {
bestScore = score;
bestIndex = i;
}
// optimization: we can't get better than 0, so we can quit now
if ( bestScore == 0 )
return new Pair<Integer, Integer>(bestIndex, 0);
}
final int maxPossibleStart = ref.length - read.getReadLength();
for ( int i = originalAlignment + 1; i <= maxPossibleStart; i++ ) {
int score = mismatchQualitySumIgnoreCigar(read, ref, i, bestScore);
if ( score < bestScore ) {
bestScore = score;
bestIndex = i;
}
// optimization: we can't get better than 0, so we can quit now
if ( bestScore == 0 )
return new Pair<Integer, Integer>(bestIndex, 0);
}
return new Pair<Integer, Integer>(bestIndex, bestScore);
}
private boolean updateRead(final Cigar altCigar, final int altPosOnRef, final int myPosOnAlt, final AlignedRead aRead, final int leftmostIndex) {
Cigar readCigar = new Cigar();
// special case: there is no indel
if ( altCigar.getCigarElements().size() == 1 ) {
aRead.setAlignmentStart(leftmostIndex + myPosOnAlt);
readCigar.add(new CigarElement(aRead.getReadLength(), CigarOperator.M));
aRead.setCigar(readCigar);
return true;
}
CigarElement altCE1 = altCigar.getCigarElement(0);
CigarElement altCE2 = altCigar.getCigarElement(1);
int leadingMatchingBlockLength = 0; // length of the leading M element or 0 if the leading element is I
CigarElement indelCE;
if ( altCE1.getOperator() == CigarOperator.I ) {
indelCE=altCE1;
if ( altCE2.getOperator() != CigarOperator.M ) {
logger.warn("When the first element of the alt consensus is I, the second one must be M. Actual: " + altCigar.toString() + ". Skipping this site...");
return false;
}
}
else {
if ( altCE1.getOperator() != CigarOperator.M ) {
logger.warn("First element of the alt consensus cigar must be M or I. Actual: " + altCigar.toString() + ". Skipping this site...");
return false;
}
if ( altCE2.getOperator() == CigarOperator.I || altCE2.getOperator() == CigarOperator.D ) {
indelCE=altCE2;
} else {
logger.warn("When first element of the alt consensus is M, the second one must be I or D. Actual: " + altCigar.toString() + ". Skipping this site...");
return false;
}
leadingMatchingBlockLength = altCE1.getLength();
}
// the easiest thing to do is to take each case separately
int endOfFirstBlock = altPosOnRef + leadingMatchingBlockLength;
boolean sawAlignmentStart = false;
// for reads starting before the indel
if ( myPosOnAlt < endOfFirstBlock) {
aRead.setAlignmentStart(leftmostIndex + myPosOnAlt);
sawAlignmentStart = true;
// for reads ending before the indel
if ( myPosOnAlt + aRead.getReadLength() <= endOfFirstBlock) {
//readCigar.add(new CigarElement(aRead.getReadLength(), CigarOperator.M));
//aRead.setCigar(readCigar);
aRead.setCigar(null); // reset to original alignment
return true;
}
readCigar.add(new CigarElement(endOfFirstBlock - myPosOnAlt, CigarOperator.M));
}
// forward along the indel
//int indelOffsetOnRef = 0, indelOffsetOnRead = 0;
if ( indelCE.getOperator() == CigarOperator.I ) {
// for reads that end in an insertion
if ( myPosOnAlt + aRead.getReadLength() < endOfFirstBlock + indelCE.getLength() ) {
int partialInsertionLength = myPosOnAlt + aRead.getReadLength() - endOfFirstBlock;
// if we also started inside the insertion, then we need to modify the length
if ( !sawAlignmentStart )
partialInsertionLength = aRead.getReadLength();
readCigar.add(new CigarElement(partialInsertionLength, CigarOperator.I));
aRead.setCigar(readCigar);
return true;
}
// for reads that start in an insertion
if ( !sawAlignmentStart && myPosOnAlt < endOfFirstBlock + indelCE.getLength() ) {
aRead.setAlignmentStart(leftmostIndex + endOfFirstBlock);
readCigar.add(new CigarElement(indelCE.getLength() - (myPosOnAlt - endOfFirstBlock), CigarOperator.I));
//indelOffsetOnRead = myPosOnAlt - endOfFirstBlock;
sawAlignmentStart = true;
} else if ( sawAlignmentStart ) {
readCigar.add(indelCE);
//indelOffsetOnRead = indelCE.getLength();
}
} else if ( indelCE.getOperator() == CigarOperator.D ) {
if ( sawAlignmentStart )
readCigar.add(indelCE);
//indelOffsetOnRef = indelCE.getLength();
}
// for reads that start after the indel
if ( !sawAlignmentStart ) {
//aRead.setAlignmentStart(leftmostIndex + myPosOnAlt + indelOffsetOnRef - indelOffsetOnRead);
//readCigar.add(new CigarElement(aRead.getReadLength(), CigarOperator.M));
//aRead.setCigar(readCigar);
aRead.setCigar(null); // reset to original alignment
return true;
}
int readRemaining = aRead.getReadBases().length;
for ( CigarElement ce : readCigar.getCigarElements() ) {
if ( ce.getOperator() != CigarOperator.D )
readRemaining -= ce.getLength();
}
if ( readRemaining > 0 )
readCigar.add(new CigarElement(readRemaining, CigarOperator.M));
aRead.setCigar(readCigar);
return true;
}
private boolean alternateReducesEntropy(final List<AlignedRead> reads, final byte[] reference, final int leftmostIndex) {
final int[] originalMismatchBases = new int[reference.length];
final int[] cleanedMismatchBases = new int[reference.length];
final int[] totalOriginalBases = new int[reference.length];
final int[] totalCleanedBases = new int[reference.length];
// set to 1 to prevent dividing by zero
for ( int i=0; i < reference.length; i++ )
originalMismatchBases[i] = totalOriginalBases[i] = cleanedMismatchBases[i] = totalCleanedBases[i] = 0;
for (int i=0; i < reads.size(); i++) {
final AlignedRead read = reads.get(i);
if ( read.getRead().getAlignmentBlocks().size() > 1 )
continue;
int refIdx = read.getOriginalAlignmentStart() - leftmostIndex;
final byte[] readStr = read.getReadBases();
final byte[] quals = read.getBaseQualities();
for (int j=0; j < readStr.length; j++, refIdx++ ) {
if ( refIdx < 0 || refIdx >= reference.length ) {
//System.out.println( "Read: "+read.getRead().getReadName() + "; length = " + readStr.length() );
//System.out.println( "Ref left: "+ leftmostIndex +"; ref length=" + reference.length() + "; read alignment start: "+read.getOriginalAlignmentStart() );
break;
}
totalOriginalBases[refIdx] += quals[j];
if ( readStr[j] != reference[refIdx] )
originalMismatchBases[refIdx] += quals[j];
}
// reset and now do the calculation based on the cleaning
refIdx = read.getAlignmentStart() - leftmostIndex;
int altIdx = 0;
Cigar c = read.getCigar();
for (int j = 0 ; j < c.numCigarElements() ; j++) {
CigarElement ce = c.getCigarElement(j);
int elementLength = ce.getLength();
switch ( ce.getOperator() ) {
case M:
for (int k = 0 ; k < elementLength ; k++, refIdx++, altIdx++ ) {
if ( refIdx >= reference.length )
break;
totalCleanedBases[refIdx] += quals[altIdx];
if ( readStr[altIdx] != reference[refIdx] )
cleanedMismatchBases[refIdx] += quals[altIdx];
}
break;
case I:
altIdx += elementLength;
break;
case D:
refIdx += elementLength;
break;
case S:
default:
break;
}
}
}
int originalMismatchColumns = 0, cleanedMismatchColumns = 0;
StringBuilder sb = new StringBuilder();
for ( int i=0; i < reference.length; i++ ) {
if ( cleanedMismatchBases[i] == originalMismatchBases[i] )
continue;
boolean didMismatch = false, stillMismatches = false;
if ( originalMismatchBases[i] > totalOriginalBases[i] * MISMATCH_THRESHOLD ) {
didMismatch = true;
originalMismatchColumns++;
if ( totalCleanedBases[i] > 0 && ((double)cleanedMismatchBases[i] / (double)totalCleanedBases[i]) > ((double)originalMismatchBases[i] / (double)totalOriginalBases[i]) * (1.0 - MISMATCH_COLUMN_CLEANED_FRACTION) ) {
stillMismatches = true;
cleanedMismatchColumns++;
}
} else if ( cleanedMismatchBases[i] > totalCleanedBases[i] * MISMATCH_THRESHOLD ) {
cleanedMismatchColumns++;
}
if ( snpsOutput != null ) {
if ( didMismatch ) {
sb.append(reads.get(0).getRead().getReferenceName() + ":");
sb.append((leftmostIndex + i));
if ( stillMismatches )
sb.append(" SAME_SNP\n");
else
sb.append(" NOT_SNP\n");
}
}
}
//logger.debug("Original mismatch columns = " + originalMismatchColumns + "; cleaned mismatch columns = " + cleanedMismatchColumns);
final boolean reduces = (originalMismatchColumns == 0 || cleanedMismatchColumns < originalMismatchColumns);
if ( reduces && snpsOutput != null ) {
try {
snpsOutput.write(sb.toString());
snpsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("snpsOutput", "Failed to write SNPs output file", e);
}
}
return reduces;
}
protected static Cigar unclipCigar(Cigar cigar) {
ArrayList<CigarElement> elements = new ArrayList<CigarElement>(cigar.numCigarElements());
for ( CigarElement ce : cigar.getCigarElements() ) {
if ( !isClipOperator(ce.getOperator()) )
elements.add(ce);
}
return new Cigar(elements);
}
private static boolean isClipOperator(CigarOperator op) {
return op == CigarOperator.S || op == CigarOperator.H || op == CigarOperator.P;
}
protected static Cigar reclipCigar(Cigar cigar, SAMRecord read) {
ArrayList<CigarElement> elements = new ArrayList<CigarElement>();
int i = 0;
int n = read.getCigar().numCigarElements();
while ( i < n && isClipOperator(read.getCigar().getCigarElement(i).getOperator()) )
elements.add(read.getCigar().getCigarElement(i++));
elements.addAll(cigar.getCigarElements());
i++;
while ( i < n && !isClipOperator(read.getCigar().getCigarElement(i).getOperator()) )
i++;
while ( i < n && isClipOperator(read.getCigar().getCigarElement(i).getOperator()) )
elements.add(read.getCigar().getCigarElement(i++));
return new Cigar(elements);
}
private class AlignedRead {
private final GATKSAMRecord read;
private byte[] readBases = null;
private byte[] baseQuals = null;
private Cigar newCigar = null;
private int newStart = -1;
private int mismatchScoreToReference = 0;
private long alignerMismatchScore = 0;
public AlignedRead(GATKSAMRecord read) {
this.read = read;
mismatchScoreToReference = 0;
}
public GATKSAMRecord getRead() {
return read;
}
public int getReadLength() {
return readBases != null ? readBases.length : read.getReadLength();
}
public byte[] getReadBases() {
if ( readBases == null )
getUnclippedBases();
return readBases;
}
public byte[] getBaseQualities() {
if ( baseQuals == null )
getUnclippedBases();
return baseQuals;
}
// pull out the bases that aren't clipped out
private void getUnclippedBases() {
readBases = new byte[getReadLength()];
baseQuals = new byte[getReadLength()];
byte[] actualReadBases = read.getReadBases();
byte[] actualBaseQuals = read.getBaseQualities();
int fromIndex = 0, toIndex = 0;
for ( CigarElement ce : read.getCigar().getCigarElements() ) {
int elementLength = ce.getLength();
switch ( ce.getOperator() ) {
case S:
fromIndex += elementLength;
break;
case M:
case I:
System.arraycopy(actualReadBases, fromIndex, readBases, toIndex, elementLength);
System.arraycopy(actualBaseQuals, fromIndex, baseQuals, toIndex, elementLength);
fromIndex += elementLength;
toIndex += elementLength;
default:
break;
}
}
// if we got clipped, trim the array
if ( fromIndex != toIndex ) {
byte[] trimmedRB = new byte[toIndex];
byte[] trimmedBQ = new byte[toIndex];
System.arraycopy(readBases, 0, trimmedRB, 0, toIndex);
System.arraycopy(baseQuals, 0, trimmedBQ, 0, toIndex);
readBases = trimmedRB;
baseQuals = trimmedBQ;
}
}
public Cigar getCigar() {
return (newCigar != null ? newCigar : read.getCigar());
}
public void setCigar(Cigar cigar) {
setCigar(cigar, true);
}
// tentatively sets the new Cigar, but it needs to be confirmed later
public void setCigar(Cigar cigar, boolean fixClippedCigar) {
if ( cigar == null ) {
newCigar = null;
return;
}
if ( fixClippedCigar && getReadBases().length < read.getReadLength() )
cigar = reclipCigar(cigar);
// no change?
if ( read.getCigar().equals(cigar) ) {
newCigar = null;
return;
}
// no indel?
String str = cigar.toString();
if ( !str.contains("D") && !str.contains("I") ) {
logger.debug("Modifying a read with no associated indel; although this is possible, it is highly unlikely. Perhaps this region should be double-checked: " + read.getReadName() + " near " + read.getReferenceName() + ":" + read.getAlignmentStart());
// newCigar = null;
// return;
}
newCigar = cigar;
}
// pull out the bases that aren't clipped out
private Cigar reclipCigar(Cigar cigar) {
return IndelRealigner.reclipCigar(cigar, read);
}
// tentatively sets the new start, but it needs to be confirmed later
public void setAlignmentStart(int start) {
newStart = start;
}
public int getAlignmentStart() {
return (newStart != -1 ? newStart : read.getAlignmentStart());
}
public int getOriginalAlignmentStart() {
return read.getAlignmentStart();
}
// finalizes the changes made.
// returns true if this record actually changes, false otherwise
public boolean finalizeUpdate() {
// if we haven't made any changes, don't do anything
if ( newCigar == null )
return false;
if ( newStart == -1 )
newStart = read.getAlignmentStart();
else if ( Math.abs(newStart - read.getAlignmentStart()) > MAX_POS_MOVE_ALLOWED ) {
logger.debug(String.format("Attempting to realign read %s at %d more than %d bases to %d.", read.getReadName(), read.getAlignmentStart(), MAX_POS_MOVE_ALLOWED, newStart));
return false;
}
// annotate the record with the original cigar (and optionally the alignment start)
if ( !NO_ORIGINAL_ALIGNMENT_TAGS ) {
read.setAttribute(ORIGINAL_CIGAR_TAG, read.getCigar().toString());
if ( newStart != read.getAlignmentStart() )
read.setAttribute(ORIGINAL_POSITION_TAG, read.getAlignmentStart());
}
read.setCigar(newCigar);
read.setAlignmentStart(newStart);
return true;
}
public void setMismatchScoreToReference(int score) {
mismatchScoreToReference = score;
}
public int getMismatchScoreToReference() {
return mismatchScoreToReference;
}
public void setAlignerMismatchScore(long score) {
alignerMismatchScore = score;
}
public long getAlignerMismatchScore() {
return alignerMismatchScore;
}
}
private static class Consensus {
public final byte[] str;
public final ArrayList<Pair<Integer, Integer>> readIndexes;
public final int positionOnReference;
public int mismatchSum;
public Cigar cigar;
public Consensus(byte[] str, Cigar cigar, int positionOnReference) {
this.str = str;
this.cigar = cigar;
this.positionOnReference = positionOnReference;
mismatchSum = 0;
readIndexes = new ArrayList<Pair<Integer, Integer>>();
}
@Override
public boolean equals(Object o) {
return ( this == o || (o instanceof Consensus && Arrays.equals(this.str,(((Consensus)o).str)) ) );
}
public boolean equals(Consensus c) {
return ( this == c || Arrays.equals(this.str,c.str) ) ;
}
@Override
public int hashCode() {
return Arrays.hashCode(this.str);
}
}
private class ReadBin implements HasGenomeLocation {
private final ArrayList<GATKSAMRecord> reads = new ArrayList<GATKSAMRecord>();
private byte[] reference = null;
private GenomeLoc loc = null;
public ReadBin() { }
// Return false if we can't process this read bin because the reads are not correctly overlapping.
// This can happen if e.g. there's a large known indel with no overlapping reads.
public void add(GATKSAMRecord read) {
GenomeLoc locForRead = getToolkit().getGenomeLocParser().createGenomeLoc(read);
if ( loc == null )
loc = locForRead;
else if ( locForRead.getStop() > loc.getStop() )
loc = getToolkit().getGenomeLocParser().createGenomeLoc(loc.getContig(), loc.getStart(), locForRead.getStop());
reads.add(read);
}
public List<GATKSAMRecord> getReads() { return reads; }
public byte[] getReference(IndexedFastaSequenceFile referenceReader) {
// set up the reference if we haven't done so yet
if ( reference == null ) {
// first, pad the reference to handle deletions in narrow windows (e.g. those with only 1 read)
int padLeft = Math.max(loc.getStart()-REFERENCE_PADDING, 1);
int padRight = Math.min(loc.getStop()+REFERENCE_PADDING, referenceReader.getSequenceDictionary().getSequence(loc.getContig()).getSequenceLength());
loc = getToolkit().getGenomeLocParser().createGenomeLoc(loc.getContig(), padLeft, padRight);
reference = referenceReader.getSubsequenceAt(loc.getContig(), loc.getStart(), loc.getStop()).getBases();
StringUtil.toUpperCase(reference);
}
return reference;
}
public GenomeLoc getLocation() { return loc; }
public int size() { return reads.size(); }
public void clear() {
reads.clear();
reference = null;
loc = null;
}
}
}
| true | true | private void clean(ReadBin readsToClean) {
final List<GATKSAMRecord> reads = readsToClean.getReads();
if ( reads.size() == 0 )
return;
byte[] reference = readsToClean.getReference(referenceReader);
int leftmostIndex = readsToClean.getLocation().getStart();
final ArrayList<GATKSAMRecord> refReads = new ArrayList<GATKSAMRecord>(); // reads that perfectly match ref
final ArrayList<AlignedRead> altReads = new ArrayList<AlignedRead>(); // reads that don't perfectly match
final LinkedList<AlignedRead> altAlignmentsToTest = new LinkedList<AlignedRead>(); // should we try to make an alt consensus from the read?
final Set<Consensus> altConsenses = new LinkedHashSet<Consensus>(); // list of alt consenses
// if there are any known indels for this region, get them and create alternate consenses
generateAlternateConsensesFromKnownIndels(altConsenses, leftmostIndex, reference);
// decide which reads potentially need to be cleaned;
// if there are reads with a single indel in them, add that indel to the list of alternate consenses
long totalRawMismatchSum = determineReadsThatNeedCleaning(reads, refReads, altReads, altAlignmentsToTest, altConsenses, leftmostIndex, reference);
// use 'Smith-Waterman' to create alternate consenses from reads that mismatch the reference, using totalRawMismatchSum as the random seed
if ( consensusModel == ConsensusDeterminationModel.USE_SW )
generateAlternateConsensesFromReads(altAlignmentsToTest, altConsenses, reference, leftmostIndex);
// if ( debugOn ) System.out.println("------\nChecking consenses...\n--------\n");
Consensus bestConsensus = null;
Iterator<Consensus> iter = altConsenses.iterator();
while ( iter.hasNext() ) {
Consensus consensus = iter.next();
//logger.debug("Trying new consensus: " + consensus.cigar + " " + new String(consensus.str));
// if ( DEBUG ) {
// System.out.println("Checking consensus with alignment at "+consensus.positionOnReference+" cigar "+consensus.cigar);
// System.out.println(new String(consensus.str));
// int z = 0;
// for ( ; z < consensus.positionOnReference; z++ ) System.out.print('.');
// for ( z=0 ; z < consensus.cigar.getCigarElement(0).getLength() ; z++ ) System.out.print('.');
// if ( consensus.cigar.getCigarElement(1).getOperator() == CigarOperator.I ) for ( z= 0; z < consensus.cigar.getCigarElement(1).getLength(); z++ ) System.out.print('I');
// System.out.println();
// }
// if ( debugOn ) System.out.println("Consensus: "+consensus.str);
for ( int j = 0; j < altReads.size(); j++ ) {
AlignedRead toTest = altReads.get(j);
Pair<Integer, Integer> altAlignment = findBestOffset(consensus.str, toTest, leftmostIndex);
// the mismatch score is the min of its alignment vs. the reference and vs. the alternate
int myScore = altAlignment.second;
if ( myScore > toTest.getAlignerMismatchScore() || myScore >= toTest.getMismatchScoreToReference() )
myScore = toTest.getMismatchScoreToReference();
// keep track of reads that align better to the alternate consensus.
// By pushing alignments with equal scores to the alternate, it means we'll over-call (het -> hom non ref) but are less likely to under-call (het -> ref, het non ref -> het)
else
consensus.readIndexes.add(new Pair<Integer, Integer>(j, altAlignment.first));
//logger.debug(consensus.cigar + " vs. " + toTest.getRead().getReadName() + "-" + toTest.getRead().getReadString() + " => " + myScore + " vs. " + toTest.getMismatchScoreToReference());
if ( !toTest.getRead().getDuplicateReadFlag() )
consensus.mismatchSum += myScore;
// optimization: once the mismatch sum is higher than the best consensus, quit since this one can't win
// THIS MUST BE DISABLED IF WE DECIDE TO ALLOW MORE THAN ONE ALTERNATE CONSENSUS!
if ( bestConsensus != null && consensus.mismatchSum > bestConsensus.mismatchSum )
break;
}
//logger.debug("Mismatch sum of new consensus: " + consensus.mismatchSum);
if ( bestConsensus == null || bestConsensus.mismatchSum > consensus.mismatchSum) {
// we do not need this alt consensus, release memory right away!!
if ( bestConsensus != null )
bestConsensus.readIndexes.clear();
bestConsensus = consensus;
//logger.debug("New consensus " + bestConsensus.cigar + " is now best consensus");
} else {
// we do not need this alt consensus, release memory right away!!
consensus.readIndexes.clear();
}
}
// if:
// 1) the best alternate consensus has a smaller sum of quality score mismatches than the aligned version of the reads,
// 2) beats the LOD threshold for the sum of quality score mismatches of the raw version of the reads,
// 3) didn't just move around the mismatching columns (i.e. it actually reduces entropy),
// then clean!
final double improvement = (bestConsensus == null ? -1 : ((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0);
if ( improvement >= LOD_THRESHOLD ) {
bestConsensus.cigar = AlignmentUtils.leftAlignIndel(bestConsensus.cigar, reference, bestConsensus.str, bestConsensus.positionOnReference, bestConsensus.positionOnReference);
// start cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
AlignedRead aRead = altReads.get(indexPair.first);
if ( !updateRead(bestConsensus.cigar, bestConsensus.positionOnReference, indexPair.second, aRead, leftmostIndex) )
return;
}
if ( consensusModel != ConsensusDeterminationModel.KNOWNS_ONLY && !alternateReducesEntropy(altReads, reference, leftmostIndex) ) {
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tFAIL (bad indel)\t"); // if improvement > LOD_THRESHOLD *BUT* entropy is not reduced (SNPs still exist)
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
} else {
//logger.debug("CLEAN: " + bestConsensus.cigar + " " + bestConsensus.str.toString() + " " + bestConsensus.cigar.numCigarElements() );
if ( indelOutput != null && bestConsensus.cigar.numCigarElements() > 1 ) {
// NOTE: indels are printed out in the format specified for the low-coverage pilot1
// indel calls (tab-delimited): chr position size type sequence
StringBuilder str = new StringBuilder();
str.append(reads.get(0).getReferenceName());
int position = bestConsensus.positionOnReference + bestConsensus.cigar.getCigarElement(0).getLength();
str.append("\t" + (leftmostIndex + position - 1));
CigarElement ce = bestConsensus.cigar.getCigarElement(1);
str.append("\t" + ce.getLength() + "\t" + ce.getOperator() + "\t");
int length = ce.getLength();
if ( ce.getOperator() == CigarOperator.D ) {
for ( int i = 0; i < length; i++)
str.append((char)reference[position+i]);
} else {
for ( int i = 0; i < length; i++)
str.append((char)bestConsensus.str[position+i]);
}
str.append("\t" + (((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0) + "\n");
try {
indelOutput.write(str.toString());
indelOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("indelOutput", "Failed to write indel output file", e);
}
}
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tCLEAN"); // if improvement > LOD_THRESHOLD *AND* entropy is reduced
if ( bestConsensus.cigar.numCigarElements() > 1 )
statsOutput.write(" (found indel)");
statsOutput.write("\t");
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
// finish cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
final AlignedRead aRead = altReads.get(indexPair.first);
if ( aRead.finalizeUpdate() ) {
// We need to update the mapping quality score of the cleaned reads;
// however we don't have enough info to use the proper MAQ scoring system.
// For now, we will just arbitrarily add 10 to the mapping quality. [EB, 6/7/2010].
// TODO -- we need a better solution here
GATKSAMRecord read = aRead.getRead();
read.setMappingQuality(Math.min(aRead.getRead().getMappingQuality() + 10, 254));
// before we fix the attribute tags we first need to make sure we have enough of the reference sequence
int neededBasesToLeft = leftmostIndex - read.getAlignmentStart();
int neededBasesToRight = read.getAlignmentEnd() - leftmostIndex - reference.length + 1;
int neededBases = Math.max(neededBasesToLeft, neededBasesToRight);
if ( neededBases > 0 ) {
int padLeft = Math.max(leftmostIndex-neededBases, 1);
int padRight = Math.min(leftmostIndex+reference.length+neededBases, referenceReader.getSequenceDictionary().getSequence(currentInterval.getContig()).getSequenceLength());
reference = referenceReader.getSubsequenceAt(currentInterval.getContig(), padLeft, padRight).getBases();
leftmostIndex = padLeft;
}
// now, fix the attribute tags
// TODO -- get rid of this try block when Picard does the right thing for reads aligned off the end of the reference
try {
if ( read.getAttribute(SAMTag.NM.name()) != null )
read.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(read, reference, leftmostIndex-1));
if ( read.getAttribute(SAMTag.UQ.name()) != null )
read.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(read, reference, leftmostIndex-1));
} catch (Exception e) {
// ignore it
}
// TODO -- this is only temporary until Tim adds code to recalculate this value
if ( read.getAttribute(SAMTag.MD.name()) != null )
read.setAttribute(SAMTag.MD.name(), null);
// mark that it was actually cleaned
readsActuallyCleaned.add(read);
}
}
}
// END IF ( improvement >= LOD_THRESHOLD )
} else if ( statsOutput != null ) {
try {
statsOutput.write(String.format("%s\tFAIL\t%.1f%n",
currentInterval.toString(), improvement));
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
}
| private void clean(ReadBin readsToClean) {
final List<GATKSAMRecord> reads = readsToClean.getReads();
if ( reads.size() == 0 )
return;
byte[] reference = readsToClean.getReference(referenceReader);
int leftmostIndex = readsToClean.getLocation().getStart();
final ArrayList<GATKSAMRecord> refReads = new ArrayList<GATKSAMRecord>(); // reads that perfectly match ref
final ArrayList<AlignedRead> altReads = new ArrayList<AlignedRead>(); // reads that don't perfectly match
final LinkedList<AlignedRead> altAlignmentsToTest = new LinkedList<AlignedRead>(); // should we try to make an alt consensus from the read?
final Set<Consensus> altConsenses = new LinkedHashSet<Consensus>(); // list of alt consenses
// if there are any known indels for this region, get them and create alternate consenses
generateAlternateConsensesFromKnownIndels(altConsenses, leftmostIndex, reference);
// decide which reads potentially need to be cleaned;
// if there are reads with a single indel in them, add that indel to the list of alternate consenses
long totalRawMismatchSum = determineReadsThatNeedCleaning(reads, refReads, altReads, altAlignmentsToTest, altConsenses, leftmostIndex, reference);
// use 'Smith-Waterman' to create alternate consenses from reads that mismatch the reference, using totalRawMismatchSum as the random seed
if ( consensusModel == ConsensusDeterminationModel.USE_SW )
generateAlternateConsensesFromReads(altAlignmentsToTest, altConsenses, reference, leftmostIndex);
// if ( debugOn ) System.out.println("------\nChecking consenses...\n--------\n");
Consensus bestConsensus = null;
Iterator<Consensus> iter = altConsenses.iterator();
while ( iter.hasNext() ) {
Consensus consensus = iter.next();
//logger.debug("Trying new consensus: " + consensus.cigar + " " + new String(consensus.str));
// if ( DEBUG ) {
// System.out.println("Checking consensus with alignment at "+consensus.positionOnReference+" cigar "+consensus.cigar);
// System.out.println(new String(consensus.str));
// int z = 0;
// for ( ; z < consensus.positionOnReference; z++ ) System.out.print('.');
// for ( z=0 ; z < consensus.cigar.getCigarElement(0).getLength() ; z++ ) System.out.print('.');
// if ( consensus.cigar.getCigarElement(1).getOperator() == CigarOperator.I ) for ( z= 0; z < consensus.cigar.getCigarElement(1).getLength(); z++ ) System.out.print('I');
// System.out.println();
// }
// if ( debugOn ) System.out.println("Consensus: "+consensus.str);
for ( int j = 0; j < altReads.size(); j++ ) {
AlignedRead toTest = altReads.get(j);
Pair<Integer, Integer> altAlignment = findBestOffset(consensus.str, toTest, leftmostIndex);
// the mismatch score is the min of its alignment vs. the reference and vs. the alternate
int myScore = altAlignment.second;
if ( myScore > toTest.getAlignerMismatchScore() || myScore >= toTest.getMismatchScoreToReference() )
myScore = toTest.getMismatchScoreToReference();
// keep track of reads that align better to the alternate consensus.
// By pushing alignments with equal scores to the alternate, it means we'll over-call (het -> hom non ref) but are less likely to under-call (het -> ref, het non ref -> het)
else
consensus.readIndexes.add(new Pair<Integer, Integer>(j, altAlignment.first));
//logger.debug(consensus.cigar + " vs. " + toTest.getRead().getReadName() + "-" + toTest.getRead().getReadString() + " => " + myScore + " vs. " + toTest.getMismatchScoreToReference());
if ( !toTest.getRead().getDuplicateReadFlag() )
consensus.mismatchSum += myScore;
// optimization: once the mismatch sum is higher than the best consensus, quit since this one can't win
// THIS MUST BE DISABLED IF WE DECIDE TO ALLOW MORE THAN ONE ALTERNATE CONSENSUS!
if ( bestConsensus != null && consensus.mismatchSum > bestConsensus.mismatchSum )
break;
}
//logger.debug("Mismatch sum of new consensus: " + consensus.mismatchSum);
if ( bestConsensus == null || bestConsensus.mismatchSum > consensus.mismatchSum) {
// we do not need this alt consensus, release memory right away!!
if ( bestConsensus != null )
bestConsensus.readIndexes.clear();
bestConsensus = consensus;
//logger.debug("New consensus " + bestConsensus.cigar + " is now best consensus");
} else {
// we do not need this alt consensus, release memory right away!!
consensus.readIndexes.clear();
}
}
// if:
// 1) the best alternate consensus has a smaller sum of quality score mismatches than the aligned version of the reads,
// 2) beats the LOD threshold for the sum of quality score mismatches of the raw version of the reads,
// 3) didn't just move around the mismatching columns (i.e. it actually reduces entropy),
// then clean!
final double improvement = (bestConsensus == null ? -1 : ((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0);
if ( improvement >= LOD_THRESHOLD ) {
bestConsensus.cigar = AlignmentUtils.leftAlignIndel(bestConsensus.cigar, reference, bestConsensus.str, bestConsensus.positionOnReference, bestConsensus.positionOnReference);
// start cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
AlignedRead aRead = altReads.get(indexPair.first);
if ( !updateRead(bestConsensus.cigar, bestConsensus.positionOnReference, indexPair.second, aRead, leftmostIndex) )
return;
}
if ( consensusModel != ConsensusDeterminationModel.KNOWNS_ONLY && !alternateReducesEntropy(altReads, reference, leftmostIndex) ) {
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tFAIL (bad indel)\t"); // if improvement > LOD_THRESHOLD *BUT* entropy is not reduced (SNPs still exist)
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
} else {
//logger.debug("CLEAN: " + bestConsensus.cigar + " " + bestConsensus.str.toString() + " " + bestConsensus.cigar.numCigarElements() );
if ( indelOutput != null && bestConsensus.cigar.numCigarElements() > 1 ) {
// NOTE: indels are printed out in the format specified for the low-coverage pilot1
// indel calls (tab-delimited): chr position size type sequence
StringBuilder str = new StringBuilder();
str.append(reads.get(0).getReferenceName());
int position = bestConsensus.positionOnReference + bestConsensus.cigar.getCigarElement(0).getLength();
str.append("\t" + (leftmostIndex + position - 1));
CigarElement ce = bestConsensus.cigar.getCigarElement(1);
str.append("\t" + ce.getLength() + "\t" + ce.getOperator() + "\t");
int length = ce.getLength();
if ( ce.getOperator() == CigarOperator.D ) {
for ( int i = 0; i < length; i++)
str.append((char)reference[position+i]);
} else {
for ( int i = 0; i < length; i++)
str.append((char)bestConsensus.str[position+i]);
}
str.append("\t" + (((double)(totalRawMismatchSum - bestConsensus.mismatchSum))/10.0) + "\n");
try {
indelOutput.write(str.toString());
indelOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("indelOutput", "Failed to write indel output file", e);
}
}
if ( statsOutput != null ) {
try {
statsOutput.write(currentInterval.toString());
statsOutput.write("\tCLEAN"); // if improvement > LOD_THRESHOLD *AND* entropy is reduced
if ( bestConsensus.cigar.numCigarElements() > 1 )
statsOutput.write(" (found indel)");
statsOutput.write("\t");
statsOutput.write(Double.toString(improvement));
statsOutput.write("\n");
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
// finish cleaning the appropriate reads
for ( Pair<Integer, Integer> indexPair : bestConsensus.readIndexes ) {
final AlignedRead aRead = altReads.get(indexPair.first);
if ( aRead.finalizeUpdate() ) {
// We need to update the mapping quality score of the cleaned reads;
// however we don't have enough info to use the proper MAQ scoring system.
// For now, we will just arbitrarily add 10 to the mapping quality. [EB, 6/7/2010].
// TODO -- we need a better solution here
GATKSAMRecord read = aRead.getRead();
if ( read.getMappingQuality() != 255 ) // 255 == Unknown, so don't modify it
read.setMappingQuality(Math.min(aRead.getRead().getMappingQuality() + 10, 254));
// before we fix the attribute tags we first need to make sure we have enough of the reference sequence
int neededBasesToLeft = leftmostIndex - read.getAlignmentStart();
int neededBasesToRight = read.getAlignmentEnd() - leftmostIndex - reference.length + 1;
int neededBases = Math.max(neededBasesToLeft, neededBasesToRight);
if ( neededBases > 0 ) {
int padLeft = Math.max(leftmostIndex-neededBases, 1);
int padRight = Math.min(leftmostIndex+reference.length+neededBases, referenceReader.getSequenceDictionary().getSequence(currentInterval.getContig()).getSequenceLength());
reference = referenceReader.getSubsequenceAt(currentInterval.getContig(), padLeft, padRight).getBases();
leftmostIndex = padLeft;
}
// now, fix the attribute tags
// TODO -- get rid of this try block when Picard does the right thing for reads aligned off the end of the reference
try {
if ( read.getAttribute(SAMTag.NM.name()) != null )
read.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(read, reference, leftmostIndex-1));
if ( read.getAttribute(SAMTag.UQ.name()) != null )
read.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(read, reference, leftmostIndex-1));
} catch (Exception e) {
// ignore it
}
// TODO -- this is only temporary until Tim adds code to recalculate this value
if ( read.getAttribute(SAMTag.MD.name()) != null )
read.setAttribute(SAMTag.MD.name(), null);
// mark that it was actually cleaned
readsActuallyCleaned.add(read);
}
}
}
// END IF ( improvement >= LOD_THRESHOLD )
} else if ( statsOutput != null ) {
try {
statsOutput.write(String.format("%s\tFAIL\t%.1f%n",
currentInterval.toString(), improvement));
statsOutput.flush();
} catch (Exception e) {
throw new UserException.CouldNotCreateOutputFile("statsOutput", "Failed to write stats output file", e);
}
}
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/cli/SVN.java b/javasvn/src/org/tmatesoft/svn/cli/SVN.java
index 8612f21ff..866555a72 100644
--- a/javasvn/src/org/tmatesoft/svn/cli/SVN.java
+++ b/javasvn/src/org/tmatesoft/svn/cli/SVN.java
@@ -1,77 +1,76 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://tmate.org/svn/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.cli;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.ws.fs.FSEntryFactory;
import org.tmatesoft.svn.core.io.SVNException;
import org.tmatesoft.svn.util.DebugLog;
/**
* @author TMate Software Ltd.
*/
public class SVN {
public static void main(String[] args) {
if (args == null || args.length < 1) {
DebugLog.log("invliad arguments!");
System.err.println("usage: svn commandName commandArguments");
System.exit(0);
}
StringBuffer commandLineString = new StringBuffer();
for(int i = 0; i < args.length; i++) {
commandLineString.append(args[i] + (i < args.length - 1 ? " " : ""));
}
DebugLog.log("command line: " + commandLineString.toString());
SVNCommandLine commandLine = null;
try {
try {
commandLine = new SVNCommandLine(args);
} catch (SVNException e) {
DebugLog.error(e);
System.err.println("error: " + e.getMessage());
System.exit(1);
}
String commandName = commandLine.getCommandName();
DebugLog.log("COMMAND NAME: " + commandName + " ========================================== ");
SVNCommand command = SVNCommand.getCommand(commandName);
DebugLog.log("command: " + command);
if (command != null) {
DAVRepositoryFactory.setup();
SVNRepositoryFactoryImpl.setup();
FSEntryFactory.setup();
command.setCommandLine(commandLine);
try {
command.run(System.out, System.err);
} catch (SVNException e) {
- System.err.println("error: " + e.getMessage());
- e.printStackTrace(System.err);
+ System.err.println(e.getMessage());
DebugLog.error(e);
}
} else {
System.err.println("error: unknown command name '" + commandName + "'");
System.exit(1);
}
} catch (Throwable th) {
DebugLog.error(th);
System.exit(-1);
}
System.exit(0);
}
}
| true | true | public static void main(String[] args) {
if (args == null || args.length < 1) {
DebugLog.log("invliad arguments!");
System.err.println("usage: svn commandName commandArguments");
System.exit(0);
}
StringBuffer commandLineString = new StringBuffer();
for(int i = 0; i < args.length; i++) {
commandLineString.append(args[i] + (i < args.length - 1 ? " " : ""));
}
DebugLog.log("command line: " + commandLineString.toString());
SVNCommandLine commandLine = null;
try {
try {
commandLine = new SVNCommandLine(args);
} catch (SVNException e) {
DebugLog.error(e);
System.err.println("error: " + e.getMessage());
System.exit(1);
}
String commandName = commandLine.getCommandName();
DebugLog.log("COMMAND NAME: " + commandName + " ========================================== ");
SVNCommand command = SVNCommand.getCommand(commandName);
DebugLog.log("command: " + command);
if (command != null) {
DAVRepositoryFactory.setup();
SVNRepositoryFactoryImpl.setup();
FSEntryFactory.setup();
command.setCommandLine(commandLine);
try {
command.run(System.out, System.err);
} catch (SVNException e) {
System.err.println("error: " + e.getMessage());
e.printStackTrace(System.err);
DebugLog.error(e);
}
} else {
System.err.println("error: unknown command name '" + commandName + "'");
System.exit(1);
}
} catch (Throwable th) {
DebugLog.error(th);
System.exit(-1);
}
System.exit(0);
}
| public static void main(String[] args) {
if (args == null || args.length < 1) {
DebugLog.log("invliad arguments!");
System.err.println("usage: svn commandName commandArguments");
System.exit(0);
}
StringBuffer commandLineString = new StringBuffer();
for(int i = 0; i < args.length; i++) {
commandLineString.append(args[i] + (i < args.length - 1 ? " " : ""));
}
DebugLog.log("command line: " + commandLineString.toString());
SVNCommandLine commandLine = null;
try {
try {
commandLine = new SVNCommandLine(args);
} catch (SVNException e) {
DebugLog.error(e);
System.err.println("error: " + e.getMessage());
System.exit(1);
}
String commandName = commandLine.getCommandName();
DebugLog.log("COMMAND NAME: " + commandName + " ========================================== ");
SVNCommand command = SVNCommand.getCommand(commandName);
DebugLog.log("command: " + command);
if (command != null) {
DAVRepositoryFactory.setup();
SVNRepositoryFactoryImpl.setup();
FSEntryFactory.setup();
command.setCommandLine(commandLine);
try {
command.run(System.out, System.err);
} catch (SVNException e) {
System.err.println(e.getMessage());
DebugLog.error(e);
}
} else {
System.err.println("error: unknown command name '" + commandName + "'");
System.exit(1);
}
} catch (Throwable th) {
DebugLog.error(th);
System.exit(-1);
}
System.exit(0);
}
|
diff --git a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
index 1f4123ea..774ef50b 100644
--- a/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
+++ b/plugins/org.eclipse.acceleo.ide.ui/src/org/eclipse/acceleo/internal/ide/ui/builders/AcceleoBuilder.java
@@ -1,451 +1,453 @@
/*******************************************************************************
* Copyright (c) 2008, 2011 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.internal.ide.ui.builders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.common.internal.utils.AcceleoPackageRegistry;
import org.eclipse.acceleo.ide.ui.AcceleoUIActivator;
import org.eclipse.acceleo.ide.ui.resources.AcceleoProject;
import org.eclipse.acceleo.internal.ide.ui.AcceleoUIMessages;
import org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoMainClass;
import org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleowizardmodelFactory;
import org.eclipse.acceleo.internal.ide.ui.builders.runner.CreateRunnableAcceleoOperation;
import org.eclipse.acceleo.internal.ide.ui.generators.AcceleoUIGenerator;
import org.eclipse.acceleo.internal.parser.cst.utils.FileContent;
import org.eclipse.acceleo.internal.parser.cst.utils.Sequence;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IncrementalProjectBuilder;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
/**
* The builder compiles the Acceleo templates in a background task. Compilation errors are put in the problems
* view when it is necessary.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
*/
public class AcceleoBuilder extends IncrementalProjectBuilder {
/**
* The builder ID.
*/
public static final String BUILDER_ID = "org.eclipse.acceleo.ide.ui.acceleoBuilder"; //$NON-NLS-1$
/**
* The output folder to ignore.
*/
private IPath outputFolder;
/**
* Constructor.
*/
public AcceleoBuilder() {
super();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IncrementalProjectBuilder#build(int, java.util.Map,
* org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
@SuppressWarnings("rawtypes")
protected IProject[] build(int kind, Map arguments, IProgressMonitor monitor) throws CoreException {
if (getProject() == null || !getProject().isAccessible()) {
return new IProject[] {};
}
outputFolder = getOutputFolder(getProject());
try {
if (kind == FULL_BUILD) {
clean(monitor);
fullBuild(monitor);
} else {
IResourceDelta delta = getDelta(getProject());
if (delta == null) {
clean(monitor);
fullBuild(monitor);
} else {
incrementalBuild(delta, monitor);
}
}
} catch (OperationCanceledException e) {
// We've only thrown this to cancel everything, stop propagation
} finally {
outputFolder = null;
}
return null;
}
/**
* It does a full build.
*
* @param monitor
* is the progress monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
protected void fullBuild(IProgressMonitor monitor) throws CoreException {
List<IFile> filesOutput = new ArrayList<IFile>();
AcceleoBuilderUtils.members(filesOutput, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
if (filesOutput.size() > 0) {
Collections.sort(filesOutput, new Comparator<IFile>() {
public int compare(IFile arg0, IFile arg1) {
long m0 = arg0.getLocation().toFile().lastModified();
long m1 = arg1.getLocation().toFile().lastModified();
if (m0 < m1) {
return 1;
}
return -1;
}
});
registerAccessibleEcoreFiles();
IFile[] files = filesOutput.toArray(new IFile[filesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, false);
compileOperation.run(monitor);
validateAcceleoBuildFile(monitor);
}
}
/**
* Register the accessible workspace ecore files.
*
* @throws CoreException
* when an issue occurs
*/
private void registerAccessibleEcoreFiles() throws CoreException {
List<IFile> ecoreFiles = new ArrayList<IFile>();
AcceleoProject acceleoProject = new AcceleoProject(getProject());
for (IProject project : acceleoProject.getRecursivelyAccessibleProjects()) {
if (project.isAccessible()) {
AcceleoBuilderUtils.members(ecoreFiles, project, "ecore", outputFolder); //$NON-NLS-1$
}
}
for (IFile ecoreFile : ecoreFiles) {
AcceleoPackageRegistry.INSTANCE.registerEcorePackages(ecoreFile.getFullPath().toString(),
AcceleoPackageRegistry.DYNAMIC_METAMODEL_RESOURCE_SET);
}
}
/**
* It checks the build configuration of the Acceleo module. It creates the build.acceleo file and the
* build.xml file if they don't exist.
*
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
if (outputFolder != null && outputFolder.segmentCount() > 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
- AcceleoUIGenerator.getDefault().generateBuildXML(
- acceleoMainClass,
- AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
- getProject().getFile("build.xml").getLocation()).toString(), //$NON-NLS-1$
- AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
- getProject().getFile("build.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
+ AcceleoUIGenerator
+ .getDefault()
+ .generateBuildXML(
+ acceleoMainClass,
+ AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
+ getProject().getFile("buildstandalone.xml").getLocation()).toString(), //$NON-NLS-1$
+ AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
+ getProject().getFile("buildstandalone.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
/**
* It does an incremental build.
*
* @param delta
* is the resource delta
* @param monitor
* is the progress monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
protected void incrementalBuild(IResourceDelta delta, IProgressMonitor monitor) throws CoreException {
List<IFile> deltaFilesOutput = new ArrayList<IFile>();
deltaMembers(deltaFilesOutput, delta, monitor);
if (deltaFilesOutput.size() > 0) {
boolean containsManifest = false;
for (int i = 0; !containsManifest && i < deltaFilesOutput.size(); i++) {
containsManifest = "MANIFEST.MF".equals(deltaFilesOutput.get(i).getName()); //$NON-NLS-1$
}
if (containsManifest) {
deltaFilesOutput.clear();
AcceleoBuilderUtils.members(deltaFilesOutput, getProject(),
IAcceleoConstants.MTL_FILE_EXTENSION, outputFolder);
} else {
computeOtherFilesToBuild(deltaFilesOutput);
}
} else {
computeOtherFilesToBuild(deltaFilesOutput);
}
if (deltaFilesOutput.size() > 0) {
Collections.sort(deltaFilesOutput, new Comparator<IFile>() {
public int compare(IFile arg0, IFile arg1) {
long m0 = arg0.getLocation().toFile().lastModified();
long m1 = arg1.getLocation().toFile().lastModified();
if (m0 < m1) {
return 1;
}
return -1;
}
});
registerAccessibleEcoreFiles();
IFile[] files = deltaFilesOutput.toArray(new IFile[deltaFilesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, false);
compileOperation.run(monitor);
validateAcceleoBuildFile(monitor);
} else {
// We have deleted a file, let's build the whole project.
IResourceDelta[] affectedChildren = delta.getAffectedChildren();
if (affectedChildren.length == 2 && affectedChildren[0].getResource() instanceof IFolder
&& affectedChildren[1].getResource() instanceof IFolder) {
this.fullBuild(monitor);
}
}
}
/**
* Gets also the files that depend of the templates to build.
*
* @param deltaFiles
* is an output parameter to get all the templates to build
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void computeOtherFilesToBuild(List<IFile> deltaFiles) throws CoreException {
AcceleoProject acceleoProject = new AcceleoProject(getProject());
List<IFile> otherTemplates = new ArrayList<IFile>();
AcceleoBuilderUtils.members(otherTemplates, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
List<Sequence> importSequencesToSearch = new ArrayList<Sequence>();
for (int i = 0; i < deltaFiles.size(); i++) {
IFile deltaFile = deltaFiles.get(i);
if (IAcceleoConstants.MTL_FILE_EXTENSION.equals(deltaFile.getFileExtension())) {
importSequencesToSearch.addAll(AcceleoBuilderUtils.getImportSequencesToSearch(acceleoProject,
deltaFile));
otherTemplates.remove(deltaFile);
}
}
List<IFile> otherTemplatesToBuild = getOtherTemplatesToBuild(acceleoProject, otherTemplates,
importSequencesToSearch);
while (otherTemplatesToBuild.size() > 0) {
for (int i = 0; i < otherTemplatesToBuild.size(); i++) {
IFile otherTemplateToBuild = otherTemplatesToBuild.get(i);
otherTemplates.remove(otherTemplateToBuild);
if (!deltaFiles.contains(otherTemplateToBuild)) {
deltaFiles.add(otherTemplateToBuild);
importSequencesToSearch.addAll(AcceleoBuilderUtils.getImportSequencesToSearch(
acceleoProject, otherTemplateToBuild));
}
}
otherTemplatesToBuild = getOtherTemplatesToBuild(acceleoProject, otherTemplates,
importSequencesToSearch);
}
}
/**
* Gets the files that import the given dependencies.
*
* @param acceleoProject
* is the project
* @param otherTemplates
* are the other templates that we can decide to build
* @param importSequencesToSearch
* are the dependencies to detect in the "import" section of the other templates
* @return the other templates to build
*/
private List<IFile> getOtherTemplatesToBuild(AcceleoProject acceleoProject, List<IFile> otherTemplates,
List<Sequence> importSequencesToSearch) {
List<IFile> result = new ArrayList<IFile>();
for (int i = 0; i < otherTemplates.size(); i++) {
IFile otherTemplate = otherTemplates.get(i);
IPath outputPath = acceleoProject.getOutputFilePath(otherTemplate);
if (outputPath != null && !getProject().getFile(outputPath.removeFirstSegments(1)).exists()) {
result.add(otherTemplate);
} else {
StringBuffer otherTemplateContent = FileContent.getFileContent(otherTemplate.getLocation()
.toFile());
for (int j = 0; j < importSequencesToSearch.size(); j++) {
Sequence importSequence = importSequencesToSearch.get(j);
if (importSequence.search(otherTemplateContent).b() > -1) {
result.add(otherTemplate);
}
}
}
}
return result;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IncrementalProjectBuilder#clean(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected void clean(IProgressMonitor monitor) throws CoreException {
super.clean(monitor);
List<IFile> filesOutput = new ArrayList<IFile>();
AcceleoBuilderUtils.members(filesOutput, getProject(), IAcceleoConstants.MTL_FILE_EXTENSION,
outputFolder);
if (filesOutput.size() > 0) {
IFile[] files = filesOutput.toArray(new IFile[filesOutput.size()]);
AcceleoCompileOperation compileOperation = new AcceleoCompileOperation(getProject(), files, true);
compileOperation.run(monitor);
}
}
/**
* Computes a list of all the modified files (Acceleo files only).
*
* @param deltaFilesOutput
* an output parameter to get all the modified files
* @param delta
* the resource delta represents changes in the state of a resource tree
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void deltaMembers(List<IFile> deltaFilesOutput, IResourceDelta delta, IProgressMonitor monitor)
throws CoreException {
if (delta != null) {
IResource resource = delta.getResource();
if (resource instanceof IFile) {
if (delta.getKind() == IResourceDelta.REMOVED
&& IAcceleoConstants.MTL_FILE_EXTENSION.equals(resource.getFileExtension())) {
removeOutputFile((IFile)resource, monitor);
}
if (delta.getKind() != IResourceDelta.REMOVED
&& (IAcceleoConstants.MTL_FILE_EXTENSION.equals(resource.getFileExtension()) || "MANIFEST.MF" //$NON-NLS-1$
.equals(resource.getName()))) {
deltaFilesOutput.add((IFile)resource);
}
} else {
if (outputFolder == null || !outputFolder.isPrefixOf(resource.getFullPath())) {
IResourceDelta[] children = delta.getAffectedChildren();
for (int i = 0; i < children.length; i++) {
deltaMembers(deltaFilesOutput, children[i], monitor);
}
}
}
}
}
/**
* Removes the output file that corresponding to the input file.
*
* @param inputFile
* is the input file ('.acceleo')
* @param monitor
* is the monitor
* @throws CoreException
* contains a status object describing the cause of the exception
*/
private void removeOutputFile(IFile inputFile, IProgressMonitor monitor) throws CoreException {
AcceleoProject acceleoProject = new AcceleoProject(getProject());
IPath outputPath = acceleoProject.getOutputFilePath(inputFile);
IResource outputFile = ResourcesPlugin.getWorkspace().getRoot().findMember(outputPath);
if (outputFile instanceof IFile && outputFile.isAccessible()) {
outputFile.delete(true, monitor);
}
}
/**
* Gets the output folder of the project. For example : '/MyProject/bin'.
*
* @param aProject
* is a project of the workspace
* @return the output folder of the project, or null if it doesn't exist
*/
private IPath getOutputFolder(IProject aProject) {
final IJavaProject javaProject = JavaCore.create(aProject);
try {
IPath output = javaProject.getOutputLocation();
if (output != null && output.segmentCount() > 1) {
IFolder folder = aProject.getWorkspace().getRoot().getFolder(output);
if (folder.isAccessible()) {
return folder.getFullPath();
}
}
} catch (JavaModelException e) {
// continue
AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
}
return null;
}
}
| true | true | private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
if (outputFolder != null && outputFolder.segmentCount() > 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
AcceleoUIGenerator.getDefault().generateBuildXML(
acceleoMainClass,
AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
getProject().getFile("build.xml").getLocation()).toString(), //$NON-NLS-1$
AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
getProject().getFile("build.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
| private void validateAcceleoBuildFile(IProgressMonitor monitor) throws CoreException {
IFile buildProperties = getProject().getFile("build.properties"); //$NON-NLS-1$
if (outputFolder != null && outputFolder.segmentCount() > 1) {
IFile buildAcceleo = getProject().getFile("build.acceleo"); //$NON-NLS-1$
AcceleoProject project = new AcceleoProject(getProject());
List<IProject> dependencies = project.getRecursivelyAccessibleProjects();
dependencies.remove(getProject());
org.eclipse.acceleo.internal.ide.ui.acceleowizardmodel.AcceleoProject acceleoProject = AcceleowizardmodelFactory.eINSTANCE
.createAcceleoProject();
List<String> pluginDependencies = acceleoProject.getPluginDependencies();
for (IProject iProject : dependencies) {
pluginDependencies.add(iProject.getName());
}
AcceleoUIGenerator.getDefault().generateBuildAcceleo(acceleoProject, buildAcceleo.getParent());
List<String> resolvedClasspath = new ArrayList<String>();
Iterator<IPath> entries = project.getResolvedClasspath().iterator();
IPath eclipseWorkspace = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath eclipseHome = new Path(Platform.getInstallLocation().getURL().getPath());
while (entries.hasNext()) {
IPath path = entries.next();
if (eclipseWorkspace.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_WORKSPACE}/" //$NON-NLS-1$
+ path.toString().substring(eclipseWorkspace.toString().length()));
} else if (eclipseHome.isPrefixOf(path)) {
resolvedClasspath.add("${ECLIPSE_HOME}/" //$NON-NLS-1$
+ path.toString().substring(eclipseHome.toString().length()));
}
}
AcceleoMainClass acceleoMainClass = AcceleowizardmodelFactory.eINSTANCE.createAcceleoMainClass();
acceleoMainClass.setProjectName(getProject().getName());
List<String> classPath = acceleoMainClass.getResolvedClassPath();
classPath.addAll(resolvedClasspath);
IPath workspacePathRelativeToFile = CreateRunnableAcceleoOperation.computeWorkspacePath();
IPath eclipsePathRelativeToFile = CreateRunnableAcceleoOperation.computeEclipsePath();
AcceleoUIGenerator
.getDefault()
.generateBuildXML(
acceleoMainClass,
AcceleoProject.makeRelativeTo(eclipsePathRelativeToFile,
getProject().getFile("buildstandalone.xml").getLocation()).toString(), //$NON-NLS-1$
AcceleoProject.makeRelativeTo(workspacePathRelativeToFile,
getProject().getFile("buildstandalone.xml").getLocation()).toString(), getProject()); //$NON-NLS-1$
if (FileContent.getFileContent(buildProperties.getLocation().toFile()).indexOf(
buildAcceleo.getName()) == -1) {
AcceleoUIActivator.getDefault().getLog().log(
new Status(IStatus.ERROR, AcceleoUIActivator.PLUGIN_ID, AcceleoUIMessages.getString(
"AcceleoBuilder.AcceleoBuildFileIssue", new Object[] {getProject() //$NON-NLS-1$
.getName(), })));
}
}
}
|
diff --git a/commands/src/main/java/org/jclouds/karaf/commands/table/internal/ManagedShellTableFactory.java b/commands/src/main/java/org/jclouds/karaf/commands/table/internal/ManagedShellTableFactory.java
index e8a8ad5..57b0804 100644
--- a/commands/src/main/java/org/jclouds/karaf/commands/table/internal/ManagedShellTableFactory.java
+++ b/commands/src/main/java/org/jclouds/karaf/commands/table/internal/ManagedShellTableFactory.java
@@ -1,67 +1,69 @@
/*
* Copyright (C) 2011, the original authors
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.karaf.commands.table.internal;
import org.jclouds.karaf.commands.table.BasicShellTableFactory;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import java.util.Dictionary;
import java.util.Enumeration;
public class ManagedShellTableFactory extends BasicShellTableFactory implements ManagedService {
/**
* Update the configuration for a Managed Service.
* <p/>
* <p/>
* When the implementation of <code>updated(Dictionary)</code> detects any
* kind of error in the configuration properties, it should create a new
* <code>ConfigurationException</code> which describes the problem. This
* can allow a management system to provide useful information to a human
* administrator.
* <p/>
* <p/>
* If this method throws any other <code>Exception</code>, the
* Configuration Admin service must catch it and should log it.
* <p/>
* The Configuration Admin service must call this method asynchronously
* which initiated the callback. This implies that implementors of Managed
* Service can be assured that the callback will not take place during
* registration when they execute the registration in a synchronized method.
*
* @param properties A copy of the Configuration properties, or
* <code>null</code>. This argument must not contain the
* "service.bundleLocation" property. The value of this property may
* be obtained from the <code>Configuration.getBundleLocation</code>
* method.
* @throws org.osgi.service.cm.ConfigurationException
* when the update fails
*/
@Override
public void updated(Dictionary properties) throws ConfigurationException {
- Enumeration keys = properties.keys();
- getProperties().clear();
- while (keys.hasMoreElements()) {
- Object key = keys.nextElement();
- Object value = properties.get(key);
- getProperties().put(key, value);
+ if (properties != null) {
+ Enumeration keys = properties.keys();
+ getProperties().clear();
+ while (keys.hasMoreElements()) {
+ Object key = keys.nextElement();
+ Object value = properties.get(key);
+ getProperties().put(key, value);
+ }
}
}
}
| true | true | public void updated(Dictionary properties) throws ConfigurationException {
Enumeration keys = properties.keys();
getProperties().clear();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = properties.get(key);
getProperties().put(key, value);
}
}
| public void updated(Dictionary properties) throws ConfigurationException {
if (properties != null) {
Enumeration keys = properties.keys();
getProperties().clear();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = properties.get(key);
getProperties().put(key, value);
}
}
}
|
diff --git a/Sourcecode/zisko/multicastor/program/controller/ViewController.java b/Sourcecode/zisko/multicastor/program/controller/ViewController.java
index 9a89869..cd22751 100644
--- a/Sourcecode/zisko/multicastor/program/controller/ViewController.java
+++ b/Sourcecode/zisko/multicastor/program/controller/ViewController.java
@@ -1,2378 +1,2381 @@
package zisko.multicastor.program.controller;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.TableColumn;
import zisko.multicastor.program.view.FrameFileChooser;
import zisko.multicastor.program.view.FrameMain;
import zisko.multicastor.program.view.MiscBorder;
import zisko.multicastor.program.view.MiscTableModel;
import zisko.multicastor.program.view.PanelMulticastConfig;
import zisko.multicastor.program.view.PanelMulticastControl;
import zisko.multicastor.program.view.PanelStatusBar;
import zisko.multicastor.program.view.PanelTabbed;
import zisko.multicastor.program.view.PopUpMenu;
import zisko.multicastor.program.view.MiscBorder.BorderTitle;
import zisko.multicastor.program.view.MiscBorder.BorderType;
import zisko.multicastor.program.view.ReceiverGraph.valueType;
import zisko.multicastor.program.view.SnakeGimmick;
import zisko.multicastor.program.view.SnakeGimmick.SNAKE_DIRECTION;
import zisko.multicastor.program.data.MulticastData;
import zisko.multicastor.program.data.UserInputData;
import zisko.multicastor.program.data.UserlevelData;
import zisko.multicastor.program.data.MulticastData.Typ;
import zisko.multicastor.program.data.UserlevelData.Userlevel;
import zisko.multicastor.program.model.InputValidator;
import zisko.multicastor.program.model.NetworkAdapter;
/**
* Steuerungsklasse des GUI
* @author Daniel Becker
*
*/
public class ViewController implements ActionListener, MouseListener, ChangeListener, ComponentListener,
ListSelectionListener, KeyListener, DocumentListener, ItemListener,
ContainerListener, TableColumnModelListener, WindowListener{
/**
* Enum welches angibt um was f�r eine Art von GUI Benachrichtigung es sich handelt.
* @author Daniel Becker
*
*/
public enum MessageTyp {
INFO, WARNING, ERROR
}
/**
* Enum welches angibt um was f�r eine Art von GUI Update es sich handelt.
* @author Daniel Becker
*
*/
public enum UpdateTyp{
UPDATE, INSERT, DELETE
}
private SnakeGimmick.SNAKE_DIRECTION snakeDir = SNAKE_DIRECTION.E;
/**
* Referenz zum MulticastController, wichtigste Schnittstelle der Klasse.
*/
private MulticastController mc;
/**
* Referenz zum Frame in welchem das MultiCastor Tool angezeigt wird.
*/
private FrameMain f;
/**
* 2-Dimensionales Boolean Feld welches angibt in welchem Feld des jeweiligen Konfiguration Panels
* eine richtige oder falsche eingabe get�tigt wurde.
*/
private boolean[][] input = new boolean[4][6];
/**
* Hilfsvariable welche ben�tigt wird um die gemeinsamen Revceiver Graph Daten
* (JITTER, LOST PACKETS, MEASURED PACKET RATE) von mehreren Mutlicasts zu berechnen.
*/
private MulticastData[] graphData;
/**
* Hilfsvariable welche angibt wann die Initialisierung der GUI abgeschlossen ist.
*/
private boolean initFinished=false;
public void setInitFinished(boolean initFinished) {
this.initFinished = initFinished;
}
/**
* Datenobjekt welches den Input des IPv4 Senders enth�lt.
*/
private UserInputData inputData_S4;
public boolean isInitFinished() {
return initFinished;
}
/**
* Datenobjekt welches den Input des IPv6 Senders enth�lt.
*/
private UserInputData inputData_S6;
/**
* Datenobjekt welches den Input des IPv4 Receivers enth�lt.
*/
private UserInputData inputData_R4;
/**
* Datenobjekt welches den Input des IPv6 Receivers enth�lt.
*/
private UserInputData inputData_R6;
/**
* Standardkonstruktor der GUI, hierbei wird die GUI noch nicht initialisiert!
*/
public ViewController(){
//initialize(null);
}
/**
* Implementierung des ActionListeners, betrifft die meisten GUI Komponenten.
* Diese Funktion wird aufgerufen wenn eine Interaktion mit einer GUI Komponente stattfindet, welche
* den ActionListener dieser ViewController Klasse h�lt. Die IF-THEN-ELSEIF Abragen dienen dazu
* die Komponente zu identifizieren bei welcher die Interaktion stattgefunden hat.
*/
public void actionPerformed(ActionEvent e) {
if(e.getSource()==f.getMi_saveconfig()){
//System.out.println("Saving!");
f.getFc_save().toggle();
}
else if(e.getSource()==f.getMi_loadconfig()){
//System.out.println("Loading!");
f.getFc_load().toggle();
setColumnSettings(getUserInputData(getSelectedTab()), getSelectedTab());
}
else if(e.getSource()==f.getMi_snake()){
if(getSelectedTab()!=Typ.UNDEFINED && getSelectedTab()!=Typ.CONFIG){
if(getFrame().getPanelPart(getSelectedTab()).getPan_graph().runSnake)
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(false);
else
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(true);
}
}
else if(e.getSource()==f.getMi_exit()){
closeProgram();
}
// V1.5: Wenn "Titel aendern" im Menue ausgewaehlt wurde, oeffne einen InputDialog
else if (e.getSource() == f.getMi_setTitle()) {
- f.setBaseTitle(JOptionPane.showInputDialog("Bitte geben Sie einen neuen Titel ein", f.getBaseTitle()));
- f.updateTitle();
+ String temp = JOptionPane.showInputDialog("Bitte geben Sie einen neuen Titel ein", f.getBaseTitle());
+ if (temp != null) {
+ f.setBaseTitle(temp);
+ f.updateTitle();
+ }
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getTb_active()){
toggleBTactive(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getTb_active()){
toggleBTactive(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getTb_active()){
toggleBTactive(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getTb_active()){
toggleBTactive(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getBt_enter()){
pressBTenter(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getBt_enter()){
pressBTenter(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getBt_enter()){
pressBTenter(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getBt_enter()){
pressBTenter(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDelete()){
pressBTDelete(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDelete()){
pressBTDelete(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDelete()){
pressBTDelete(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDelete()){
pressBTDelete(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStop()){
pressBTStop(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStop()){
pressBTStop(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStop()){
pressBTStop(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStop()){
pressBTStop(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStart()){
pressBTStart(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStart()){
pressBTStart(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStart()){
pressBTStart(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStart()){
pressBTStart(Typ.RECEIVER_V6);
}
else if(e.getSource()==getFrame().getFc_save().getChooser()){
saveFileEvent(e);
}
else if(e.getSource()==getFrame().getFc_load().getChooser()){
loadFileEvent(e);
}
else if(e.getActionCommand().equals("hide")){
hideColumnClicked();
getTable(getSelectedTab()).getColumnModel().removeColumn(getTable(getSelectedTab()).getColumnModel().getColumn(PopUpMenu.getSelectedColumn()));
}
else if(e.getActionCommand().equals("showall")){
popUpResetColumnsPressed();
}
else if(e.getActionCommand().equals("PopupCheckBox")){
popUpCheckBoxPressed();
}
else if(e.getActionCommand().equals("lastConfig1")){
loadConfig(f.getLastConfigs().get(0), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig2")){
loadConfig(f.getLastConfigs().get(1), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig3")){
loadConfig(f.getLastConfigs().get(2), true, true, true, true, true);
}
autoSave();
}
/**
* Funktion welche aufgerufen wird wenn der User Reset View im Popup Menu des Tabellenkopf dr�ckt.
* Stellt das urspr�ngliche Aussehen der Tabelle wieder her.
*/
private void popUpResetColumnsPressed() {
getUserInputData(getSelectedTab()).resetColumns();
getPanTabbed(getSelectedTab()).setTableModel(this, getSelectedTab());
}
/**
* Funktion die aufgerufen wird wenn eine Checkbox im Popup Menu des Tabellenkopfs gedr�ckt wird.
* Wird verwendet zum Einblenden und Ausblenden von Tabellenspalten.
*/
private void popUpCheckBoxPressed() {
ArrayList<Integer> visibility = new ArrayList<Integer>();
UserInputData store = new UserInputData();
store.setColumnOrder(getUserInputData(getSelectedTab()).getColumnOrder());
JCheckBox[] columns = PopUpMenu.getColumns();
for(int i = 0 ; i < columns.length ; i++){
if(columns[i].isSelected()){
String s = columns[i].getText();
if(s.equals("STATE")){
visibility.add(new Integer(0));
}
else if(s.equals("ID")){
visibility.add(new Integer(1));
}
else if(s.equals("GRP IP")){
visibility.add(new Integer(2));
}
else if(s.equals("D RATE")){
visibility.add(new Integer(3));
}
else if(s.equals("M RATE")){
visibility.add(new Integer(4));
}
else if(s.equals("Mbit/s")){
visibility.add(new Integer(5));
}
else if(s.equals("PORT")){
visibility.add(new Integer(6));
}
else if(s.equals("SRC IP") || s.equals("LOSS/S")){
visibility.add(new Integer(7));
}
else if(s.equals("#SENT") || s.equals("AVG INT")){
visibility.add(new Integer(8));
}
else if(s.equals("#INT") || s.equals("TTL")){
visibility.add(new Integer(9));
}
else if(s.equals("SRC") || s.equals("LENGTH")){
visibility.add(new Integer(10));
}
}
}
store.setColumnVisibility(visibility);
setColumnSettings(store, getSelectedTab());
}
/**
* Added einen Container und einen Keylistener zu dem
* Component c. Hat die Komponente Kinder, mache das
* gleiche mit jedem Child
* @param c Container, der die Listener erhalten soll
*/
private void addKeyAndContainerListenerToAll(Component c)
{
c.addKeyListener(this);
//Wenn Container, noch containerListener ben�tigt
//Au�erdem ben�tigen die Childs den gleichen listener
if(c instanceof Container) {
Container cont = (Container)c;
cont.addContainerListener(this);
Component[] children = cont.getComponents();
for(int i = 0; i < children.length; i++){
addKeyAndContainerListenerToAll(children[i]);
}
}
}
/**
* Funktion welche eni neues Multicast Datenobjekt an den MultiCast Controller weitergibt zur Verarbeitung.
* @param mcd neu erstelltes Multicast DatenObjekt welches verarbeitet werden soll.
*/
public void addMC(MulticastData mcd){
mc.addMC(mcd);
updateTable(mcd.getTyp(),UpdateTyp.INSERT);
}
@Override
/**
* Funktion welche aufgerufen wird wenn sich die Parameter eines Textfelds ge�ndert haben.
*/
public void changedUpdate(DocumentEvent arg0) {
}
/**
* Funktion welche ein ge�ndertes Multicast Datenobjekt an den MultiCast Controller weitergibt zur Verarbeitung.
* @param mcd Das ge�nderter MulticastData Object.
*/
public void changeMC(MulticastData mcd){
//System.out.println(mcd.toString());
mc.changeMC(mcd);
updateTable(mcd.getTyp(),UpdateTyp.UPDATE);
}
/**
* Hilfsfunktion welche den momentanen Input des KonfigurationsPanels in ein Multicast Datenobjekt schreibt.
* Wird ben�tigt zum anlegen neuer Multicast sowie zum �ndern vorhandener Multicasts.
* @param mcd MulticastData Objet welches ge�ndert werden soll.
* @param typ Programmteil aus welchem die Input Daten ausgelesen werden sollen.
* @return Ge�nderters Multicast Datenobjekt.
*/
private MulticastData changeMCData(MulticastData mcd, MulticastData.Typ typ){
switch(typ){
case SENDER_V4:
if(!getPanConfig(typ).getTf_groupIPaddress().getText().equals("...")){
mcd.setGroupIp(InputValidator.checkMC_IPv4(getPanConfig(typ).getTf_groupIPaddress().getText()));
}
if(!(getPanConfig(typ).getCb_sourceIPaddress().getSelectedIndex()==0)){
mcd.setSourceIp(getPanConfig(typ).getSelectedAddress(typ));
}
if(!getPanConfig(typ).getTf_udp_packetlength().getText().equals("...")){
mcd.setPacketLength(InputValidator.checkIPv4PacketLength(getPanConfig(typ).getTf_udp_packetlength().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setPacketLength(InputValidator.checkIPv4PacketLength("2048"));
}
}
if(!getPanConfig(typ).getTf_ttl().getText().equals("...")){
mcd.setTtl(InputValidator.checkTimeToLive(getPanConfig(typ).getTf_ttl().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setTtl(InputValidator.checkTimeToLive("32"));
}
}
if(!getPanConfig(typ).getTf_packetrate().getText().equals("...")){
mcd.setPacketRateDesired(InputValidator.checkPacketRate(getPanConfig(typ).getTf_packetrate().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setPacketRateDesired(InputValidator.checkPacketRate("50"));
}
}
break;
case SENDER_V6:
if(!getPanConfig(typ).getTf_groupIPaddress().getText().equals("...")){
mcd.setGroupIp(InputValidator.checkMC_IPv6(getPanConfig(typ).getTf_groupIPaddress().getText()));
}
if(!(getPanConfig(typ).getCb_sourceIPaddress().getSelectedIndex()==0)){
mcd.setSourceIp(getPanConfig(typ).getSelectedAddress(typ));
}
if(!getPanConfig(typ).getTf_udp_packetlength().getText().equals("...")){
mcd.setPacketLength(InputValidator.checkIPv6PacketLength(getPanConfig(typ).getTf_udp_packetlength().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setPacketLength(InputValidator.checkIPv6PacketLength("2048"));
}
}
if(!getPanConfig(typ).getTf_ttl().getText().equals("...")){
mcd.setTtl(InputValidator.checkTimeToLive(getPanConfig(typ).getTf_ttl().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setTtl(InputValidator.checkTimeToLive("32"));
}
}
if(!getPanConfig(typ).getTf_packetrate().getText().equals("...")){
mcd.setPacketRateDesired(InputValidator.checkPacketRate(getPanConfig(typ).getTf_packetrate().getText()));
if(getSelectedUserLevel() == Userlevel.BEGINNER){
mcd.setPacketRateDesired(InputValidator.checkPacketRate("50"));
}
}
break;
case RECEIVER_V4:
if(!getPanConfig(typ).getTf_groupIPaddress().getText().equals("...")){
mcd.setGroupIp(InputValidator.checkMC_IPv4(getPanConfig(typ).getTf_groupIPaddress().getText()));
}
break;
case RECEIVER_V6:
if(!getPanConfig(typ).getTf_groupIPaddress().getText().equals("...")){
mcd.setGroupIp(InputValidator.checkMC_IPv6(getPanConfig(typ).getTf_groupIPaddress().getText()));
}
break;
default: System.out.println("changeMCData(Multicastdata mcd) - ERROR");
}
if(!getPanConfig(typ).getTf_udp_port().getText().equals("...")){
mcd.setUdpPort(InputValidator.checkPort(getPanConfig(typ).getTf_udp_port().getText()));
}
if(!getPanConfig(typ).getTb_active().getText().equals("multiple")){
mcd.setActive(getPanConfig(typ).getTb_active().isSelected());
}
mcd.setTyp(typ);
//System.out.println(mcd.toString());
return mcd;
}
/**
* Funktion welche aufgerufen wird wenn der User das Netzwerk Interface in einem Sender �ndert.
* @param typ Programmteil in welchem das Netzwerkinterface ge�ndert wurde.
*/
private void changeNetworkInterface(Typ typ) {
PanelMulticastConfig configpart = getPanConfig(typ);
int selectedIndex = configpart.getTf_sourceIPaddress().getSelectedIndex();
if(selectedIndex != 0){
if(typ==Typ.SENDER_V4 || typ == Typ.RECEIVER_V4){
configpart.getPan_sourceIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4SOURCE, BorderType.TRUE));
if(typ==Typ.SENDER_V4){
input[0][1]=true;
}
else{
input[1][1]=true;
}
}
else{
configpart.getPan_sourceIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv6SOURCE, BorderType.TRUE));
if(typ==Typ.SENDER_V6){
input[2][1]=true;
}
else{
input[3][1]=true;
}
}
}
else if(getSelectedRows(typ).length > 1 && configpart.getCb_sourceIPaddress().getItemAt(0).equals("...")){
if(typ==Typ.SENDER_V4 || typ == Typ.RECEIVER_V4){
configpart.getPan_sourceIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4SOURCE, BorderType.TRUE));
if(typ==Typ.SENDER_V4){
input[0][1]=true;
}
else{
input[1][1]=true;
}
}
else{
configpart.getPan_sourceIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv6SOURCE, BorderType.TRUE));
if(typ==Typ.SENDER_V6){
input[2][1]=true;
}
else{
input[3][1]=true;
}
}
}
else{
switch(typ){
case SENDER_V4: input[0][1]=false; break;
case RECEIVER_V4: input[1][1]=false; break;
case SENDER_V6: input[2][1]=false; break;
case RECEIVER_V6: input[3][1]=false; break;
}
if(typ == Typ.SENDER_V6){
configpart.getPan_sourceIPaddress()
.setBorder(MiscBorder.getBorder(BorderTitle.IPv6SOURCE, BorderType.NEUTRAL));
}
else{
configpart.getPan_sourceIPaddress()
.setBorder(MiscBorder.getBorder(BorderTitle.IPv4SOURCE, BorderType.NEUTRAL));
}
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn sich der Inhalt eines Textfelds im Konfigurations Panel �ndert.
* Pr�ft ob alle eingaben korrekt sind.
* @param typ Programmteil in welchem die Eingaben gepr�ft werden sollen.
*/
private void checkInput(Typ typ){
if(getSelectedUserLevel()==Userlevel.BEGINNER){
input[0][3] = true;
input[0][4] = true;
input[0][5] = true;
input[2][3] = true;
input[2][4] = true;
input[2][5] = true;
}
switch(typ){
case SENDER_V4:
if( input[0][0] &&
input[0][1] &&
input[0][2] &&
input[0][3] &&
input[0][4] &&
input[0][5]){
getPanConfig(typ).getBt_enter().setEnabled(true);
}
else if(getSelectedRows(getSelectedTab()).length <=1){
getPanConfig(typ).getBt_enter().setEnabled(false);
}
break;
case RECEIVER_V4:
if( input[1][0] &&
input[1][2]){
f.getPanel_rec_ipv4().getPan_config().getBt_enter().setEnabled(true);
}
else if(getSelectedRows(typ).length <=1){
f.getPanel_rec_ipv4().getPan_config().getBt_enter().setEnabled(false);
}
break;
case SENDER_V6:
if( input[2][0] &&
input[2][1] &&
input[2][2] &&
input[2][3] &&
input[2][4] &&
input[2][5]){
f.getPanel_sen_ipv6().getPan_config().getBt_enter().setEnabled(true);
}
else if(getSelectedRows(getSelectedTab()).length <=1){
f.getPanel_sen_ipv6().getPan_config().getBt_enter().setEnabled(false);
}
break;
case RECEIVER_V6:
if( input[3][0] &&
input[3][2]){
f.getPanel_rec_ipv6().getPan_config().getBt_enter().setEnabled(true);
}
else if(getSelectedRows(getSelectedTab()).length <=1){
f.getPanel_rec_ipv6().getPan_config().getBt_enter().setEnabled(false);
}
break;
}
}
/**
* Funktion welche aufgerufen wird wenn die Eingaben der Textfelder des Konfigurations Panels zur�ckgesetzt werden sollen.
* @param typ Programmteil in welchem die Textfelder zur�ckgesetzt werden sollen.
*/
private void clearInput(Typ typ){
if(initFinished){
//System.out.println("clearinput");
getPanConfig(typ).getTf_groupIPaddress().setText("-");
getPanConfig(typ).getTf_udp_port().setText("-");
getPanConfig(typ).getTf_groupIPaddress().setText("");;
getPanConfig(typ).getTf_udp_port().setText("");
if(typ==Typ.SENDER_V4 || typ==Typ.SENDER_V6){
getPanConfig(typ).getTf_sourceIPaddress().setSelectedIndex(0);
getPanConfig(typ).getTf_ttl().setText("");
getPanConfig(typ).getTf_packetrate().setText("");;
getPanConfig(typ).getTf_udp_packetlength().setText("");;
getPanConfig(typ).getCb_sourceIPaddress().removeItemAt(0);
getPanConfig(typ).getCb_sourceIPaddress().insertItemAt("", 0);
getPanConfig(typ).getTf_sourceIPaddress().setSelectedIndex(0);
}
getPanConfig(typ).getTb_active().setSelected(false);
getPanConfig(typ).getTb_active().setText("inactive");
getPanConfig(typ).getTb_active().setForeground(Color.red);
getPanConfig(typ).getTf_groupIPaddress().requestFocusInWindow();
}
}
/**
* Funktion welche aufgerufen wird wenn das Programm beendet wird.
* Sorgt f�r ein sauberes Beenden des Programms. (nicht immer m�glich)
*/
private void closeProgram() {
//System.out.println("Shutting down GUI...");
f.setVisible(false);
//System.out.println("Cleanup...");
mc.destroy();
//System.out.println("Closing program...");
System.exit(0);
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Spalte zur Tabelle hinzugef�gt wird.
*/
public void columnAdded(TableColumnModelEvent arg0) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn sich der Aussenabstand der Tabellenspalte �ndert.
*/
public void columnMarginChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Spalte in der Tabelle verschoben wird.
*/
public void columnMoved(TableColumnModelEvent arg0) {
if(arg0.getFromIndex() != arg0.getToIndex()){
//System.out.println("column moved from "+arg0.getFromIndex()+" "+arg0.getToIndex());
getUserInputData(getSelectedTab()).changeColumns(arg0.getFromIndex(), arg0.getToIndex());
autoSave();
}
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Spalte aus der Tabelle entfernt wird.
*/
public void columnRemoved(TableColumnModelEvent arg0) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Andere Spalte in der Tabelle selektiert wird.
*/
public void columnSelectionChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener zum ViewPort hinzugef�gt wird.
*/
public void componentAdded(ContainerEvent e) {
addKeyAndContainerListenerToAll(e.getChild());
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener unsichtbar gemacht wird.
*/
public void componentHidden(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener verschoben wird.
*/
public void componentMoved(ComponentEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener von dem ViewPane entfernt wird.
*/
public void componentRemoved(ContainerEvent e) {
removeKeyAndContainerListenerToAll(e.getChild());
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener in der Gr��e ver�ndert wird.
*/
public void componentResized(ComponentEvent e) {
if(e.getSource()==getFrame()){
frameResizeEvent();
}
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine Komponente mit dem ComponentListener sichtbar gemacht wird.
*/
public void componentShown(ComponentEvent e) {
// TODO Auto-generated method stub
}
/**
* Hilfsfunktion welche alle Multicasts aus dem jeweiligen Programmteil l�scht
* @param typ
*/
public void deleteAllMulticasts(Typ typ){
pressBTSelectAll(typ);
pressBTDelete(typ);
}
/**
* Funktion welche aufgerufen wird wenn ein bestimmter Multicast gel�scht werden soll.
* @param mcd MulticastData Objekt des Multicasts welcher gel�scht werden soll.
*/
public void deleteMC(MulticastData mcd){
mc.deleteMC(mcd);
updateTable(mcd.getTyp(),UpdateTyp.DELETE);
}
/**
* Funktion welche aufgerufen wird wenn der Input des Group IP Adress Felds ge�ndert wurde.
* @param typ Programmteil in welchem das Group IP Adress Feld ge�ndert wurde.
*/
private void docEventTFgrp(Typ typ){
if(typ==Typ.SENDER_V4 || typ == Typ.RECEIVER_V4){
if((InputValidator.checkMC_IPv4(getPanConfig(typ).getTf_groupIPaddress().getText())!= null)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_groupIPaddress().getText().equals("..."))){
getPanConfig(typ).getPan_groupIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4GROUP, BorderType.TRUE));
if(typ==Typ.SENDER_V4){
input[0][0]=true;
}
else{
input[1][0]=true;
}
}
else{
getPanConfig(typ).getPan_groupIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4GROUP, BorderType.FALSE));
if(typ==Typ.SENDER_V4){
input[0][0]=false;
}
else{
input[1][0]=false;
}
}
if(getPanConfig(typ).getTf_groupIPaddress().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_groupIPaddress()
.setBorder(MiscBorder.getBorder(BorderTitle.IPv4GROUP, BorderType.NEUTRAL));
}
}
else if(typ==Typ.SENDER_V6 || typ == Typ.RECEIVER_V6){
if((InputValidator.checkMC_IPv6(getPanConfig(typ).getTf_groupIPaddress().getText())!= null)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_groupIPaddress().getText().equals("..."))){
getPanConfig(typ).getPan_groupIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv6GROUP, BorderType.TRUE));
if(typ==Typ.SENDER_V6){
input[2][0]=true;
}
else{
input[3][0]=true;
}
}
else{
getPanConfig(typ).getPan_groupIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv6GROUP, BorderType.FALSE));
if(typ==Typ.SENDER_V6){
input[2][0]=false;
}
else{
input[3][0]=false;
}
}
if(getPanConfig(typ).getTf_groupIPaddress().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_groupIPaddress()
.setBorder(MiscBorder.getBorder(BorderTitle.IPv6GROUP, BorderType.NEUTRAL));
}
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Input des Packet Length Felds ge�ndert wurde.
* @param typ Programmteil in welchem das Packet Length Feld ge�ndert wurde.
*/
private void docEventTFlength(Typ typ){
switch(typ){
case SENDER_V4:
if((InputValidator.checkIPv4PacketLength(getPanConfig(typ).getTf_udp_packetlength().getText())> 0)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_udp_packetlength().getText().equals("..."))){
getPanConfig(typ).getPan_packetlength()
.setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.TRUE));
input[0][5]=true;
}
else{
getPanConfig(typ).getPan_packetlength()
.setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.FALSE));
input[0][5]=false;
}
break;
case SENDER_V6:
if((InputValidator.checkIPv6PacketLength(getPanConfig(typ).getTf_udp_packetlength().getText())> 0)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_udp_packetlength().getText().equals("..."))){
getPanConfig(typ).getPan_packetlength()
.setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.TRUE));
input[2][5]=true;
}
else{
getPanConfig(typ).getPan_packetlength()
.setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.FALSE));
input[2][5]=false;
}
}
if(getPanConfig(typ).getTf_udp_packetlength().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_packetlength()
.setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.NEUTRAL));
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Input des Port Felds ge�ndert wurde.
* @param typ Programmteil in welchem das Port Feld ge�ndert wurde.
*/
private void docEventTFport(Typ typ){
if((InputValidator.checkPort(getPanConfig(typ).getTf_udp_port().getText()) > 0)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_udp_port().getText().equals("..."))){
getPanConfig(typ).getPan_udp_port().setBorder(MiscBorder.getBorder(BorderTitle.PORT, BorderType.TRUE));
if(typ==Typ.SENDER_V4){
input[0][2]=true;
}
else if(typ == Typ.RECEIVER_V4){
input[1][2]=true;
}
else if(typ == Typ.SENDER_V6){
input[2][2]=true;
}
else if(typ == Typ.RECEIVER_V6){
input[3][2]=true;
}
}
else{
getPanConfig(typ).getPan_udp_port().setBorder(MiscBorder.getBorder(BorderTitle.PORT, BorderType.FALSE));
if(typ==Typ.SENDER_V4){
input[0][2]=false;
}
else if(typ == Typ.RECEIVER_V4){
input[1][2]=false;
}
else if(typ == Typ.SENDER_V6){
input[2][2]=false;
}
else if(typ == Typ.RECEIVER_V6){
input[3][2]=false;
}
}
if(getPanConfig(typ).getTf_udp_port().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_udp_port()
.setBorder(MiscBorder.getBorder(BorderTitle.PORT, BorderType.NEUTRAL));
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Input des Packet Rate Felds ge�ndert wurde.
* @param typ Programmteil in welchem das Packet Rate Feld ge�ndert wurde.
*/
private void docEventTFrate(Typ typ){
if((InputValidator.checkPacketRate(getPanConfig(typ).getTf_packetrate().getText())> 0)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_packetrate().getText().equals("..."))){
getPanConfig(typ).getPan_packetrate()
.setBorder(MiscBorder.getBorder(BorderTitle.RATE, BorderType.TRUE));
if(typ == Typ.SENDER_V4){
input[0][4]=true;
}
else if(typ == Typ.SENDER_V6){
input[2][4]=true;
}
}
else{
getPanConfig(typ).getPan_packetrate()
.setBorder(MiscBorder.getBorder(BorderTitle.RATE, BorderType.FALSE));
if(typ == Typ.SENDER_V4){
input[0][4]=false;
}
else if(typ == Typ.SENDER_V6){
input[2][4]=false;
}
}
if(getPanConfig(typ).getTf_packetrate().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_packetrate()
.setBorder(MiscBorder.getBorder(BorderTitle.RATE, BorderType.NEUTRAL));
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Input des TTL Felds ge�ndert wurde.
* @param typ Programmteil in welchem das TTL Feld ge�ndert wurde.
*/
private void docEventTFttl(Typ typ){
if((InputValidator.checkTimeToLive(getPanConfig(typ).getTf_ttl().getText())> 0)
|| (getSelectedRows(typ).length > 1 && getPanConfig(typ).getTf_ttl().getText().equals("..."))){
getPanConfig(typ).getPan_ttl()
.setBorder(MiscBorder.getBorder(BorderTitle.TTL, BorderType.TRUE));
if(typ == Typ.SENDER_V4){
input[0][3]=true;
}
else if(typ == Typ.SENDER_V6){
input[2][3]=true;
}
}
else{
getPanConfig(typ).getPan_ttl()
.setBorder(MiscBorder.getBorder(BorderTitle.TTL, BorderType.FALSE));
if(typ == Typ.SENDER_V4){
input[0][3]=false;
}
else if(typ == Typ.SENDER_V6){
input[2][3]=false;
}
}
if(getPanConfig(typ).getTf_ttl().getText().equalsIgnoreCase("")){
getPanConfig(typ).getPan_ttl()
.setBorder(MiscBorder.getBorder(BorderTitle.TTL, BorderType.NEUTRAL));
}
checkInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn die Fenstergr��e ge�ndert wurde.
* Passt die Komponenten der GUI auf die neue Gr��e an.
*/
private void frameResizeEvent() {
if(getSelectedTab() != Typ.UNDEFINED){
if(getFrame().getSize().width > 1000){
getTable(getSelectedTab()).setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
}
else{
getTable(getSelectedTab()).setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
if(getSelectedTab() == Typ.SENDER_V4 || getSelectedTab() == Typ.SENDER_V6){
if(getPanTabbed(getSelectedTab()).getPan_graph().isVisible() && getPanTabbed(getSelectedTab()).getTab_console().isVisible()){
getPanTabbed(getSelectedTab()).getPan_graph().resize(new Dimension(getFrame().getSize().width-262,100));
}
}
else if(getSelectedTab() == Typ.RECEIVER_V4 || getSelectedTab() == Typ.RECEIVER_V6){
if(getPanTabbed(getSelectedTab()).getPan_graph().isVisible() && getPanTabbed(getSelectedTab()).getTab_console().isVisible()){
getPanTabbed(getSelectedTab()).getPan_recGraph().resize(new Dimension(getFrame().getSize().width-262,100));
}
}
}
/**
* Hilfsfunktion welche das Frame zur�ckgibt in welchem das MultiCastor Tool gezeichnet wird.
* @return FrameMain Objekt welches angefordert wurde.
*/
public FrameMain getFrame() {
return f;
}
/**
* Hilfsfunktion welche die aktuelle Anzahl an Multicasts vom MulticastController anfordert.
* @param typ Programmteil in welchem die Multicasts gez�hlt werden sollen.
* @return Z�hler der angibt wievielel Multicasts sich in einem Programmteil befinden.
*/
public int getMCCount(Typ typ){
return mc.getMCs(typ).size();
}
/**
* Hilfsfunktion welche Multicast Daten vom MulticastController anfordert.
* @param i Index des angeforderten Multicasts (Index in der Tabelle).
* @param typ Programmteil in zu welchem der Multicast geh�rt.
* @return MulticastData Objekt welches vom MulticastController zur�ckgegeben wird.
*/
public MulticastData getMCData(int i, MulticastData.Typ typ){
return mc.getMC(i, typ);
}
/**
* Hilfsfunktion welche das Configuration Panel eines bestimmten Programmteils zur�ckgibt.
* @param typ Programmteil in welchem sich das Configuration Panel befindet.
* @return PnaleMulticastConfig, welches angefordert wurde.
*/
private PanelMulticastConfig getPanConfig(Typ typ){
PanelMulticastConfig configpart = null;
switch(typ){
case SENDER_V4: configpart=f.getPanel_sen_ipv4().getPan_config(); break;
case RECEIVER_V4: configpart=f.getPanel_rec_ipv4().getPan_config(); break;
case SENDER_V6: configpart=f.getPanel_sen_ipv6().getPan_config(); break;
case RECEIVER_V6: configpart=f.getPanel_rec_ipv6().getPan_config(); break;
}
return configpart;
}
/**
* Hilfsfunktion welche das Control Panel eines bestimmten Programmteils zur�ckgibt.
* @param typ Programmteil in welchem sich das Control Panel befindet.
* @return PanelMulticastControl, welches angefordert wurde.
*/
private PanelMulticastControl getPanControl(Typ typ){
PanelMulticastControl controlpart = null;
switch(typ){
case SENDER_V4: controlpart=f.getPanel_sen_ipv4().getPan_control(); break;
case RECEIVER_V4: controlpart=f.getPanel_rec_ipv4().getPan_control(); break;
case SENDER_V6: controlpart=f.getPanel_sen_ipv6().getPan_control(); break;
case RECEIVER_V6: controlpart=f.getPanel_rec_ipv6().getPan_control(); break;
}
return controlpart;
}
/**
* Hilfsfunktion welche die Statusbar des jeweiligen Programmteils zur�ck gibt.
* @param typ Programmteil in welchem sich die Statusbar befindet.
* @return PanelStatusbar welche angefordert wurde.
*/
private PanelStatusBar getPanStatus(Typ typ){
PanelStatusBar statusbarpart = null;
switch(typ){
case SENDER_V4: statusbarpart=f.getPanel_sen_ipv4().getPan_status(); break;
case RECEIVER_V4: statusbarpart=f.getPanel_rec_ipv4().getPan_status(); break;
case SENDER_V6: statusbarpart=f.getPanel_sen_ipv6().getPan_status(); break;
case RECEIVER_V6: statusbarpart=f.getPanel_rec_ipv6().getPan_status(); break;
}
return statusbarpart;
}
/**
* Hilfsfunktion welche einen bestimten Programmteil zur�ck gibt.
* @param typ Programmteil welcher angeforder wird.
* @return JPanel mit dem angeforderten Programmteil.
*/
public PanelTabbed getPanTabbed(Typ typ){
PanelTabbed ret = null;
switch(typ){
case SENDER_V4: ret=f.getPanel_sen_ipv4(); break;
case RECEIVER_V4: ret=f.getPanel_rec_ipv4(); break;
case SENDER_V6: ret=f.getPanel_sen_ipv6(); break;
case RECEIVER_V6: ret=f.getPanel_rec_ipv6(); break;
}
return ret;
}
/**
* Hilfsfunktion welche ein Integer Array mit den Selektierten Zeilen einer Tabele zur�ckgibt.
* @param typ Programmteil in welchem sich die Tabelle befindet.
* @return Integer Array mit selektierten Zeilen. (leer wenn keine Zeile selektiert ist).
*/
public int[] getSelectedRows(Typ typ){
int[] ret=null;
ret = getTable(typ).getSelectedRows();
return ret;
}
/**
* Hilfsfunktion welche den Programmteil zur�ckgibt welcher im Moment per Tab selektiert ist.
* @return Programmteil welcher im Vordergrund ist.
*/
public Typ getSelectedTab() {
String title = f.getTabpane().getTitleAt(f.getTabpane().getSelectedIndex());
Typ typ;
if(title.equals(" Receiver IPv4 ")) typ = Typ.RECEIVER_V4;
else if(title.equals(" Sender IPv4 ")) typ = Typ.SENDER_V4;
else if(title.equals(" Receiver IPv6 ")) typ = Typ.RECEIVER_V6;
else if(title.equals(" Sender IPv6 ")) typ = Typ.SENDER_V6;
else typ = Typ.UNDEFINED;
return typ;
}
/**
* Hilfsfunktion welche die Richtung im SnakeProgramm zur�ckgibt.
* @return Richtung in welche die "Snake" laufen soll
*/
public SNAKE_DIRECTION getSnakeDir(){
return snakeDir;
}
/**
* Hilfsfunktion welche die Tabelle des jeweiligen Programmteil zur�ckgibt.
* @param typ Programmteil aus welchem die Tabelle angeforder wird.
* @return Die JTable welche angefordert wurde.
*/
public JTable getTable(Typ typ){
JTable tablepart = null;
switch(typ){
case SENDER_V4: tablepart=f.getPanel_sen_ipv4().getTable(); break;
case RECEIVER_V4: tablepart=f.getPanel_rec_ipv4().getTable(); break;
case SENDER_V6: tablepart=f.getPanel_sen_ipv6().getTable(); break;
case RECEIVER_V6: tablepart=f.getPanel_rec_ipv6().getTable(); break;
}
return tablepart;
}
/**
* Hilfsfunktion welches das Model der jeweiligen Tabelle zur�ckgibt.
* @param typ Programmteil von welchem das Tabellenmodel angeforder wird.
* @return das Tabellenmodel des spezifizierten Programmteils.
*/
public MiscTableModel getTableModel(Typ typ){
return ((MiscTableModel) getTable(typ).getModel());
}
/**
* Hilfsfunktion zum Berechnen des insgesamten Traffics welcher vom Multicast Tool empfangen wird (IPv4 & IPv6).
* @return Gibt den Insgesamten Traffic des IPv4SENDER und IPv6SENDER als String zur�ck (Mbit/s) im Format "##0.000"
*/
public String getTotalTrafficDown(){
DecimalFormat ret = new DecimalFormat("##0.000");
double sum = 0.0;
for(int i = 0; i < getTable(Typ.RECEIVER_V4).getModel().getRowCount(); i++){
sum = sum + Double.parseDouble(((String) getTable(Typ.RECEIVER_V4).getModel().getValueAt(i, 5)).replace(",", "."));
}
for(int i = 0; i < getTable(Typ.RECEIVER_V6).getModel().getRowCount(); i++){
sum = sum + Double.parseDouble(((String) getTable(Typ.RECEIVER_V6).getModel().getValueAt(i, 5)).replace(",", "."));
}
return ret.format(sum);
}
/**
* Hilfsfunktion zum Berechnen des insgesamten Traffics welcher vom Multicast Tool verschickt wird (IPv4 & IPv6).
*/
public String getTotalTrafficUP(){
DecimalFormat ret = new DecimalFormat("##0.000");
double sum = 0.0;
for(int i = 0; i < getTable(Typ.SENDER_V4).getModel().getRowCount(); i++){
sum = sum + Double.parseDouble(((String) getTable(Typ.SENDER_V4).getModel().getValueAt(i, 5)).replace(",", "."));
}
for(int i = 0; i < getTable(Typ.SENDER_V6).getModel().getRowCount(); i++){
sum = sum + Double.parseDouble(((String) getTable(Typ.SENDER_V6).getModel().getValueAt(i, 5)).replace(",", "."));
}
return ret.format(sum);
}
/**
* Funktion welche aufgerufen wird wenn Hide im PopupMenu des Tabellenkopfs gedr�ckt wurde
*/
private void hideColumnClicked() {
getUserInputData(getSelectedTab()).hideColumn(PopUpMenu.getSelectedColumn());
// PopUpMenu.updateCheckBoxes(this);
// removeColumnsFromTable(PopUpMenu.getSelectedColumn());
}
/**
* Funktion welche die GUI startet und initialisiert
* @param p_mc Referenz zum MultiCast Controller, die wichtigste Schnittstelle der GUI.
*/
public void initialize(MulticastController p_mc){
mc = p_mc;
inputData_S4 = new UserInputData();
inputData_S6 = new UserInputData();
inputData_R4 = new UserInputData();
inputData_R6 = new UserInputData();
//levelData = new UserlevelData();
f = new FrameMain(this);
addKeyAndContainerListenerToAll(f);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Hilfsfunktion zum Testen des Programm mits realen daten, durch diese Funktion k�nnen extrem gro�e
* Datenmengen simuliert werden.
*/
private void insertTestData(){
for(int i = 1 ; i < 6 ; i++){
getPanConfig(Typ.SENDER_V4).getTf_groupIPaddress().setText("224.0.0."+i);
getPanConfig(Typ.SENDER_V4).getCb_sourceIPaddress().setSelectedIndex(1);
getPanConfig(Typ.SENDER_V4).getTf_udp_port().setText("4000"+i);
getPanConfig(Typ.SENDER_V4).getTf_ttl().setText("32");
getPanConfig(Typ.SENDER_V4).getTf_packetrate().setText(""+10*i);
getPanConfig(Typ.SENDER_V4).getTf_udp_packetlength().setText("2048");
getPanConfig(Typ.SENDER_V4).getTb_active().setSelected(true);
pressBTAdd(Typ.SENDER_V4);
//Thread.sleep(100);
getPanConfig(Typ.RECEIVER_V4).getTf_groupIPaddress().setText("224.0.0."+i);
getPanConfig(Typ.RECEIVER_V4).getTf_udp_port().setText("4000"+i);
getPanConfig(Typ.RECEIVER_V4).getTb_active().setSelected(true);
pressBTAdd(Typ.RECEIVER_V4);
//Thread.sleep(100);
getPanConfig(Typ.SENDER_V6).getTf_groupIPaddress().setText("ff00::"+i);
getPanConfig(Typ.SENDER_V6).getCb_sourceIPaddress().setSelectedIndex(1);
getPanConfig(Typ.SENDER_V6).getTf_udp_port().setText("4000"+i);
getPanConfig(Typ.SENDER_V6).getTf_ttl().setText("32");
getPanConfig(Typ.SENDER_V6).getTf_packetrate().setText(""+10*i);
getPanConfig(Typ.SENDER_V6).getTf_udp_packetlength().setText("1024");
getPanConfig(Typ.SENDER_V6).getTb_active().setSelected(true);
pressBTAdd(Typ.SENDER_V6);
//Thread.sleep(100);
getPanConfig(Typ.RECEIVER_V6).getTf_groupIPaddress().setText("ff00::"+i);
getPanConfig(Typ.RECEIVER_V6).getTf_udp_port().setText("4000"+i);
getPanConfig(Typ.RECEIVER_V6).getTb_active().setSelected(true);
pressBTAdd(Typ.RECEIVER_V6);
//Thread.sleep(100);
}
}
@Override
/**
* Funktion welche aufgerufen wird wenn Inhalt in ein Feld des Configuration Panel eingetrgen wird.
*/
public void insertUpdate(DocumentEvent source) {
//KEY Event in IPv4 Sender - GroupAddress
if(source.getDocument() == getPanConfig(Typ.SENDER_V4).getTf_groupIPaddress().getDocument()){
docEventTFgrp(Typ.SENDER_V4);
}
//KEY Event in IPv4 Receiver - GroupAddress
else if(source.getDocument() == getPanConfig(Typ.RECEIVER_V4).getTf_groupIPaddress().getDocument()){
docEventTFgrp(Typ.RECEIVER_V4);
}
//KEY Event in IPv6 Sender - GroupAddress
else if(source.getDocument() == getPanConfig(Typ.SENDER_V6).getTf_groupIPaddress().getDocument()){
docEventTFgrp(Typ.SENDER_V6);
}
//KEY Event in IPv6 Receiver - GroupAddress
else if(source.getDocument() == getPanConfig(Typ.RECEIVER_V6).getTf_groupIPaddress().getDocument()){
docEventTFgrp(Typ.RECEIVER_V6);
}
//KEY Event in IPv4 Sender - UDP Port
else if(source.getDocument() == getPanConfig(Typ.SENDER_V4).getTf_udp_port().getDocument()){
docEventTFport(Typ.SENDER_V4);
}
//KEY Event in IPv4 Receiver - UDP Port
else if(source.getDocument() == getPanConfig(Typ.RECEIVER_V4).getTf_udp_port().getDocument()){
docEventTFport(Typ.RECEIVER_V4);
}
//KEY Event in IPv6 Sender - UDP Port
else if(source.getDocument() == getPanConfig(Typ.SENDER_V6).getTf_udp_port().getDocument()){
docEventTFport(Typ.SENDER_V6);
}
//KEY Event in IPv6 Receiver - UDP Port
else if(source.getDocument() == getPanConfig(Typ.RECEIVER_V6).getTf_udp_port().getDocument()){
docEventTFport(Typ.RECEIVER_V6);
}
//KEY Event in IPv4 Sender - TTL
else if(source.getDocument() == getPanConfig(Typ.SENDER_V4).getTf_ttl().getDocument()){
docEventTFttl(Typ.SENDER_V4);
}
//KEY Event in IPv6 Sender - TTL
else if(source.getDocument() == getPanConfig(Typ.SENDER_V6).getTf_ttl().getDocument()){
docEventTFttl(Typ.SENDER_V6);
}
//KEY Event in IPv4 Sender - PacketRate
else if(source.getDocument() == getPanConfig(Typ.SENDER_V4).getTf_packetrate().getDocument()){
docEventTFrate(Typ.SENDER_V4);
}
//KEY Event in IPv6 Sender - PacketRate
else if(source.getDocument() == getPanConfig(Typ.SENDER_V6).getTf_packetrate().getDocument()){
docEventTFrate(Typ.SENDER_V6);
}
//KEY Event in IPv4 Sender - PacketLength
else if(source.getDocument() == getPanConfig(Typ.SENDER_V4).getTf_udp_packetlength().getDocument()){
docEventTFlength(Typ.SENDER_V4);
}
//KEY Event in IPv6 Sender - PacketLength
else if(source.getDocument() == getPanConfig(Typ.SENDER_V6).getTf_udp_packetlength().getDocument()){
docEventTFlength(Typ.SENDER_V6);
}
autoSave();
}
@Override
/**
* Funktion welche aufgerufen wird wenn eine GUI Komponente mit dem ItemListener selektiert oder deselektiert wird.
* Dieser Listener wird f�r RadioButtons und Checkboxen verwendet.
*/
public void itemStateChanged(ItemEvent arg0) {
if(arg0.getStateChange() == arg0.SELECTED){
if(arg0.getSource() == getPanConfig(Typ.SENDER_V4).getTf_sourceIPaddress()){
changeNetworkInterface(Typ.SENDER_V4);
}
else if(arg0.getSource() == getPanConfig(Typ.RECEIVER_V4).getTf_sourceIPaddress()){
changeNetworkInterface(Typ.RECEIVER_V4);
}
else if(arg0.getSource() == getPanConfig(Typ.SENDER_V6).getTf_sourceIPaddress()){
changeNetworkInterface(Typ.SENDER_V6);
}
else if(arg0.getSource() == getPanConfig(Typ.RECEIVER_V6).getTf_sourceIPaddress()){
changeNetworkInterface(Typ.RECEIVER_V6);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().getLostPktsRB()){
//System.out.println("RECEIVER_V4 - LostPacketsRB");
getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().selectionChanged(valueType.LOSTPKT);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().getJitterRB()){
//System.out.println("RECEIVER_V4 - JitterRB");
getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().selectionChanged(valueType.JITTER);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().getMeasPktRtRB()){
//System.out.println("RECEIVER_V4 - MeasPktRtRB");
getPanTabbed(Typ.RECEIVER_V4).getPan_recGraph().selectionChanged(valueType.MEASPKT);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().getLostPktsRB()){
//System.out.println("RECEIVER_V6 - LostPacketsRB");
getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().selectionChanged(valueType.LOSTPKT);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().getJitterRB()){
//System.out.println("RECEIVER_V6 - JitterRB");
getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().selectionChanged(valueType.JITTER);
}
else if(arg0.getSource() == getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().getMeasPktRtRB()){
//System.out.println("RECEIVER_V6 - MeasPktRtRB");
getPanTabbed(Typ.RECEIVER_V6).getPan_recGraph().selectionChanged(valueType.MEASPKT);
}
else if(arg0.getSource() == f.getRb_beginner()){
changeUserLevel(Userlevel.BEGINNER);
//System.out.println("userlevel beginner");
}
else if(arg0.getSource() == f.getRb_expert()){
changeUserLevel(Userlevel.EXPERT);
//System.out.println("userlevel expert");
}
else if(arg0.getSource() == f.getRb_custom()){
changeUserLevel(Userlevel.CUSTOM);
//System.out.println("userlevel custom");
}
}
else{
if(arg0.getSource() == f.getMi_autoSave()){
if(arg0.getStateChange() == ItemEvent.DESELECTED)
submitInputData();
}
}
if(arg0.getSource() == f.getMi_autoSave()){
f.setAutoSave(f.isAutoSaveEnabled());
}
autoSave();
}
/**
* Funktion welche aufgerufen wird wenn der User �ber das Menu UserLevel das Benutzerlevel einstellt.
* @param level Nutzerlevel welches eingestellt wurde in der Menubar.
*/
private void selectUserLevel(Userlevel level){
switch(level){
case BEGINNER: f.getRb_beginner().setSelected(true); break;
case EXPERT: f.getRb_expert().setSelected(true);; break;
case CUSTOM: f.getRb_custom().setSelected(true);; break;
default: f.getRb_expert().setSelected(true);; break;
}
}
private void changeUserLevel(Userlevel level) {
//load userlevel data
UserlevelData levelDataSv4 = mc.getUserLevel(Typ.SENDER_V4, level);
UserlevelData levelDataSv6 = mc.getUserLevel(Typ.SENDER_V6, level);
UserlevelData levelDataRv4 = mc.getUserLevel(Typ.RECEIVER_V4, level);
UserlevelData levelDataRv6 = mc.getUserLevel(Typ.RECEIVER_V6, level);
if(levelDataSv4 != null && levelDataSv6 !=null && levelDataRv4 != null && levelDataRv6!=null){
//configure visibility settings for panels
getPanTabbed(Typ.SENDER_V4).setPanels( levelDataSv4.isConfigPanel(),
levelDataSv4.isControlPanel(),
levelDataSv4.isStatusBar(),
levelDataSv4.isConsole(),
levelDataSv4.isGraph());
getPanTabbed(Typ.SENDER_V6).setPanels( levelDataSv6.isConfigPanel(),
levelDataSv6.isControlPanel(),
levelDataSv6.isStatusBar(),
levelDataSv6.isConsole(),
levelDataSv6.isGraph());
getPanTabbed(Typ.RECEIVER_V4).setPanels(levelDataRv4.isConfigPanel(),
levelDataRv4.isControlPanel(),
levelDataRv4.isStatusBar(),
levelDataRv4.isConsole(),
levelDataRv4.isGraph());
getPanTabbed(Typ.RECEIVER_V4).setPanels(levelDataRv6.isConfigPanel(),
levelDataRv6.isControlPanel(),
levelDataRv6.isStatusBar(),
levelDataRv6.isConsole(),
levelDataRv6.isGraph());
//configure visibility settings for control panel
//configure visibility settings for start button
getPanControl(Typ.SENDER_V4).getStart().setVisible(levelDataSv4.isStartButton());
getPanControl(Typ.SENDER_V6).getStart().setVisible(levelDataSv6.isStartButton());
getPanControl(Typ.RECEIVER_V4).getStart().setVisible(levelDataRv4.isStartButton());
getPanControl(Typ.RECEIVER_V6).getStart().setVisible(levelDataRv6.isStartButton());
//configure visibility settings for stop button
getPanControl(Typ.SENDER_V4).getStop().setVisible(levelDataSv4.isStopButton());
getPanControl(Typ.SENDER_V6).getStop().setVisible(levelDataSv6.isStopButton());
getPanControl(Typ.RECEIVER_V4).getStop().setVisible(levelDataRv4.isStopButton());
getPanControl(Typ.RECEIVER_V6).getStop().setVisible(levelDataRv6.isStopButton());
//configure visibility settings for select all button
getPanControl(Typ.SENDER_V4).getSelect_all().setVisible(levelDataSv4.isSelectAllButton());
getPanControl(Typ.SENDER_V6).getSelect_all().setVisible(levelDataSv6.isSelectAllButton());
getPanControl(Typ.RECEIVER_V4).getSelect_all().setVisible(levelDataRv4.isSelectAllButton());
getPanControl(Typ.RECEIVER_V6).getSelect_all().setVisible(levelDataRv6.isSelectAllButton());
//configure visibility settings for deselect all button
getPanControl(Typ.SENDER_V4).getDeselect_all().setVisible(levelDataSv4.isDeselectAllButton());
getPanControl(Typ.SENDER_V6).getDeselect_all().setVisible(levelDataSv6.isDeselectAllButton());
getPanControl(Typ.RECEIVER_V4).getDeselect_all().setVisible(levelDataRv4.isDeselectAllButton());
getPanControl(Typ.RECEIVER_V6).getDeselect_all().setVisible(levelDataRv6.isDeselectAllButton());
//configure visibility settings for new multicast button
getPanControl(Typ.SENDER_V4).getNewmulticast().setVisible(levelDataSv4.isNewButton());
getPanControl(Typ.SENDER_V6).getNewmulticast().setVisible(levelDataSv6.isNewButton());
getPanControl(Typ.RECEIVER_V4).getNewmulticast().setVisible(levelDataRv4.isNewButton());
getPanControl(Typ.RECEIVER_V6).getNewmulticast().setVisible(levelDataRv6.isNewButton());
//configure visibility settings for delete button
getPanControl(Typ.SENDER_V4).getDelete().setVisible(levelDataSv4.isDeleteButton());
getPanControl(Typ.SENDER_V6).getDelete().setVisible(levelDataSv6.isDeleteButton());
getPanControl(Typ.RECEIVER_V4).getDelete().setVisible(levelDataRv4.isDeleteButton());
getPanControl(Typ.RECEIVER_V6).getDelete().setVisible(levelDataRv6.isDeleteButton());
//configure visibility settings for config panel
//configure visibility settings for group ip address field
getPanConfig(Typ.SENDER_V4).getPan_groupIPaddress().setVisible(levelDataSv4.isGroupIpField());
getPanConfig(Typ.SENDER_V6).getPan_groupIPaddress().setVisible(levelDataSv6.isGroupIpField());
getPanConfig(Typ.RECEIVER_V4).getPan_groupIPaddress().setVisible(levelDataRv4.isGroupIpField());
getPanConfig(Typ.RECEIVER_V6).getPan_groupIPaddress().setVisible(levelDataRv6.isGroupIpField());
//configure visibility settings for source ip address field
getPanConfig(Typ.SENDER_V4).getPan_sourceIPaddress().setVisible(levelDataSv4.isSourceIpField());
getPanConfig(Typ.SENDER_V6).getPan_sourceIPaddress().setVisible(levelDataSv6.isSourceIpField());
//configure visibility settings for port field
getPanConfig(Typ.SENDER_V4).getPan_udp_port().setVisible(levelDataSv4.isPortField());
getPanConfig(Typ.SENDER_V6).getPan_udp_port().setVisible(levelDataSv6.isPortField());
getPanConfig(Typ.RECEIVER_V4).getPan_udp_port().setVisible(levelDataRv4.isPortField());
getPanConfig(Typ.RECEIVER_V6).getPan_udp_port().setVisible(levelDataRv6.isPortField());
//configure visibility settings for TTL field
getPanConfig(Typ.SENDER_V4).getPan_ttl().setVisible(levelDataSv4.isTtlField());
getPanConfig(Typ.SENDER_V6).getPan_ttl().setVisible(levelDataSv6.isTtlField());
//configure visibility settings for packetlength field
getPanConfig(Typ.SENDER_V4).getPan_packetlength().setVisible(levelDataSv4.isPacketLengthField());
getPanConfig(Typ.SENDER_V6).getPan_packetlength().setVisible(levelDataSv6.isPacketLengthField());
//configure visibility settings for packetrate field
getPanConfig(Typ.SENDER_V4).getPan_packetrate().setVisible(levelDataSv4.isPacketRateField());
getPanConfig(Typ.SENDER_V6).getPan_packetrate().setVisible(levelDataSv6.isPacketRateField());
//configure visibility settings for active button
getPanConfig(Typ.SENDER_V4).getTb_active().setVisible(levelDataSv4.isActiveField());
getPanConfig(Typ.SENDER_V6).getTb_active().setVisible(levelDataSv6.isActiveField());
getPanConfig(Typ.RECEIVER_V4).getTb_active().setVisible(levelDataRv4.isActiveField());
getPanConfig(Typ.RECEIVER_V6).getTb_active().setVisible(levelDataRv6.isActiveField());
//configure visibility settings for enter button
getPanConfig(Typ.SENDER_V4).getBt_enter().setVisible(levelDataSv4.isEnterField());
getPanConfig(Typ.SENDER_V6).getBt_enter().setVisible(levelDataSv4.isEnterField());
getPanConfig(Typ.RECEIVER_V4).getBt_enter().setVisible(levelDataSv4.isEnterField());
getPanConfig(Typ.RECEIVER_V6).getBt_enter().setVisible(levelDataSv4.isEnterField());
//configure visibility settings for menu items
//configure visibility settings for load dialog
f.getMi_loadconfig().setVisible(levelDataSv4.isLoadConfigDialog());
f.getMi_loadconfig().setVisible(levelDataSv6.isLoadConfigDialog());
f.getMi_loadconfig().setVisible(levelDataRv4.isLoadConfigDialog());
f.getMi_loadconfig().setVisible(levelDataRv6.isLoadConfigDialog());
//configure visibility settings for save dialog
f.getMi_saveconfig().setVisible(levelDataSv4.isSaveConfigDialog());
f.getMi_saveconfig().setVisible(levelDataSv6.isSaveConfigDialog());
f.getMi_saveconfig().setVisible(levelDataRv4.isSaveConfigDialog());
f.getMi_saveconfig().setVisible(levelDataRv6.isSaveConfigDialog());
//configure visibility settings for userlevel dialog
f.getM_scale().setVisible(levelDataSv4.isUserLevelRadioGrp());
f.getM_scale().setVisible(levelDataSv6.isUserLevelRadioGrp());
f.getM_scale().setVisible(levelDataRv4.isUserLevelRadioGrp());
f.getM_scale().setVisible(levelDataRv6.isUserLevelRadioGrp());
//configure visibility settings for autosave dialog
f.getMi_autoSave().setVisible(levelDataSv4.isAutoSaveCheckbox());
f.getMi_autoSave().setVisible(levelDataSv6.isAutoSaveCheckbox());
f.getMi_autoSave().setVisible(levelDataRv4.isAutoSaveCheckbox());
f.getMi_autoSave().setVisible(levelDataRv6.isAutoSaveCheckbox());
//configure visibility settings for snake dialog
f.getMi_snake().setVisible(levelDataSv4.isSnakeGame());
f.getMi_snake().setVisible(levelDataSv6.isSnakeGame());
f.getMi_snake().setVisible(levelDataRv4.isSnakeGame());
f.getMi_snake().setVisible(levelDataRv6.isSnakeGame());
//configure access rights in multicast table
//configure state checkbox access in column 0 in jtable
getTableModel(Typ.SENDER_V4).setStateCheckboxEnabled(levelDataSv4.isStartStopCheckBox());
getTableModel(Typ.SENDER_V6).setStateCheckboxEnabled(levelDataSv6.isStartStopCheckBox());
getTableModel(Typ.RECEIVER_V4).setStateCheckboxEnabled(levelDataRv4.isStartStopCheckBox());
getTableModel(Typ.RECEIVER_V6).setStateCheckboxEnabled(levelDataRv6.isStartStopCheckBox());
//configure popup menu for jtable columns
getPanTabbed(Typ.SENDER_V4).setPopupsAllowed(levelDataSv4.isPopupsEnabled());
getPanTabbed(Typ.SENDER_V6).setPopupsAllowed(levelDataSv6.isPopupsEnabled());
getPanTabbed(Typ.RECEIVER_V4).setPopupsAllowed(levelDataRv4.isPopupsEnabled());
getPanTabbed(Typ.RECEIVER_V6).setPopupsAllowed(levelDataRv6.isPopupsEnabled());
f.setLevel(level);
}
else{
resetRBGroupTo(f.getLevel());
}
}
private void resetRBGroupTo(Userlevel level) {
//System.out.println("userlevel "+level);
switch(level){
case BEGINNER: f.getRb_beginner().setSelected(true); break;
case EXPERT: f.getRb_expert().setSelected(true); break;
case CUSTOM: f.getRb_custom().setSelected(true); break;
}
}
/**
* Funktion welche Aufgerufen wird wenn eine Taste der Tastatur gedr�ckt wird.
*/
public void keyPressed(KeyEvent arg0) {
switch(arg0.getKeyCode()){
case 38: snakeDir = SnakeGimmick.SNAKE_DIRECTION.N;
break;
case 40: snakeDir = SnakeGimmick.SNAKE_DIRECTION.S;
break;
case 37: snakeDir = SnakeGimmick.SNAKE_DIRECTION.W;
break;
case 39: snakeDir = SnakeGimmick.SNAKE_DIRECTION.E;
default:
}
}
@Override
/**
* Funktion welche Aufgerufen wird wenn eine Taste der Tastatur losgelassen wird.
*/
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
/**
* Funktion welche Aufgerufen wird sobald die Tastatur einen Input bei gedr�ckter Taste an das System weitergibt.
*/
public void keyTyped(KeyEvent arg0) {
}
/**
* Funktion welche ausgel�st wird wenn der User eine oder mehrere Zeilen in der Tabelle selektiert.
* @param typ Programmteil in welchem der User die Zeilen selektiert hat.
*/
private void listSelectionEventFired(Typ typ) {
PanelTabbed tabpart = null;
switch(typ){
case SENDER_V4: tabpart=f.getPanel_sen_ipv4(); break;
case RECEIVER_V4: tabpart=f.getPanel_rec_ipv4(); break;
case SENDER_V6: tabpart=f.getPanel_sen_ipv6(); break;
case RECEIVER_V6: tabpart=f.getPanel_rec_ipv6(); break;
}
int[] selectedRows = tabpart.getTable().getSelectedRows();
tabpart.getPan_status().getLb_multicasts_selected()
.setText(selectedRows.length+" Multicasts Selected ");
if(selectedRows.length > 1){
multipleSelect(typ);
}
if(selectedRows.length == 1){
tabpart.getPan_config().getBt_enter().setText("Change");
tabpart.getPan_config().getTf_groupIPaddress().setEnabled(true);
tabpart.getPan_config().getTf_udp_port().setEnabled(true);
tabpart.getPan_config().getTf_groupIPaddress().setText(getMCData(selectedRows[0],typ).getGroupIp().toString().substring(1));
//System.out.println("Index: "+NetworkAdapter.findAddressIndex(typ, getMCData(selectedRows[0],typ).getSourceIp().toString()));
//tabpart.getPan_config().getTf_sourceIPaddress().setText(getMCData(selectedRows[0],typ).getSourceIp().toString().substring(1));;
tabpart.getPan_config().getTf_udp_port().setText(""+getMCData(selectedRows[0],typ).getUdpPort());;;
if(typ==Typ.SENDER_V4 || typ == Typ.SENDER_V6){
getPanConfig(typ).getCb_sourceIPaddress().removeItemAt(0);
getPanConfig(typ).getCb_sourceIPaddress().insertItemAt("", 0);
tabpart.getPan_config().getTf_sourceIPaddress().setEnabled(true);
tabpart.getPan_config().getTf_sourceIPaddress().setSelectedIndex(NetworkAdapter.findAddressIndex(typ, getMCData(selectedRows[0],typ).getSourceIp().toString())+1);
tabpart.getPan_config().getTf_ttl().setText(""+getMCData(selectedRows[0],typ).getTtl());;
tabpart.getPan_config().getTf_packetrate().setText(""+getMCData(selectedRows[0],typ).getPacketRateDesired());;
tabpart.getPan_config().getTf_udp_packetlength().setText(""+getMCData(selectedRows[0],typ).getPacketLength());;
}
setTBactive(selectedRows, typ);
setBTStartStopDelete(typ);
}
else if(selectedRows.length == 0){
clearInput(typ);
tabpart.getPan_config().getBt_enter().setText("Add");
tabpart.getPan_config().getTf_groupIPaddress().setEnabled(true);
if(typ==Typ.SENDER_V4 || typ==Typ.SENDER_V6){
tabpart.getPan_config().getTf_sourceIPaddress().setEnabled(true);
}
tabpart.getPan_config().getTf_udp_port().setEnabled(true);
setTBactive(selectedRows, typ);
}
}
/**
* Funktion welche ausgel�st wird, wenn der User versucht eine Konfigurationsdatei mit dem "Datei Laden"
* Dialog zu laden.
*/
private void loadFileEvent(ActionEvent e) {
if(e.getActionCommand().equals("ApproveSelection")){
FrameFileChooser fc_load = getFrame().getFc_load();
loadConfig( fc_load.getSelectedFile(),
fc_load.isCbSenderV4Selected(),
fc_load.isCbSenderV6Selected(),
fc_load.isCbReceiverV4Selected(),
fc_load.isCbReceiverV4Selected(),
fc_load.isCbIncrementalSelected());
fc_load.getChooser().rescanCurrentDirectory();
fc_load.toggle();
}
else if(e.getActionCommand().equals("CancelSelection")){
getFrame().getFc_load().toggle();
}
}
private void loadConfig(String s, boolean sv4, boolean sv6, boolean rv4, boolean rv6, boolean incremental) {
if(incremental){
//System.out.println("incremental selected");
if(sv4){
deleteAllMulticasts(Typ.SENDER_V4);
}
if(sv6){
deleteAllMulticasts(Typ.SENDER_V6);
}
if(rv4){
deleteAllMulticasts(Typ.RECEIVER_V4);
}
if(rv6){
deleteAllMulticasts(Typ.RECEIVER_V6);
}
}
mc.loadConfigFile(s,sv4,sv6,rv4,rv6);
}
@Override
/**
* MouseEvent welches ausgel�st wird wenn eine Maustaste gedr�ckt und wieder losgelassen wird.
*/
public void mouseClicked(MouseEvent e) {
//is rightclick?
if(e.getButton() == MouseEvent.BUTTON3){
//Source of click is table header of selected tab?
if(getSelectedTab() != Typ.CONFIG && getSelectedTab() != Typ.UNDEFINED){
if(e.getSource()==getTable(getSelectedTab()).getTableHeader()){
if(getPanTabbed(getSelectedTab()).isPopupsAllowed()){
PopUpMenu.createTableHeaderPopup(getTable(getSelectedTab()), this, e);
}
}
}
}
autoSave();
}
@Override
/**
* MouseEvent welches auf das Betreten einer Komponente der Maus reagiert.
*/
public void mouseEntered(MouseEvent e) {
}
@Override
/**
* MouseEvent welches auf das Verlassen einer Komponente der Maus reagiert.
*/
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* MouseEvent welches auf Dr�cken einer Maustaste reagiert.
*/
public void mousePressed(MouseEvent e) {
}
@Override
/**
* MouseEvent welches auf Loslassen einer Maustaste reagiert.
*/
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
/**
* Funktion welche aufgerufen wird wenn mehr als ein Multicast in der Tabelle selektiert wurde.
* Passt die GUI entsprechend an.
* @param typ Programmteil in welchem mehrere Multicasts Selektiert wurden.
*/
private void multipleSelect(Typ typ) {
getPanConfig(typ).getBt_enter().setText("Change All");
if(typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6){
getPanConfig(typ).getTf_sourceIPaddress().removeItemListener(this);
getPanConfig(typ).getTf_packetrate().getDocument().removeDocumentListener(this);
getPanConfig(typ).getTf_udp_packetlength().getDocument().removeDocumentListener(this);
getPanConfig(typ).getTf_ttl().getDocument().removeDocumentListener(this);
getPanConfig(typ).getPan_sourceIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4SOURCE, BorderType.TRUE));
getPanConfig(typ).getPan_packetrate().setBorder(MiscBorder.getBorder(BorderTitle.RATE, BorderType.TRUE));
getPanConfig(typ).getPan_packetlength().setBorder(MiscBorder.getBorder(BorderTitle.LENGTH, BorderType.TRUE));
getPanConfig(typ).getPan_ttl().setBorder(MiscBorder.getBorder(BorderTitle.TTL, BorderType.TRUE));
getPanConfig(typ).getTf_sourceIPaddress().setSelectedIndex(0);
getPanConfig(typ).getTf_packetrate().setText("...");
getPanConfig(typ).getTf_udp_packetlength().setText("...");
getPanConfig(typ).getTf_ttl().setText("...");
getPanConfig(typ).getTf_sourceIPaddress().addItemListener(this);
getPanConfig(typ).getTf_packetrate().getDocument().addDocumentListener(this);
getPanConfig(typ).getTf_udp_packetlength().getDocument().addDocumentListener(this);
getPanConfig(typ).getTf_ttl().getDocument().addDocumentListener(this);
getPanConfig(typ).getCb_sourceIPaddress().removeItemAt(0);
getPanConfig(typ).getCb_sourceIPaddress().insertItemAt("...", 0);
getPanConfig(typ).getCb_sourceIPaddress().setSelectedIndex(0);
}
getPanConfig(typ).getTf_groupIPaddress().getDocument().removeDocumentListener(this);
getPanConfig(typ).getTf_udp_port().getDocument().removeDocumentListener(this);
getPanConfig(typ).getPan_groupIPaddress().setBorder(MiscBorder.getBorder(BorderTitle.IPv4GROUP, BorderType.TRUE));
getPanConfig(typ).getPan_udp_port().setBorder(MiscBorder.getBorder(BorderTitle.PORT, BorderType.TRUE));
getPanConfig(typ).getTf_groupIPaddress().setText("...");
getPanConfig(typ).getTf_udp_port().setText("...");
getPanConfig(typ).getTb_active().setText("multiple");
getPanConfig(typ).getTb_active().setForeground(Color.green);
getPanConfig(typ).getTb_active().setSelected(false);
getPanConfig(typ).getTf_groupIPaddress().getDocument().addDocumentListener(this);
getPanConfig(typ).getTf_udp_port().getDocument().addDocumentListener(this);
getPanConfig(typ).getBt_enter().setEnabled(true);
setBTStartStopDelete(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Add Button gedr�ckt wird.
* @param typ Programmteil in welchem der Add Button gedr�ckt wurde
*/
private void pressBTAdd(Typ typ) {
this.addMC(changeMCData(new MulticastData(), typ));
clearInput(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Change Button gedr�ckt wird. Bei selektierten Multicast(s).
* @param typ Programmteil in welchem der Change Button gedr�ckt wurde
*/
private void pressBTChange(Typ typ) {
int[] selectedList = getSelectedRows(typ);
if(selectedList.length == 1){
MulticastData mcd = getMCData(selectedList[0],typ);
changeMC(changeMCData(mcd, typ));
getTable(typ).getSelectionModel().setSelectionInterval(0, 0);
}
else{
PanelMulticastConfig config = getPanConfig(typ);
if((typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6)
&& (config.getTf_groupIPaddress().getText().equals("..."))
&& (config.getCb_sourceIPaddress().getSelectedIndex()==0)
&& (config.getTf_udp_port().getText().equals("..."))
&& (config.getTf_ttl().getText().equals("..."))
&& (config.getTf_packetrate().getText().equals("..."))
&& (config.getTf_udp_packetlength().getText().equals("..."))
&& (config.getTf_udp_port().getText().equals("..."))
&& (config.getTb_active().getText().equals("multiple"))){
showMessage(MessageTyp.INFO, "No changes were made.\n\"...\" keeps old values!");
}
else if((typ == Typ.RECEIVER_V4 || typ == Typ.RECEIVER_V6)
&& (config.getTf_groupIPaddress().getText().equals("..."))
&& (config.getTf_udp_port().getText().equals("..."))
&& (config.getTb_active().getText().equals("multiple"))){
showMessage(MessageTyp.INFO, "No changes were made.\n\"...\" keeps old values!");
}
else{
for(int i=selectedList.length-1; i >= 0 ; i--){
//System.out.println("selected: "+i+": "+selectedList[i]);
//System.out.println("getting: "+((selectedList.length-1)-i));
MulticastData mcd = getMCData(selectedList[i]+((selectedList.length-1)-i),typ);
changeMC(changeMCData(mcd, typ));
}
getTable(typ).getSelectionModel().setSelectionInterval(0, selectedList.length-1);
}
setBTStartStopDelete(getSelectedTab());
}
}
/**
* Funktion welche aufgerufen wird wenn der Delete Button gedr�ckt wird.
* @param typ Programmteil in welchem der Delete Button gedr�ckt wurde
*/
private void pressBTDelete(Typ typ) {
int[] selectedRows =getTable(typ).getSelectedRows();
for(int i=0 ; i<selectedRows.length ; i++){
//System.out.println("l�sche zeile: "+selectedRows[i]);
deleteMC(getMCData(selectedRows[i]-i, typ));
}
setBTStartStopDelete(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Deselect All Button gedr�ckt wird.
* @param typ Programmteil in welchem der Deselect All Button gedr�ckt wurde
*/
private void pressBTDeselectAll(Typ typ) {
getTable(typ).clearSelection();
setBTStartStopDelete(typ);
if(typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6){
getPanConfig(typ).getCb_sourceIPaddress().removeItemAt(0);
getPanConfig(typ).getCb_sourceIPaddress().insertItemAt("", 0);
getPanConfig(typ).getTf_sourceIPaddress().setSelectedIndex(0);
}
getPanStatus(typ).getLb_multicasts_selected().setText("0 Multicasts Selected ");
}
/**
* Funktion welche aufgerufen wird wenn der Add Button gedr�ckt wird.
* Diese Funktion unterscheided ob eine �nderung an einem Multicast stattfinden soll,
* oder ein Neuer angelegt werden soll.
* @param typ Programmteil in welchem der Add Button gedr�ckt wurde
*/
private void pressBTenter(Typ typ) {
if(getPanConfig(typ).getBt_enter().getText().equals("Add")){
pressBTAdd(typ);
}
else{
pressBTChange(typ);
}
}
/**
* Funktion welche aufgerufen wird wenn der New Button gedr�ckt wird.
* @param typ Programmteil in welchem der New Button gedr�ckt wurde
*/
private void pressBTNewMC(Typ typ) {
clearInput(typ);
getTable(typ).clearSelection();
setBTStartStopDelete(typ);
getPanStatus(typ).getLb_multicasts_selected().setText("0 Multicasts Selected ");
}
/**
* Funktion welche aufgerufen wird wenn der Select All Button gedr�ckt wird.
* @param typ Programmteil in welchem der Select All Button gedr�ckt wurde
*/
private void pressBTSelectAll(Typ typ) {
getTable(typ).selectAll();
if(getSelectedRows(typ).length > 1){
multipleSelect(typ);
}
}
/**
* Funktion welche aufgerufen wird wenn der Start Button gedr�ckt wird.
* @param typ Programmteil in welchem der Start Button gedr�ckt wurde
*/
private void pressBTStart(Typ typ){
int[] selectedLine = getSelectedRows(typ);
for(int i = 0 ; i < selectedLine.length ; i++){
if(!getMCData(selectedLine[i], typ).isActive()){
startMC(selectedLine[i], typ);
updateTable(typ, UpdateTyp.UPDATE);
}
}
setBTStartStopDelete(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Stop Button gedr�ckt wird.
* @param typ Programmteil in welchem der Stop Button gedr�ckt wurde
*/
private void pressBTStop(Typ typ){
int[] selectedLine = getSelectedRows(typ);
for(int i = 0 ; i < selectedLine.length ; i++){
if(getMCData(selectedLine[i], typ).isActive()){
stopMC(selectedLine[i], typ);
updateTable(typ, UpdateTyp.UPDATE);
}
}
setBTStartStopDelete(typ);
}
/**
* Funktion welche es dem Multicast Controller und somit den restlichen Programmteilen erm�glicht
* Ausgaben in der Konsole des GUI zu t�tigen.
* @param s Nachricht welche in der Konsole der GUI ausgegeben werden soll
*/
public void printConsole(String s){
getFrame().getPanelPart(Typ.SENDER_V4).getTa_console().append(s+"\n");
getFrame().getPanelPart(Typ.SENDER_V6).getTa_console().append(s+"\n");
getFrame().getPanelPart(Typ.RECEIVER_V4).getTa_console().append(s+"\n");
getFrame().getPanelPart(Typ.RECEIVER_V6).getTa_console().append(s+"\n");
getFrame().getPanelPart(Typ.SENDER_V6).getTa_console().setCaretPosition(getFrame().getPanelPart(Typ.SENDER_V6).getTa_console().getText().length());
getFrame().getPanelPart(Typ.RECEIVER_V4).getTa_console().setCaretPosition(getFrame().getPanelPart(Typ.RECEIVER_V4).getTa_console().getText().length());
getFrame().getPanelPart(Typ.RECEIVER_V6).getTa_console().setCaretPosition(getFrame().getPanelPart(Typ.RECEIVER_V6).getTa_console().getText().length());
}
/**
* Removed einen Container und einen Keylistener vom
* Component c. Hat die Komponente Kinder, mache das
* gleiche mit jedem Child
* @param c Container, von dem die Listener entfernt werden sollen
*/
private void removeKeyAndContainerListenerToAll(Component c)
{
c.removeKeyListener(this);
if(c instanceof Container) {
Container cont = (Container)c;
cont.removeContainerListener(this);
Component[] children = cont.getComponents();
for(int i = 0; i < children.length; i++){
removeKeyAndContainerListenerToAll(children[i]);
}
}
}
@Override
/**
* Funktion welche aufgerufen wird wenn ein Zeichen aus einem Textfeld gel�scht wird.
*/
public void removeUpdate(DocumentEvent e) {
insertUpdate(e);
}
/**
* Funktion welche aufgerufen wird wenn versucht wird eine Datei zu speichern im Datei speichern Dialog.
* @param e ActionEvent welches vom Datei speichern Dialog erzeugt wird
*/
private void saveFileEvent(ActionEvent e) {
if(e.getActionCommand().equals("ApproveSelection")){
FrameFileChooser fc_save = getFrame().getFc_save();
//System.out.println("selected File: "+fc_save.getSelectedFile());
mc.saveConfig( fc_save.getSelectedFile(),
fc_save.isCbSenderV4Selected(),
fc_save.isCbSenderV6Selected(),
fc_save.isCbReceiverV4Selected(),
fc_save.isCbReceiverV6Selected());
f.updateLastConfigs(fc_save.getSelectedFile());
fc_save.getChooser().rescanCurrentDirectory();
fc_save.toggle();
}
else if(e.getActionCommand().equals("CancelSelection")){
getFrame().getFc_save().toggle();
}
}
/**
* Funktion welche das Aussehen des Start Stop und Delete Buttons anpasst je nach dem welche Multicasts ausgew�hlt wurden.
* @param typ Programmteil in welchem die Buttons angepasst werden sollen.
*/
private void setBTStartStopDelete(Typ typ) {
int[] selectedLine=getSelectedRows(typ);
if(selectedLine.length == 1){
getPanControl(typ).getDelete().setEnabled(true);
if(getMCData(selectedLine[0],typ).isActive()){
getPanControl(typ).getStart().setEnabled(false);
getPanControl(typ).getStop().setEnabled(true);
}
else{
getPanControl(typ).getStart().setEnabled(true);
getPanControl(typ).getStop().setEnabled(false);
}
}
else if(selectedLine.length == 0){
getPanControl(typ).getStart().setEnabled(false);
getPanControl(typ).getStop().setEnabled(false);
getPanControl(typ).getDelete().setEnabled(false);
}
else{
getPanControl(typ).getDelete().setEnabled(true);
for(int i = 1 ; i < selectedLine.length ; i++){
if(getMCData(selectedLine[i-1], typ).isActive() && getMCData(selectedLine[i], typ).isActive()){
getPanControl(typ).getStart().setEnabled(false);
}
else{
getPanControl(typ).getStart().setEnabled(true);
break;
}
}
for(int i = 1 ; i < selectedLine.length ; i++){
if((!getMCData(selectedLine[i-1], typ).isActive()) && (!getMCData(selectedLine[i], typ).isActive())){
getPanControl(typ).getStop().setEnabled(false);
}
else{
getPanControl(typ).getStop().setEnabled(true);
break;
}
}
}
}
/**
* Funktion welche das aussehen des ActiveButtons anpasst (Togglefunktion)
* @param b Array welches die Selektierten Reihen in einem Programmteil angibt
* @param typ Programmteil in welchem sich der Active Button befindet
*/
private void setTBactive(boolean b, Typ typ) {
if(b){
getPanConfig(typ).getTb_active().setSelected(true);
getPanConfig(typ).getTb_active().setText("active");
getPanConfig(typ).getTb_active().setForeground(new Color(0,175,0));
}
else{
getPanConfig(typ).getTb_active().setSelected(false);
getPanConfig(typ).getTb_active().setText("inactive");
getPanConfig(typ).getTb_active().setForeground(new Color(200,0,0));
}
}
/**
* Funktion welche das aussehen des ActiveButtons anpasst je nach dem welcher Multicast selektiert ist in der Tabelle
* @param selectedLine Array welches die Selektierten Reihen in einem Programmteil angibt
* @param typ Programmteil in welchem sich der Active Button befindet
*/
public void setTBactive(int[] selectedLine, Typ typ){
getPanConfig(typ).getTb_active().setEnabled(true);
if(selectedLine.length==1){
if(mc.getMC(selectedLine[0], typ).isActive()){
getPanConfig(typ).getTb_active().setSelected(true);
getPanConfig(typ).getTb_active().setText("active");
getPanConfig(typ).getTb_active().setForeground(new Color(0,175,0));
}
else{
getPanConfig(typ).getTb_active().setSelected(false);
getPanConfig(typ).getTb_active().setText("inactive");
getPanConfig(typ).getTb_active().setForeground(new Color(200,0,0));
}
}
}
/**
* Funktion welche erm�glich Nachrichten in der GUI anzuzeigen. Gibt anderen Programmteilen �ber den
* MulticastController die M�glichkeit Informations, Warnungs und Errormeldungen auf dem GUI auszugeben.
* @param typ Art der Nachricht (INFO / WARNING / ERROR)
* @param message Die eigentliche Nachricht welche angezeigt werden soll
*/
public void showMessage(MessageTyp typ, String message){ //type 0 == info, type 1 == warning, type 2 == error
switch(typ){
case INFO: JOptionPane.showMessageDialog(null, message, "Information", JOptionPane.INFORMATION_MESSAGE); break;
case WARNING: JOptionPane.showMessageDialog(null, message, "Warning", JOptionPane.WARNING_MESSAGE); break;
case ERROR: JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); break;
}
}
/**
* Bildet die Schnittstelle zum Multicast Controller zum starten von einem Bestimmten Multicast.
* Sorgt f�r die ensprechenden Updates in der GUI nach dem Versuch den Multicast zu stoppen.
* @param row Zeilenindex des Multicast welcher gestartet werden soll
* @param typ Programmteil in welchem sich der Multicast befindet welcher gestartet werden soll
*/
public void startMC(int row, Typ typ){
mc.startMC(mc.getMC(row, typ));
setBTStartStopDelete(typ);
}
@Override
/**
* Funktion welche aufgerufen wird wenn das Frame in der Gr��e ge�ndert oder verschoben wird.
*/
public void stateChanged(ChangeEvent arg0) {
if(arg0.getSource() == getFrame().getTabpane()){
frameResizeEvent();
}
}
/**
* Bildet die Schnittstelle zum Multicast Controller zum stoppen von einem Bestimmten Multicast.
* Sorgt f�r die ensprechenden Updates in der GUI nach dem Versuch den Multicast zu stoppen.
* @param row Zeilenindex des Multicast welcher gestoppt werden soll
* @param typ Programmteil in welchem sich der Multicast befindet welcher gestoppt werden soll
*/
public void stopMC(int row, Typ typ){
mc.stopMC(mc.getMC(row, typ));
setBTStartStopDelete(typ);
}
/**
* Funktion welche aufgerufen wird wenn der Active Button im ControlPanel gedr�ckt wird.
* @param typ Bestimmt den Programmteil in welchem der Active Button gedr�ckt wurde
*/
private void toggleBTactive(Typ typ) {
if(getPanConfig(typ).getTb_active().isSelected()){
setTBactive(true, typ);
}
else{
setTBactive(false, typ);
}
}
/**
* Funktion welche sich um das Update des Graphen k�mmert.
* @param typ bestimmt welcher Graph in welchem Programmteil geupdatet werden soll
*/
private void updateGraph(Typ typ) {
//boolean variable which determines if graph can be painted or not, is graph in front of SRC address dropdown
boolean showupdate=false;
//check if graph is selected
if(getPanTabbed(typ).getTab_console().getSelectedIndex()==0){
if(getPanTabbed(typ).getPan_graph().isVisible() && getPanTabbed(typ).getTab_console().isVisible()){
//System.out.println("panel graph visible");
if(typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6){
showupdate = !getPanConfig(typ).getCb_sourceIPaddress().isPopupVisible() &&
!PopUpMenu.isPopUpVisible();
}
else{
showupdate = !PopUpMenu.isPopUpVisible();
}
}
else{
showupdate=false;
}
}
//check which tab is selected and update graph for specific program part
if(typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6){
//System.out.println("showupdate "+showupdate);
getPanTabbed(typ).getPan_graph().updateGraph(mc.getPPSSender(typ), showupdate);
}
else{
graphData = new MulticastData[getSelectedRows(typ).length];
for(int i = 0; i < getSelectedRows(typ).length ; i++){
graphData[i]=mc.getMC(getSelectedRows(typ)[i], typ);
}
getPanTabbed(typ).getPan_recGraph().updateGraph(graphData, showupdate);
}
}
/**
* Funktion welche unterscheidet welche Art von Update in der Multicast Tabelle erfolgt ist.
* Hierbei kann zwischen Einf�gen, L�schen und Updaten einer Zeile unterschieden werden.
* @param typ Bestimmt den Programmteil welcher geupdated wird
* @param utyp Bestimmt die Art des Updates welches Erfolgt ist
*/
public void updateTable(Typ typ, UpdateTyp utyp){ //i=0 -> insert, i=1 -> delete, i=2 -> change
PanelTabbed tabpart = getPanTabbed(typ);
switch(utyp){
case INSERT: tabpart.getTableModel().insertUpdate();
tabpart.getPan_status().getLb_multicast_count().setText(getMCCount(typ)+" Multicasts Total");
if(initFinished){
clearInput(typ);
}
break;
case DELETE: tabpart.getTableModel().deleteUpdate();
tabpart.getPan_status().getLb_multicast_count().setText(getMCCount(typ)+" Multicasts Total");
if(initFinished){
clearInput(typ);
}
break;
case UPDATE: tabpart.getTableModel().changeUpdate();
break;
}
}
/**
* Funktion die einen bestimmten Programmteil updatet.
* @param typ Programmteil der geupdatet werden soll
*/
public void updateTablePart(Typ typ){
if(typ != Typ.UNDEFINED){
updateTable(typ, UpdateTyp.UPDATE);
}
}
@Override
/**
* Implementierung des ListSelectionListeners, sorgt f�r korrektes Verhalten der GUI
* beim Selektieren und Deselektieren von einer oder mehreren Zeilen in der Tabelle.
*/
public void valueChanged(ListSelectionEvent e) {
if(e.getSource()==getTable(Typ.SENDER_V4).getSelectionModel()){
listSelectionEventFired(Typ.SENDER_V4);
}
if(e.getSource()==getTable(Typ.RECEIVER_V4).getSelectionModel()){
listSelectionEventFired(Typ.RECEIVER_V4);
}
if(e.getSource()==getTable(Typ.SENDER_V6).getSelectionModel()){
listSelectionEventFired(Typ.SENDER_V6);
}
if(e.getSource()==getTable(Typ.RECEIVER_V6).getSelectionModel()){
listSelectionEventFired(Typ.RECEIVER_V6);
}
autoSave();
}
/**
* Diese Funktion bildet die eigentliche Schnittstelle zum MulticastController und erm�glicht
* die GUI zu einem bestimmen Zeitpunkt zu updaten.
*/
public void viewUpdate(){
Typ typ = getSelectedTab();
if(typ!=Typ.UNDEFINED){
updateTablePart(typ);
updateGraph(typ);
getPanStatus(typ).updateTraffic(this);
}
}
/**
* Diese Funktion liest die akutellen Benutzereingaben in der GUI aus und speichert sie
* in den 4 UserInputData Objekten und gibt sie weiter zum speichern in der permanenten
* Konfigurationsdatei.
*/
public void submitInputData(){
inputData_S4.setSelectedTab(getSelectedTab());
inputData_S6.setSelectedTab(getSelectedTab());
inputData_R4.setSelectedTab(getSelectedTab());
inputData_R6.setSelectedTab(getSelectedTab());
inputData_S4.setSelectedRowsArray(getSelectedRows(Typ.SENDER_V4));
inputData_S6.setSelectedRowsArray(getSelectedRows(Typ.SENDER_V6));
inputData_R4.setSelectedRowsArray(getSelectedRows(Typ.RECEIVER_V4));
inputData_R6.setSelectedRowsArray(getSelectedRows(Typ.RECEIVER_V6));
inputData_S4.setNetworkInterface(getPanConfig(Typ.SENDER_V4).getSelectedSourceIndex());
inputData_S6.setNetworkInterface(getPanConfig(Typ.SENDER_V6).getSelectedSourceIndex());
inputData_S4.setSelectedUserlevel(f.getSelectedUserlevel());
inputData_S6.setSelectedUserlevel(f.getSelectedUserlevel());
inputData_R4.setSelectedUserlevel(f.getSelectedUserlevel());
inputData_R6.setSelectedUserlevel(f.getSelectedUserlevel());
inputData_S4.setGroupadress(getPanConfig(Typ.SENDER_V4).getTf_groupIPaddress().getText());
inputData_S6.setGroupadress(getPanConfig(Typ.SENDER_V6).getTf_groupIPaddress().getText());
inputData_R4.setGroupadress(getPanConfig(Typ.RECEIVER_V4).getTf_groupIPaddress().getText());
inputData_R6.setGroupadress(getPanConfig(Typ.RECEIVER_V6).getTf_groupIPaddress().getText());
inputData_S4.setPort(getPanConfig(Typ.SENDER_V4).getTf_udp_port().getText());
inputData_S6.setPort(getPanConfig(Typ.SENDER_V6).getTf_udp_port().getText());
inputData_R4.setPort(getPanConfig(Typ.RECEIVER_V4).getTf_udp_port().getText());
inputData_R6.setPort(getPanConfig(Typ.RECEIVER_V6).getTf_udp_port().getText());
inputData_S4.setTtl(getPanConfig(Typ.SENDER_V4).getTf_ttl().getText());
inputData_S6.setTtl(getPanConfig(Typ.SENDER_V6).getTf_ttl().getText());
inputData_S4.setPacketrate(getPanConfig(Typ.SENDER_V4).getTf_packetrate().getText());
inputData_S6.setPacketrate(getPanConfig(Typ.SENDER_V6).getTf_packetrate().getText());
inputData_S4.setPacketlength(getPanConfig(Typ.SENDER_V4).getTf_udp_packetlength().getText());
inputData_S6.setPacketlength(getPanConfig(Typ.SENDER_V6).getTf_udp_packetlength().getText());
inputData_S4.setActiveButton(getPanConfig(Typ.SENDER_V4).getTb_active().isSelected());
inputData_S6.setActiveButton(getPanConfig(Typ.SENDER_V6).getTb_active().isSelected());
inputData_R4.setActiveButton(getPanConfig(Typ.RECEIVER_V4).getTb_active().isSelected());
inputData_R6.setActiveButton(getPanConfig(Typ.RECEIVER_V6).getTb_active().isSelected());
inputData_S4.setSelectedRows(getSelectedRows(Typ.SENDER_V4));
inputData_S6.setSelectedRows(getSelectedRows(Typ.SENDER_V6));
inputData_R4.setSelectedRows(getSelectedRows(Typ.RECEIVER_V4));
inputData_R6.setSelectedRows(getSelectedRows(Typ.RECEIVER_V6));
inputData_S4.setIsAutoSaveEnabled(""+f.getMi_autoSave().isSelected());
inputData_S6.setIsAutoSaveEnabled(""+f.getMi_autoSave().isSelected());
inputData_R4.setIsAutoSaveEnabled(""+f.getMi_autoSave().isSelected());
inputData_R6.setIsAutoSaveEnabled(""+f.getMi_autoSave().isSelected());
Vector<UserInputData> packet = new Vector<UserInputData>();
packet.add(inputData_R4);
packet.add(inputData_S4);
packet.add(inputData_R6);
packet.add(inputData_S6);
mc.autoSave(packet);
}
/**
* Hilfsfunktion zur Bestimmung des UserInputData Objekts anhand des Typs.
* @param typ Programmteil f�r welchen das UserInputData Objekt angefordert wird
* @return Gibt das UserInputData Objekt des entsprechenden Typs zur�ck
*/
public UserInputData getUserInputData(Typ typ){
UserInputData ret = null;
switch(typ){
case SENDER_V4: ret = inputData_S4; break;
case SENDER_V6: ret = inputData_S6; break;
case RECEIVER_V4: ret = inputData_R4; break;
case RECEIVER_V6: ret = inputData_R6; break;
}
return ret;
}
/**
* liest die UserInputData f�r einen bestimmten Programmteil,
* ordnet die Tabellenspalten entsprechend an und setzt die Sichtbarkeit der Tabellenspalten.
* @param input UserInputData Objekt welches aus der permanenten Konfigurationsdatei gelesen wird
* @param typ Bestimmt den Programmteil f�r welchen die Tabelle angepasst werden soll
*/
public void setColumnSettings(UserInputData input, Typ typ){
ArrayList<TableColumn> columns = getPanTabbed(typ).getColumns();
ArrayList<Integer> saved_visibility = input.getColumnVisbility();
ArrayList<Integer> saved_order = input.getColumnOrder();
int columnCount = getTable(typ).getColumnCount();
for(int i = 0 ; i < columnCount ; i++){
getTable(getSelectedTab()).getColumnModel().removeColumn(getTable(getSelectedTab()).getColumnModel().getColumn(0));
}
//System.out.println("saved visibility size"+saved_visibility.size());
for(int i = 0; i < saved_visibility.size() ; i++){
getTable(getSelectedTab()).getColumnModel().addColumn(columns.get(saved_visibility.get(i).intValue()));
}
getUserInputData(typ).setColumnOrder(saved_order);
getUserInputData(typ).setColumnVisibility(saved_visibility);
}
/**
* Funktion welche die aktuellen Nutzereingaben im Programm speichert.
*/
public void autoSave(){
if(initFinished && f.isAutoSaveEnabled()){
submitInputData();
}
}
/**
* Funktion welche bei Programmstart die Automatische
*/
public void loadAutoSave() {
Vector<UserInputData> loaded = mc.loadAutoSave();
//System.out.println("loaded.size "+loaded.size());
if((loaded != null) && (loaded.size()==4)){
inputData_R4 = loaded.get(0);
inputData_S4 = loaded.get(1);
inputData_R6 = loaded.get(2);
inputData_S6 = loaded.get(3);
loadAutoSavePart(inputData_R4, Typ.RECEIVER_V4);
loadAutoSavePart(inputData_S4, Typ.SENDER_V4);
loadAutoSavePart(inputData_R6, Typ.RECEIVER_V6);
loadAutoSavePart(inputData_S6, Typ.SENDER_V6);
f.setLastConfigs(mc.getLastConfigs(), false);
//System.out.println("size: "+mc.getLastConfigs().size());
}
initFinished=true;
}
/**
* Hilfsfunktion zum teilweise laden der Autosave Date, unterschieden nach Programmteil
* welche sie betreffen
* @param die zu ladenden UserInputData
* @param typ der zu den UserInputData zugeh�rige Programmtetil
*/
public void loadAutoSavePart(UserInputData data, Typ typ){
//System.out.println("typ: "+typ);
switch(data.getTyp()){
case RECEIVER_V4: f.getTabpane().setSelectedIndex(0); break;
case SENDER_V4: f.getTabpane().setSelectedIndex(1); break;
case RECEIVER_V6: f.getTabpane().setSelectedIndex(2); break;
case SENDER_V6: f.getTabpane().setSelectedIndex(3); break;
default: f.getTabpane().setSelectedIndex(0);
}
f.setAutoSave((data.isAutoSaveEnabled()));
selectUserLevel(data.getUserLevel());
//System.out.println("setgroupIP: "+data.getGroupadress());
getPanConfig(typ).getTf_groupIPaddress().setText(data.getGroupadress());
//System.out.println("setport: "+data.getPort());
getPanConfig(typ).getTf_udp_port().setText(data.getPort());
//System.out.println("setactive: "+data.isActive());
if(data.isActive()){
//System.out.println("toggle bt");
setTBactive(true, typ);
}
if(typ == Typ.SENDER_V4 || typ == Typ.SENDER_V6){
//System.out.println("adapter index: "+data.getSourceAdressIndex());
getPanConfig(typ).getCb_sourceIPaddress().setSelectedIndex(data.getSourceAdressIndex());
//System.out.println("packetrate: "+data.getPacketrate());
getPanConfig(typ).getTf_packetrate().setText(data.getPacketrate());
//System.out.println("ttl: "+data.getTtl());
getPanConfig(typ).getTf_ttl().setText(data.getTtl());
//System.out.println("length: "+data.getPacketlength());
getPanConfig(typ).getTf_udp_packetlength().setText(data.getPacketlength());
}
}
public Userlevel getSelectedUserLevel(){
Userlevel ret = Userlevel.UNDEFINED;
if(f.getRb_beginner().isSelected()){
ret = Userlevel.BEGINNER;
}
else if(f.getRb_expert().isSelected()){
ret = Userlevel.EXPERT;
}
else if(f.getRb_custom().isSelected()){
ret = Userlevel.CUSTOM;
}
return ret;
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster Object aktiviert wird
*/
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster geschlossen wird
*/
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster ge�ffnet wird
*/
public void windowClosing(WindowEvent e) {
closeProgram();
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster Object deaktiviert wird
*/
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster de-minimiert wurde
*/
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster minimiert wurde
*/
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
/**
* Listener welcher darauf reagiert wenn das Fenster ge�ffnet wird
*/
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
}
| true | true | public void actionPerformed(ActionEvent e) {
if(e.getSource()==f.getMi_saveconfig()){
//System.out.println("Saving!");
f.getFc_save().toggle();
}
else if(e.getSource()==f.getMi_loadconfig()){
//System.out.println("Loading!");
f.getFc_load().toggle();
setColumnSettings(getUserInputData(getSelectedTab()), getSelectedTab());
}
else if(e.getSource()==f.getMi_snake()){
if(getSelectedTab()!=Typ.UNDEFINED && getSelectedTab()!=Typ.CONFIG){
if(getFrame().getPanelPart(getSelectedTab()).getPan_graph().runSnake)
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(false);
else
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(true);
}
}
else if(e.getSource()==f.getMi_exit()){
closeProgram();
}
// V1.5: Wenn "Titel aendern" im Menue ausgewaehlt wurde, oeffne einen InputDialog
else if (e.getSource() == f.getMi_setTitle()) {
f.setBaseTitle(JOptionPane.showInputDialog("Bitte geben Sie einen neuen Titel ein", f.getBaseTitle()));
f.updateTitle();
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getTb_active()){
toggleBTactive(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getTb_active()){
toggleBTactive(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getTb_active()){
toggleBTactive(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getTb_active()){
toggleBTactive(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getBt_enter()){
pressBTenter(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getBt_enter()){
pressBTenter(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getBt_enter()){
pressBTenter(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getBt_enter()){
pressBTenter(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDelete()){
pressBTDelete(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDelete()){
pressBTDelete(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDelete()){
pressBTDelete(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDelete()){
pressBTDelete(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStop()){
pressBTStop(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStop()){
pressBTStop(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStop()){
pressBTStop(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStop()){
pressBTStop(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStart()){
pressBTStart(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStart()){
pressBTStart(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStart()){
pressBTStart(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStart()){
pressBTStart(Typ.RECEIVER_V6);
}
else if(e.getSource()==getFrame().getFc_save().getChooser()){
saveFileEvent(e);
}
else if(e.getSource()==getFrame().getFc_load().getChooser()){
loadFileEvent(e);
}
else if(e.getActionCommand().equals("hide")){
hideColumnClicked();
getTable(getSelectedTab()).getColumnModel().removeColumn(getTable(getSelectedTab()).getColumnModel().getColumn(PopUpMenu.getSelectedColumn()));
}
else if(e.getActionCommand().equals("showall")){
popUpResetColumnsPressed();
}
else if(e.getActionCommand().equals("PopupCheckBox")){
popUpCheckBoxPressed();
}
else if(e.getActionCommand().equals("lastConfig1")){
loadConfig(f.getLastConfigs().get(0), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig2")){
loadConfig(f.getLastConfigs().get(1), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig3")){
loadConfig(f.getLastConfigs().get(2), true, true, true, true, true);
}
autoSave();
}
| public void actionPerformed(ActionEvent e) {
if(e.getSource()==f.getMi_saveconfig()){
//System.out.println("Saving!");
f.getFc_save().toggle();
}
else if(e.getSource()==f.getMi_loadconfig()){
//System.out.println("Loading!");
f.getFc_load().toggle();
setColumnSettings(getUserInputData(getSelectedTab()), getSelectedTab());
}
else if(e.getSource()==f.getMi_snake()){
if(getSelectedTab()!=Typ.UNDEFINED && getSelectedTab()!=Typ.CONFIG){
if(getFrame().getPanelPart(getSelectedTab()).getPan_graph().runSnake)
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(false);
else
getFrame().getPanelPart(getSelectedTab()).getPan_graph().snake(true);
}
}
else if(e.getSource()==f.getMi_exit()){
closeProgram();
}
// V1.5: Wenn "Titel aendern" im Menue ausgewaehlt wurde, oeffne einen InputDialog
else if (e.getSource() == f.getMi_setTitle()) {
String temp = JOptionPane.showInputDialog("Bitte geben Sie einen neuen Titel ein", f.getBaseTitle());
if (temp != null) {
f.setBaseTitle(temp);
f.updateTitle();
}
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getTb_active()){
toggleBTactive(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getTb_active()){
toggleBTactive(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getTb_active()){
toggleBTactive(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getTb_active()){
toggleBTactive(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V4).getBt_enter()){
pressBTenter(Typ.SENDER_V4);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V4).getBt_enter()){
pressBTenter(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanConfig(Typ.SENDER_V6).getBt_enter()){
pressBTenter(Typ.SENDER_V6);
}
else if(e.getSource()==getPanConfig(Typ.RECEIVER_V6).getBt_enter()){
pressBTenter(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDelete()){
pressBTDelete(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDelete()){
pressBTDelete(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDelete()){
pressBTDelete(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDelete()){
pressBTDelete(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getDeselect_all()){
pressBTDeselectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getSelect_all()){
pressBTSelectAll(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getSelect_all()){
pressBTSelectAll(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getNewmulticast()){
pressBTNewMC(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getNewmulticast()){
pressBTNewMC(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStop()){
pressBTStop(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStop()){
pressBTStop(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStop()){
pressBTStop(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStop()){
pressBTStop(Typ.RECEIVER_V6);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V4).getStart()){
pressBTStart(Typ.SENDER_V4);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V4).getStart()){
pressBTStart(Typ.RECEIVER_V4);
}
else if(e.getSource()==getPanControl(Typ.SENDER_V6).getStart()){
pressBTStart(Typ.SENDER_V6);
}
else if(e.getSource()==getPanControl(Typ.RECEIVER_V6).getStart()){
pressBTStart(Typ.RECEIVER_V6);
}
else if(e.getSource()==getFrame().getFc_save().getChooser()){
saveFileEvent(e);
}
else if(e.getSource()==getFrame().getFc_load().getChooser()){
loadFileEvent(e);
}
else if(e.getActionCommand().equals("hide")){
hideColumnClicked();
getTable(getSelectedTab()).getColumnModel().removeColumn(getTable(getSelectedTab()).getColumnModel().getColumn(PopUpMenu.getSelectedColumn()));
}
else if(e.getActionCommand().equals("showall")){
popUpResetColumnsPressed();
}
else if(e.getActionCommand().equals("PopupCheckBox")){
popUpCheckBoxPressed();
}
else if(e.getActionCommand().equals("lastConfig1")){
loadConfig(f.getLastConfigs().get(0), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig2")){
loadConfig(f.getLastConfigs().get(1), true, true, true, true, true);
}
else if(e.getActionCommand().equals("lastConfig3")){
loadConfig(f.getLastConfigs().get(2), true, true, true, true, true);
}
autoSave();
}
|
diff --git a/src/main/com/mongodb/DBCollection.java b/src/main/com/mongodb/DBCollection.java
index c118bcc7f..b4f7c7e03 100644
--- a/src/main/com/mongodb/DBCollection.java
+++ b/src/main/com/mongodb/DBCollection.java
@@ -1,1004 +1,1004 @@
// DBCollection.java
/**
* Copyright (C) 2008 10gen 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.mongodb;
import java.util.*;
import org.bson.types.*;
import com.mongodb.util.*;
/** This class provides a skeleton implementation of a database collection.
* <p>A typical invocation sequence is thus
* <blockquote><pre>
* Mongo mongo = new Mongo( new DBAddress( "localhost", 127017 ) );
* DB db = mongo.getDB( "mydb" );
* DBCollection collection = db.getCollection( "test" );
* </pre></blockquote>
* @dochub collections
*/
@SuppressWarnings("unchecked")
public abstract class DBCollection {
final static boolean DEBUG = Boolean.getBoolean( "DEBUG.DB" );
/**
* Saves document(s) to the database.
* if doc doesn't have an _id, one will be added
* you can get the _id that was added from doc after the insert
*
* @param arr array of documents to save
* @dochub insert
*/
public abstract WriteResult insert(DBObject[] arr , WriteConcern concern ) throws MongoException;
/**
* Inserts a document into the database.
* if doc doesn't have an _id, one will be added
* you can get the _id that was added from doc after the insert
*
* @param arr array of documents to save
* @dochub insert
*/
public WriteResult insert(DBObject o , WriteConcern concern )
throws MongoException {
return insert( new DBObject[]{ o } , concern );
}
/**
* Saves document(s) to the database.
* if doc doesn't have an _id, one will be added
* you can get the _id that was added from doc after the insert
*
* @param arr array of documents to save
* @dochub insert
*/
public WriteResult insert(DBObject ... arr)
throws MongoException {
return insert( arr , getWriteConcern() );
}
/**
* Saves document(s) to the database.
* if doc doesn't have an _id, one will be added
* you can get the _id that was added from doc after the insert
*
* @param list list of documents to save
* @dochub insert
*/
public WriteResult insert(List<DBObject> list)
throws MongoException {
return insert( list.toArray( new DBObject[list.size()] ) , getWriteConcern() );
}
/**
* Performs an update operation.
* @param q search query for old object to update
* @param o object with which to update <tt>q</tt>
* @param upsert if the database should create the element if it does not exist
* @param multi if the update should be applied to all objects matching (db version 1.1.3 and above)
* See http://www.mongodb.org/display/DOCS/Atomic+Operations
* @param concern WriteConcern for this operation
* @dochub update
*/
public abstract WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern ) throws MongoException ;
/**
* Performs an update operation.
* @param q search query for old object to update
* @param o object with which to update <tt>q</tt>
* @param upsert if the database should create the element if it does not exist
* @param multi if the update should be applied to all objects matching (db version 1.1.3 and above)
* See http://www.mongodb.org/display/DOCS/Atomic+Operations
* @dochub update
*/
public WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi )
throws MongoException {
return update( q , o , upsert , multi , getWriteConcern() );
}
/**
* @dochub update
*/
public WriteResult update( DBObject q , DBObject o ) throws MongoException {
return update( q , o , false , false );
}
/**
* @dochub update
*/
public WriteResult updateMulti( DBObject q , DBObject o ) throws MongoException {
return update( q , o , false , true );
}
/** Adds any necessary fields to a given object before saving it to the collection.
* @param o object to which to add the fields
*/
protected abstract void doapply( DBObject o );
/** Removes objects from the database collection.
* @param o the object that documents to be removed must match
* @param concern WriteConcern for this operation
* @dochub remove
*/
public abstract WriteResult remove( DBObject o , WriteConcern concern ) throws MongoException ;
/** Removes objects from the database collection.
* @param o the object that documents to be removed must match
* @dochub remove
*/
public WriteResult remove( DBObject o )
throws MongoException {
return remove( o , getWriteConcern() );
}
/** Finds an object.
* @param ref query used to search
* @param fields the fields of matching objects to return
* @param numToSkip will not return the first <tt>numToSkip</tt> matches
* @param batchSize if positive, is the # of objects per batch sent back from the db. all objects that match will be returned. if batchSize < 0, its a hard limit, and only 1 batch will either batchSize or the # that fit in a batch
* @param options - see Bytes QUERYOPTION_*
* @return the objects, if found
* @dochub find
*/
abstract Iterator<DBObject> __find( DBObject ref , DBObject fields , int numToSkip , int batchSize , int options ) throws MongoException ;
/** Finds an object.
* @param ref query used to search
* @param fields the fields of matching objects to return
* @param numToSkip will not return the first <tt>numToSkip</tt> matches
* @param batchSize if positive, is the # of objects per batch sent back from the db. all objects that match will be returned. if batchSize < 0, its a hard limit, and only 1 batch will either batchSize or the # that fit in a batch
* @param options - see Bytes QUERYOPTION_*
* @return the objects, if found
* @dochub find
*/
public final DBCursor find( DBObject ref , DBObject fields , int numToSkip , int batchSize , int options ) throws MongoException{
return find(ref, fields, numToSkip, batchSize).addOption(options);
}
/** Finds an object.
* @param ref query used to search
* @param fields the fields of matching objects to return
* @param numToSkip will not return the first <tt>numToSkip</tt> matches
* @param batchSize if positive, is the # of objects per batch sent back from the db. all objects that match will be returned. if batchSize < 0, its a hard limit, and only 1 batch will either batchSize or the # that fit in a batch
* @return the objects, if found
* @dochub find
*/
public final DBCursor find( DBObject ref , DBObject fields , int numToSkip , int batchSize ) {
DBCursor cursor = find(ref, fields).skip(numToSkip).batchSize(batchSize);
if ( batchSize < 0 )
cursor.limit( Math.abs(batchSize) );
return cursor;
}
/** Finds an object.
* @param ref query used to search
* @param fields the fields of matching objects to return
* @param numToSkip will not return the first <tt>numToSkip</tt> matches
* @param batchSize if positive, is the # of objects per batch sent back from the db. all objects that match will be returned. if batchSize < 0, its a hard limit, and only 1 batch will either batchSize or the # that fit in a batch
* @return the objects, if found
* @dochub find
*/
Iterator<DBObject> __find( DBObject ref , DBObject fields , int numToSkip , int batchSize )
throws MongoException {
return __find( ref , fields , numToSkip , batchSize , 0 );
}
protected abstract void createIndex( DBObject keys , DBObject options ) throws MongoException ;
// ------
/**
* Finds an object by its id.
* This compares the passed in value to the _id field of the document
*
* @param obj any valid object
* @return the object, if found, otherwise <code>null</code>
*/
public final DBObject findOne( Object obj )
throws MongoException {
return findOne(obj, null);
}
/**
* Finds an object by its id.
* This compares the passed in value to the _id field of the document
*
* @param obj any valid object
* @param fields fields to return
* @return the object, if found, otherwise <code>null</code>
* @dochub find
*/
public final DBObject findOne( Object obj, DBObject fields ) {
Iterator<DBObject> iterator = __find(new BasicDBObject("_id", obj), fields, 0, -1, 0);
return (iterator != null ? iterator.next() : null);
}
/**
* Finds the first document in the query (sorted) and updates it.
* If remove is specified it will be removed. If new is specified then the updated
* document will be returned, otherwise the old document is returned (or it would be lost forever).
* You can also specify the fields to return in the document, optionally.
* @return the found document (before, or after the update)
*/
public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) {
if ( DEBUG ) System.out.println( "findAndModify: " + _fullName +
" query:" + JSON.serialize( query ) +
" sort:" + JSON.serialize( sort )+
" remove:" + remove +
" update: " + JSON.serialize( update )+
" upsert: " + upsert+
" returnNew:" + returnNew);
BasicDBObject cmd = new BasicDBObject( "findandmodify", _name);
if (query != null && !query.keySet().isEmpty())
cmd.append( "query", query );
if (fields != null && !fields.keySet().isEmpty())
cmd.append( "fields", fields );
if (sort != null && !sort.keySet().isEmpty())
cmd.append( "sort", sort );
if (remove)
cmd.append( "remove", remove );
else {
if (update != null && !update.keySet().isEmpty())
cmd.append( "update", update );
if (returnNew)
cmd.append( "new", returnNew );
if (upsert)
- cmd.append( "upsert", returnNew );
+ cmd.append( "upsert", upsert );
}
if (remove && !(update == null || update.keySet().isEmpty() || returnNew))
throw new MongoException("FindAndModify: Remove cannot be mixed with the Update, or returnNew params!");
return (DBObject) this._db.command( cmd ).get( "value" );
}
/**
* Finds the first document in the query (sorted) and updates it.
* @return the old document
*/
public DBObject findAndModify( DBObject query , DBObject sort , DBObject update){
return findAndModify( query, null, null, false, update, false, false);
}
/**
* Finds the first document in the query and updates it.
* @return the old document
*/
public DBObject findAndModify( DBObject query , DBObject update ) {
return findAndModify( query, null, null, false, update, false, false );
}
/**
* Finds the first document in the query and removes it.
* @return the removed document
*/
public DBObject findAndRemove( DBObject query ) {
return findAndModify( query, null, null, true, null, false, false );
}
// --- START INDEX CODE ---
/** Forces creation of an index on a set of fields, if one does not already exist.
* @param keys an object with a key set of the fields desired for the index
*/
public final void createIndex( final DBObject keys )
throws MongoException {
createIndex( keys , defaultOptions( keys ) );
}
public final void ensureIndex( final String name ){
ensureIndex( new BasicDBObject( name , 1 ) );
}
/** Creates an index on a set of fields, if one does not already exist.
* @param keys an object with a key set of the fields desired for the index
*/
public final void ensureIndex( final DBObject keys )
throws MongoException {
ensureIndex( keys , defaultOptions( keys ) );
}
/** Ensures an index on this collection (that is, the index will be created if it does not exist).
* ensureIndex is optimized and is inexpensive if the index already exists.
* @param keys fields to use for index
* @param name an identifier for the index
* @dochub indexes
*/
public void ensureIndex( DBObject keys , String name )
throws MongoException {
ensureIndex( keys , name , false );
}
/** Ensures an optionally unique index on this collection.
* @param keys fields to use for index
* @param name an identifier for the index
* @param unique if the index should be unique
*/
public void ensureIndex( DBObject keys , String name , boolean unique )
throws MongoException {
DBObject options = defaultOptions( keys );
options.put( "name" , name );
if ( unique )
options.put( "unique" , Boolean.TRUE );
ensureIndex( keys , options );
}
public final void ensureIndex( final DBObject keys , final DBObject optionsIN )
throws MongoException {
if ( checkReadOnly( false ) ) return;
final DBObject options = defaultOptions( keys );
for ( String k : optionsIN.keySet() )
options.put( k , optionsIN.get( k ) );
final String name = options.get( "name" ).toString();
boolean doEnsureIndex = false;
if ( ! _createIndexes.contains( name ) )
doEnsureIndex = true;
else if ( _anyUpdateSave && ! _createIndexesAfterSave.contains( name ) )
doEnsureIndex = true;
if ( ! doEnsureIndex )
return;
createIndex( keys , options );
_createIndexes.add( name );
if ( _anyUpdateSave )
_createIndexesAfterSave.add( name );
}
/** Clears all indices that have not yet been applied to this collection. */
public void resetIndexCache(){
_createIndexes.clear();
}
DBObject defaultOptions( DBObject keys ){
DBObject o = new BasicDBObject();
o.put( "name" , genIndexName( keys ) );
o.put( "ns" , _fullName );
return o;
}
/** Generate an index name from the set of fields it is over.
* @param keys the names of the fields used in this index
* @return a string representation of this index's fields
*/
public static String genIndexName( DBObject keys ){
String name = "";
for ( String s : keys.keySet() ){
if ( name.length() > 0 )
name += "_";
name += s + "_";
Object val = keys.get( s );
if ( val instanceof Number || val instanceof String )
name += val.toString().replace( ' ' , '_' );
}
return name;
}
// --- END INDEX CODE ---
/** Set hint fields for this collection.
* @param lst a list of <code>DBObject</code>s to be used as hints
*/
public void setHintFields( List<DBObject> lst ){
_hintFields = lst;
}
/** Queries for an object in this collection.
* @param ref object for which to search
* @return an iterator over the results
* @dochub find
*/
public final DBCursor find( DBObject ref ){
return new DBCursor( this, ref, null );
}
/** Queries for an object in this collection.
*
* <p>
* An empty DBObject will match every document in the collection.
* Regardless of fields specified, the _id fields are always returned.
* </p>
* <p>
* An example that returns the "x" and "_id" fields for every document
* in the collection that has an "x" field:
* </p>
* <blockquote><pre>
* BasicDBObject keys = new BasicDBObject();
* keys.put("x", 1);
*
* DBCursor cursor = collection.find(new BasicDBObject(), keys);
* </pre></blockquote>
*
* @param ref object for which to search
* @param keys fields to return
* @return a cursor to iterate over results
* @dochub find
*/
public final DBCursor find( DBObject ref , DBObject keys ){
return new DBCursor( this, ref, keys );
}
/** Queries for all objects in this collection.
* @return a cursor which will iterate over every object
* @dochub find
*/
public final DBCursor find(){
return new DBCursor( this, new BasicDBObject(), null );
}
/**
* Returns a single object from this collection.
* @return the object found, or <code>null</code> if the collection is empty
*/
public final DBObject findOne()
throws MongoException {
return findOne( new BasicDBObject() );
}
/**
* Returns a single object from this collection matching the query.
* @param o the query object
* @return the object found, or <code>null</code> if no such object exists
*/
public final DBObject findOne( DBObject o )
throws MongoException {
return findOne(o, null);
}
/**
* Returns a single object from this collection matching the query.
* @param o the query object
* @param fields fields to return
* @return the object found, or <code>null</code> if no such object exists
* @dochub find
*/
public final DBObject findOne( DBObject o, DBObject fields ) {
Iterator<DBObject> i = __find( o , fields , 0 , -1 , 0 );
if ( i == null || ! i.hasNext() )
return null;
return i.next();
}
/** Adds the "private" fields _id to an object.
* @param o <code>DBObject</code> to which to add fields
* @return the modified parameter object
*/
public final Object apply( DBObject o ){
return apply( o , true );
}
/** Adds the "private" fields _id to an object.
* @param jo object to which to add fields
* @param ensureID whether to add an <code>_id</code> field or not
* @return the modified object <code>o</code>
*/
public final Object apply( DBObject jo , boolean ensureID ){
Object id = jo.get( "_id" );
if ( ensureID && id == null ){
id = ObjectId.get();
jo.put( "_id" , id );
}
doapply( jo );
return id;
}
/** Saves an object to this collection.
* @param jo the <code>DBObject</code> to save
* will add <code>_id</code> field to jo if needed
*/
public final WriteResult save( DBObject jo ) {
return save(jo, null);
}
/** Saves an object to this collection.
* @param jo the <code>DBObject</code> to save
* will add <code>_id</code> field to jo if needed
*/
public final WriteResult save( DBObject jo, WriteConcern concern )
throws MongoException {
if ( checkReadOnly( true ) )
return null;
_checkObject( jo , false , false );
Object id = jo.get( "_id" );
if ( DEBUG ) System.out.println( "id : " + id );
if ( id == null || ( id instanceof ObjectId && ((ObjectId)id).isNew() ) ){
if ( DEBUG ) System.out.println( "saving new object" );
if ( id != null && id instanceof ObjectId )
((ObjectId)id).notNew();
if ( concern == null )
return insert( jo );
else
return insert( jo, concern );
}
if ( DEBUG ) System.out.println( "doing implicit upsert : " + jo.get( "_id" ) );
DBObject q = new BasicDBObject();
q.put( "_id" , id );
if ( concern == null )
return update( q , jo , true , false );
else
return update( q , jo , true , false , concern );
}
// ---- DB COMMANDS ----
/** Drops all indices from this collection
*/
public void dropIndexes()
throws MongoException {
dropIndexes( "*" );
}
public void dropIndexes( String name )
throws MongoException {
DBObject cmd = BasicDBObjectBuilder.start()
.add( "deleteIndexes" , getName() )
.add( "index" , name )
.get();
CommandResult res = _db.command( cmd );
if ( res.ok() || res.getErrorMessage().equals( "ns not found" ) ){
resetIndexCache();
return;
}
throw new MongoException( "error dropping indexes : " + res );
}
/** Drops (deletes) this collection
*/
public void drop()
throws MongoException {
CommandResult res =_db.command( BasicDBObjectBuilder.start().add( "drop" , getName() ).get() );
if ( res.ok() || res.getErrorMessage().equals( "ns not found" ) )
return;
throw new MongoException( "error dropping : " + res );
}
public long count()
throws MongoException {
return getCount(new BasicDBObject(), null);
}
public long count(DBObject query)
throws MongoException {
return getCount(query, null);
}
/**
* Returns the number of documents in the collection
* @return number of documents that match query
*/
public long getCount()
throws MongoException {
return getCount(new BasicDBObject(), null);
}
/**
* Returns the number of documents in the collection
* that match the specified query
*
* @param query query to select documents to count
* @return number of documents that match query
*/
public long getCount(DBObject query)
throws MongoException {
return getCount(query, null);
}
/**
* Returns the number of documents in the collection
* that match the specified query
*
* @param query query to select documents to count
* @param fields fields to return
* @return number of documents that match query and fields
*/
public long getCount(DBObject query, DBObject fields)
throws MongoException {
return getCount( query , fields , 0 , 0 );
}
/**
* Returns the number of documents in the collection
* that match the specified query
*
* @param query query to select documents to count
* @param fields fields to return
* @return number of documents that match query and fields
*/
public long getCount(DBObject query, DBObject fields, long limit, long skip )
throws MongoException {
BasicDBObject cmd = new BasicDBObject();
cmd.put("count", getName());
cmd.put("query", query);
if (fields != null) {
cmd.put("fields", fields);
}
if ( limit > 0 )
cmd.put( "limit" , limit );
if ( skip > 0 )
cmd.put( "skip" , skip );
CommandResult res = _db.command(cmd);
if ( ! res.ok() ){
String errmsg = res.getErrorMessage();
if ( errmsg.equals("ns does not exist") ||
errmsg.equals("ns missing" ) ){
// for now, return 0 - lets pretend it does exist
return 0;
}
throw new MongoException( "error counting : " + res );
}
return res.getLong("n");
}
/**
* does a rename of this collection to newName
* @param newName new collection name (not a full namespace)
* @return the new collection
*/
public DBCollection rename( String newName )
throws MongoException {
CommandResult ret =
_db.getSisterDB( "admin" )
.command( BasicDBObjectBuilder.start()
.add( "renameCollection" , _fullName )
.add( "to" , _db._name + "." + newName )
.get() );
ret.throwOnError();
return _db.getCollection( newName );
}
/**
* @param key - { a : true }
* @param cond - optional condition on query
* @param reduce javascript reduce function
* @param initial initial value for first match on a key
*/
public DBObject group( DBObject key , DBObject cond , DBObject initial , String reduce )
throws MongoException {
CommandResult res = _db.command( new BasicDBObject( "group" ,
BasicDBObjectBuilder.start()
.add( "ns" , getName() )
.add( "key" , key )
.add( "cond" , cond )
.add( "$reduce" , reduce )
.add( "initial" , initial )
.get() ) );
res.throwOnError();
return (DBObject)res.get( "retval" );
}
/**
* find distinct values for a key
*/
public List distinct( String key ){
return distinct( key , new BasicDBObject() );
}
/**
* find distinct values for a key
* @param query query to apply on collection
*/
public List distinct( String key , DBObject query ){
DBObject c = BasicDBObjectBuilder.start()
.add( "distinct" , getName() )
.add( "key" , key )
.add( "query" , query )
.get();
CommandResult res = _db.command( c );
res.throwOnError();
return (List)(res.get( "values" ));
}
/**
performs a map reduce operation
* @param outputCollection optional - leave null if want to use temp collection
* @param query optional - leave null if you want all objects
* @dochub mapreduce
*/
public MapReduceOutput mapReduce( String map , String reduce , String outputCollection , DBObject query )
throws MongoException {
BasicDBObjectBuilder b = BasicDBObjectBuilder.start()
.add( "mapreduce" , _name )
.add( "map" , map )
.add( "reduce" , reduce );
if ( outputCollection != null )
b.add( "out" , outputCollection );
if ( query != null )
b.add( "query" , query );
return mapReduce( b.get() );
}
public MapReduceOutput mapReduce( DBObject command )
throws MongoException {
if ( command.get( "mapreduce" ) == null )
throw new IllegalArgumentException( "need mapreduce arg" );
CommandResult res = _db.command( command );
res.throwOnError();
return new MapReduceOutput( this , res );
}
/**
* Return a list of the indexes for this collection. Each object
* in the list is the "info document" from MongoDB
*
* @return list of index documents
*/
public List<DBObject> getIndexInfo() {
BasicDBObject cmd = new BasicDBObject();
cmd.put("ns", getFullName());
DBCursor cur = _db.getCollection("system.indexes").find(cmd);
List<DBObject> list = new ArrayList<DBObject>();
while(cur.hasNext()) {
list.add(cur.next());
}
return list;
}
public void dropIndex( DBObject keys )
throws MongoException {
dropIndexes( genIndexName( keys ) );
}
public void dropIndex( String name )
throws MongoException {
dropIndexes( name );
}
public CommandResult getStats() {
return(getDB().command(new BasicDBObject("collstats", getName())));
}
public boolean isCapped() {
CommandResult stats = getStats();
Object capped = stats.get("capped");
return(capped != null && (Integer)capped == 1);
}
// ------
/** Initializes a new collection.
* @param base database in which to create the collection
* @param name the name of the collection
*/
protected DBCollection( DB base , String name ){
_db = base;
_name = name;
_fullName = _db.getName() + "." + name;
}
private DBObject _checkObject( DBObject o , boolean canBeNull , boolean query ){
if ( o == null ){
if ( canBeNull )
return null;
throw new IllegalArgumentException( "can't be null" );
}
if ( o.isPartialObject() && ! query )
throw new IllegalArgumentException( "can't save partial objects" );
if ( ! query ){
_checkKeys(o);
}
return o;
}
/**
* Checks key strings for invalid characters.
*/
private void _checkKeys( DBObject o ) {
for ( String s : o.keySet() ){
if ( s.contains( "." ) )
throw new IllegalArgumentException( "fields stored in the db can't have . in them" );
if ( s.charAt( 0 ) == '$' )
throw new IllegalArgumentException( "fields stored in the db can't start with '$'" );
Object inner;
if ( (inner = o.get( s )) instanceof DBObject ) {
_checkKeys( (DBObject)inner );
}
}
}
/** Find a collection that is prefixed with this collection's name.
* A typical use of this might be
* <blockquote><pre>
* DBCollection users = mongo.getCollection( "wiki" ).getCollection( "users" );
* </pre></blockquote>
* Which is equilalent to
* <pre><blockquote>
* DBCollection users = mongo.getCollection( "wiki.users" );
* </pre></blockquote>
* @param n the name of the collection to find
* @return the matching collection
*/
public DBCollection getCollection( String n ){
return _db.getCollection( _name + "." + n );
}
/** Returns the name of this collection.
* @return the name of this collection
*/
public String getName(){
return _name;
}
/** Returns the full name of this collection, with the database name as a prefix.
* @return the name of this collection
*/
public String getFullName(){
return _fullName;
}
/** Returns the database this collection is a member of.
* @return this collection's database
*/
public DB getDB(){
return _db;
}
/** Returns if this collection's database is read-only
* @param strict if an exception should be thrown if the database is read-only
* @return if this collection's database is read-only
* @throws RuntimeException if the database is read-only and <code>strict</code> is set
*/
protected boolean checkReadOnly( boolean strict ){
if ( ! _db._readOnly )
return false;
if ( ! strict )
return true;
throw new IllegalStateException( "db is read only" );
}
/** Calculates the hash code for this collection.
* @return the hash code
*/
public int hashCode(){
return _fullName.hashCode();
}
/** Checks if this collection is equal to another object.
* @param o object with which to compare this collection
* @return if the two collections are the same object
*/
public boolean equals( Object o ){
return o == this;
}
/** Returns name of the collection.
* @return name of the collection.
*/
public String toString(){
return _name;
}
/** Set a default class for objects in this collection
* @param c the class
* @throws IllegalArgumentException if <code>c</code> is not a DBObject
*/
public void setObjectClass( Class c ){
if ( ! DBObject.class.isAssignableFrom( c ) )
throw new IllegalArgumentException( c.getName() + " is not a DBObject" );
_objectClass = c;
if ( ReflectionDBObject.class.isAssignableFrom( c ) )
_wrapper = ReflectionDBObject.getWrapper( c );
else
_wrapper = null;
}
/** Gets the default class for objects in the collection
* @return the class
*/
public Class getObjectClass(){
return _objectClass;
}
public void setInternalClass( String path , Class c ){
_internalClass.put( path , c );
}
protected Class getInternalClass( String path ){
Class c = _internalClass.get( path );
if ( c != null )
return c;
if ( _wrapper == null )
return null;
return _wrapper.getInternalClass( path );
}
/**
* Set the write concern for this collection. Will be used for
* writes to this collection. Overrides any setting of write
* concern at the DB level. See the documentation for
* {@link WriteConcern} for more information.
*
* @param concern write concern to use
*/
public void setWriteConcern( WriteConcern concern ){
_concern = concern;
}
/**
* Get the write concern for this collection.
*/
public WriteConcern getWriteConcern(){
if ( _concern != null )
return _concern;
return _db.getWriteConcern();
}
final DB _db;
final protected String _name;
final protected String _fullName;
protected List<DBObject> _hintFields;
private WriteConcern _concern = null;
protected Class _objectClass = null;
private Map<String,Class> _internalClass = Collections.synchronizedMap( new HashMap<String,Class>() );
private ReflectionDBObject.JavaWrapper _wrapper = null;
private boolean _anyUpdateSave = false;
final private Set<String> _createIndexes = new HashSet<String>();
final private Set<String> _createIndexesAfterSave = new HashSet<String>();
}
| true | true | public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) {
if ( DEBUG ) System.out.println( "findAndModify: " + _fullName +
" query:" + JSON.serialize( query ) +
" sort:" + JSON.serialize( sort )+
" remove:" + remove +
" update: " + JSON.serialize( update )+
" upsert: " + upsert+
" returnNew:" + returnNew);
BasicDBObject cmd = new BasicDBObject( "findandmodify", _name);
if (query != null && !query.keySet().isEmpty())
cmd.append( "query", query );
if (fields != null && !fields.keySet().isEmpty())
cmd.append( "fields", fields );
if (sort != null && !sort.keySet().isEmpty())
cmd.append( "sort", sort );
if (remove)
cmd.append( "remove", remove );
else {
if (update != null && !update.keySet().isEmpty())
cmd.append( "update", update );
if (returnNew)
cmd.append( "new", returnNew );
if (upsert)
cmd.append( "upsert", returnNew );
}
if (remove && !(update == null || update.keySet().isEmpty() || returnNew))
throw new MongoException("FindAndModify: Remove cannot be mixed with the Update, or returnNew params!");
return (DBObject) this._db.command( cmd ).get( "value" );
}
| public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert) {
if ( DEBUG ) System.out.println( "findAndModify: " + _fullName +
" query:" + JSON.serialize( query ) +
" sort:" + JSON.serialize( sort )+
" remove:" + remove +
" update: " + JSON.serialize( update )+
" upsert: " + upsert+
" returnNew:" + returnNew);
BasicDBObject cmd = new BasicDBObject( "findandmodify", _name);
if (query != null && !query.keySet().isEmpty())
cmd.append( "query", query );
if (fields != null && !fields.keySet().isEmpty())
cmd.append( "fields", fields );
if (sort != null && !sort.keySet().isEmpty())
cmd.append( "sort", sort );
if (remove)
cmd.append( "remove", remove );
else {
if (update != null && !update.keySet().isEmpty())
cmd.append( "update", update );
if (returnNew)
cmd.append( "new", returnNew );
if (upsert)
cmd.append( "upsert", upsert );
}
if (remove && !(update == null || update.keySet().isEmpty() || returnNew))
throw new MongoException("FindAndModify: Remove cannot be mixed with the Update, or returnNew params!");
return (DBObject) this._db.command( cmd ).get( "value" );
}
|
diff --git a/parser-java-api/src/main/java/org/jboss/forge/parser/java/Visibility.java b/parser-java-api/src/main/java/org/jboss/forge/parser/java/Visibility.java
index 7850076d7..ca1aad3f6 100644
--- a/parser-java-api/src/main/java/org/jboss/forge/parser/java/Visibility.java
+++ b/parser-java-api/src/main/java/org/jboss/forge/parser/java/Visibility.java
@@ -1,101 +1,101 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt 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.forge.parser.java;
import org.jboss.forge.parser.java.util.Assert;
/**
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*
*/
public enum Visibility
{
PUBLIC("public"),
PROTECTED("protected"),
PRIVATE("private"),
PACKAGE_PRIVATE("");
private Visibility(String scope)
{
this.scope = scope;
}
private String scope;
/**
* private, public, protected, package private("")
*/
public String scope()
{
return scope;
}
public static Visibility getFrom(VisibilityScoped<?> target)
{
Assert.notNull(target, "VisibilityScoped<T> target must not be null.");
if (target.isPackagePrivate())
return PACKAGE_PRIVATE;
if (target.isPrivate())
return PRIVATE;
if (target.isPublic())
return PUBLIC;
if (target.isProtected())
return PROTECTED;
else
{
throw new IllegalStateException(VisibilityScoped.class.getSimpleName()
+ " target does not comply with visibility scoping. Must be one of " + Visibility.values() + "[ "
+ target + "]");
}
}
@Override
public String toString()
{
return scope;
}
public static <T extends VisibilityScoped<?>> T set(T target, Visibility scope)
{
Assert.notNull(target, "VisibilityScoped<T> target must not be null.");
Assert.notNull(scope, "Visibility scope must not be null");
if (PRIVATE.equals(scope))
target.setPrivate();
- if (PACKAGE_PRIVATE.equals(scope))
+ else if (PACKAGE_PRIVATE.equals(scope))
target.setPackagePrivate();
- if (PROTECTED.equals(scope))
+ else if (PROTECTED.equals(scope))
target.setProtected();
- if (PUBLIC.equals(scope))
+ else if (PUBLIC.equals(scope))
target.setPublic();
else
{
throw new IllegalStateException("Unknown Visibility scope.");
}
return target;
}
}
| false | true | public static <T extends VisibilityScoped<?>> T set(T target, Visibility scope)
{
Assert.notNull(target, "VisibilityScoped<T> target must not be null.");
Assert.notNull(scope, "Visibility scope must not be null");
if (PRIVATE.equals(scope))
target.setPrivate();
if (PACKAGE_PRIVATE.equals(scope))
target.setPackagePrivate();
if (PROTECTED.equals(scope))
target.setProtected();
if (PUBLIC.equals(scope))
target.setPublic();
else
{
throw new IllegalStateException("Unknown Visibility scope.");
}
return target;
}
| public static <T extends VisibilityScoped<?>> T set(T target, Visibility scope)
{
Assert.notNull(target, "VisibilityScoped<T> target must not be null.");
Assert.notNull(scope, "Visibility scope must not be null");
if (PRIVATE.equals(scope))
target.setPrivate();
else if (PACKAGE_PRIVATE.equals(scope))
target.setPackagePrivate();
else if (PROTECTED.equals(scope))
target.setProtected();
else if (PUBLIC.equals(scope))
target.setPublic();
else
{
throw new IllegalStateException("Unknown Visibility scope.");
}
return target;
}
|
diff --git a/illaclient/src/illarion/client/IllaClient.java b/illaclient/src/illarion/client/IllaClient.java
index d1f42b83..18b06048 100644
--- a/illaclient/src/illarion/client/IllaClient.java
+++ b/illaclient/src/illarion/client/IllaClient.java
@@ -1,589 +1,593 @@
/*
* This file is part of the Illarion Client.
*
* Copyright © 2012 - Illarion e.V.
*
* The Illarion Client is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Illarion Client is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Illarion Client. If not, see <http://www.gnu.org/licenses/>.
*/
package illarion.client;
import illarion.client.crash.DefaultCrashHandler;
import illarion.client.net.client.LogoutCmd;
import illarion.client.resources.SongFactory;
import illarion.client.resources.SoundFactory;
import illarion.client.resources.loaders.SongLoader;
import illarion.client.resources.loaders.SoundLoader;
import illarion.client.util.ChatLog;
import illarion.client.util.GlobalExecutorService;
import illarion.client.util.Lang;
import illarion.client.world.Player;
import illarion.client.world.World;
import illarion.common.bug.CrashReporter;
import illarion.common.config.Config;
import illarion.common.config.ConfigChangedEvent;
import illarion.common.config.ConfigSystem;
import illarion.common.util.*;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.bushe.swing.event.*;
import org.illarion.engine.Backend;
import org.illarion.engine.DesktopGameContainer;
import org.illarion.engine.EngineException;
import org.illarion.engine.EngineManager;
import org.illarion.engine.graphic.GraphicResolution;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.Timer;
/**
* Main Class of the Illarion Client, this loads up the whole game and runs the main loop of the Illarion Client.
*
* @author Nop
* @author Martin Karing <[email protected]>
*/
public final class IllaClient implements EventTopicSubscriber<ConfigChangedEvent> {
/**
* The name of this application.
*/
public static final String APPLICATION = "Illarion Client"; //$NON-NLS-1$
/**
* The version information of this client. This version is shows at multiple positions within the client.
*/
public static final String VERSION = "2.1.1"; //$NON-NLS-1$
/**
* The default server the client connects too. The client will always connect to this server.
*/
@Nonnull
public static final Servers DEFAULT_SERVER;
static {
String server = System.getProperty("illarion.server");
if ("testserver".equals(server)) {
DEFAULT_SERVER = Servers.testserver;
} else if ("devserver".equals(server)) {
DEFAULT_SERVER = Servers.devserver;
} else {
DEFAULT_SERVER = Servers.realserver;
}
}
/**
* The error and debug logger of the client.
*/
static final Logger LOGGER = Logger.getLogger(IllaClient.class);
/**
* Stores if there currently is a exit requested to avoid that the question area is opened multiple times.
*/
private static boolean exitRequested;
/**
* The singleton instance of this class.
*/
private static final IllaClient INSTANCE = new IllaClient();
/**
* Storage of the properties that are used by the logger settings. This is needed to set up the correct paths to
* the
* files.
*/
@Nonnull
private static final Properties tempProps = new Properties();
/**
* The configuration of the client settings.
*/
private ConfigSystem cfg;
/**
* Stores the debug level of the client.
*/
private int debugLevel = 0;
/**
* The class loader of the this class. It is used to get the resource streams that contain the resource data of the
* client.
*/
private final ClassLoader rscLoader = IllaClient.class.getClassLoader();
/**
* Stores the server the client shall connect to.
*/
private Servers usedServer = DEFAULT_SERVER;
/**
* This is the reference to the Illarion Game instance.
*/
private Game game;
/**
* The container that is used to display the game.
*/
private DesktopGameContainer gameContainer;
/**
* The default empty constructor used to create the singleton instance of this class.
*/
private IllaClient() {
}
private void init() {
try {
+ EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_EVENT_BUS, null);
+ EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_SWING_EVENT_SERVICE, null);
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_EVENT_BUS, new ThreadSafeEventService());
+ EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_SWING_EVENT_SERVICE,
+ EventServiceLocator.getEventBusService());
} catch (EventServiceExistsException e1) {
LOGGER.error("Failed preparing the EventBus. Settings the Service handler happened too late");
}
prepareConfig();
assert cfg != null;
try {
initLogfiles();
} catch (IOException e) {
System.err.println("Failed to setup logging system!");
e.printStackTrace(System.err);
}
Lang.getInstance().recheckLocale(cfg.getString(Lang.LOCALE_CFG));
CrashReporter.getInstance().setConfig(getCfg());
// Report errors of the released version only
if (DEFAULT_SERVER != Servers.realserver) {
CrashReporter.getInstance().setMode(CrashReporter.MODE_NEVER);
}
// Preload sound and music
try {
new SongLoader().setTarget(SongFactory.getInstance()).call();
new SoundLoader().setTarget(SoundFactory.getInstance()).call();
} catch (Exception e) {
LOGGER.error("Failed to load sounds and music!");
}
game = new Game();
GraphicResolution res = null;
final String resolutionString = cfg.getString(CFG_RESOLUTION);
if (resolutionString != null) {
try {
res = new GraphicResolution(resolutionString);
} catch (@Nonnull final IllegalArgumentException ex) {
LOGGER.error("Failed to initialize screen resolution. Falling back.");
}
}
if (res == null) {
res = new GraphicResolution(800, 600, 32, 60);
}
try {
final int requestedWidth;
final int requestedHeight;
final boolean fullScreenMode;
if (cfg.getBoolean(CFG_FULLSCREEN)) {
fullScreenMode = true;
requestedHeight = res.getHeight();
requestedWidth = res.getWidth();
} else {
fullScreenMode = false;
final int windowedWidth = cfg.getInteger("windowWidth");
final int windowedHeight = cfg.getInteger("windowHeight");
requestedHeight = (windowedHeight < 0) ? res.getHeight() : windowedHeight;
requestedWidth = (windowedWidth < 0) ? res.getWidth() : windowedWidth;
}
gameContainer = EngineManager.createDesktopGame(Backend.libGDX, game,
requestedWidth, requestedHeight, fullScreenMode);
} catch (@Nonnull final EngineException e) {
LOGGER.error("Fatal error creating game screen!!!", e);
System.exit(-1);
}
gameContainer.setTitle(APPLICATION + ' ' + VERSION);
gameContainer.setIcons(new String[]{"illarion_client16.png", "illarion_client32.png",
"illarion_client64.png", "illarion_client256.png"});
EventBus.subscribe(CFG_FULLSCREEN, this);
EventBus.subscribe(CFG_RESOLUTION, this);
try {
gameContainer.setResizeable(true);
gameContainer.startGame();
} catch (@Nonnull final Exception e) {
LOGGER.fatal("Exception while launching game.", e);
exitGameContainer();
}
}
/**
* Get the container that is used to display the game inside.
*
* @return the are used to display the game inside
*/
public DesktopGameContainer getContainer() {
return gameContainer;
}
/**
* Show a question frame if the client shall really quit and exit the client in case the user selects yes.
*/
public static void ensureExit() {
if (exitRequested) {
return;
}
exitRequested = true;
INSTANCE.game.enterState(Game.STATE_ENDING);
}
public static void exitGameContainer() {
INSTANCE.gameContainer.exitGame();
LOGGER.info("Client shutdown initiated.");
getInstance().quitGame();
World.cleanEnvironment();
getCfg().save();
GlobalExecutorService.shutdown();
LOGGER.info("Cleanup done.");
startFinalKiller();
}
/**
* Show an error message and leave the client.
*
* @param message the error message that shall be displayed.
*/
@SuppressWarnings("nls")
public static void errorExit(final String message) {
World.cleanEnvironment();
LOGGER.info("Client terminated on user request.");
LOGGER.fatal(Lang.getMsg(message));
LOGGER.fatal("Terminating client!");
INSTANCE.cfg.save();
LogManager.shutdown();
new Thread(new Runnable() {
@Override
public void run() {
JOptionPane.showMessageDialog(null, Lang.getMsg(message), "Error", JOptionPane.ERROR_MESSAGE);
startFinalKiller();
}
}).start();
}
/**
* Quit the client and restart the connection with the login screen right away.
*
* @param message the message that shall be displayed in the login screen
*/
public static void fallbackToLogin(final String message) {
LOGGER.warn(message);
ensureExit();
//INSTANCE.game.enterState(Game.STATE_LOGIN);
//World.cleanEnvironment();
}
/**
* Get the configuration handler of the basic client settings.
*
* @return the configuration handler
*/
public static Config getCfg() {
return INSTANCE.cfg;
}
/**
* Get the full path to a file. This includes the default path that was set up and the name of the file this
* function gets.
*
* @param name the name of the file that shall be append to the folder
* @return the full path to a file
*/
public static String getFile(final String name) {
return new File(DirectoryManager.getInstance().getUserDirectory(), name).getAbsolutePath();
}
/**
* Get the singleton instance of this client main object.
*
* @return the singleton instance of this class
*/
@Nonnull
public static IllaClient getInstance() {
return INSTANCE;
}
/**
* Load a resource as stream via the basic class loader.
*
* @param path the path to the object that shall be loaded
* @return the data stream of the object
*/
public static InputStream getResource(final String path) {
return INSTANCE.rscLoader.getResourceAsStream(path);
}
/**
* Get a text that identifies the version of this client.
*
* @return the version text of this client
*/
@Nonnull
public static String getVersionText() {
return "Illarion Client " + VERSION; //$NON-NLS-1$
}
/**
* Check if a debug flag is set or not.
*
* @param flag the debug flag that shall be checked
* @return true in case the flag is enabled, false if not
*/
public static boolean isDebug(@Nonnull final Debug flag) {
return (INSTANCE.debugLevel & (1 << flag.ordinal())) > 0;
}
/**
* Main function starts the client and sets up all data.
*
* @param args the arguments handed over to the client
*/
@SuppressWarnings("nls")
public static void main(final String[] args) {
final String folder = checkFolder();
// Setup the crash reporter so the client is able to crash properly.
CrashReporter.getInstance().setMessageSource(Lang.getInstance());
CrashReporter.getInstance().setDisplay(CrashReporter.DISPLAY_SWING);
// in case the server is now known, update the files if needed and
// launch the client.
if (folder == null) {
return;
}
INSTANCE.init();
}
/**
* This method is the final one to be called before the client is killed for sure. It gives the rest of the client
* 10 seconds before it forcefully shuts down everything. This is used to ensure that the client quits when it has
* to, but in case it does so faster, it won't be killed like that.
*/
@SuppressWarnings("nls")
public static void startFinalKiller() {
final Timer finalKiller = new Timer("Final Death", true);
finalKiller.schedule(new TimerTask() {
@Override
public void run() {
CrashReporter.getInstance().waitForReport();
System.err.println("Killed by final death");
System.exit(-1);
}
}, 10000);
}
/**
* This function changes the state of the exit requested parameter.
*
* @param newValue the new value for the exitRequested parameter
*/
static void setExitRequested(final boolean newValue) {
exitRequested = newValue;
}
/**
* Get if there is currently a exit request pending. Means of the really exit dialog is opened or not.
*
* @return true in case the exit dialog is currently displayed
*/
private static boolean getExitRequested() {
return exitRequested;
}
/**
* This function determines the user data directory and requests the folder to store the client data in case it is
* needed. It also performs checks to see if the folder is valid.
*
* @return a string with the path to the folder or null in case no folder is set
*/
@SuppressWarnings("nls")
private static String checkFolder() {
if (!DirectoryManager.getInstance().hasUserDirectory()) {
JOptionPane.showMessageDialog(null, "Installation ist fehlerhaft. Bitte neu ausführen.\n\n" +
"Installation is corrupted, please run it again.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(-1);
}
final File userDirectory = DirectoryManager.getInstance().getUserDirectory();
assert userDirectory != null;
return userDirectory.getAbsolutePath();
}
/**
* Get the server that was selected as connection target.
*
* @return the selected server
*/
public Servers getUsedServer() {
return usedServer;
}
/**
* End the game by user request and send the logout command to the server.
*/
public void quitGame() {
try {
World.getNet().sendCommand(new LogoutCmd());
} catch (@Nonnull final IllegalStateException ex) {
// the NET was not launched up yet. This does not really matter.
}
}
/**
* Set the server that shall be used to login at.
*
* @param server the server that is used to connect with
*/
public void setUsedServer(final Servers server) {
usedServer = server;
}
/**
* Basic initialization of the log files and the debug settings.
*/
@SuppressWarnings("nls")
private static void initLogfiles() throws IOException {
tempProps.load(getResource("logging.properties"));
tempProps.put("log4j.appender.IllaLogfileAppender.file", getFile("error.log"));
tempProps.put("log4j.appender.ChatAppender.file", getFile("illarion.log"));
tempProps.put("log4j.reset", "true");
new PropertyConfigurator().doConfigure(tempProps, LOGGER.getLoggerRepository());
Thread.setDefaultUncaughtExceptionHandler(DefaultCrashHandler.getInstance());
System.out.println("Startup done.");
LOGGER.info(getVersionText() + " started.");
LOGGER.info("VM: " + System.getProperty("java.version"));
LOGGER.info("OS: " + System.getProperty("os.name") + ' ' + System.getProperty("os.version") + ' ' + System
.getProperty("os.arch"));
//java.util.logging.Logger.getAnonymousLogger().getParent().setLevel(Level.SEVERE);
//java.util.logging.Logger.getLogger("de.lessvoid.nifty").setLevel(Level.SEVERE);
java.util.logging.Logger.getLogger("javolution").setLevel(Level.SEVERE);
JavaLogToLog4J.setup();
StdOutToLog4J.setup();
}
public static final String CFG_FULLSCREEN = "fullscreen";
public static final String CFG_RESOLUTION = "resolution";
/**
* Prepare the configuration system and the decryption system.
*/
@SuppressWarnings("nls")
private void prepareConfig() {
cfg = new ConfigSystem(getFile("Illarion.xcfgz"));
cfg.setDefault("debugLevel", 1);
cfg.setDefault("showIDs", false);
cfg.setDefault("soundOn", true);
cfg.setDefault("soundVolume", Player.MAX_CLIENT_VOL);
cfg.setDefault("musicOn", true);
cfg.setDefault("musicVolume", Player.MAX_CLIENT_VOL * 0.75f);
cfg.setDefault(ChatLog.CFG_TEXTLOG, true);
cfg.setDefault(CFG_FULLSCREEN, false);
cfg.setDefault(CFG_RESOLUTION, new GraphicResolution(800, 600, 32, 60).toString());
cfg.setDefault("windowWidth", -1);
cfg.setDefault("windowHeight", -1);
cfg.setDefault("savePassword", false);
cfg.setDefault("showFps", false);
cfg.setDefault(CrashReporter.CFG_KEY, CrashReporter.MODE_ASK);
cfg.setDefault(Lang.LOCALE_CFG, Lang.LOCALE_CFG_ENGLISH);
cfg.setDefault("inventoryPosX", "100px");
cfg.setDefault("inventoryPosY", "10px");
cfg.setDefault("bookDisplayPosX", "150px");
cfg.setDefault("bookDisplayPosY", "15px");
cfg.setDefault("skillWindowPosX", "200px");
cfg.setDefault("skillWindowPosY", "20px");
cfg.setDefault("questWindowPosX", "100px");
cfg.setDefault("questWindowPosY", "100px");
cfg.setDefault("questShowFinished", false);
cfg.setDefault("runAutoAvoid", true);
cfg.setDefault("server", Login.DEVSERVER);
cfg.setDefault("serverAddress", Servers.customserver.getServerHost());
cfg.setDefault("serverPort", Servers.customserver.getServerPort());
cfg.setDefault("clientVersion", Servers.customserver.getClientVersion());
cfg.setDefault("serverAccountLogin", true);
@Nonnull final Toolkit awtDefaultToolkit = Toolkit.getDefaultToolkit();
@Nullable final Object doubleClick = awtDefaultToolkit.getDesktopProperty("awt.multiClickInterval");
if (doubleClick instanceof Number) {
cfg.setDefault("doubleClickInterval", ((Number) doubleClick).intValue());
} else {
cfg.setDefault("doubleClickInterval", 500);
}
final Crypto crypt = new Crypto();
crypt.loadPublicKey();
TableLoader.setCrypto(crypt);
}
@Override
public void onEvent(final String topic, final ConfigChangedEvent data) {
if (CFG_RESOLUTION.equals(topic) || CFG_FULLSCREEN.equals(topic)) {
final String resolutionString = cfg.getString(CFG_RESOLUTION);
if (resolutionString == null) {
LOGGER.error("Failed reading new resolution.");
return;
}
try {
final GraphicResolution res = new GraphicResolution(resolutionString);
final boolean fullScreen = cfg.getBoolean(CFG_FULLSCREEN);
if (fullScreen) {
gameContainer.setFullScreenResolution(res);
gameContainer.setFullScreen(true);
} else {
gameContainer.setWindowSize(res.getWidth(), res.getHeight());
gameContainer.setFullScreen(false);
}
if (!fullScreen) {
cfg.set("windowHeight", res.getHeight());
cfg.set("windowWidth", res.getWidth());
}
} catch (@Nonnull final EngineException e) {
LOGGER.error("Failed to apply graphic mode: " + resolutionString);
} catch (@Nonnull final IllegalArgumentException ex) {
LOGGER.error("Failed to apply graphic mode: " + resolutionString);
}
}
}
}
| false | true | private void init() {
try {
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_EVENT_BUS, new ThreadSafeEventService());
} catch (EventServiceExistsException e1) {
LOGGER.error("Failed preparing the EventBus. Settings the Service handler happened too late");
}
prepareConfig();
assert cfg != null;
try {
initLogfiles();
} catch (IOException e) {
System.err.println("Failed to setup logging system!");
e.printStackTrace(System.err);
}
Lang.getInstance().recheckLocale(cfg.getString(Lang.LOCALE_CFG));
CrashReporter.getInstance().setConfig(getCfg());
// Report errors of the released version only
if (DEFAULT_SERVER != Servers.realserver) {
CrashReporter.getInstance().setMode(CrashReporter.MODE_NEVER);
}
// Preload sound and music
try {
new SongLoader().setTarget(SongFactory.getInstance()).call();
new SoundLoader().setTarget(SoundFactory.getInstance()).call();
} catch (Exception e) {
LOGGER.error("Failed to load sounds and music!");
}
game = new Game();
GraphicResolution res = null;
final String resolutionString = cfg.getString(CFG_RESOLUTION);
if (resolutionString != null) {
try {
res = new GraphicResolution(resolutionString);
} catch (@Nonnull final IllegalArgumentException ex) {
LOGGER.error("Failed to initialize screen resolution. Falling back.");
}
}
if (res == null) {
res = new GraphicResolution(800, 600, 32, 60);
}
try {
final int requestedWidth;
final int requestedHeight;
final boolean fullScreenMode;
if (cfg.getBoolean(CFG_FULLSCREEN)) {
fullScreenMode = true;
requestedHeight = res.getHeight();
requestedWidth = res.getWidth();
} else {
fullScreenMode = false;
final int windowedWidth = cfg.getInteger("windowWidth");
final int windowedHeight = cfg.getInteger("windowHeight");
requestedHeight = (windowedHeight < 0) ? res.getHeight() : windowedHeight;
requestedWidth = (windowedWidth < 0) ? res.getWidth() : windowedWidth;
}
gameContainer = EngineManager.createDesktopGame(Backend.libGDX, game,
requestedWidth, requestedHeight, fullScreenMode);
} catch (@Nonnull final EngineException e) {
LOGGER.error("Fatal error creating game screen!!!", e);
System.exit(-1);
}
gameContainer.setTitle(APPLICATION + ' ' + VERSION);
gameContainer.setIcons(new String[]{"illarion_client16.png", "illarion_client32.png",
"illarion_client64.png", "illarion_client256.png"});
EventBus.subscribe(CFG_FULLSCREEN, this);
EventBus.subscribe(CFG_RESOLUTION, this);
try {
gameContainer.setResizeable(true);
gameContainer.startGame();
} catch (@Nonnull final Exception e) {
LOGGER.fatal("Exception while launching game.", e);
exitGameContainer();
}
}
| private void init() {
try {
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_EVENT_BUS, null);
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_SWING_EVENT_SERVICE, null);
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_EVENT_BUS, new ThreadSafeEventService());
EventServiceLocator.setEventService(EventServiceLocator.SERVICE_NAME_SWING_EVENT_SERVICE,
EventServiceLocator.getEventBusService());
} catch (EventServiceExistsException e1) {
LOGGER.error("Failed preparing the EventBus. Settings the Service handler happened too late");
}
prepareConfig();
assert cfg != null;
try {
initLogfiles();
} catch (IOException e) {
System.err.println("Failed to setup logging system!");
e.printStackTrace(System.err);
}
Lang.getInstance().recheckLocale(cfg.getString(Lang.LOCALE_CFG));
CrashReporter.getInstance().setConfig(getCfg());
// Report errors of the released version only
if (DEFAULT_SERVER != Servers.realserver) {
CrashReporter.getInstance().setMode(CrashReporter.MODE_NEVER);
}
// Preload sound and music
try {
new SongLoader().setTarget(SongFactory.getInstance()).call();
new SoundLoader().setTarget(SoundFactory.getInstance()).call();
} catch (Exception e) {
LOGGER.error("Failed to load sounds and music!");
}
game = new Game();
GraphicResolution res = null;
final String resolutionString = cfg.getString(CFG_RESOLUTION);
if (resolutionString != null) {
try {
res = new GraphicResolution(resolutionString);
} catch (@Nonnull final IllegalArgumentException ex) {
LOGGER.error("Failed to initialize screen resolution. Falling back.");
}
}
if (res == null) {
res = new GraphicResolution(800, 600, 32, 60);
}
try {
final int requestedWidth;
final int requestedHeight;
final boolean fullScreenMode;
if (cfg.getBoolean(CFG_FULLSCREEN)) {
fullScreenMode = true;
requestedHeight = res.getHeight();
requestedWidth = res.getWidth();
} else {
fullScreenMode = false;
final int windowedWidth = cfg.getInteger("windowWidth");
final int windowedHeight = cfg.getInteger("windowHeight");
requestedHeight = (windowedHeight < 0) ? res.getHeight() : windowedHeight;
requestedWidth = (windowedWidth < 0) ? res.getWidth() : windowedWidth;
}
gameContainer = EngineManager.createDesktopGame(Backend.libGDX, game,
requestedWidth, requestedHeight, fullScreenMode);
} catch (@Nonnull final EngineException e) {
LOGGER.error("Fatal error creating game screen!!!", e);
System.exit(-1);
}
gameContainer.setTitle(APPLICATION + ' ' + VERSION);
gameContainer.setIcons(new String[]{"illarion_client16.png", "illarion_client32.png",
"illarion_client64.png", "illarion_client256.png"});
EventBus.subscribe(CFG_FULLSCREEN, this);
EventBus.subscribe(CFG_RESOLUTION, this);
try {
gameContainer.setResizeable(true);
gameContainer.startGame();
} catch (@Nonnull final Exception e) {
LOGGER.fatal("Exception while launching game.", e);
exitGameContainer();
}
}
|
diff --git a/src/main/java/gov/usgs/gdp/analysis/GridCellGeometry.java b/src/main/java/gov/usgs/gdp/analysis/GridCellGeometry.java
index 114d6a76..bb073410 100644
--- a/src/main/java/gov/usgs/gdp/analysis/GridCellGeometry.java
+++ b/src/main/java/gov/usgs/gdp/analysis/GridCellGeometry.java
@@ -1,133 +1,133 @@
package gov.usgs.gdp.analysis;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.geotools.geometry.jts.JTSFactoryFinder;
import ucar.nc2.dataset.CoordinateAxis1D;
import ucar.nc2.dt.GridCoordSystem;
import ucar.unidata.geoloc.LatLonPointImpl;
import ucar.unidata.geoloc.Projection;
import ucar.unidata.geoloc.ProjectionPointImpl;
/**
*
* @author tkunicki
*/
public class GridCellGeometry {
private final GridCoordSystem gridCoordSystem;
private final int xCellCount;
private final int yCellCount;
private final int cellCount;
private Geometry[] cellGeometrys;
public GridCellGeometry(GridCoordSystem gridCoordSystem) {
this.gridCoordSystem = gridCoordSystem;
xCellCount = (int) gridCoordSystem.getXHorizAxis().getSize();
yCellCount = (int) gridCoordSystem.getYHorizAxis().getSize();
cellCount = xCellCount * yCellCount;
cellGeometrys = buildGeometries();
}
public GridCoordSystem getGridCoordSystem() {
return gridCoordSystem;
}
public int getCellCountX() {
return xCellCount;
}
public int getCellCountY() {
return yCellCount;
}
public int getCellCount() {
return cellCount;
}
public Geometry getCellGeometry(int xIndex, int yIndex) {
return cellGeometrys[xIndex + yIndex * xCellCount];
}
private Geometry[] buildGeometries() {
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
CoordinateAxis1D xAxis = (CoordinateAxis1D) gridCoordSystem.getXHorizAxis();
CoordinateAxis1D yAxis = (CoordinateAxis1D) gridCoordSystem.getYHorizAxis();
double[] xCellEdges = xAxis.getCoordEdges();
double[] yCellEdges = yAxis.getCoordEdges();
int xCellEdgeCount = xCellEdges.length;
Geometry[] cellGeometry = new Geometry[cellCount];
final CoordinateBuilder coordinateBuilder = gridCoordSystem.isLatLon()
? new CoordinateBuilder()
: new ProjectedCoordinateBuilder();
Coordinate[] lowerCorner = null;
Coordinate[] upperCorner = new Coordinate[xCellEdgeCount];
// prime data storage for algorithm below...
for (int xCellIndex = 1; xCellIndex < xCellEdgeCount; ++xCellIndex) {
upperCorner[xCellIndex] = coordinateBuilder.getCoordinate(
xCellEdges[xCellIndex], yCellEdges[0]);
}
for (int yIndexLower = 0; yIndexLower < yCellCount; ++yIndexLower) {
int yOffset = xCellCount * yIndexLower;
int yIndexUpper = yIndexLower + 1;
lowerCorner = upperCorner;
upperCorner = new Coordinate[xCellEdgeCount];
lowerCorner[0] = coordinateBuilder.getCoordinate(xCellEdges[0], yCellEdges[yIndexLower]);
- for (int xCellLower = 0; xCellLower < xCellCount; ++xCellLower) {
- int xCellUpper = xCellLower + 1;
- upperCorner[xCellUpper] = coordinateBuilder.getCoordinate(
- xCellEdges[xCellUpper],
+ for (int xIndexLower = 0; xIndexLower < xCellCount; ++xIndexLower) {
+ int xIndexUpper = xIndexLower + 1;
+ upperCorner[xIndexUpper] = coordinateBuilder.getCoordinate(
+ xCellEdges[xIndexUpper],
yCellEdges[yIndexUpper]);
Envelope cellEnvelope = new Envelope(
- lowerCorner[xCellLower],
- upperCorner[xCellUpper]);
- cellGeometry[yOffset + xCellLower] = geometryFactory.toGeometry(cellEnvelope);
+ lowerCorner[xIndexLower],
+ upperCorner[xIndexUpper]);
+ cellGeometry[yOffset + xIndexLower] = geometryFactory.toGeometry(cellEnvelope);
}
}
return cellGeometry;
}
private class CoordinateBuilder {
public Coordinate getCoordinate(double x, double y) {
return new Coordinate(x, y);
}
}
private class ProjectedCoordinateBuilder extends CoordinateBuilder {
private Projection projection;
private ProjectionPointImpl projectionPoint;
private LatLonPointImpl latLonPoint;
public ProjectedCoordinateBuilder() {
projection = gridCoordSystem.getProjection();
projectionPoint = new ProjectionPointImpl();
latLonPoint = new LatLonPointImpl();
}
@Override
public Coordinate getCoordinate(double x, double y) {
projectionPoint.setLocation(x, y);
projection.projToLatLon(projectionPoint, latLonPoint);
return super.getCoordinate(latLonPoint.getLongitude(), latLonPoint.getLatitude());
}
}
}
| false | true | private Geometry[] buildGeometries() {
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
CoordinateAxis1D xAxis = (CoordinateAxis1D) gridCoordSystem.getXHorizAxis();
CoordinateAxis1D yAxis = (CoordinateAxis1D) gridCoordSystem.getYHorizAxis();
double[] xCellEdges = xAxis.getCoordEdges();
double[] yCellEdges = yAxis.getCoordEdges();
int xCellEdgeCount = xCellEdges.length;
Geometry[] cellGeometry = new Geometry[cellCount];
final CoordinateBuilder coordinateBuilder = gridCoordSystem.isLatLon()
? new CoordinateBuilder()
: new ProjectedCoordinateBuilder();
Coordinate[] lowerCorner = null;
Coordinate[] upperCorner = new Coordinate[xCellEdgeCount];
// prime data storage for algorithm below...
for (int xCellIndex = 1; xCellIndex < xCellEdgeCount; ++xCellIndex) {
upperCorner[xCellIndex] = coordinateBuilder.getCoordinate(
xCellEdges[xCellIndex], yCellEdges[0]);
}
for (int yIndexLower = 0; yIndexLower < yCellCount; ++yIndexLower) {
int yOffset = xCellCount * yIndexLower;
int yIndexUpper = yIndexLower + 1;
lowerCorner = upperCorner;
upperCorner = new Coordinate[xCellEdgeCount];
lowerCorner[0] = coordinateBuilder.getCoordinate(xCellEdges[0], yCellEdges[yIndexLower]);
for (int xCellLower = 0; xCellLower < xCellCount; ++xCellLower) {
int xCellUpper = xCellLower + 1;
upperCorner[xCellUpper] = coordinateBuilder.getCoordinate(
xCellEdges[xCellUpper],
yCellEdges[yIndexUpper]);
Envelope cellEnvelope = new Envelope(
lowerCorner[xCellLower],
upperCorner[xCellUpper]);
cellGeometry[yOffset + xCellLower] = geometryFactory.toGeometry(cellEnvelope);
}
}
return cellGeometry;
}
| private Geometry[] buildGeometries() {
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
CoordinateAxis1D xAxis = (CoordinateAxis1D) gridCoordSystem.getXHorizAxis();
CoordinateAxis1D yAxis = (CoordinateAxis1D) gridCoordSystem.getYHorizAxis();
double[] xCellEdges = xAxis.getCoordEdges();
double[] yCellEdges = yAxis.getCoordEdges();
int xCellEdgeCount = xCellEdges.length;
Geometry[] cellGeometry = new Geometry[cellCount];
final CoordinateBuilder coordinateBuilder = gridCoordSystem.isLatLon()
? new CoordinateBuilder()
: new ProjectedCoordinateBuilder();
Coordinate[] lowerCorner = null;
Coordinate[] upperCorner = new Coordinate[xCellEdgeCount];
// prime data storage for algorithm below...
for (int xCellIndex = 1; xCellIndex < xCellEdgeCount; ++xCellIndex) {
upperCorner[xCellIndex] = coordinateBuilder.getCoordinate(
xCellEdges[xCellIndex], yCellEdges[0]);
}
for (int yIndexLower = 0; yIndexLower < yCellCount; ++yIndexLower) {
int yOffset = xCellCount * yIndexLower;
int yIndexUpper = yIndexLower + 1;
lowerCorner = upperCorner;
upperCorner = new Coordinate[xCellEdgeCount];
lowerCorner[0] = coordinateBuilder.getCoordinate(xCellEdges[0], yCellEdges[yIndexLower]);
for (int xIndexLower = 0; xIndexLower < xCellCount; ++xIndexLower) {
int xIndexUpper = xIndexLower + 1;
upperCorner[xIndexUpper] = coordinateBuilder.getCoordinate(
xCellEdges[xIndexUpper],
yCellEdges[yIndexUpper]);
Envelope cellEnvelope = new Envelope(
lowerCorner[xIndexLower],
upperCorner[xIndexUpper]);
cellGeometry[yOffset + xIndexLower] = geometryFactory.toGeometry(cellEnvelope);
}
}
return cellGeometry;
}
|
diff --git a/web/src/main/java/org/fao/geonet/services/metadata/Update.java b/web/src/main/java/org/fao/geonet/services/metadata/Update.java
index 047a7a40ad..4dd35ead36 100644
--- a/web/src/main/java/org/fao/geonet/services/metadata/Update.java
+++ b/web/src/main/java/org/fao/geonet/services/metadata/Update.java
@@ -1,127 +1,128 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.metadata;
import jeeves.constants.Jeeves;
import jeeves.interfaces.Service;
import jeeves.resources.dbms.Dbms;
import jeeves.server.ServiceConfig;
import jeeves.server.UserSession;
import jeeves.server.context.ServiceContext;
import jeeves.utils.Util;
import jeeves.utils.Xml;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.constants.Params;
import org.fao.geonet.exceptions.ConcurrentUpdateEx;
import org.fao.geonet.kernel.DataManager;
import org.jdom.Element;
//=============================================================================
/** For editing : update leaves information. Access is restricted
*/
public class Update implements Service
{
private ServiceConfig config;
//--------------------------------------------------------------------------
//---
//--- Init
//---
//--------------------------------------------------------------------------
public void init(String appPath, ServiceConfig params) throws Exception
{
config = params;
}
//--------------------------------------------------------------------------
//---
//--- Service
//---
//--------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context) throws Exception
{
AjaxEditUtils ajaxEditUtils = new AjaxEditUtils(context);
ajaxEditUtils.preprocessUpdate(params, context);
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
UserSession session = context.getUserSession();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
String id = Util.getParam(params, Params.ID);
String version = Util.getParam(params, Params.VERSION);
String isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String showValidationErrors = Util.getParam(params, Params.SHOWVALIDATIONERRORS, "false");
String title = params.getChildText(Params.TITLE);
String data = params.getChildText(Params.DATA);
boolean finished = config.getValue(Params.FINISHED, "no").equals("yes");
boolean forget = config.getValue(Params.FORGET, "no").equals("yes");
if (!forget) {
dataMan.setTemplateExt(dbms, Integer.parseInt(id), isTemplate, title);
if (data != null) {
Element md = Xml.loadString(data, false);
String changeDate = null;
- boolean validate = true;
+ boolean validate = showValidationErrors.equals("true");
boolean ufo = true;
boolean index = true;
- if (!dataMan.updateMetadata(context.getUserSession(), dbms, id, md, validate, ufo, index, context.getLanguage(), changeDate));
+ if (!dataMan.updateMetadata(context.getUserSession(), dbms, id, md, validate, ufo, index, context.getLanguage(), changeDate)) {
throw new ConcurrentUpdateEx(id);
+ }
}
else {
ajaxEditUtils.updateContent(params, false, true);
}
}
//-----------------------------------------------------------------------
//--- update element and return status
Element elResp = new Element(Jeeves.Elem.RESPONSE);
elResp.addContent(new Element(Geonet.Elem.ID).setText(id));
elResp.addContent(new Element(Geonet.Elem.SHOWVALIDATIONERRORS).setText(showValidationErrors));
boolean justCreated = Util.getParam(params, Params.JUST_CREATED, null) != null ;
if(justCreated) {
elResp.addContent(new Element(Geonet.Elem.JUSTCREATED).setText("true"));
}
//--- if finished then remove the XML from the session
if (finished) {
ajaxEditUtils.removeMetadataEmbedded(session, id);
}
return elResp;
}
}
//=============================================================================
| false | true | public Element exec(Element params, ServiceContext context) throws Exception
{
AjaxEditUtils ajaxEditUtils = new AjaxEditUtils(context);
ajaxEditUtils.preprocessUpdate(params, context);
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
UserSession session = context.getUserSession();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
String id = Util.getParam(params, Params.ID);
String version = Util.getParam(params, Params.VERSION);
String isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String showValidationErrors = Util.getParam(params, Params.SHOWVALIDATIONERRORS, "false");
String title = params.getChildText(Params.TITLE);
String data = params.getChildText(Params.DATA);
boolean finished = config.getValue(Params.FINISHED, "no").equals("yes");
boolean forget = config.getValue(Params.FORGET, "no").equals("yes");
if (!forget) {
dataMan.setTemplateExt(dbms, Integer.parseInt(id), isTemplate, title);
if (data != null) {
Element md = Xml.loadString(data, false);
String changeDate = null;
boolean validate = true;
boolean ufo = true;
boolean index = true;
if (!dataMan.updateMetadata(context.getUserSession(), dbms, id, md, validate, ufo, index, context.getLanguage(), changeDate));
throw new ConcurrentUpdateEx(id);
}
else {
ajaxEditUtils.updateContent(params, false, true);
}
}
//-----------------------------------------------------------------------
//--- update element and return status
Element elResp = new Element(Jeeves.Elem.RESPONSE);
elResp.addContent(new Element(Geonet.Elem.ID).setText(id));
elResp.addContent(new Element(Geonet.Elem.SHOWVALIDATIONERRORS).setText(showValidationErrors));
boolean justCreated = Util.getParam(params, Params.JUST_CREATED, null) != null ;
if(justCreated) {
elResp.addContent(new Element(Geonet.Elem.JUSTCREATED).setText("true"));
}
//--- if finished then remove the XML from the session
if (finished) {
ajaxEditUtils.removeMetadataEmbedded(session, id);
}
return elResp;
}
| public Element exec(Element params, ServiceContext context) throws Exception
{
AjaxEditUtils ajaxEditUtils = new AjaxEditUtils(context);
ajaxEditUtils.preprocessUpdate(params, context);
GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
DataManager dataMan = gc.getDataManager();
UserSession session = context.getUserSession();
Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
String id = Util.getParam(params, Params.ID);
String version = Util.getParam(params, Params.VERSION);
String isTemplate = Util.getParam(params, Params.TEMPLATE, "n");
String showValidationErrors = Util.getParam(params, Params.SHOWVALIDATIONERRORS, "false");
String title = params.getChildText(Params.TITLE);
String data = params.getChildText(Params.DATA);
boolean finished = config.getValue(Params.FINISHED, "no").equals("yes");
boolean forget = config.getValue(Params.FORGET, "no").equals("yes");
if (!forget) {
dataMan.setTemplateExt(dbms, Integer.parseInt(id), isTemplate, title);
if (data != null) {
Element md = Xml.loadString(data, false);
String changeDate = null;
boolean validate = showValidationErrors.equals("true");
boolean ufo = true;
boolean index = true;
if (!dataMan.updateMetadata(context.getUserSession(), dbms, id, md, validate, ufo, index, context.getLanguage(), changeDate)) {
throw new ConcurrentUpdateEx(id);
}
}
else {
ajaxEditUtils.updateContent(params, false, true);
}
}
//-----------------------------------------------------------------------
//--- update element and return status
Element elResp = new Element(Jeeves.Elem.RESPONSE);
elResp.addContent(new Element(Geonet.Elem.ID).setText(id));
elResp.addContent(new Element(Geonet.Elem.SHOWVALIDATIONERRORS).setText(showValidationErrors));
boolean justCreated = Util.getParam(params, Params.JUST_CREATED, null) != null ;
if(justCreated) {
elResp.addContent(new Element(Geonet.Elem.JUSTCREATED).setText("true"));
}
//--- if finished then remove the XML from the session
if (finished) {
ajaxEditUtils.removeMetadataEmbedded(session, id);
}
return elResp;
}
|
diff --git a/galapagos/GalapagosFrame.java b/galapagos/GalapagosFrame.java
index a6d6f4a..7df373c 100644
--- a/galapagos/GalapagosFrame.java
+++ b/galapagos/GalapagosFrame.java
@@ -1,402 +1,402 @@
package galapagos;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
/**
* A graphical user-interface for creating and viewing Biotope's.
* At the top of the screen there are a set of buttons for creating and simulating the Biotope.
* At the middle of the screen the Biotope is shown graphically.
* At the bottom of the screen there are a panel with statistics about the different types of behaviors
* Its possible to spawn new Finches by choosing a behavior on the right and "draw" them on the Biotope.
* On the left part of the screen you can turn on and of the graphical display and the logger (for performance),
* its also here you change the updaterate.
*
*/
public class GalapagosFrame extends JFrame implements Observer {
private AreaPanel area;
public TreeMap<String, Color> colorMap;
public int pixelSize;
private NicerStatisticsPanel statistics;
private BiotopeLogger logger;
private BiotopeController controller;
public final BiotopeCreator biotopeCreator;
private Biotope biotope;
private JButton newBiotope;
private JButton nextRound;
private JSpinner numberOfRounds;
private JButton severalRounds;
private JButton unlimitedRounds;
private JButton stopRounds;
private JCheckBox toggleLogging;
private JCheckBox toggleDisplayRefresh;
private JSpinner timerInterval;
private ButtonGroup behaviorButtons;
private Container behaviorButtonsBox;
private JLabel behaviorButtonsLabel;
private Behavior selectedBehavior;
private boolean isLogging;
private boolean isRefreshing;
private static final Dimension minimumButtonDimension = new Dimension(0,30);
private static final Dimension standardSpinnerSize = new Dimension(100,22);
private List<Behavior> behaviors;
/**
* Create a GalapagosFrame simulating finches with the provided
* behaviors and using the provided colors to visually represent
* the simulation state.
*
* @param behaviors A mapping from behavior objects to colors. The
* behavior objects specify which behaviors should be available
* for use in the simulation (the user may choose to disable some
* of them, so they are not guaranteed to participate in the run),
* and the associated color will be used to draw a visual
* representation of finches with that behavior.
*
* @require For every two distrinct behavior objects b1, b2 in
* behaviors, b1.toString() != b2.toString() must hold.
*/
public GalapagosFrame(Map<Behavior, Color> behaviors)
{
makeBehaviorListAndColorMap(behaviors);
pixelSize = 5;
isRefreshing = true;
area = new AreaPanel();
MouseInputAdapter listener = new MouseInputAdapter () {
public void maybeAddFinchAt(int x, int y, Behavior b) {
// Only add a finch if x,y is within the bounds of
// the world.
if (0 <= x && x < biotope.world.width() &&
0 <= y && y < biotope.world.height())
biotope.putFinch(x, y, b.clone());
}
public void mousePressed(MouseEvent e) {
maybeAddFinchAt(e.getX() / pixelSize, e.getY() / pixelSize,
selectedBehavior);
}
public void mouseDragged(MouseEvent e) {
maybeAddFinchAt(e.getX() / pixelSize, e.getY() / pixelSize,
selectedBehavior);
}
};
area.addMouseListener(listener);
area.addMouseMotionListener(listener);
statistics = new NicerStatisticsPanel(colorMap);
logger = new BiotopeLogger();
controller = new BiotopeController(biotope);
this.setLayout(new BorderLayout());
this.doLayout();
this.addWindowListener(new Terminator());
this.setTitle("Galapagos Finch Simulator");
initializeControls();
// Create a new Biotope with the default-settings of the BiotopeCreator.
biotopeCreator = new BiotopeCreator(this.behaviors);
setBiotope(biotopeCreator.createBiotope());
}
public void setBiotope(Biotope biotope)
{
this.biotope = biotope;
//Create RadioButton's on the GalapagosFrame
//for the spawning-tool
behaviorButtons = new ButtonGroup();
behaviorButtonsBox.removeAll();
behaviorButtonsBox.add(Box.createGlue());
behaviorButtonsBox.add(behaviorButtonsLabel);
for (final Behavior b : biotope.behaviors()) {
JRadioButton button = new JRadioButton(b.toString());
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedBehavior = b;
}
});
behaviorButtons.add(button);
behaviorButtonsBox.add(button);
}
behaviorButtonsBox.add(Box.createGlue());
selectedBehavior = null;
controller.setBiotope(biotope);
area.reset(biotope.world.width(), biotope.world.height(), pixelSize);
biotope.addObserver(statistics);
if (isLogging)
biotope.addObserver(logger);
if (isRefreshing)
biotope.addObserver(this);
biotope.doNotifyObservers();
this.setSize(combinedSize());
this.validate();
}
/**
* Create and position the controls of the main interface.
*/
private void initializeControls()
{
//create top controls
newBiotope = newButton ("New Biotope", "newBiotope");
newBiotope = new JButton("New Biotope");
newBiotope.setActionCommand("newBiotope");
newBiotope.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
disableButtons();
biotopeCreator.setVisible(true);
Biotope biotope = biotopeCreator.biotope();
if(biotope != GalapagosFrame.this.biotope && biotope != null)
GalapagosFrame.this.setBiotope(biotope);
enableButtons();
}
});
nextRound = newButton ("Next Round", "nextRound");
severalRounds = newButton ("Compute Several Rounds", "severalRounds");
unlimitedRounds = newButton ("Go!", "unlimitedRounds");
stopRounds = newButton ("Stop Simulation", "stopRounds");
numberOfRounds = new JSpinner(new RevisedSpinnerNumberModel(50,0,Integer.MAX_VALUE,10));
numberOfRounds.setPreferredSize(standardSpinnerSize);
numberOfRounds.setName("numberOfRoundsSpinner");
numberOfRounds.addChangeListener(controller);
numberOfRounds.setMaximumSize(new Dimension(100,30));
numberOfRounds.setMinimumSize(minimumButtonDimension);
toggleLogging = new JCheckBox("Perform logging", isLogging);
toggleLogging.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isLogging)
biotope.deleteObserver(logger);
else
biotope.addObserver(logger);
isLogging = !isLogging;
}
});
toggleDisplayRefresh = new JCheckBox("Update display", isRefreshing);
toggleDisplayRefresh.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isRefreshing)
biotope.deleteObserver(GalapagosFrame.this);
else
biotope.addObserver(GalapagosFrame.this);
isRefreshing = !isRefreshing;
}
});
timerInterval = new JSpinner(new RevisedSpinnerNumberModel(200,0,Integer.MAX_VALUE,100));
timerInterval.setPreferredSize(standardSpinnerSize);
timerInterval.setMaximumSize(new Dimension(100,30));
timerInterval.setMinimumSize(minimumButtonDimension);
timerInterval.addChangeListener(controller);
- numberOfRounds.setName("timerIntervalSpinner");
+ timerInterval.setName("timerIntervalSpinner");
Container topContainer = Box.createHorizontalBox();
topContainer.add(Box.createGlue());
topContainer.add(newBiotope);
topContainer.add(nextRound);
topContainer.add(numberOfRounds);
topContainer.add(severalRounds);
topContainer.add(unlimitedRounds);
topContainer.add(stopRounds);
topContainer.add(Box.createGlue());
//this container's only purpose is to center area
Container centerContainer = new Container();
centerContainer.setLayout(new GridBagLayout());
centerContainer.add(area);
JPanel leftContainer = new JPanel(new GridBagLayout());
leftContainer.add(toggleLogging, getComponentConstraints(0,0, GridBagConstraints.CENTER));
leftContainer.add(toggleDisplayRefresh, getComponentConstraints(0,1, GridBagConstraints.CENTER));
leftContainer.add(new JLabel("Milliseconds between rounds"), getComponentConstraints(0,2, GridBagConstraints.CENTER));
leftContainer.add(timerInterval,getComponentConstraints(0,3, GridBagConstraints.CENTER));
leftContainer.setMaximumSize(leftContainer.getPreferredSize());
Container outerLeftContainer = Box.createVerticalBox();
outerLeftContainer.add(Box.createGlue());
outerLeftContainer.add(leftContainer);
outerLeftContainer.add(Box.createGlue());
behaviorButtonsBox = Box.createVerticalBox();
behaviorButtonsLabel = new JLabel("Pencil for freehand finch drawing");
this.add(topContainer, BorderLayout.NORTH);
this.add(centerContainer,BorderLayout.CENTER);
this.add(statistics, BorderLayout.SOUTH);
this.add(outerLeftContainer, BorderLayout.WEST);
this.add(behaviorButtonsBox, BorderLayout.EAST);
}
/**
* Create a new JButton with the specified text and actionCommand.
*
* @param text The button's text
* @param command The button's actionCommand
* @return The new JButton
*/
public JButton newButton(String text, String command)
{
JButton button = new JButton(text);
button.setActionCommand(command);
button.addActionListener(this.controller);
button.setMinimumSize(minimumButtonDimension);
return button;
}
/**
* A set of GridBagConstraints for use with the GridBagLayout. Recommended for single components.
* @param x the horisontal position of the component.
* @param y the vertical position of the component.
* @param alignment the alignment of the component in its display area.
*/
private GridBagConstraints getComponentConstraints (int x, int y, int alignment) {
return new GridBagConstraints(x, y, 1, 1, 1.0, 1.0,
alignment,
GridBagConstraints.NONE,
new Insets(5,5,5,5),
0, 0);
}
public void update(Observable observableBiotope, Object arg)
{
Biotope biotope = (Biotope) observableBiotope;
for(World<GalapagosFinch>.Place place : biotope.world)
{
GalapagosFinch element = place.getElement();
if(element != null)
area.pixel(place.xPosition(), place.yPosition(), colorByBehavior(element.behavior()));
else
area.pixel(place.xPosition(), place.yPosition(), Color.BLACK);
}
area.update();
}
/**
* Get the color associated with the behavior
* @param behavior The behavior to look-up in the ColorMap
* @return The color associated with behavior.
* @require colorMap.containsKey(behavior)
* @ensure colorByBehavior(behavior).equals(colorMap.get(behavior.toString())
*/
public Color colorByBehavior(Behavior behavior)
{
Color c = colorMap.get(behavior.toString());
assert c != null : "Color not defined for this Behavior";
return c;
}
/**
* Maps each color in the behaviors-map to the associated behaviors name (Behavior.toString()).
*
* @require For every two distrinct behavior objects b1, b2 in
* behaviors, b1.toString() != b2.toString() must hold.
*
* @ensure this.colorByBehavior(b).equals(behaviors.get(b)) for all Behavior objects b in behaviors.
*/
private void makeBehaviorListAndColorMap(Map<Behavior, Color> behaviors)
{
this.behaviors = new ArrayList<Behavior>();
this.colorMap = new TreeMap<String, Color>();
Behavior currentBehavior;
//go through all the behaviors in the behaviors-map and add its string representation to new map
for(Map.Entry<Behavior, Color> entry : behaviors.entrySet()) {
currentBehavior = entry.getKey();
assert !this.colorMap.containsKey(currentBehavior.toString()) : "Duplicate behaviors in Behavior-Color Map";
this.behaviors.add(currentBehavior);
this.colorMap.put(currentBehavior.toString(), entry.getValue());
}
}
/**
* Get the number of rounds specified by the numberOfRounds-textfield
* @return
*/
public int getNumberOfRounds () {
return ((SpinnerNumberModel) numberOfRounds.getModel()).getNumber().intValue();
}
/**
* Get the timer interval specified by the timerInterval-textfield
* @return
*/
public int getTimerInterval () {
return ((SpinnerNumberModel) timerInterval.getModel()).getNumber().intValue();
}
/**
* Disable the control buttons of this frame. The biotope-simulation is stopped.
*/
public void disableButtons() {
newBiotope.setEnabled(false);
nextRound.setEnabled(false);
numberOfRounds.setEnabled(false);
severalRounds.setEnabled(false);
unlimitedRounds.setEnabled(false);
stopRounds.doClick();
stopRounds.setEnabled(false);
}
/**
* Enable the control buttons of this frame. The biotope-simulation is stopped.
*/
public void enableButtons() {
newBiotope.setEnabled(true);
nextRound.setEnabled(true);
numberOfRounds.setEnabled(true);
severalRounds.setEnabled(true);
unlimitedRounds.setEnabled(true);
stopRounds.setEnabled(true);
}
/**
* Get the combined size of all components preferred sizes plus 50 extra pixels in width and height.
*/
public Dimension combinedSize() {
BorderLayout layout = (BorderLayout) this.getContentPane().getLayout();
Dimension centerDim = layout.getLayoutComponent(BorderLayout.CENTER).getPreferredSize();
Dimension topDim = layout.getLayoutComponent(BorderLayout.NORTH).getPreferredSize();
Dimension leftDim = layout.getLayoutComponent(BorderLayout.WEST).getPreferredSize();
Dimension rightDim = layout.getLayoutComponent(BorderLayout.EAST).getPreferredSize();
Dimension bottomDim = layout.getLayoutComponent(BorderLayout.SOUTH).getPreferredSize();
int width = 50 + Math.max(leftDim.width + centerDim.width + rightDim.width, Math.max(topDim.width, bottomDim.width));
int height = 50 + Math.max(topDim.height + centerDim.height + bottomDim.height, Math.max(leftDim.height, rightDim.height));
return new Dimension(width, height);
}
/**
* Get the BiotopeController used in this GalapagosFrame.
*/
public BiotopeController controller() {
return controller;
}
/**
* Get the Biotope simulated in this GalapagosFrame.
*/
public Biotope biotope() {
return biotope;
}
}
| true | true | private void initializeControls()
{
//create top controls
newBiotope = newButton ("New Biotope", "newBiotope");
newBiotope = new JButton("New Biotope");
newBiotope.setActionCommand("newBiotope");
newBiotope.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
disableButtons();
biotopeCreator.setVisible(true);
Biotope biotope = biotopeCreator.biotope();
if(biotope != GalapagosFrame.this.biotope && biotope != null)
GalapagosFrame.this.setBiotope(biotope);
enableButtons();
}
});
nextRound = newButton ("Next Round", "nextRound");
severalRounds = newButton ("Compute Several Rounds", "severalRounds");
unlimitedRounds = newButton ("Go!", "unlimitedRounds");
stopRounds = newButton ("Stop Simulation", "stopRounds");
numberOfRounds = new JSpinner(new RevisedSpinnerNumberModel(50,0,Integer.MAX_VALUE,10));
numberOfRounds.setPreferredSize(standardSpinnerSize);
numberOfRounds.setName("numberOfRoundsSpinner");
numberOfRounds.addChangeListener(controller);
numberOfRounds.setMaximumSize(new Dimension(100,30));
numberOfRounds.setMinimumSize(minimumButtonDimension);
toggleLogging = new JCheckBox("Perform logging", isLogging);
toggleLogging.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isLogging)
biotope.deleteObserver(logger);
else
biotope.addObserver(logger);
isLogging = !isLogging;
}
});
toggleDisplayRefresh = new JCheckBox("Update display", isRefreshing);
toggleDisplayRefresh.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isRefreshing)
biotope.deleteObserver(GalapagosFrame.this);
else
biotope.addObserver(GalapagosFrame.this);
isRefreshing = !isRefreshing;
}
});
timerInterval = new JSpinner(new RevisedSpinnerNumberModel(200,0,Integer.MAX_VALUE,100));
timerInterval.setPreferredSize(standardSpinnerSize);
timerInterval.setMaximumSize(new Dimension(100,30));
timerInterval.setMinimumSize(minimumButtonDimension);
timerInterval.addChangeListener(controller);
numberOfRounds.setName("timerIntervalSpinner");
Container topContainer = Box.createHorizontalBox();
topContainer.add(Box.createGlue());
topContainer.add(newBiotope);
topContainer.add(nextRound);
topContainer.add(numberOfRounds);
topContainer.add(severalRounds);
topContainer.add(unlimitedRounds);
topContainer.add(stopRounds);
topContainer.add(Box.createGlue());
//this container's only purpose is to center area
Container centerContainer = new Container();
centerContainer.setLayout(new GridBagLayout());
centerContainer.add(area);
JPanel leftContainer = new JPanel(new GridBagLayout());
leftContainer.add(toggleLogging, getComponentConstraints(0,0, GridBagConstraints.CENTER));
leftContainer.add(toggleDisplayRefresh, getComponentConstraints(0,1, GridBagConstraints.CENTER));
leftContainer.add(new JLabel("Milliseconds between rounds"), getComponentConstraints(0,2, GridBagConstraints.CENTER));
leftContainer.add(timerInterval,getComponentConstraints(0,3, GridBagConstraints.CENTER));
leftContainer.setMaximumSize(leftContainer.getPreferredSize());
Container outerLeftContainer = Box.createVerticalBox();
outerLeftContainer.add(Box.createGlue());
outerLeftContainer.add(leftContainer);
outerLeftContainer.add(Box.createGlue());
behaviorButtonsBox = Box.createVerticalBox();
behaviorButtonsLabel = new JLabel("Pencil for freehand finch drawing");
this.add(topContainer, BorderLayout.NORTH);
this.add(centerContainer,BorderLayout.CENTER);
this.add(statistics, BorderLayout.SOUTH);
this.add(outerLeftContainer, BorderLayout.WEST);
this.add(behaviorButtonsBox, BorderLayout.EAST);
}
| private void initializeControls()
{
//create top controls
newBiotope = newButton ("New Biotope", "newBiotope");
newBiotope = new JButton("New Biotope");
newBiotope.setActionCommand("newBiotope");
newBiotope.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
disableButtons();
biotopeCreator.setVisible(true);
Biotope biotope = biotopeCreator.biotope();
if(biotope != GalapagosFrame.this.biotope && biotope != null)
GalapagosFrame.this.setBiotope(biotope);
enableButtons();
}
});
nextRound = newButton ("Next Round", "nextRound");
severalRounds = newButton ("Compute Several Rounds", "severalRounds");
unlimitedRounds = newButton ("Go!", "unlimitedRounds");
stopRounds = newButton ("Stop Simulation", "stopRounds");
numberOfRounds = new JSpinner(new RevisedSpinnerNumberModel(50,0,Integer.MAX_VALUE,10));
numberOfRounds.setPreferredSize(standardSpinnerSize);
numberOfRounds.setName("numberOfRoundsSpinner");
numberOfRounds.addChangeListener(controller);
numberOfRounds.setMaximumSize(new Dimension(100,30));
numberOfRounds.setMinimumSize(minimumButtonDimension);
toggleLogging = new JCheckBox("Perform logging", isLogging);
toggleLogging.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isLogging)
biotope.deleteObserver(logger);
else
biotope.addObserver(logger);
isLogging = !isLogging;
}
});
toggleDisplayRefresh = new JCheckBox("Update display", isRefreshing);
toggleDisplayRefresh.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
if (isRefreshing)
biotope.deleteObserver(GalapagosFrame.this);
else
biotope.addObserver(GalapagosFrame.this);
isRefreshing = !isRefreshing;
}
});
timerInterval = new JSpinner(new RevisedSpinnerNumberModel(200,0,Integer.MAX_VALUE,100));
timerInterval.setPreferredSize(standardSpinnerSize);
timerInterval.setMaximumSize(new Dimension(100,30));
timerInterval.setMinimumSize(minimumButtonDimension);
timerInterval.addChangeListener(controller);
timerInterval.setName("timerIntervalSpinner");
Container topContainer = Box.createHorizontalBox();
topContainer.add(Box.createGlue());
topContainer.add(newBiotope);
topContainer.add(nextRound);
topContainer.add(numberOfRounds);
topContainer.add(severalRounds);
topContainer.add(unlimitedRounds);
topContainer.add(stopRounds);
topContainer.add(Box.createGlue());
//this container's only purpose is to center area
Container centerContainer = new Container();
centerContainer.setLayout(new GridBagLayout());
centerContainer.add(area);
JPanel leftContainer = new JPanel(new GridBagLayout());
leftContainer.add(toggleLogging, getComponentConstraints(0,0, GridBagConstraints.CENTER));
leftContainer.add(toggleDisplayRefresh, getComponentConstraints(0,1, GridBagConstraints.CENTER));
leftContainer.add(new JLabel("Milliseconds between rounds"), getComponentConstraints(0,2, GridBagConstraints.CENTER));
leftContainer.add(timerInterval,getComponentConstraints(0,3, GridBagConstraints.CENTER));
leftContainer.setMaximumSize(leftContainer.getPreferredSize());
Container outerLeftContainer = Box.createVerticalBox();
outerLeftContainer.add(Box.createGlue());
outerLeftContainer.add(leftContainer);
outerLeftContainer.add(Box.createGlue());
behaviorButtonsBox = Box.createVerticalBox();
behaviorButtonsLabel = new JLabel("Pencil for freehand finch drawing");
this.add(topContainer, BorderLayout.NORTH);
this.add(centerContainer,BorderLayout.CENTER);
this.add(statistics, BorderLayout.SOUTH);
this.add(outerLeftContainer, BorderLayout.WEST);
this.add(behaviorButtonsBox, BorderLayout.EAST);
}
|
diff --git a/MobileLoggerServer/src/main/java/cs/wintoosa/service/SessionService.java b/MobileLoggerServer/src/main/java/cs/wintoosa/service/SessionService.java
index 274b515..77a1471 100644
--- a/MobileLoggerServer/src/main/java/cs/wintoosa/service/SessionService.java
+++ b/MobileLoggerServer/src/main/java/cs/wintoosa/service/SessionService.java
@@ -1,188 +1,188 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cs.wintoosa.service;
import cs.wintoosa.domain.Acceleration;
import cs.wintoosa.domain.Compass;
import cs.wintoosa.domain.Gps;
import cs.wintoosa.domain.KeyPress;
import cs.wintoosa.domain.Keyboard;
import cs.wintoosa.domain.Log;
import cs.wintoosa.domain.Orientation;
import cs.wintoosa.domain.SessionLog;
import cs.wintoosa.domain.Touch;
import java.util.List;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author vkukkola
*/
@Service
public class SessionService implements ISessionService {
@Autowired
ILogService logService;
@Override
public DataHolder formatForJsp(SessionLog session) {
DataHolder data = new DataHolder(session);
if (session != null) {
List<Acceleration> accLogs = pullFromDb(Acceleration.class, data);
List<Compass> comLogs = pullFromDb(Compass.class, data);
List<KeyPress> keyPresses = pullFromDb(KeyPress.class, data);
List<Keyboard> keyboards = pullFromDb(Keyboard.class, data);
List<Orientation> gyroLogs = pullFromDb(Orientation.class, data);
List<Gps> gpsLogs = pullFromDb(Gps.class, data);
List<Touch> touchLogs = pullFromDb(Touch.class, data);
int accI = 0;
int comI = 0;
int pressI = 0;
int keybI = 0;
int gyroI = 0;
int gpsI = 0;
int touchI = 0;
for (Long time : data.getTimestamps()) {
if (accLogs != null && accLogs.size() > accI && (accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
while ((accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
if ((accLogs.get(accI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Acc X", accLogs.get(accI).getAccX().toString());
data.addToColumn("Acc Y", accLogs.get(accI).getAccY().toString());
data.addToColumn("Acc Z", accLogs.get(accI).getAccZ().toString());
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
accI++;
if (accLogs.size() >= accI)
break;
}
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
if (comLogs != null && comLogs.size() > comI && (comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
while ((comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
if ((comLogs.get(comI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Heading, true", comLogs.get(comI).getTrueHeading().toString());
data.addToColumn("Heading, magnetic", comLogs.get(comI).getMagneticHeading().toString());
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
comI++;
if (comLogs.size() >= comI)
break;
}
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
if (keyPresses != null && keyPresses.size() > pressI && (keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
while ((keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
if ((keyPresses.get(pressI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Key pressed", keyPresses.get(pressI).getKeyPressed());
} else {
- data.addToColumn("key pressed", "");
+ data.addToColumn("Key pressed", "");
}
pressI++;
if (keyPresses.size() >= pressI)
break;
}
} else {
- data.addToColumn("key pressed", "");
+ data.addToColumn("Key pressed", "");
}
- if (keyboards != null && keyboards.size() > keybI) {
+ if (keyboards != null && keyboards.size() > keybI && (keyboards.get(keybI).getTimestamp() / 10) * 10 <= time) {
while ((keyboards.get(keybI).getTimestamp() / 10) * 10 <= time) {
if ((keyboards.get(keybI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Keyboard status", keyboards.get(keybI).getKeyboardFocus());
} else {
data.addToColumn("Keyboard status", "");
}
keybI++;
if (keyboards.size() >= keybI)
break;
}
} else {
data.addToColumn("Keyboard status", "");
}
if (gyroLogs != null && gyroLogs.size() > gyroI && (gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
while ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
if ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Gyro X", gyroLogs.get(gyroI).getCurrentRotationRateX().toString());
data.addToColumn("Gyro Y", gyroLogs.get(gyroI).getCurrentRotationRateY().toString());
data.addToColumn("Gyro Z", gyroLogs.get(gyroI).getCurrentRotationRateZ().toString());
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
gyroI++;
if (gyroLogs.size() >= gyroI)
break;
}
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
if (gpsLogs != null && gpsLogs.size() > gpsI && (gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
while ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
if ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("gps Latitude", gpsLogs.get(gpsI).getLat().toString());
data.addToColumn("gps Longitude", gpsLogs.get(gpsI).getLon().toString());
data.addToColumn("gps Altitude", gpsLogs.get(gpsI).getAlt().toString());
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
gpsI++;
if (gpsLogs.size() >= gpsI)
break;
}
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
if (touchLogs != null && touchLogs.size() > touchI && (touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
while ((touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
if ((touchLogs.get(touchI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("touch x", ""+touchLogs.get(touchI).getXcoord());
data.addToColumn("touch y", ""+touchLogs.get(touchI).getYcoord());
data.addToColumn("touch action", touchLogs.get(touchI).getAction());
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
touchI++;
if (touchLogs.size() >= touchI)
break;
}
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
}
}
return data;
}
private <T extends Log> List<T> pullFromDb(Class<T> cls, DataHolder data) {
return logService.getAllBySessionId(cls, data.getSession());
}
}
| false | true | public DataHolder formatForJsp(SessionLog session) {
DataHolder data = new DataHolder(session);
if (session != null) {
List<Acceleration> accLogs = pullFromDb(Acceleration.class, data);
List<Compass> comLogs = pullFromDb(Compass.class, data);
List<KeyPress> keyPresses = pullFromDb(KeyPress.class, data);
List<Keyboard> keyboards = pullFromDb(Keyboard.class, data);
List<Orientation> gyroLogs = pullFromDb(Orientation.class, data);
List<Gps> gpsLogs = pullFromDb(Gps.class, data);
List<Touch> touchLogs = pullFromDb(Touch.class, data);
int accI = 0;
int comI = 0;
int pressI = 0;
int keybI = 0;
int gyroI = 0;
int gpsI = 0;
int touchI = 0;
for (Long time : data.getTimestamps()) {
if (accLogs != null && accLogs.size() > accI && (accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
while ((accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
if ((accLogs.get(accI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Acc X", accLogs.get(accI).getAccX().toString());
data.addToColumn("Acc Y", accLogs.get(accI).getAccY().toString());
data.addToColumn("Acc Z", accLogs.get(accI).getAccZ().toString());
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
accI++;
if (accLogs.size() >= accI)
break;
}
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
if (comLogs != null && comLogs.size() > comI && (comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
while ((comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
if ((comLogs.get(comI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Heading, true", comLogs.get(comI).getTrueHeading().toString());
data.addToColumn("Heading, magnetic", comLogs.get(comI).getMagneticHeading().toString());
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
comI++;
if (comLogs.size() >= comI)
break;
}
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
if (keyPresses != null && keyPresses.size() > pressI && (keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
while ((keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
if ((keyPresses.get(pressI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Key pressed", keyPresses.get(pressI).getKeyPressed());
} else {
data.addToColumn("key pressed", "");
}
pressI++;
if (keyPresses.size() >= pressI)
break;
}
} else {
data.addToColumn("key pressed", "");
}
if (keyboards != null && keyboards.size() > keybI) {
while ((keyboards.get(keybI).getTimestamp() / 10) * 10 <= time) {
if ((keyboards.get(keybI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Keyboard status", keyboards.get(keybI).getKeyboardFocus());
} else {
data.addToColumn("Keyboard status", "");
}
keybI++;
if (keyboards.size() >= keybI)
break;
}
} else {
data.addToColumn("Keyboard status", "");
}
if (gyroLogs != null && gyroLogs.size() > gyroI && (gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
while ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
if ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Gyro X", gyroLogs.get(gyroI).getCurrentRotationRateX().toString());
data.addToColumn("Gyro Y", gyroLogs.get(gyroI).getCurrentRotationRateY().toString());
data.addToColumn("Gyro Z", gyroLogs.get(gyroI).getCurrentRotationRateZ().toString());
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
gyroI++;
if (gyroLogs.size() >= gyroI)
break;
}
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
if (gpsLogs != null && gpsLogs.size() > gpsI && (gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
while ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
if ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("gps Latitude", gpsLogs.get(gpsI).getLat().toString());
data.addToColumn("gps Longitude", gpsLogs.get(gpsI).getLon().toString());
data.addToColumn("gps Altitude", gpsLogs.get(gpsI).getAlt().toString());
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
gpsI++;
if (gpsLogs.size() >= gpsI)
break;
}
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
if (touchLogs != null && touchLogs.size() > touchI && (touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
while ((touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
if ((touchLogs.get(touchI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("touch x", ""+touchLogs.get(touchI).getXcoord());
data.addToColumn("touch y", ""+touchLogs.get(touchI).getYcoord());
data.addToColumn("touch action", touchLogs.get(touchI).getAction());
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
touchI++;
if (touchLogs.size() >= touchI)
break;
}
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
}
}
return data;
}
| public DataHolder formatForJsp(SessionLog session) {
DataHolder data = new DataHolder(session);
if (session != null) {
List<Acceleration> accLogs = pullFromDb(Acceleration.class, data);
List<Compass> comLogs = pullFromDb(Compass.class, data);
List<KeyPress> keyPresses = pullFromDb(KeyPress.class, data);
List<Keyboard> keyboards = pullFromDb(Keyboard.class, data);
List<Orientation> gyroLogs = pullFromDb(Orientation.class, data);
List<Gps> gpsLogs = pullFromDb(Gps.class, data);
List<Touch> touchLogs = pullFromDb(Touch.class, data);
int accI = 0;
int comI = 0;
int pressI = 0;
int keybI = 0;
int gyroI = 0;
int gpsI = 0;
int touchI = 0;
for (Long time : data.getTimestamps()) {
if (accLogs != null && accLogs.size() > accI && (accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
while ((accLogs.get(accI).getTimestamp() / 10) * 10 <= time) {
if ((accLogs.get(accI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Acc X", accLogs.get(accI).getAccX().toString());
data.addToColumn("Acc Y", accLogs.get(accI).getAccY().toString());
data.addToColumn("Acc Z", accLogs.get(accI).getAccZ().toString());
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
accI++;
if (accLogs.size() >= accI)
break;
}
} else {
data.addToColumn("Acc X", "");
data.addToColumn("Acc Y", "");
data.addToColumn("Acc Z", "");
}
if (comLogs != null && comLogs.size() > comI && (comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
while ((comLogs.get(comI).getTimestamp() / 10) * 10 <= time) {
if ((comLogs.get(comI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Heading, true", comLogs.get(comI).getTrueHeading().toString());
data.addToColumn("Heading, magnetic", comLogs.get(comI).getMagneticHeading().toString());
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
comI++;
if (comLogs.size() >= comI)
break;
}
} else {
data.addToColumn("Heading, true", "");
data.addToColumn("Heading, magnetic", "");
}
if (keyPresses != null && keyPresses.size() > pressI && (keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
while ((keyPresses.get(pressI).getTimestamp() / 10) * 10 <= time) {
if ((keyPresses.get(pressI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Key pressed", keyPresses.get(pressI).getKeyPressed());
} else {
data.addToColumn("Key pressed", "");
}
pressI++;
if (keyPresses.size() >= pressI)
break;
}
} else {
data.addToColumn("Key pressed", "");
}
if (keyboards != null && keyboards.size() > keybI && (keyboards.get(keybI).getTimestamp() / 10) * 10 <= time) {
while ((keyboards.get(keybI).getTimestamp() / 10) * 10 <= time) {
if ((keyboards.get(keybI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Keyboard status", keyboards.get(keybI).getKeyboardFocus());
} else {
data.addToColumn("Keyboard status", "");
}
keybI++;
if (keyboards.size() >= keybI)
break;
}
} else {
data.addToColumn("Keyboard status", "");
}
if (gyroLogs != null && gyroLogs.size() > gyroI && (gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
while ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 <= time) {
if ((gyroLogs.get(gyroI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("Gyro X", gyroLogs.get(gyroI).getCurrentRotationRateX().toString());
data.addToColumn("Gyro Y", gyroLogs.get(gyroI).getCurrentRotationRateY().toString());
data.addToColumn("Gyro Z", gyroLogs.get(gyroI).getCurrentRotationRateZ().toString());
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
gyroI++;
if (gyroLogs.size() >= gyroI)
break;
}
} else {
data.addToColumn("Gyro X", "");
data.addToColumn("Gyro Y", "");
data.addToColumn("Gyro Z", "");
}
if (gpsLogs != null && gpsLogs.size() > gpsI && (gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
while ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 <= time) {
if ((gpsLogs.get(gpsI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("gps Latitude", gpsLogs.get(gpsI).getLat().toString());
data.addToColumn("gps Longitude", gpsLogs.get(gpsI).getLon().toString());
data.addToColumn("gps Altitude", gpsLogs.get(gpsI).getAlt().toString());
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
gpsI++;
if (gpsLogs.size() >= gpsI)
break;
}
} else {
data.addToColumn("gps Latitude", "");
data.addToColumn("gps Longitude", "");
data.addToColumn("gps Altitude", "");
}
if (touchLogs != null && touchLogs.size() > touchI && (touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
while ((touchLogs.get(touchI).getTimestamp() / 10) * 10 <= time) {
if ((touchLogs.get(touchI).getTimestamp() / 10) * 10 == time) {
data.addToColumn("touch x", ""+touchLogs.get(touchI).getXcoord());
data.addToColumn("touch y", ""+touchLogs.get(touchI).getYcoord());
data.addToColumn("touch action", touchLogs.get(touchI).getAction());
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
touchI++;
if (touchLogs.size() >= touchI)
break;
}
} else {
data.addToColumn("touch x", "");
data.addToColumn("touch y", "");
data.addToColumn("touch action", "");
}
}
}
return data;
}
|
diff --git a/Search/zylabPatisClient/src/main/java/nl/maastro/eureca/aida/search/zylabpatisclient/API_Demo.java b/Search/zylabPatisClient/src/main/java/nl/maastro/eureca/aida/search/zylabpatisclient/API_Demo.java
index ff3607c8..939f80c5 100644
--- a/Search/zylabPatisClient/src/main/java/nl/maastro/eureca/aida/search/zylabpatisclient/API_Demo.java
+++ b/Search/zylabPatisClient/src/main/java/nl/maastro/eureca/aida/search/zylabpatisclient/API_Demo.java
@@ -1,82 +1,82 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.maastro.eureca.aida.search.zylabpatisclient;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import javax.xml.rpc.ServiceException;
import nl.maastro.eureca.aida.search.zylabpatisclient.config.Config;
import org.apache.lucene.search.Query;
/**
*
* @author kasper2
*/
public class API_Demo {
static public void main(String[] args) {
try {
// Read config file
// InputStream s = new FileInputStream("/home/kasper2/git/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
InputStream s = new FileInputStream("/home/administrator/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
Config config = Config.init(s);
// Use config to initialise a searcher
Searcher searcher = config.getSearcher();
// Dummy list of patients; reading a list of patisnumbers is not yet in API
List<PatisNumber> patients = Arrays.<PatisNumber>asList(
// PatisNumber.create("12345"),
// PatisNumber.create("11111"),
PatisNumber.create("71358"), // Exp 0
PatisNumber.create("71314"),
PatisNumber.create("71415"), // Exp 0
PatisNumber.create("71539"),
PatisNumber.create("71586"),
PatisNumber.create("70924"),
PatisNumber.create("71785"),
PatisNumber.create("71438"),
PatisNumber.create("71375"),
PatisNumber.create("71448"),
PatisNumber.create("71681"), // Exp 1
PatisNumber.create("71692"),
PatisNumber.create("71757"),
PatisNumber.create("70986"),
PatisNumber.create("46467"));
// Get a QueryPattern; normally the Query is retrieved via its
// URI and not via an internal enum constant
Query queryPattern = PreconstructedQueries.instance().getQuery(
PreconstructedQueries.LocalParts.METASTASIS_IV);
Iterable<SearchResult> result = searcher.searchForAll(
queryPattern,
patients);
// Do something with the results
for (SearchResult searchResult : result) {
System.out.printf("PatisNr: %s found in %d documents\nSnippets:\n",
searchResult.patient.value, searchResult.nHits);
for (String docId : searchResult.snippets.keySet()) {
System.out.printf("\tDocument: %s\n", docId);
for (String snippet : searchResult.snippets.get(docId)) {
- System.out.println("\t\t<snippet>%s</snippet>\n");
+ System.out.printf("\t\t<snippet>%s</snippet>\n", snippet);
}
}
}
} catch (ServiceException | IOException ex) {
throw new Error(ex);
}
}
}
| true | true | static public void main(String[] args) {
try {
// Read config file
// InputStream s = new FileInputStream("/home/kasper2/git/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
InputStream s = new FileInputStream("/home/administrator/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
Config config = Config.init(s);
// Use config to initialise a searcher
Searcher searcher = config.getSearcher();
// Dummy list of patients; reading a list of patisnumbers is not yet in API
List<PatisNumber> patients = Arrays.<PatisNumber>asList(
// PatisNumber.create("12345"),
// PatisNumber.create("11111"),
PatisNumber.create("71358"), // Exp 0
PatisNumber.create("71314"),
PatisNumber.create("71415"), // Exp 0
PatisNumber.create("71539"),
PatisNumber.create("71586"),
PatisNumber.create("70924"),
PatisNumber.create("71785"),
PatisNumber.create("71438"),
PatisNumber.create("71375"),
PatisNumber.create("71448"),
PatisNumber.create("71681"), // Exp 1
PatisNumber.create("71692"),
PatisNumber.create("71757"),
PatisNumber.create("70986"),
PatisNumber.create("46467"));
// Get a QueryPattern; normally the Query is retrieved via its
// URI and not via an internal enum constant
Query queryPattern = PreconstructedQueries.instance().getQuery(
PreconstructedQueries.LocalParts.METASTASIS_IV);
Iterable<SearchResult> result = searcher.searchForAll(
queryPattern,
patients);
// Do something with the results
for (SearchResult searchResult : result) {
System.out.printf("PatisNr: %s found in %d documents\nSnippets:\n",
searchResult.patient.value, searchResult.nHits);
for (String docId : searchResult.snippets.keySet()) {
System.out.printf("\tDocument: %s\n", docId);
for (String snippet : searchResult.snippets.get(docId)) {
System.out.println("\t\t<snippet>%s</snippet>\n");
}
}
}
} catch (ServiceException | IOException ex) {
throw new Error(ex);
}
}
| static public void main(String[] args) {
try {
// Read config file
// InputStream s = new FileInputStream("/home/kasper2/git/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
InputStream s = new FileInputStream("/home/administrator/aida.git/Search/zylabPatisClient/src/main/webapp/WEB-INF/zpsc-config.xml");
Config config = Config.init(s);
// Use config to initialise a searcher
Searcher searcher = config.getSearcher();
// Dummy list of patients; reading a list of patisnumbers is not yet in API
List<PatisNumber> patients = Arrays.<PatisNumber>asList(
// PatisNumber.create("12345"),
// PatisNumber.create("11111"),
PatisNumber.create("71358"), // Exp 0
PatisNumber.create("71314"),
PatisNumber.create("71415"), // Exp 0
PatisNumber.create("71539"),
PatisNumber.create("71586"),
PatisNumber.create("70924"),
PatisNumber.create("71785"),
PatisNumber.create("71438"),
PatisNumber.create("71375"),
PatisNumber.create("71448"),
PatisNumber.create("71681"), // Exp 1
PatisNumber.create("71692"),
PatisNumber.create("71757"),
PatisNumber.create("70986"),
PatisNumber.create("46467"));
// Get a QueryPattern; normally the Query is retrieved via its
// URI and not via an internal enum constant
Query queryPattern = PreconstructedQueries.instance().getQuery(
PreconstructedQueries.LocalParts.METASTASIS_IV);
Iterable<SearchResult> result = searcher.searchForAll(
queryPattern,
patients);
// Do something with the results
for (SearchResult searchResult : result) {
System.out.printf("PatisNr: %s found in %d documents\nSnippets:\n",
searchResult.patient.value, searchResult.nHits);
for (String docId : searchResult.snippets.keySet()) {
System.out.printf("\tDocument: %s\n", docId);
for (String snippet : searchResult.snippets.get(docId)) {
System.out.printf("\t\t<snippet>%s</snippet>\n", snippet);
}
}
}
} catch (ServiceException | IOException ex) {
throw new Error(ex);
}
}
|
diff --git a/src/main/java/org/elasticsearch/action/support/replication/ShardReplicationOperationRequest.java b/src/main/java/org/elasticsearch/action/support/replication/ShardReplicationOperationRequest.java
index 970063a1df8..c050acf5f14 100644
--- a/src/main/java/org/elasticsearch/action/support/replication/ShardReplicationOperationRequest.java
+++ b/src/main/java/org/elasticsearch/action/support/replication/ShardReplicationOperationRequest.java
@@ -1,183 +1,183 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.action.support.replication;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.WriteConsistencyLevel;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.action.ValidateActions.addValidationError;
/**
*
*/
public abstract class ShardReplicationOperationRequest<T extends ShardReplicationOperationRequest> extends ActionRequest<T> {
public static final TimeValue DEFAULT_TIMEOUT = new TimeValue(1, TimeUnit.MINUTES);
protected TimeValue timeout = DEFAULT_TIMEOUT;
protected String index;
private boolean threadedOperation = true;
private ReplicationType replicationType = ReplicationType.DEFAULT;
private WriteConsistencyLevel consistencyLevel = WriteConsistencyLevel.DEFAULT;
protected ShardReplicationOperationRequest() {
}
public ShardReplicationOperationRequest(ActionRequest request) {
super(request);
}
public ShardReplicationOperationRequest(T request) {
super(request);
this.timeout = request.timeout();
this.index = request.index();
- this.threadedOperation = request.threadedOperation;
+ this.threadedOperation = request.operationThreaded();
this.replicationType = request.replicationType();
this.consistencyLevel = request.consistencyLevel();
}
/**
* Controls if the operation will be executed on a separate thread when executed locally.
*/
public final boolean operationThreaded() {
return threadedOperation;
}
/**
* Controls if the operation will be executed on a separate thread when executed locally. Defaults
* to <tt>true</tt> when running in embedded mode.
*/
@SuppressWarnings("unchecked")
public final T operationThreaded(boolean threadedOperation) {
this.threadedOperation = threadedOperation;
return (T) this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
@SuppressWarnings("unchecked")
public final T timeout(TimeValue timeout) {
this.timeout = timeout;
return (T) this;
}
/**
* A timeout to wait if the index operation can't be performed immediately. Defaults to <tt>1m</tt>.
*/
public final T timeout(String timeout) {
return timeout(TimeValue.parseTimeValue(timeout, null));
}
public TimeValue timeout() {
return timeout;
}
public String index() {
return this.index;
}
@SuppressWarnings("unchecked")
public final T index(String index) {
this.index = index;
return (T) this;
}
/**
* The replication type.
*/
public ReplicationType replicationType() {
return this.replicationType;
}
/**
* Sets the replication type.
*/
@SuppressWarnings("unchecked")
public final T replicationType(ReplicationType replicationType) {
this.replicationType = replicationType;
return (T) this;
}
/**
* Sets the replication type.
*/
public final T replicationType(String replicationType) {
return replicationType(ReplicationType.fromString(replicationType));
}
public WriteConsistencyLevel consistencyLevel() {
return this.consistencyLevel;
}
/**
* Sets the consistency level of write. Defaults to {@link org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}
*/
@SuppressWarnings("unchecked")
public final T consistencyLevel(WriteConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return (T) this;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (index == null) {
validationException = addValidationError("index is missing", validationException);
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
replicationType = ReplicationType.fromId(in.readByte());
consistencyLevel = WriteConsistencyLevel.fromId(in.readByte());
timeout = TimeValue.readTimeValue(in);
index = in.readString();
// no need to serialize threaded* parameters, since they only matter locally
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeByte(replicationType.id());
out.writeByte(consistencyLevel.id());
timeout.writeTo(out);
out.writeString(index);
}
/**
* Called before the request gets forked into a local thread.
*/
public void beforeLocalFork() {
}
}
| true | true | public ShardReplicationOperationRequest(T request) {
super(request);
this.timeout = request.timeout();
this.index = request.index();
this.threadedOperation = request.threadedOperation;
this.replicationType = request.replicationType();
this.consistencyLevel = request.consistencyLevel();
}
| public ShardReplicationOperationRequest(T request) {
super(request);
this.timeout = request.timeout();
this.index = request.index();
this.threadedOperation = request.operationThreaded();
this.replicationType = request.replicationType();
this.consistencyLevel = request.consistencyLevel();
}
|
diff --git a/src/org/jacorb/orb/util/FixIOR.java b/src/org/jacorb/orb/util/FixIOR.java
index 77a07b1b..667f452c 100644
--- a/src/org/jacorb/orb/util/FixIOR.java
+++ b/src/org/jacorb/orb/util/FixIOR.java
@@ -1,143 +1,145 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2002 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.orb.util;
import org.jacorb.orb.connection.CodeSet;
import org.jacorb.orb.ParsedIOR;
import org.jacorb.orb.*;
import org.omg.IOP.*;
import org.omg.GIOP.*;
import org.omg.IIOP.*;
import org.omg.SSLIOP.*;
import org.omg.CSIIOP.*;
import org.omg.CONV_FRAME.*;
import java.io.*;
/**
* Utility class to patch host and port information into an IOR.
*
* @author Steve Osselton
*/
public class FixIOR
{
public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
- System.err.println ("IOR must be in the standard IOR URL scheme");
+ System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
+ is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
private FixIOR ()
{
}
}
| false | true | public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL scheme");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
| public static void main (String args[])
throws Exception
{
org.omg.CORBA.ORB orb;
String iorString;
String host;
BufferedReader br;
BufferedWriter bw;
CDRInputStream is;
CDROutputStream os;
ParsedIOR pior;
IOR ior;
TaggedProfile[] profiles;
ProfileBody_1_0 body10;
ProfileBody_1_1 body11;
short port;
int iport;
if (args.length != 4)
{
System.err.println ("Usage: FixIOR ior_file ior_out_file host port");
System.exit( 1 );
}
host = args[2];
orb = org.omg.CORBA.ORB.init (args, null);
// Read in IOR from file
br = new BufferedReader (new FileReader (args[0]));
iorString = br.readLine ();
br.close ();
if (! iorString.startsWith ("IOR:"))
{
System.err.println ("IOR must be in the standard IOR URL format");
System.exit (1);
}
iport = Integer.parseInt (args[3]);
if (iport > 32767)
{
iport = iport - 65536;
}
port = (short) iport;
// Parse IOR
pior = new ParsedIOR (iorString);
ior = pior.getIOR ();
// Iterate through IIOP profiles setting host and port
profiles = ior.profiles;
for (int i = 0; i < profiles.length; i++)
{
if (profiles[i].tag == TAG_INTERNET_IOP.value)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body10 = ProfileBody_1_0Helper.read (is);
is.close ();
os = new CDROutputStream ();
os.beginEncapsulatedArray ();
if (body10.iiop_version.minor > 0)
{
is = new CDRInputStream (orb, profiles[i].profile_data);
is.openEncapsulatedArray ();
body11 = ProfileBody_1_1Helper.read (is);
is.close ();
body11.host = host;
body11.port = port;
ProfileBody_1_1Helper.write (os, body11);
}
else
{
body10.host = host;
body10.port = port;
ProfileBody_1_0Helper.write (os, body10);
}
profiles[i].profile_data = os.getBufferCopy ();
}
}
pior = new ParsedIOR (ior);
// Write out new IOR to file
bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (args[1])));
bw.write (pior.getIORString ());
bw.close ();
}
|
diff --git a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/LogicalObjectStructureInterfaceType.java b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/LogicalObjectStructureInterfaceType.java
index e363c2369..114f6ddc7 100644
--- a/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/LogicalObjectStructureInterfaceType.java
+++ b/org.eclipse.jdt.debug/model/org/eclipse/jdt/internal/debug/core/logicalstructures/LogicalObjectStructureInterfaceType.java
@@ -1,196 +1,199 @@
/*******************************************************************************
* 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.jdt.internal.debug.core.logicalstructures;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IStatusHandler;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.ILogicalStructureTypeDelegate;
import org.eclipse.debug.core.model.IThread;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.jdt.debug.core.IEvaluationRunnable;
import org.eclipse.jdt.debug.core.IJavaClassType;
import org.eclipse.jdt.debug.core.IJavaDebugTarget;
import org.eclipse.jdt.debug.core.IJavaInterfaceType;
import org.eclipse.jdt.debug.core.IJavaObject;
import org.eclipse.jdt.debug.core.IJavaThread;
import org.eclipse.jdt.debug.core.IJavaType;
import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin;
/**
* Common facilities for logical structure types for instances of an interface
*/
public abstract class LogicalObjectStructureInterfaceType implements ILogicalStructureTypeDelegate {
private IJavaObject fObject; // the map to provide structure for
private IValue fResult; // the resulting structure
private boolean fDone = false; // done the evaluation
private static IStatus fgNeedThread = new Status(IStatus.INFO, JDIDebugPlugin.getUniqueIdentifier(), LogicalObjectStructureInterfaceType.INFO_EVALUATION_THREAD, "Provides thread context for an evaluation", null); //$NON-NLS-1$
private static IStatusHandler fgThreadProvider;
/**
* Status code used by the debug model to retrieve a thread to use
* for evalutaions, via a status handler. A status handler is contributed by
* the Java debug UI. When not present, the debug model uses any suspended thread.
*
* @since 3.0
*/
public static final int INFO_EVALUATION_THREAD = 110;
/* (non-Javadoc)
* @see org.eclipse.debug.core.model.ILogicalStructureType#providesLogicalStructure(org.eclipse.debug.core.model.IValue)
*/
public boolean providesLogicalStructure(IValue value) {
if (value instanceof IJavaObject) {
IJavaObject object = (IJavaObject) value;
try {
IJavaType type = object.getJavaType();
if (type instanceof IJavaClassType) {
IJavaClassType classType = (IJavaClassType) type;
IJavaInterfaceType[] interfaceTypes = classType.getAllInterfaces();
String targetInterface = getTargetInterfaceName();
for (int i = 0; i < interfaceTypes.length; i++) {
IJavaInterfaceType inter = interfaceTypes[i];
if (inter.getName().equals(targetInterface)) {
return true;
}
}
}
} catch (DebugException e) {
}
}
return false;
}
/**
* Returns the name of an interface that an object must implement for this
* structure type to be appropriate.
*
* @return the name of an interface that an object must implement for this
* structure type to be appropriate
*/
protected abstract String getTargetInterfaceName();
/**
* Returns the evaluation that computes the logical object structure for this
* strucutre type.
*
* @return the evaluation that computes the logical object structure for this
* strucutre type
*/
protected abstract IEvaluationRunnable getEvaluation();
/* (non-Javadoc)
* @see org.eclipse.debug.core.model.ILogicalStructureType#getLogicalStructure(org.eclipse.debug.core.model.IValue)
*/
public synchronized IValue getLogicalStructure(IValue value) throws CoreException {
final IJavaThread thread = getThread(value);
if (thread == null) {
// can't do it
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.getString("LogicalObjectStructureType.1"), null)); //$NON-NLS-1$
}
setObject((IJavaObject)value);
final IEvaluationRunnable evaluation = getEvaluation();
final CoreException[] ex = new CoreException[1];
final Object lock = this;
fDone = false;
if (thread.isPerformingEvaluation() && thread.isSuspended()) {
return value;
}
thread.queueRunnable(new Runnable() {
public void run() {
try {
thread.runEvaluation(evaluation, null, DebugEvent.EVALUATION_IMPLICIT, false);
} catch (DebugException e) {
ex[0] = e;
}
synchronized (lock) {
fDone = true;
lock.notifyAll();
}
}
});
try {
synchronized (lock) {
if (!fDone) {
lock.wait();
}
}
} catch (InterruptedException e) {
}
+ if (ex[0] != null) {
+ throw ex[0];
+ }
return fResult;
}
private IJavaThread getThread(IValue value) throws CoreException {
IStatusHandler handler = getThreadProvider();
if (handler != null) {
IJavaThread thread = (IJavaThread)handler.handleStatus(fgNeedThread, value);
if (thread != null) {
return thread;
}
}
IDebugTarget target = value.getDebugTarget();
IJavaDebugTarget javaTarget = (IJavaDebugTarget) target.getAdapter(IJavaDebugTarget.class);
if (javaTarget != null) {
IThread[] threads = javaTarget.getThreads();
for (int i = 0; i < threads.length; i++) {
IThread thread = threads[i];
if (thread.isSuspended()) {
return (IJavaThread)thread;
}
}
}
return null;
}
private static IStatusHandler getThreadProvider() {
if (fgThreadProvider == null) {
fgThreadProvider = DebugPlugin.getDefault().getStatusHandler(fgNeedThread);
}
return fgThreadProvider;
}
/**
* Sets the object for which a logical structure is to be provided.
*
* @param object the object for which a logical structure is to be provided
*/
private void setObject(IJavaObject object) {
fObject = object;
}
/**
* Returns the object for which a logical structure is to be provided
*
* @return the object for which a logical structure is to be provided
*/
protected IJavaObject getObject() {
return fObject;
}
/**
* Sets the object representing the logical structure.
*
* @param result the object representing the logical structure
*/
protected void setLogicalStructure(IValue result) {
fResult = result;
}
}
| true | true | public synchronized IValue getLogicalStructure(IValue value) throws CoreException {
final IJavaThread thread = getThread(value);
if (thread == null) {
// can't do it
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.getString("LogicalObjectStructureType.1"), null)); //$NON-NLS-1$
}
setObject((IJavaObject)value);
final IEvaluationRunnable evaluation = getEvaluation();
final CoreException[] ex = new CoreException[1];
final Object lock = this;
fDone = false;
if (thread.isPerformingEvaluation() && thread.isSuspended()) {
return value;
}
thread.queueRunnable(new Runnable() {
public void run() {
try {
thread.runEvaluation(evaluation, null, DebugEvent.EVALUATION_IMPLICIT, false);
} catch (DebugException e) {
ex[0] = e;
}
synchronized (lock) {
fDone = true;
lock.notifyAll();
}
}
});
try {
synchronized (lock) {
if (!fDone) {
lock.wait();
}
}
} catch (InterruptedException e) {
}
return fResult;
}
| public synchronized IValue getLogicalStructure(IValue value) throws CoreException {
final IJavaThread thread = getThread(value);
if (thread == null) {
// can't do it
throw new CoreException(new Status(IStatus.ERROR, JDIDebugPlugin.getUniqueIdentifier(), JDIDebugPlugin.INTERNAL_ERROR, LogicalStructuresMessages.getString("LogicalObjectStructureType.1"), null)); //$NON-NLS-1$
}
setObject((IJavaObject)value);
final IEvaluationRunnable evaluation = getEvaluation();
final CoreException[] ex = new CoreException[1];
final Object lock = this;
fDone = false;
if (thread.isPerformingEvaluation() && thread.isSuspended()) {
return value;
}
thread.queueRunnable(new Runnable() {
public void run() {
try {
thread.runEvaluation(evaluation, null, DebugEvent.EVALUATION_IMPLICIT, false);
} catch (DebugException e) {
ex[0] = e;
}
synchronized (lock) {
fDone = true;
lock.notifyAll();
}
}
});
try {
synchronized (lock) {
if (!fDone) {
lock.wait();
}
}
} catch (InterruptedException e) {
}
if (ex[0] != null) {
throw ex[0];
}
return fResult;
}
|
diff --git a/src/test/java/com/versionone/om/tests/AttachmentTester.java b/src/test/java/com/versionone/om/tests/AttachmentTester.java
index 7bf98af..47a50a1 100644
--- a/src/test/java/com/versionone/om/tests/AttachmentTester.java
+++ b/src/test/java/com/versionone/om/tests/AttachmentTester.java
@@ -1,226 +1,227 @@
/*(c) Copyright 2008, VersionOne, Inc. All rights reserved. (c)*/
package com.versionone.om.tests;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import com.versionone.om.*;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import com.versionone.DB.DateTime;
public class AttachmentTester extends BaseSDKTester {
private static final String ATTACHMENT_1783 = "Attachment:1783";
@Test
public void testAttachmentProperties() throws IOException {
Attachment attachment = getInstance().get().attachmentByID(
ATTACHMENT_1783);
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Assert.assertEquals(project, attachment.getAsset());
Assert.assertEquals("text/plain", attachment.getContentType());
Assert.assertEquals("Sample attachment<br>", attachment.getDescription());
Assert.assertEquals("Attachment A", attachment.getName());
Assert.assertEquals("sample.txt", attachment.getFilename());
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
attachment.writeTo(output);
Assert.assertEquals("This is a sample attachment", output.toString());
} finally {
try {
output.close();
} catch (IOException e) {
// do nothing
}
}
}
@Test
public void testURLTester() {
Attachment attachment = getInstance().get().attachmentByID(
ATTACHMENT_1783);
Assert.assertEquals(getApplicationUrl() + "attachment.v1/1783",
attachment.getContentURL());
Assert.assertEquals(getApplicationUrl()
+ "assetdetail.v1/?oid=" + ATTACHMENT_1783, attachment.getURL());
}
@Test
public void testCreate() throws IOException {
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Attachment attachment;
String content = "This is the first attachment's content. At: "
+ DateTime.now();
InputStream input = new ByteArrayInputStream(content.getBytes());
try {
attachment = project.createAttachment("First Attachment",
"test.txt", input);
} finally {
try {
input.close();
} catch (IOException e) {}
}
String attachmentID = attachment.getID().toString();
resetInstance();
Attachment newAttachment = getInstance().get().attachmentByID(
attachmentID);
Project newProject = getInstance().get().projectByID(SCOPE_ZERO);
Assert.assertEquals(newProject, newAttachment.getAsset());
Assert.assertEquals("text/plain", attachment.getContentType());
Assert.assertEquals("test.txt", attachment.getFilename());
Assert.assertEquals("First Attachment", attachment.getName());
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
newAttachment.writeTo(output);
} finally {
try {
output.close();
} catch (IOException e) {}
}
Assert.assertEquals(content, output.toString());// use ASCII
}
@Test
public void testCreateAttachmentWithAttributes() {
final String description = "Test for Attachment creation with required attributes";
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("Description", description);
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Attachment attachment;
String content = "This is the first attachment's content. At: " + DateTime.now();
InputStream input = new ByteArrayInputStream(content.getBytes());
try {
attachment = project.createAttachment("First Attachment", "test.txt", input, attributes);
} finally {
try {
input.close();
} catch (IOException e) {}
}
String attachmentID = attachment.getID().toString();
resetInstance();
Attachment newAttachment = getInstance().get().attachmentByID(attachmentID);
Assert.assertEquals(project, newAttachment.getAsset());
Assert.assertEquals(description, attachment.getDescription());
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
newAttachment.writeTo(output);
} finally {
try {
output.close();
} catch (IOException e) {}
}
Assert.assertEquals(content, output.toString());
}
@Test
public void testCreateFromFile() throws IOException,
ApplicationUnavailableException {
final String fileName = "logo.png";
final int fileSize = 3 * 1024; // 3k
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Attachment attachment;
InputStream input = AttachmentTester.class
- .getResourceAsStream(fileName);
+ .getResourceAsStream("./" + fileName);
try {
attachment = project.createAttachment("Second Attachment",
fileName, input);
} finally {
if (input != null) {
input.close();
}
}
String attachmentID = attachment.getID().toString();
resetInstance();
Attachment newAttachment = getInstance().get().attachmentByID(
attachmentID);
Assert.assertEquals("image/png", newAttachment.getContentType());
ByteArrayOutputStream output = new ByteArrayOutputStream(fileSize);
try {
newAttachment.writeTo(output);
input = AttachmentTester.class.getResourceAsStream(fileName);
if (input != null) input.mark(0);
} finally {
if (output != null) {
output.close();
}
}
InputStream expected = new ByteArrayInputStream(output.toByteArray());
try {
+ Assert.assertNotNull("input stream is null", input);
Assert.assertTrue(StreamComparer.compareStream(input, expected));
} finally {
if (expected != null) {
expected.close();
}
if (input != null) {
input.close();
}
}
}
@Test
public void testDelete() {
final String fileName = "test.txt";
final String content = "This is the first attachment's content. At: "
+ DateTime.now();
InputStream input = new ByteArrayInputStream(content.getBytes());
Story story = getInstance().create().story("StoryForAttachment", getSandboxProject());
Attachment attachment = getInstance().create().attachment("AttachmentName", story, fileName, input);
final String attachmentID = attachment.getID().toString();
attachment = getInstance().get().attachmentByID(attachmentID);
Assert.assertNotNull(attachment);
Assert.assertTrue(attachment.canDelete());
attachment.delete();
resetInstance();
Assert.assertNull(getInstance().get().attachmentByID(attachmentID));
}
@Test(expected = AttachmentLengthExceededException.class)
public void testMaximumFileSize() throws IOException {
Project project = getInstance().get().projectByID(SCOPE_ZERO);
InputStream input = new RandomStream(
getInstance().getConfiguration().maximumAttachmentSize + 1);
project.createAttachment("Random Attachment", "random.txt", input);
}
@Test
public void testUnderMaximumFileSize() throws IOException {
Project project = getInstance().get().projectByID(SCOPE_ZERO);
InputStream input = new RandomStream(
getInstance().getConfiguration().maximumAttachmentSize);
Attachment att = project.createAttachment("Random Attachment",
"random.txt", input);
Assert.assertNotNull(att);
}
}
| false | true | public void testCreateFromFile() throws IOException,
ApplicationUnavailableException {
final String fileName = "logo.png";
final int fileSize = 3 * 1024; // 3k
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Attachment attachment;
InputStream input = AttachmentTester.class
.getResourceAsStream(fileName);
try {
attachment = project.createAttachment("Second Attachment",
fileName, input);
} finally {
if (input != null) {
input.close();
}
}
String attachmentID = attachment.getID().toString();
resetInstance();
Attachment newAttachment = getInstance().get().attachmentByID(
attachmentID);
Assert.assertEquals("image/png", newAttachment.getContentType());
ByteArrayOutputStream output = new ByteArrayOutputStream(fileSize);
try {
newAttachment.writeTo(output);
input = AttachmentTester.class.getResourceAsStream(fileName);
if (input != null) input.mark(0);
} finally {
if (output != null) {
output.close();
}
}
InputStream expected = new ByteArrayInputStream(output.toByteArray());
try {
Assert.assertTrue(StreamComparer.compareStream(input, expected));
} finally {
if (expected != null) {
expected.close();
}
if (input != null) {
input.close();
}
}
}
| public void testCreateFromFile() throws IOException,
ApplicationUnavailableException {
final String fileName = "logo.png";
final int fileSize = 3 * 1024; // 3k
Project project = getInstance().get().projectByID(SCOPE_ZERO);
Attachment attachment;
InputStream input = AttachmentTester.class
.getResourceAsStream("./" + fileName);
try {
attachment = project.createAttachment("Second Attachment",
fileName, input);
} finally {
if (input != null) {
input.close();
}
}
String attachmentID = attachment.getID().toString();
resetInstance();
Attachment newAttachment = getInstance().get().attachmentByID(
attachmentID);
Assert.assertEquals("image/png", newAttachment.getContentType());
ByteArrayOutputStream output = new ByteArrayOutputStream(fileSize);
try {
newAttachment.writeTo(output);
input = AttachmentTester.class.getResourceAsStream(fileName);
if (input != null) input.mark(0);
} finally {
if (output != null) {
output.close();
}
}
InputStream expected = new ByteArrayInputStream(output.toByteArray());
try {
Assert.assertNotNull("input stream is null", input);
Assert.assertTrue(StreamComparer.compareStream(input, expected));
} finally {
if (expected != null) {
expected.close();
}
if (input != null) {
input.close();
}
}
}
|
diff --git a/src/me/libraryaddict/disguise/utilities/PacketsManager.java b/src/me/libraryaddict/disguise/utilities/PacketsManager.java
index 13be7e8..7e89c99 100644
--- a/src/me/libraryaddict/disguise/utilities/PacketsManager.java
+++ b/src/me/libraryaddict/disguise/utilities/PacketsManager.java
@@ -1,1221 +1,1221 @@
package me.libraryaddict.disguise.utilities;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import me.libraryaddict.disguise.DisguiseAPI;
import me.libraryaddict.disguise.LibsDisguises;
import me.libraryaddict.disguise.disguisetypes.Disguise;
import me.libraryaddict.disguise.disguisetypes.DisguiseType;
import me.libraryaddict.disguise.disguisetypes.FlagWatcher;
import me.libraryaddict.disguise.disguisetypes.MiscDisguise;
import me.libraryaddict.disguise.disguisetypes.MobDisguise;
import me.libraryaddict.disguise.disguisetypes.PlayerDisguise;
import me.libraryaddict.disguise.utilities.DisguiseSound.SoundType;
import org.bukkit.Art;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Item;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import com.comphenix.protocol.Packets;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ConnectionSide;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.events.PacketListener;
import com.comphenix.protocol.reflect.StructureModifier;
import com.comphenix.protocol.wrappers.WrappedDataWatcher;
import com.comphenix.protocol.wrappers.WrappedWatchableObject;
public class PacketsManager {
private static boolean cancelSound;
private static PacketListener inventoryListenerClient;
private static PacketListener inventoryListenerServer;
private static boolean inventoryModifierEnabled;
private static LibsDisguises libsDisguises;
private static PacketListener soundsListener;
private static boolean soundsListenerEnabled;
private static PacketListener viewDisguisesListener;
private static boolean viewDisguisesListenerEnabled;
public static void addPacketListeners(JavaPlugin libsDisguises) {
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
manager.addPacketListener(new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGH,
Packets.Server.NAMED_ENTITY_SPAWN, Packets.Server.ENTITY_METADATA, Packets.Server.ARM_ANIMATION,
Packets.Server.REL_ENTITY_MOVE_LOOK, Packets.Server.ENTITY_LOOK, Packets.Server.ENTITY_TELEPORT,
Packets.Server.ADD_EXP_ORB, Packets.Server.VEHICLE_SPAWN, Packets.Server.MOB_SPAWN,
Packets.Server.ENTITY_PAINTING, Packets.Server.COLLECT, Packets.Server.UPDATE_ATTRIBUTES,
Packets.Server.ENTITY_EQUIPMENT, Packets.Server.BED) {
@Override
public void onPacketSending(PacketEvent event) {
final Player observer = event.getPlayer();
// First get the entity, the one sending this packet
StructureModifier<Entity> entityModifer = event.getPacket().getEntityModifier(observer.getWorld());
org.bukkit.entity.Entity entity = entityModifer.read((Packets.Server.COLLECT == event.getPacketID() ? 1 : 0));
// If the entity is the same as the sender. Don't disguise!
// Prevents problems and there is no advantage to be gained.
if (entity == observer)
return;
PacketContainer[] packets = transformPacket(event.getPacket(), event.getPlayer());
if (packets.length == 0)
event.setCancelled(true);
else {
event.setPacket(packets[0]);
final PacketContainer[] delayedPackets = new PacketContainer[packets.length - 1];
for (int i = 1; i < packets.length; i++) {
delayedPackets[i - 1] = packets[i];
}
if (delayedPackets.length > 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
try {
for (PacketContainer packet : delayedPackets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
}
}
});
// Now add a client listener to cancel them interacting with uninteractable disguised entitys.
// You ain't supposed to be allowed to 'interact' with a item that cannot be clicked.
// Because it kicks you for hacking.
manager.addPacketListener(new PacketAdapter(libsDisguises, ConnectionSide.CLIENT_SIDE, ListenerPriority.NORMAL,
Packets.Client.USE_ENTITY) {
@Override
public void onPacketReceiving(PacketEvent event) {
try {
Player observer = event.getPlayer();
StructureModifier<Entity> entityModifer = event.getPacket().getEntityModifier(observer.getWorld());
org.bukkit.entity.Entity entity = entityModifer.read(1);
if (DisguiseAPI.isDisguised(entity)
&& (entity instanceof ExperienceOrb || entity instanceof Item || entity instanceof Arrow)) {
event.setCancelled(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Construct the packets I need to spawn in the disguise
*/
public static PacketContainer[] constructSpawnPackets(Disguise disguise, Entity disguisedEntity) {
if (disguise.getEntity() == null)
disguise.setEntity(disguisedEntity);
Object nmsEntity = ReflectionManager.getNmsEntity(disguisedEntity);
ArrayList<PacketContainer> packets = new ArrayList<PacketContainer>();
for (int i = 0; i < 5; i++) {
int slot = i - 1;
if (slot < 0)
slot = 4;
org.bukkit.inventory.ItemStack itemstack = disguise.getWatcher().getItemStack(slot);
if (itemstack != null && itemstack.getTypeId() != 0) {
ItemStack item = null;
if (disguisedEntity instanceof LivingEntity)
if (i != 4)
item = ((LivingEntity) disguisedEntity).getEquipment().getArmorContents()[i];
else
item = ((LivingEntity) disguisedEntity).getEquipment().getItemInHand();
if (item == null || item.getType() == Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.ENTITY_EQUIPMENT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, i);
mods.write(2, ReflectionManager.getNmsItem(itemstack));
packets.add(packet);
}
}
}
PacketContainer[] spawnPackets = new PacketContainer[2 + packets.size()];
for (int i = 0; i < packets.size(); i++) {
spawnPackets[i + 2] = packets.get(i);
}
Location loc = disguisedEntity.getLocation().clone().add(0, getYModifier(disguisedEntity, disguise.getType()), 0);
byte yaw = getYaw(disguise.getType(), DisguiseType.getType(disguise.getEntity().getType()),
(byte) (int) (loc.getYaw() * 256.0F / 360.0F));
if (disguise.getType() == DisguiseType.EXPERIENCE_ORB) {
spawnPackets[0] = new PacketContainer(Packets.Server.ADD_EXP_ORB);
StructureModifier<Object> mods = spawnPackets[0].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, (int) Math.floor(loc.getX() * 32));
mods.write(2, (int) Math.floor(loc.getY() * 32) + 2);
mods.write(3, (int) Math.floor(loc.getZ() * 32));
mods.write(4, 1);
} else if (disguise.getType() == DisguiseType.PAINTING) {
spawnPackets[0] = new PacketContainer(Packets.Server.ENTITY_PAINTING);
StructureModifier<Object> mods = spawnPackets[0].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, loc.getBlockX());
mods.write(2, loc.getBlockY());
mods.write(3, loc.getBlockZ());
mods.write(4, ((int) loc.getYaw()) % 4);
int id = ((MiscDisguise) disguise).getData();
mods.write(5, ReflectionManager.getEnumArt(Art.values()[id]));
// Make the teleport packet to make it visible..
spawnPackets[1] = new PacketContainer(Packets.Server.ENTITY_TELEPORT);
mods = spawnPackets[1].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, (int) Math.floor(loc.getX() * 32D));
mods.write(2, (int) Math.floor(loc.getY() * 32D));
mods.write(3, (int) Math.floor(loc.getZ() * 32D));
mods.write(4, yaw);
mods.write(5, (byte) (int) (loc.getPitch() * 256.0F / 360.0F));
} else if (disguise.getType().isPlayer()) {
spawnPackets[0] = new PacketContainer(Packets.Server.NAMED_ENTITY_SPAWN);
StructureModifier<String> stringMods = spawnPackets[0].getStrings();
for (int i = 0; i < stringMods.size(); i++) {
stringMods.write(i, ((PlayerDisguise) disguise).getName());
}
StructureModifier<Integer> intMods = spawnPackets[0].getIntegers();
intMods.write(0, disguisedEntity.getEntityId());
intMods.write(1, (int) Math.floor(loc.getX() * 32));
intMods.write(2, (int) Math.floor(loc.getY() * 32));
intMods.write(3, (int) Math.floor(loc.getZ() * 32));
ItemStack item = null;
if (disguisedEntity instanceof Player && ((Player) disguisedEntity).getItemInHand() != null) {
item = ((Player) disguisedEntity).getItemInHand();
} else if (disguisedEntity instanceof LivingEntity) {
item = ((LivingEntity) disguisedEntity).getEquipment().getItemInHand();
}
intMods.write(4, (item == null || item.getType() == Material.AIR ? 0 : item.getTypeId()));
StructureModifier<Byte> byteMods = spawnPackets[0].getBytes();
byteMods.write(0, yaw);
byteMods.write(1, (byte) (int) (loc.getPitch() * 256F / 360F));
spawnPackets[0].getDataWatcherModifier().write(0,
createDataWatcher(WrappedDataWatcher.getEntityWatcher(disguisedEntity), disguise.getWatcher()));
} else if (disguise.getType().isMob()) {
DisguiseValues values = DisguiseValues.getDisguiseValues(disguise.getType());
Vector vec = disguisedEntity.getVelocity();
spawnPackets[0] = new PacketContainer(Packets.Server.MOB_SPAWN);
StructureModifier<Object> mods = spawnPackets[0].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, (int) disguise.getType().getEntityType().getTypeId());
double d1 = 3.9D;
double d2 = vec.getX();
double d3 = vec.getY();
double d4 = vec.getZ();
if (d2 < -d1)
d2 = -d1;
if (d3 < -d1)
d3 = -d1;
if (d4 < -d1)
d4 = -d1;
if (d2 > d1)
d2 = d1;
if (d3 > d1)
d3 = d1;
if (d4 > d1)
d4 = d1;
mods.write(2, values.getEntitySize(loc.getX()));
mods.write(3, (int) Math.floor(loc.getY() * 32D));
mods.write(4, values.getEntitySize(loc.getZ()));
mods.write(5, (int) (d2 * 8000.0D));
mods.write(6, (int) (d3 * 8000.0D));
mods.write(7, (int) (d4 * 8000.0D));
mods.write(8, yaw);
mods.write(9, (byte) (int) (loc.getPitch() * 256.0F / 360.0F));
spawnPackets[0].getDataWatcherModifier().write(0,
createDataWatcher(WrappedDataWatcher.getEntityWatcher(disguisedEntity), disguise.getWatcher()));
} else if (disguise.getType().isMisc()) {
int id = disguise.getType().getEntityId();
int data = 0;
if (((MiscDisguise) disguise).getId() >= 0) {
if (((MiscDisguise) disguise).getData() >= 0) {
data = (((MiscDisguise) disguise).getId() | ((MiscDisguise) disguise).getData() << 16);
} else {
data = ((MiscDisguise) disguise).getId();
}
}
// This won't actually work.
// But if someone constructing the disguise uses it properly. It will work.
if (disguise.getType() == DisguiseType.FISHING_HOOK)
data = disguise.getEntity().getEntityId();
/* else if (disguise.getType() == DisguiseType.ITEM_FRAME) {
data = (int) loc.getYaw();
if (data < 0)
data = -data;
}*/
spawnPackets[0] = ProtocolLibrary.getProtocolManager()
.createPacketConstructor(Packets.Server.VEHICLE_SPAWN, nmsEntity, id, data).createPacket(nmsEntity, id, data);
spawnPackets[0].getModifier().write(2, (int) Math.floor(loc.getY() * 32D));
spawnPackets[0].getModifier().write(8, yaw);
// Make the teleport packet to make it visible..
spawnPackets[1] = new PacketContainer(Packets.Server.ENTITY_TELEPORT);
StructureModifier<Object> mods = spawnPackets[1].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, (int) Math.floor(loc.getX() * 32D));
mods.write(2, (int) Math.floor(loc.getY() * 32D));
mods.write(3, (int) Math.floor(loc.getZ() * 32D));
mods.write(4, yaw);
mods.write(5, (byte) (int) (loc.getPitch() * 256.0F / 360.0F));
}
if (spawnPackets[1] == null) {
// Make a packet to turn his head!
spawnPackets[1] = new PacketContainer(Packets.Server.ENTITY_HEAD_ROTATION);
StructureModifier<Object> mods = spawnPackets[1].getModifier();
mods.write(0, disguisedEntity.getEntityId());
mods.write(1, yaw);
}
return spawnPackets;
}
/**
* Create a new datawatcher but with the 'correct' values
*/
private static WrappedDataWatcher createDataWatcher(WrappedDataWatcher watcher, FlagWatcher flagWatcher) {
WrappedDataWatcher newWatcher = new WrappedDataWatcher();
try {
// Calling c() gets the watchable objects exactly as they are.
List<WrappedWatchableObject> list = watcher.getWatchableObjects();
for (WrappedWatchableObject watchableObject : flagWatcher.convert(list)) {
newWatcher.setObject(watchableObject.getIndex(), watchableObject.getValue());
}
} catch (Exception ex) {
ex.printStackTrace();
}
return newWatcher;
}
public static byte getPitch(DisguiseType disguiseType, DisguiseType entityType, byte value) {
switch (disguiseType) {
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
value = (byte) -value;
break;
default:
break;
}
switch (entityType) {
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
value = (byte) -value;
break;
default:
break;
}
return value;
}
/**
* Add the yaw for the disguises
*/
public static byte getYaw(DisguiseType disguiseType, DisguiseType entityType, byte value) {
switch (disguiseType) {
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
value += 64;
break;
case ENDER_DRAGON:
case WITHER_SKULL:
value -= 128;
break;
// case ITEM_FRAME:
case ARROW:
value = (byte) -value;
break;
case PAINTING:
value = (byte) -(value + 128);
break;
default:
if (disguiseType.isMisc()) {
value -= 64;
}
break;
}
switch (entityType) {
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
value -= 64;
break;
case ENDER_DRAGON:
case WITHER_SKULL:
value += 128;
break;
// case ITEM_FRAME:
case ARROW:
value = (byte) -value;
break;
case PAINTING:
value = (byte) -(value - 128);
break;
default:
if (entityType.isMisc()) {
value += 64;
}
break;
}
return value;
}
/**
* Get the Y level to add to the disguise for realism.
*/
private static double getYModifier(Entity entity, DisguiseType disguiseType) {
switch (disguiseType) {
case BAT:
if (entity instanceof LivingEntity)
return ((LivingEntity) entity).getEyeHeight();
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
switch (entity.getType()) {
case MINECART:
case MINECART_CHEST:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case MINECART_TNT:
return 0;
default:
return 0.4;
}
case ARROW:
case BOAT:
case EGG:
case ENDER_PEARL:
case ENDER_SIGNAL:
case FIREWORK:
case PAINTING:
case SMALL_FIREBALL:
case SNOWBALL:
case SPLASH_POTION:
case THROWN_EXP_BOTTLE:
case WITHER_SKULL:
return 0.7;
default:
break;
}
return 0;
}
/**
* Creates the packet listeners
*/
public static void init(LibsDisguises plugin) {
libsDisguises = plugin;
soundsListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.NORMAL,
Packets.Server.NAMED_SOUND_EFFECT, Packets.Server.ENTITY_STATUS) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.isCancelled())
return;
StructureModifier<Object> mods = event.getPacket().getModifier();
Player observer = event.getPlayer();
if (event.getPacketID() == Packets.Server.NAMED_SOUND_EFFECT) {
String soundName = (String) mods.read(0);
SoundType soundType = null;
Location soundLoc = new Location(observer.getWorld(), ((Integer) mods.read(1)) / 8D,
((Integer) mods.read(2)) / 8D, ((Integer) mods.read(3)) / 8D);
Entity disguisedEntity = null;
DisguiseSound entitySound = null;
for (Entity entity : soundLoc.getChunk().getEntities()) {
if (DisguiseAPI.isDisguised(entity)) {
Location loc = entity.getLocation();
loc = new Location(observer.getWorld(), ((int) (loc.getX() * 8)) / 8D, ((int) (loc.getY() * 8)) / 8D,
((int) (loc.getZ() * 8)) / 8D);
if (loc.equals(soundLoc)) {
entitySound = DisguiseSound.getType(entity.getType().name());
if (entitySound != null) {
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
boolean hasInvun = false;
Object nmsEntity = ReflectionManager.getNmsEntity(entity);
try {
Class entityClass = ReflectionManager.getNmsClass("Entity");
if (entity instanceof LivingEntity) {
hasInvun = entityClass.getField("noDamageTicks").getInt(nmsEntity) == ReflectionManager
.getNmsClass("EntityLiving").getField("maxNoDamageTicks")
.getInt(nmsEntity);
} else {
hasInvun = (Boolean) entityClass.getMethod("isInvulnerable").invoke(nmsEntity);
}
} catch (Exception ex) {
ex.printStackTrace();
}
soundType = entitySound.getType(soundName, !hasInvun);
}
if (soundType != null) {
disguisedEntity = entity;
break;
}
}
}
}
}
Disguise disguise = DisguiseAPI.getDisguise(disguisedEntity);
if (disguise != null) {
if (disguise.isSelfDisguiseSoundsReplaced() || disguisedEntity != event.getPlayer()) {
if (disguise.isSoundsReplaced()) {
String sound = null;
DisguiseSound dSound = DisguiseSound.getType(disguise.getType().name());
if (dSound != null && soundType != null)
sound = dSound.getSound(soundType);
if (sound == null) {
event.setCancelled(true);
} else {
if (sound.equals("step.grass")) {
try {
int typeId = soundLoc.getWorld().getBlockTypeIdAt(soundLoc.getBlockX(),
soundLoc.getBlockY() - 1, soundLoc.getBlockZ());
Class blockClass = ReflectionManager.getNmsClass("Block");
Object block = ((Object[]) blockClass.getField("byId").get(null))[typeId];
if (block != null) {
Object step = blockClass.getField("stepSound").get(block);
mods.write(0, step.getClass().getMethod("getStepSound").invoke(step));
}
} catch (Exception ex) {
ex.printStackTrace();
}
// There is no else statement. Because seriously. This should never be null. Unless
// someone is
// sending fake sounds. In which case. Why cancel it.
} else {
mods.write(0, sound);
// Time to change the pitch and volume
if (soundType == SoundType.HURT || soundType == SoundType.DEATH
|| soundType == SoundType.IDLE) {
// If the volume is the default
if (soundType != SoundType.IDLE
&& ((Float) mods.read(4)).equals(entitySound.getDamageSoundVolume())) {
mods.write(4, dSound.getDamageSoundVolume());
}
// Here I assume its the default pitch as I can't calculate if its real.
if (disguise instanceof MobDisguise && disguisedEntity instanceof LivingEntity
&& ((MobDisguise) disguise).doesDisguiseAge()) {
boolean baby = false;
if (disguisedEntity instanceof Zombie) {
baby = ((Zombie) disguisedEntity).isBaby();
} else if (disguisedEntity instanceof Ageable) {
baby = !((Ageable) disguisedEntity).isAdult();
}
if (((MobDisguise) disguise).isAdult() == baby) {
float pitch = (Integer) mods.read(5);
if (baby) {
// If the pitch is not the expected
if (pitch > 97 || pitch < 111)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
// Min = 1.5
// Cap = 97.5
// Max = 1.7
// Cap = 110.5
} else {
// If the pitch is not the expected
if (pitch >= 63 || pitch <= 76)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
// Min = 1
// Cap = 63
// Max = 1.2
// Cap = 75.6
}
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
}
}
}
}
}
}
}
}
} else if (event.getPacketID() == Packets.Server.ENTITY_STATUS) {
if ((Byte) mods.read(1) == 1) {
// It made a damage animation
Entity entity = event.getPacket().getEntityModifier(observer.getWorld()).read(0);
Disguise disguise = DisguiseAPI.getDisguise(entity);
if (disguise != null && (disguise.isSelfDisguiseSoundsReplaced() || entity != event.getPlayer())) {
DisguiseSound disSound = DisguiseSound.getType(entity.getType().name());
if (disSound == null)
return;
SoundType soundType = null;
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
soundType = SoundType.HURT;
}
if (disSound.getSound(soundType) == null
|| (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer())) {
if (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer()) {
cancelSound = !cancelSound;
if (cancelSound)
return;
}
disSound = DisguiseSound.getType(disguise.getType().name());
if (disSound != null) {
String sound = disSound.getSound(soundType);
if (sound != null) {
Location loc = entity.getLocation();
PacketContainer packet = new PacketContainer(Packets.Server.NAMED_SOUND_EFFECT);
mods = packet.getModifier();
mods.write(0, sound);
mods.write(1, (int) (loc.getX() * 8D));
mods.write(2, (int) (loc.getY() * 8D));
mods.write(3, (int) (loc.getZ() * 8D));
mods.write(4, disSound.getDamageSoundVolume());
float pitch;
if (disguise instanceof MobDisguise && !((MobDisguise) disguise).isAdult()) {
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
} else
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
if (disguise.getType() == DisguiseType.BAT)
pitch *= 95F;
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
};
viewDisguisesListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGH,
Packets.Server.NAMED_ENTITY_SPAWN, Packets.Server.ATTACH_ENTITY, Packets.Server.REL_ENTITY_MOVE,
Packets.Server.REL_ENTITY_MOVE_LOOK, Packets.Server.ENTITY_LOOK, Packets.Server.ENTITY_TELEPORT,
Packets.Server.ENTITY_HEAD_ROTATION, Packets.Server.ENTITY_METADATA, Packets.Server.ENTITY_EQUIPMENT,
Packets.Server.ARM_ANIMATION, Packets.Server.ENTITY_LOCATION_ACTION, Packets.Server.MOB_EFFECT,
Packets.Server.ENTITY_VELOCITY, Packets.Server.UPDATE_ATTRIBUTES) {
@Override
public void onPacketSending(PacketEvent event) {
final Player observer = event.getPlayer();
if (event.getPacket().getIntegers().read(0) == observer.getEntityId()) {
int fakeId = DisguiseAPI.getFakeDisguise(observer.getEntityId());
if (fakeId > 0) {
// Here I grab the packets to convert them to, So I can display them as if the disguise sent them.
PacketContainer[] packets = transformPacket(event.getPacket(), observer);
final PacketContainer[] delayedPackets = new PacketContainer[packets.length > 0 ? packets.length - 1 : 0];
for (int i = 0; i < packets.length; i++) {
PacketContainer packet = packets[i];
if (packet.equals(event.getPacket()))
packet = packet.deepClone();
packet.getModifier().write(0, fakeId);
if (i == 0) {
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
delayedPackets[i - 1] = packet;
}
}
if (delayedPackets.length > 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
try {
for (PacketContainer packet : delayedPackets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
switch (event.getPacketID()) {
case Packets.Server.ENTITY_METADATA:
event.setPacket(event.getPacket().deepClone());
Iterator<WrappedWatchableObject> itel = event.getPacket().getWatchableCollectionModifier().read(0)
.iterator();
while (itel.hasNext()) {
WrappedWatchableObject watch = itel.next();
if (watch.getIndex() == 0) {
byte b = (Byte) watch.getValue();
byte a = (byte) (b | 1 << 5);
if ((b & 1 << 3) != 0)
a = (byte) (a | 1 << 3);
watch.setValue(a);
}
}
break;
case Packets.Server.NAMED_ENTITY_SPAWN:
PacketContainer packet = new PacketContainer(Packets.Server.ENTITY_METADATA);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, observer.getEntityId());
List<WrappedWatchableObject> watchableList = new ArrayList<WrappedWatchableObject>();
byte b = (byte) (0 | 1 << 5);
if (observer.isSprinting())
b = (byte) (b | 1 << 3);
watchableList.add(new WrappedWatchableObject(0, b));
packet.getWatchableCollectionModifier().write(0, watchableList);
event.setPacket(packet);
break;
case Packets.Server.ATTACH_ENTITY:
case Packets.Server.REL_ENTITY_MOVE:
case Packets.Server.REL_ENTITY_MOVE_LOOK:
case Packets.Server.ENTITY_LOOK:
case Packets.Server.ENTITY_TELEPORT:
case Packets.Server.ENTITY_HEAD_ROTATION:
case Packets.Server.MOB_EFFECT:
case Packets.Server.ENTITY_EQUIPMENT:
event.setCancelled(true);
break;
/* case Packets.Server.ENTITY_STATUS:
if (DisguiseAPI.getDisguise(entity).canHearSelfDisguise()
&& (Byte) event.getPacket().getModifier().read(1) == 1) {
event.setCancelled(true);
}
break;*/
default:
break;
}
}
}
}
};
// TODO Potentionally combine both listeners.
inventoryListenerServer = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGHEST,
Packets.Server.SET_SLOT, Packets.Server.WINDOW_ITEMS) {
@Override
public void onPacketSending(PacketEvent event) {
// If the inventory is the players inventory
if (event.getPlayer().getVehicle() == null && event.getPacket().getIntegers().read(0) == 0) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If the player is disguised, views self disguises and is hiding a item.
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If the server is setting the slot
// Need to set it to air if its in a place it shouldn't be.
// Things such as picking up a item, spawned in item. Plugin sets the item. etc. Will fire this
/**
* Done
*/
case Packets.Server.SET_SLOT: {
// The raw slot
// nms code has the start of the hotbar being 36.
int slot = event.getPacket().getIntegers().read(1);
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket().getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket()
.getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
}
}
break;
}
/**
* Done
*/
case Packets.Server.WINDOW_ITEMS: {
event.setPacket(event.getPacket().deepClone());
StructureModifier<ItemStack[]> mods = event.getPacket().getItemArrayModifier();
ItemStack[] items = mods.read(0);
for (int slot = 0; slot < items.length; slot++) {
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
}
}
}
mods.write(0, items);
break;
}
default:
break;
}
}
}
}
};
inventoryListenerClient = new PacketAdapter(libsDisguises, ConnectionSide.CLIENT_SIDE, ListenerPriority.HIGHEST,
Packets.Client.BLOCK_ITEM_SWITCH, Packets.Client.SET_CREATIVE_SLOT, Packets.Client.WINDOW_CLICK) {
@Override
public void onPacketReceiving(final PacketEvent event) {
if (event.getPlayer().getVehicle() == null) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If player is disguised, views self disguises and has a inventory modifier
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If they are in creative and clicked on a slot
case Packets.Client.SET_CREATIVE_SLOT: {
int slot = event.getPacket().getIntegers().read(0);
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
- int armorSlot = Math.abs(slot - 9);
+ int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
if (slot + 36 == currentSlot) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
// If the player switched item, aka he moved from slot 1 to slot 2
case Packets.Client.BLOCK_ITEM_SWITCH: {
if (disguise.isHidingHeldItemFromSelf()) {
// From logging, it seems that both bukkit and nms uses the same thing for the slot switching.
// 0 1 2 3 - 8
// If the packet is coming, then I need to replace the item they are switching to
// As for the old item, I need to restore it.
org.bukkit.inventory.ItemStack currentlyHeld = event.getPlayer().getItemInHand();
// If his old weapon isn't air
if (currentlyHeld != null && currentlyHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPlayer().getInventory().getHeldItemSlot() + 36);
mods.write(2, ReflectionManager.getNmsItem(currentlyHeld));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
org.bukkit.inventory.ItemStack newHeld = event.getPlayer().getInventory()
.getItem(event.getPacket().getIntegers().read(0));
// If his new weapon isn't air either!
if (newHeld != null && newHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPacket().getIntegers().read(0) + 36);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
break;
}
case Packets.Client.WINDOW_CLICK: {
int slot = event.getPacket().getIntegers().read(1);
org.bukkit.inventory.ItemStack clickedItem;
if (event.getPacket().getIntegers().read(3) == 1) {
// Its a shift click
clickedItem = event.getPacket().getItemModifier().read(0);
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// Rather than predict the clients actions
// Lets just update the entire inventory..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
event.getPlayer().updateInventory();
}
});
}
return;
} else {
// If its not a player inventory click
// Shift clicking is exempted for the item in hand..
if (event.getPacket().getIntegers().read(0) != 0) {
return;
}
clickedItem = event.getPlayer().getItemOnCursor();
}
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
default:
break;
}
}
}
}
};
}
public static boolean isHearDisguisesEnabled() {
return soundsListenerEnabled;
}
public static boolean isInventoryListenerEnabled() {
return inventoryModifierEnabled;
}
public static boolean isViewDisguisesListenerEnabled() {
return viewDisguisesListenerEnabled;
}
public static void setHearDisguisesListener(boolean enabled) {
if (soundsListenerEnabled != enabled) {
soundsListenerEnabled = enabled;
if (soundsListenerEnabled) {
ProtocolLibrary.getProtocolManager().addPacketListener(soundsListener);
} else {
ProtocolLibrary.getProtocolManager().removePacketListener(soundsListener);
}
}
}
public static void setInventoryListenerEnabled(boolean enabled) {
if (inventoryModifierEnabled != enabled) {
inventoryModifierEnabled = enabled;
if (inventoryModifierEnabled) {
ProtocolLibrary.getProtocolManager().addPacketListener(inventoryListenerClient);
ProtocolLibrary.getProtocolManager().addPacketListener(inventoryListenerServer);
} else {
ProtocolLibrary.getProtocolManager().removePacketListener(inventoryListenerClient);
ProtocolLibrary.getProtocolManager().removePacketListener(inventoryListenerServer);
}
for (Player player : Bukkit.getOnlinePlayers()) {
Disguise disguise = DisguiseAPI.getDisguise(player);
if (disguise != null) {
if (viewDisguisesListenerEnabled && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
player.updateInventory();
}
}
}
}
}
public static void setViewDisguisesListener(boolean enabled) {
if (viewDisguisesListenerEnabled != enabled) {
viewDisguisesListenerEnabled = enabled;
if (viewDisguisesListenerEnabled) {
ProtocolLibrary.getProtocolManager().addPacketListener(viewDisguisesListener);
} else {
ProtocolLibrary.getProtocolManager().removePacketListener(viewDisguisesListener);
}
for (Player player : Bukkit.getOnlinePlayers()) {
Disguise disguise = DisguiseAPI.getDisguise(player);
if (disguise != null) {
if (disguise.isSelfDisguiseVisible()) {
if (enabled) {
DisguiseUtilities.setupFakeDisguise(disguise);
} else {
DisguiseUtilities.removeSelfDisguise(player);
}
if (inventoryModifierEnabled && (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
player.updateInventory();
}
}
}
}
}
}
/**
* Transform the packet magically into the one I have always dreamed off. My true luv!!!
*/
private static PacketContainer[] transformPacket(PacketContainer sentPacket, Player observer) {
PacketContainer[] packets = new PacketContainer[] { sentPacket };
try {
// First get the entity, the one sending this packet
StructureModifier<Entity> entityModifer = sentPacket.getEntityModifier(observer.getWorld());
org.bukkit.entity.Entity entity = entityModifer.read((Packets.Server.COLLECT == sentPacket.getID() ? 1 : 0));
Disguise disguise = DisguiseAPI.getDisguise(entity);
// If disguised.
if (disguise != null) {
// If packet is Packets.Server.UPDATE_ATTRIBUTES
// This packet sends attributes
switch (sentPacket.getID()) {
case Packets.Server.UPDATE_ATTRIBUTES:
{
packets = new PacketContainer[0];
break;
}
// Else if the packet is sending entity metadata
case Packets.Server.ENTITY_METADATA:
{
List<WrappedWatchableObject> watchableObjects = disguise.getWatcher().convert(
packets[0].getWatchableCollectionModifier().read(0));
packets[0] = new PacketContainer(sentPacket.getID());
StructureModifier<Object> newMods = packets[0].getModifier();
newMods.write(0, entity.getEntityId());
packets[0].getWatchableCollectionModifier().write(0, watchableObjects);
break;
}
// Else if the packet is spawning..
case Packets.Server.NAMED_ENTITY_SPAWN:
case Packets.Server.MOB_SPAWN:
case Packets.Server.ADD_EXP_ORB:
case Packets.Server.VEHICLE_SPAWN:
case Packets.Server.ENTITY_PAINTING:
{
packets = constructSpawnPackets(disguise, entity);
break;
}
// Else if the disguise is attempting to send players a forbidden packet
case Packets.Server.ARM_ANIMATION:
{
if (disguise.getType().isMisc() || (packets[0].getIntegers().read(1) == 3 && !disguise.getType().isPlayer())) {
packets = new PacketContainer[0];
}
break;
}
case Packets.Server.COLLECT:
{
if (disguise.getType().isMisc())
packets = new PacketContainer[0];
break;
}
// Else if the disguise is moving.
case Packets.Server.REL_ENTITY_MOVE_LOOK:
case Packets.Server.ENTITY_LOOK:
case Packets.Server.ENTITY_TELEPORT:
{
if (sentPacket.getID() == Packets.Server.ENTITY_LOOK && disguise.getType() == DisguiseType.WITHER_SKULL) {
packets = new PacketContainer[0];
} else {
packets[0] = sentPacket.shallowClone();
StructureModifier<Object> mods = packets[0].getModifier();
byte yawValue = (Byte) mods.read(4);
mods.write(4, getYaw(disguise.getType(), DisguiseType.getType(entity.getType()), yawValue));
byte pitchValue = (Byte) mods.read(5);
mods.write(5, getPitch(disguise.getType(), DisguiseType.getType(entity.getType()), pitchValue));
if (sentPacket.getID() == Packets.Server.ENTITY_TELEPORT) {
double y = getYModifier(entity, disguise.getType());
if (y != 0) {
y *= 32;
mods.write(2, (Integer) mods.read(2) + (int) Math.floor(y));
}
}
}
break;
}
case Packets.Server.ENTITY_EQUIPMENT:
{
int slot = (Integer) packets[0].getModifier().read(1) - 1;
if (slot < 0)
slot = 4;
org.bukkit.inventory.ItemStack itemstack = disguise.getWatcher().getItemStack(slot);
if (itemstack != null) {
packets[0] = packets[0].shallowClone();
packets[0].getModifier().write(2,
(itemstack.getTypeId() == 0 ? null : ReflectionManager.getNmsItem(itemstack)));
}
break;
}
case Packets.Server.ENTITY_LOCATION_ACTION:
{
if (!disguise.getType().isPlayer()) {
packets = new PacketContainer[0];
}
break;
}
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return packets;
}
}
| true | true | public static void init(LibsDisguises plugin) {
libsDisguises = plugin;
soundsListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.NORMAL,
Packets.Server.NAMED_SOUND_EFFECT, Packets.Server.ENTITY_STATUS) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.isCancelled())
return;
StructureModifier<Object> mods = event.getPacket().getModifier();
Player observer = event.getPlayer();
if (event.getPacketID() == Packets.Server.NAMED_SOUND_EFFECT) {
String soundName = (String) mods.read(0);
SoundType soundType = null;
Location soundLoc = new Location(observer.getWorld(), ((Integer) mods.read(1)) / 8D,
((Integer) mods.read(2)) / 8D, ((Integer) mods.read(3)) / 8D);
Entity disguisedEntity = null;
DisguiseSound entitySound = null;
for (Entity entity : soundLoc.getChunk().getEntities()) {
if (DisguiseAPI.isDisguised(entity)) {
Location loc = entity.getLocation();
loc = new Location(observer.getWorld(), ((int) (loc.getX() * 8)) / 8D, ((int) (loc.getY() * 8)) / 8D,
((int) (loc.getZ() * 8)) / 8D);
if (loc.equals(soundLoc)) {
entitySound = DisguiseSound.getType(entity.getType().name());
if (entitySound != null) {
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
boolean hasInvun = false;
Object nmsEntity = ReflectionManager.getNmsEntity(entity);
try {
Class entityClass = ReflectionManager.getNmsClass("Entity");
if (entity instanceof LivingEntity) {
hasInvun = entityClass.getField("noDamageTicks").getInt(nmsEntity) == ReflectionManager
.getNmsClass("EntityLiving").getField("maxNoDamageTicks")
.getInt(nmsEntity);
} else {
hasInvun = (Boolean) entityClass.getMethod("isInvulnerable").invoke(nmsEntity);
}
} catch (Exception ex) {
ex.printStackTrace();
}
soundType = entitySound.getType(soundName, !hasInvun);
}
if (soundType != null) {
disguisedEntity = entity;
break;
}
}
}
}
}
Disguise disguise = DisguiseAPI.getDisguise(disguisedEntity);
if (disguise != null) {
if (disguise.isSelfDisguiseSoundsReplaced() || disguisedEntity != event.getPlayer()) {
if (disguise.isSoundsReplaced()) {
String sound = null;
DisguiseSound dSound = DisguiseSound.getType(disguise.getType().name());
if (dSound != null && soundType != null)
sound = dSound.getSound(soundType);
if (sound == null) {
event.setCancelled(true);
} else {
if (sound.equals("step.grass")) {
try {
int typeId = soundLoc.getWorld().getBlockTypeIdAt(soundLoc.getBlockX(),
soundLoc.getBlockY() - 1, soundLoc.getBlockZ());
Class blockClass = ReflectionManager.getNmsClass("Block");
Object block = ((Object[]) blockClass.getField("byId").get(null))[typeId];
if (block != null) {
Object step = blockClass.getField("stepSound").get(block);
mods.write(0, step.getClass().getMethod("getStepSound").invoke(step));
}
} catch (Exception ex) {
ex.printStackTrace();
}
// There is no else statement. Because seriously. This should never be null. Unless
// someone is
// sending fake sounds. In which case. Why cancel it.
} else {
mods.write(0, sound);
// Time to change the pitch and volume
if (soundType == SoundType.HURT || soundType == SoundType.DEATH
|| soundType == SoundType.IDLE) {
// If the volume is the default
if (soundType != SoundType.IDLE
&& ((Float) mods.read(4)).equals(entitySound.getDamageSoundVolume())) {
mods.write(4, dSound.getDamageSoundVolume());
}
// Here I assume its the default pitch as I can't calculate if its real.
if (disguise instanceof MobDisguise && disguisedEntity instanceof LivingEntity
&& ((MobDisguise) disguise).doesDisguiseAge()) {
boolean baby = false;
if (disguisedEntity instanceof Zombie) {
baby = ((Zombie) disguisedEntity).isBaby();
} else if (disguisedEntity instanceof Ageable) {
baby = !((Ageable) disguisedEntity).isAdult();
}
if (((MobDisguise) disguise).isAdult() == baby) {
float pitch = (Integer) mods.read(5);
if (baby) {
// If the pitch is not the expected
if (pitch > 97 || pitch < 111)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
// Min = 1.5
// Cap = 97.5
// Max = 1.7
// Cap = 110.5
} else {
// If the pitch is not the expected
if (pitch >= 63 || pitch <= 76)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
// Min = 1
// Cap = 63
// Max = 1.2
// Cap = 75.6
}
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
}
}
}
}
}
}
}
}
} else if (event.getPacketID() == Packets.Server.ENTITY_STATUS) {
if ((Byte) mods.read(1) == 1) {
// It made a damage animation
Entity entity = event.getPacket().getEntityModifier(observer.getWorld()).read(0);
Disguise disguise = DisguiseAPI.getDisguise(entity);
if (disguise != null && (disguise.isSelfDisguiseSoundsReplaced() || entity != event.getPlayer())) {
DisguiseSound disSound = DisguiseSound.getType(entity.getType().name());
if (disSound == null)
return;
SoundType soundType = null;
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
soundType = SoundType.HURT;
}
if (disSound.getSound(soundType) == null
|| (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer())) {
if (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer()) {
cancelSound = !cancelSound;
if (cancelSound)
return;
}
disSound = DisguiseSound.getType(disguise.getType().name());
if (disSound != null) {
String sound = disSound.getSound(soundType);
if (sound != null) {
Location loc = entity.getLocation();
PacketContainer packet = new PacketContainer(Packets.Server.NAMED_SOUND_EFFECT);
mods = packet.getModifier();
mods.write(0, sound);
mods.write(1, (int) (loc.getX() * 8D));
mods.write(2, (int) (loc.getY() * 8D));
mods.write(3, (int) (loc.getZ() * 8D));
mods.write(4, disSound.getDamageSoundVolume());
float pitch;
if (disguise instanceof MobDisguise && !((MobDisguise) disguise).isAdult()) {
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
} else
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
if (disguise.getType() == DisguiseType.BAT)
pitch *= 95F;
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
};
viewDisguisesListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGH,
Packets.Server.NAMED_ENTITY_SPAWN, Packets.Server.ATTACH_ENTITY, Packets.Server.REL_ENTITY_MOVE,
Packets.Server.REL_ENTITY_MOVE_LOOK, Packets.Server.ENTITY_LOOK, Packets.Server.ENTITY_TELEPORT,
Packets.Server.ENTITY_HEAD_ROTATION, Packets.Server.ENTITY_METADATA, Packets.Server.ENTITY_EQUIPMENT,
Packets.Server.ARM_ANIMATION, Packets.Server.ENTITY_LOCATION_ACTION, Packets.Server.MOB_EFFECT,
Packets.Server.ENTITY_VELOCITY, Packets.Server.UPDATE_ATTRIBUTES) {
@Override
public void onPacketSending(PacketEvent event) {
final Player observer = event.getPlayer();
if (event.getPacket().getIntegers().read(0) == observer.getEntityId()) {
int fakeId = DisguiseAPI.getFakeDisguise(observer.getEntityId());
if (fakeId > 0) {
// Here I grab the packets to convert them to, So I can display them as if the disguise sent them.
PacketContainer[] packets = transformPacket(event.getPacket(), observer);
final PacketContainer[] delayedPackets = new PacketContainer[packets.length > 0 ? packets.length - 1 : 0];
for (int i = 0; i < packets.length; i++) {
PacketContainer packet = packets[i];
if (packet.equals(event.getPacket()))
packet = packet.deepClone();
packet.getModifier().write(0, fakeId);
if (i == 0) {
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
delayedPackets[i - 1] = packet;
}
}
if (delayedPackets.length > 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
try {
for (PacketContainer packet : delayedPackets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
switch (event.getPacketID()) {
case Packets.Server.ENTITY_METADATA:
event.setPacket(event.getPacket().deepClone());
Iterator<WrappedWatchableObject> itel = event.getPacket().getWatchableCollectionModifier().read(0)
.iterator();
while (itel.hasNext()) {
WrappedWatchableObject watch = itel.next();
if (watch.getIndex() == 0) {
byte b = (Byte) watch.getValue();
byte a = (byte) (b | 1 << 5);
if ((b & 1 << 3) != 0)
a = (byte) (a | 1 << 3);
watch.setValue(a);
}
}
break;
case Packets.Server.NAMED_ENTITY_SPAWN:
PacketContainer packet = new PacketContainer(Packets.Server.ENTITY_METADATA);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, observer.getEntityId());
List<WrappedWatchableObject> watchableList = new ArrayList<WrappedWatchableObject>();
byte b = (byte) (0 | 1 << 5);
if (observer.isSprinting())
b = (byte) (b | 1 << 3);
watchableList.add(new WrappedWatchableObject(0, b));
packet.getWatchableCollectionModifier().write(0, watchableList);
event.setPacket(packet);
break;
case Packets.Server.ATTACH_ENTITY:
case Packets.Server.REL_ENTITY_MOVE:
case Packets.Server.REL_ENTITY_MOVE_LOOK:
case Packets.Server.ENTITY_LOOK:
case Packets.Server.ENTITY_TELEPORT:
case Packets.Server.ENTITY_HEAD_ROTATION:
case Packets.Server.MOB_EFFECT:
case Packets.Server.ENTITY_EQUIPMENT:
event.setCancelled(true);
break;
/* case Packets.Server.ENTITY_STATUS:
if (DisguiseAPI.getDisguise(entity).canHearSelfDisguise()
&& (Byte) event.getPacket().getModifier().read(1) == 1) {
event.setCancelled(true);
}
break;*/
default:
break;
}
}
}
}
};
// TODO Potentionally combine both listeners.
inventoryListenerServer = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGHEST,
Packets.Server.SET_SLOT, Packets.Server.WINDOW_ITEMS) {
@Override
public void onPacketSending(PacketEvent event) {
// If the inventory is the players inventory
if (event.getPlayer().getVehicle() == null && event.getPacket().getIntegers().read(0) == 0) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If the player is disguised, views self disguises and is hiding a item.
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If the server is setting the slot
// Need to set it to air if its in a place it shouldn't be.
// Things such as picking up a item, spawned in item. Plugin sets the item. etc. Will fire this
/**
* Done
*/
case Packets.Server.SET_SLOT: {
// The raw slot
// nms code has the start of the hotbar being 36.
int slot = event.getPacket().getIntegers().read(1);
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket().getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket()
.getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
}
}
break;
}
/**
* Done
*/
case Packets.Server.WINDOW_ITEMS: {
event.setPacket(event.getPacket().deepClone());
StructureModifier<ItemStack[]> mods = event.getPacket().getItemArrayModifier();
ItemStack[] items = mods.read(0);
for (int slot = 0; slot < items.length; slot++) {
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
}
}
}
mods.write(0, items);
break;
}
default:
break;
}
}
}
}
};
inventoryListenerClient = new PacketAdapter(libsDisguises, ConnectionSide.CLIENT_SIDE, ListenerPriority.HIGHEST,
Packets.Client.BLOCK_ITEM_SWITCH, Packets.Client.SET_CREATIVE_SLOT, Packets.Client.WINDOW_CLICK) {
@Override
public void onPacketReceiving(final PacketEvent event) {
if (event.getPlayer().getVehicle() == null) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If player is disguised, views self disguises and has a inventory modifier
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If they are in creative and clicked on a slot
case Packets.Client.SET_CREATIVE_SLOT: {
int slot = event.getPacket().getIntegers().read(0);
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
int armorSlot = Math.abs(slot - 9);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
if (slot + 36 == currentSlot) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
// If the player switched item, aka he moved from slot 1 to slot 2
case Packets.Client.BLOCK_ITEM_SWITCH: {
if (disguise.isHidingHeldItemFromSelf()) {
// From logging, it seems that both bukkit and nms uses the same thing for the slot switching.
// 0 1 2 3 - 8
// If the packet is coming, then I need to replace the item they are switching to
// As for the old item, I need to restore it.
org.bukkit.inventory.ItemStack currentlyHeld = event.getPlayer().getItemInHand();
// If his old weapon isn't air
if (currentlyHeld != null && currentlyHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPlayer().getInventory().getHeldItemSlot() + 36);
mods.write(2, ReflectionManager.getNmsItem(currentlyHeld));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
org.bukkit.inventory.ItemStack newHeld = event.getPlayer().getInventory()
.getItem(event.getPacket().getIntegers().read(0));
// If his new weapon isn't air either!
if (newHeld != null && newHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPacket().getIntegers().read(0) + 36);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
break;
}
case Packets.Client.WINDOW_CLICK: {
int slot = event.getPacket().getIntegers().read(1);
org.bukkit.inventory.ItemStack clickedItem;
if (event.getPacket().getIntegers().read(3) == 1) {
// Its a shift click
clickedItem = event.getPacket().getItemModifier().read(0);
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// Rather than predict the clients actions
// Lets just update the entire inventory..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
event.getPlayer().updateInventory();
}
});
}
return;
} else {
// If its not a player inventory click
// Shift clicking is exempted for the item in hand..
if (event.getPacket().getIntegers().read(0) != 0) {
return;
}
clickedItem = event.getPlayer().getItemOnCursor();
}
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
default:
break;
}
}
}
}
};
}
| public static void init(LibsDisguises plugin) {
libsDisguises = plugin;
soundsListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.NORMAL,
Packets.Server.NAMED_SOUND_EFFECT, Packets.Server.ENTITY_STATUS) {
@Override
public void onPacketSending(PacketEvent event) {
if (event.isCancelled())
return;
StructureModifier<Object> mods = event.getPacket().getModifier();
Player observer = event.getPlayer();
if (event.getPacketID() == Packets.Server.NAMED_SOUND_EFFECT) {
String soundName = (String) mods.read(0);
SoundType soundType = null;
Location soundLoc = new Location(observer.getWorld(), ((Integer) mods.read(1)) / 8D,
((Integer) mods.read(2)) / 8D, ((Integer) mods.read(3)) / 8D);
Entity disguisedEntity = null;
DisguiseSound entitySound = null;
for (Entity entity : soundLoc.getChunk().getEntities()) {
if (DisguiseAPI.isDisguised(entity)) {
Location loc = entity.getLocation();
loc = new Location(observer.getWorld(), ((int) (loc.getX() * 8)) / 8D, ((int) (loc.getY() * 8)) / 8D,
((int) (loc.getZ() * 8)) / 8D);
if (loc.equals(soundLoc)) {
entitySound = DisguiseSound.getType(entity.getType().name());
if (entitySound != null) {
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
boolean hasInvun = false;
Object nmsEntity = ReflectionManager.getNmsEntity(entity);
try {
Class entityClass = ReflectionManager.getNmsClass("Entity");
if (entity instanceof LivingEntity) {
hasInvun = entityClass.getField("noDamageTicks").getInt(nmsEntity) == ReflectionManager
.getNmsClass("EntityLiving").getField("maxNoDamageTicks")
.getInt(nmsEntity);
} else {
hasInvun = (Boolean) entityClass.getMethod("isInvulnerable").invoke(nmsEntity);
}
} catch (Exception ex) {
ex.printStackTrace();
}
soundType = entitySound.getType(soundName, !hasInvun);
}
if (soundType != null) {
disguisedEntity = entity;
break;
}
}
}
}
}
Disguise disguise = DisguiseAPI.getDisguise(disguisedEntity);
if (disguise != null) {
if (disguise.isSelfDisguiseSoundsReplaced() || disguisedEntity != event.getPlayer()) {
if (disguise.isSoundsReplaced()) {
String sound = null;
DisguiseSound dSound = DisguiseSound.getType(disguise.getType().name());
if (dSound != null && soundType != null)
sound = dSound.getSound(soundType);
if (sound == null) {
event.setCancelled(true);
} else {
if (sound.equals("step.grass")) {
try {
int typeId = soundLoc.getWorld().getBlockTypeIdAt(soundLoc.getBlockX(),
soundLoc.getBlockY() - 1, soundLoc.getBlockZ());
Class blockClass = ReflectionManager.getNmsClass("Block");
Object block = ((Object[]) blockClass.getField("byId").get(null))[typeId];
if (block != null) {
Object step = blockClass.getField("stepSound").get(block);
mods.write(0, step.getClass().getMethod("getStepSound").invoke(step));
}
} catch (Exception ex) {
ex.printStackTrace();
}
// There is no else statement. Because seriously. This should never be null. Unless
// someone is
// sending fake sounds. In which case. Why cancel it.
} else {
mods.write(0, sound);
// Time to change the pitch and volume
if (soundType == SoundType.HURT || soundType == SoundType.DEATH
|| soundType == SoundType.IDLE) {
// If the volume is the default
if (soundType != SoundType.IDLE
&& ((Float) mods.read(4)).equals(entitySound.getDamageSoundVolume())) {
mods.write(4, dSound.getDamageSoundVolume());
}
// Here I assume its the default pitch as I can't calculate if its real.
if (disguise instanceof MobDisguise && disguisedEntity instanceof LivingEntity
&& ((MobDisguise) disguise).doesDisguiseAge()) {
boolean baby = false;
if (disguisedEntity instanceof Zombie) {
baby = ((Zombie) disguisedEntity).isBaby();
} else if (disguisedEntity instanceof Ageable) {
baby = !((Ageable) disguisedEntity).isAdult();
}
if (((MobDisguise) disguise).isAdult() == baby) {
float pitch = (Integer) mods.read(5);
if (baby) {
// If the pitch is not the expected
if (pitch > 97 || pitch < 111)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
// Min = 1.5
// Cap = 97.5
// Max = 1.7
// Cap = 110.5
} else {
// If the pitch is not the expected
if (pitch >= 63 || pitch <= 76)
return;
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
// Min = 1
// Cap = 63
// Max = 1.2
// Cap = 75.6
}
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
}
}
}
}
}
}
}
}
} else if (event.getPacketID() == Packets.Server.ENTITY_STATUS) {
if ((Byte) mods.read(1) == 1) {
// It made a damage animation
Entity entity = event.getPacket().getEntityModifier(observer.getWorld()).read(0);
Disguise disguise = DisguiseAPI.getDisguise(entity);
if (disguise != null && (disguise.isSelfDisguiseSoundsReplaced() || entity != event.getPlayer())) {
DisguiseSound disSound = DisguiseSound.getType(entity.getType().name());
if (disSound == null)
return;
SoundType soundType = null;
Object obj = null;
if (entity instanceof LivingEntity) {
try {
obj = LivingEntity.class.getMethod("getHealth").invoke(entity);
} catch (Exception e) {
e.printStackTrace();
}
if (obj instanceof Double ? (Double) obj == 0 : (Integer) obj == 0) {
soundType = SoundType.DEATH;
} else {
obj = null;
}
}
if (obj == null) {
soundType = SoundType.HURT;
}
if (disSound.getSound(soundType) == null
|| (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer())) {
if (disguise.isSelfDisguiseSoundsReplaced() && entity == event.getPlayer()) {
cancelSound = !cancelSound;
if (cancelSound)
return;
}
disSound = DisguiseSound.getType(disguise.getType().name());
if (disSound != null) {
String sound = disSound.getSound(soundType);
if (sound != null) {
Location loc = entity.getLocation();
PacketContainer packet = new PacketContainer(Packets.Server.NAMED_SOUND_EFFECT);
mods = packet.getModifier();
mods.write(0, sound);
mods.write(1, (int) (loc.getX() * 8D));
mods.write(2, (int) (loc.getY() * 8D));
mods.write(3, (int) (loc.getZ() * 8D));
mods.write(4, disSound.getDamageSoundVolume());
float pitch;
if (disguise instanceof MobDisguise && !((MobDisguise) disguise).isAdult()) {
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.5F;
} else
pitch = (new Random().nextFloat() - new Random().nextFloat()) * 0.2F + 1.0F;
if (disguise.getType() == DisguiseType.BAT)
pitch *= 95F;
pitch *= 63;
if (pitch < 0)
pitch = 0;
if (pitch > 255)
pitch = 255;
mods.write(5, (int) pitch);
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
};
viewDisguisesListener = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGH,
Packets.Server.NAMED_ENTITY_SPAWN, Packets.Server.ATTACH_ENTITY, Packets.Server.REL_ENTITY_MOVE,
Packets.Server.REL_ENTITY_MOVE_LOOK, Packets.Server.ENTITY_LOOK, Packets.Server.ENTITY_TELEPORT,
Packets.Server.ENTITY_HEAD_ROTATION, Packets.Server.ENTITY_METADATA, Packets.Server.ENTITY_EQUIPMENT,
Packets.Server.ARM_ANIMATION, Packets.Server.ENTITY_LOCATION_ACTION, Packets.Server.MOB_EFFECT,
Packets.Server.ENTITY_VELOCITY, Packets.Server.UPDATE_ATTRIBUTES) {
@Override
public void onPacketSending(PacketEvent event) {
final Player observer = event.getPlayer();
if (event.getPacket().getIntegers().read(0) == observer.getEntityId()) {
int fakeId = DisguiseAPI.getFakeDisguise(observer.getEntityId());
if (fakeId > 0) {
// Here I grab the packets to convert them to, So I can display them as if the disguise sent them.
PacketContainer[] packets = transformPacket(event.getPacket(), observer);
final PacketContainer[] delayedPackets = new PacketContainer[packets.length > 0 ? packets.length - 1 : 0];
for (int i = 0; i < packets.length; i++) {
PacketContainer packet = packets[i];
if (packet.equals(event.getPacket()))
packet = packet.deepClone();
packet.getModifier().write(0, fakeId);
if (i == 0) {
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
delayedPackets[i - 1] = packet;
}
}
if (delayedPackets.length > 0) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
try {
for (PacketContainer packet : delayedPackets) {
ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false);
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
}
switch (event.getPacketID()) {
case Packets.Server.ENTITY_METADATA:
event.setPacket(event.getPacket().deepClone());
Iterator<WrappedWatchableObject> itel = event.getPacket().getWatchableCollectionModifier().read(0)
.iterator();
while (itel.hasNext()) {
WrappedWatchableObject watch = itel.next();
if (watch.getIndex() == 0) {
byte b = (Byte) watch.getValue();
byte a = (byte) (b | 1 << 5);
if ((b & 1 << 3) != 0)
a = (byte) (a | 1 << 3);
watch.setValue(a);
}
}
break;
case Packets.Server.NAMED_ENTITY_SPAWN:
PacketContainer packet = new PacketContainer(Packets.Server.ENTITY_METADATA);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, observer.getEntityId());
List<WrappedWatchableObject> watchableList = new ArrayList<WrappedWatchableObject>();
byte b = (byte) (0 | 1 << 5);
if (observer.isSprinting())
b = (byte) (b | 1 << 3);
watchableList.add(new WrappedWatchableObject(0, b));
packet.getWatchableCollectionModifier().write(0, watchableList);
event.setPacket(packet);
break;
case Packets.Server.ATTACH_ENTITY:
case Packets.Server.REL_ENTITY_MOVE:
case Packets.Server.REL_ENTITY_MOVE_LOOK:
case Packets.Server.ENTITY_LOOK:
case Packets.Server.ENTITY_TELEPORT:
case Packets.Server.ENTITY_HEAD_ROTATION:
case Packets.Server.MOB_EFFECT:
case Packets.Server.ENTITY_EQUIPMENT:
event.setCancelled(true);
break;
/* case Packets.Server.ENTITY_STATUS:
if (DisguiseAPI.getDisguise(entity).canHearSelfDisguise()
&& (Byte) event.getPacket().getModifier().read(1) == 1) {
event.setCancelled(true);
}
break;*/
default:
break;
}
}
}
}
};
// TODO Potentionally combine both listeners.
inventoryListenerServer = new PacketAdapter(libsDisguises, ConnectionSide.SERVER_SIDE, ListenerPriority.HIGHEST,
Packets.Server.SET_SLOT, Packets.Server.WINDOW_ITEMS) {
@Override
public void onPacketSending(PacketEvent event) {
// If the inventory is the players inventory
if (event.getPlayer().getVehicle() == null && event.getPacket().getIntegers().read(0) == 0) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If the player is disguised, views self disguises and is hiding a item.
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If the server is setting the slot
// Need to set it to air if its in a place it shouldn't be.
// Things such as picking up a item, spawned in item. Plugin sets the item. etc. Will fire this
/**
* Done
*/
case Packets.Server.SET_SLOT: {
// The raw slot
// nms code has the start of the hotbar being 36.
int slot = event.getPacket().getIntegers().read(1);
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket().getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
event.setPacket(event.getPacket().shallowClone());
event.getPacket()
.getModifier()
.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
}
}
}
}
break;
}
/**
* Done
*/
case Packets.Server.WINDOW_ITEMS: {
event.setPacket(event.getPacket().deepClone());
StructureModifier<ItemStack[]> mods = event.getPacket().getItemArrayModifier();
ItemStack[] items = mods.read(0);
for (int slot = 0; slot < items.length; slot++) {
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
// Get the bukkit armor slot!
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
items[slot] = new org.bukkit.inventory.ItemStack(0);
}
}
}
}
}
mods.write(0, items);
break;
}
default:
break;
}
}
}
}
};
inventoryListenerClient = new PacketAdapter(libsDisguises, ConnectionSide.CLIENT_SIDE, ListenerPriority.HIGHEST,
Packets.Client.BLOCK_ITEM_SWITCH, Packets.Client.SET_CREATIVE_SLOT, Packets.Client.WINDOW_CLICK) {
@Override
public void onPacketReceiving(final PacketEvent event) {
if (event.getPlayer().getVehicle() == null) {
Disguise disguise = DisguiseAPI.getDisguise(event.getPlayer());
// If player is disguised, views self disguises and has a inventory modifier
if (disguise != null && disguise.isSelfDisguiseVisible()
&& (disguise.isHidingArmorFromSelf() || disguise.isHidingHeldItemFromSelf())) {
switch (event.getPacketID()) {
// If they are in creative and clicked on a slot
case Packets.Client.SET_CREATIVE_SLOT: {
int slot = event.getPacket().getIntegers().read(0);
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
int armorSlot = Math.abs((slot - 5) - 3);
org.bukkit.inventory.ItemStack item = event.getPlayer().getInventory().getArmorContents()[armorSlot];
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
if (slot + 36 == currentSlot) {
org.bukkit.inventory.ItemStack item = event.getPlayer().getItemInHand();
if (item != null && item.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
// If the player switched item, aka he moved from slot 1 to slot 2
case Packets.Client.BLOCK_ITEM_SWITCH: {
if (disguise.isHidingHeldItemFromSelf()) {
// From logging, it seems that both bukkit and nms uses the same thing for the slot switching.
// 0 1 2 3 - 8
// If the packet is coming, then I need to replace the item they are switching to
// As for the old item, I need to restore it.
org.bukkit.inventory.ItemStack currentlyHeld = event.getPlayer().getItemInHand();
// If his old weapon isn't air
if (currentlyHeld != null && currentlyHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPlayer().getInventory().getHeldItemSlot() + 36);
mods.write(2, ReflectionManager.getNmsItem(currentlyHeld));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
org.bukkit.inventory.ItemStack newHeld = event.getPlayer().getInventory()
.getItem(event.getPacket().getIntegers().read(0));
// If his new weapon isn't air either!
if (newHeld != null && newHeld.getType() != Material.AIR) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, event.getPacket().getIntegers().read(0) + 36);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet, false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
break;
}
case Packets.Client.WINDOW_CLICK: {
int slot = event.getPacket().getIntegers().read(1);
org.bukkit.inventory.ItemStack clickedItem;
if (event.getPacket().getIntegers().read(3) == 1) {
// Its a shift click
clickedItem = event.getPacket().getItemModifier().read(0);
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// Rather than predict the clients actions
// Lets just update the entire inventory..
Bukkit.getScheduler().scheduleSyncDelayedTask(libsDisguises, new Runnable() {
public void run() {
event.getPlayer().updateInventory();
}
});
}
return;
} else {
// If its not a player inventory click
// Shift clicking is exempted for the item in hand..
if (event.getPacket().getIntegers().read(0) != 0) {
return;
}
clickedItem = event.getPlayer().getItemOnCursor();
}
if (clickedItem != null && clickedItem.getType() != Material.AIR) {
// If the slot is a armor slot
if (slot >= 5 && slot <= 8) {
if (disguise.isHidingArmorFromSelf()) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
// Else if its a hotbar slot
} else if (slot >= 36 && slot <= 44) {
if (disguise.isHidingHeldItemFromSelf()) {
int currentSlot = event.getPlayer().getInventory().getHeldItemSlot();
// Check if the player is on the same slot as the slot that its setting
if (slot == currentSlot + 36) {
PacketContainer packet = new PacketContainer(Packets.Server.SET_SLOT);
StructureModifier<Object> mods = packet.getModifier();
mods.write(0, 0);
mods.write(1, slot);
mods.write(2, ReflectionManager.getNmsItem(new org.bukkit.inventory.ItemStack(0)));
try {
ProtocolLibrary.getProtocolManager().sendServerPacket(event.getPlayer(), packet,
false);
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
break;
}
default:
break;
}
}
}
}
};
}
|
diff --git a/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java b/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
index 93cfc6b3..b37c3a99 100644
--- a/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
+++ b/src/main/java/de/lemo/dms/processing/questions/QPerformanceHistogram.java
@@ -1,138 +1,137 @@
package de.lemo.dms.processing.questions;
import static de.lemo.dms.processing.MetaParam.COURSE_IDS;
import static de.lemo.dms.processing.MetaParam.END_TIME;
import static de.lemo.dms.processing.MetaParam.START_TIME;
import static de.lemo.dms.processing.MetaParam.USER_IDS;
import static de.lemo.dms.processing.MetaParam.QUIZ_IDS;
import static de.lemo.dms.processing.MetaParam.RESOLUTION;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import de.lemo.dms.core.ServerConfigurationHardCoded;
import de.lemo.dms.db.IDBHandler;
import de.lemo.dms.db.miningDBclass.abstractions.IRatedLogObject;
import de.lemo.dms.db.miningDBclass.abstractions.IRatedObject;
import de.lemo.dms.processing.Question;
import de.lemo.dms.processing.resulttype.ResultListLongObject;
@Path("performanceHistogram")
public class QPerformanceHistogram extends Question{
/**
*
* @param courses (optional) List of course-ids that shall be included
* @param users (optional) List of user-ids
* @param quizzes (mandatory) List of learning object ids (the ids have to start with the type specific prefix (11 for "assignment", 14 for "quiz", 17 for "scorm"))
* @param resolution (mandatory)
* @param startTime (mandatory)
* @param endTime (mandatory)
* @return
*/
@POST
public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
- if(quizzes == null || quizzes.size() < 1 || quizzes.size() % 2 != 0 || resolution <= 0 || startTime == null || endTime == null)
+ if(quizzes == null || quizzes.size() < 1 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
- boolean getAll = (quizzes == null || quizzes.size() == 0);
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
- if((getAll || obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null ) && log.getFinalgrade() != null &&
+ if(obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
}
| false | true | public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
if(quizzes == null || quizzes.size() < 1 || quizzes.size() % 2 != 0 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
boolean getAll = (quizzes == null || quizzes.size() == 0);
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
if((getAll || obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null ) && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
| public ResultListLongObject compute(
@FormParam(COURSE_IDS) List<Long> courses,
@FormParam(USER_IDS) List<Long> users,
@FormParam(QUIZ_IDS) List<Long> quizzes,
@FormParam(RESOLUTION) int resolution,
@FormParam(START_TIME) Long startTime,
@FormParam(END_TIME) Long endTime) {
if(courses!=null && courses.size() > 0)
{
System.out.print("Parameter list: Courses: " + courses.get(0));
for(int i = 1; i < courses.size(); i++)
System.out.print(", " + courses.get(i));
System.out.println();
}
if(users!=null && users.size() > 0)
{
System.out.print("Parameter list: Users: " + users.get(0));
for(int i = 1; i < users.size(); i++)
System.out.print(", " + users.get(i));
System.out.println();
}
System.out.println("Parameter list: Resolution: : " + resolution);
System.out.println("Parameter list: Start time: : " + startTime);
System.out.println("Parameter list: End time: : " + endTime);
if(quizzes == null || quizzes.size() < 1 || resolution <= 0 || startTime == null || endTime == null)
{
System.out.println("Calculation aborted. At least one of the mandatory parameters is not set properly.");
return new ResultListLongObject();
}
//Determine length of result array
int objects = resolution * quizzes.size();
Long[] results = new Long[objects];
//Initialize result array
for(int i = 0; i < results.length; i++)
results[i] = 0L;
try
{
HashMap<Long, Integer> obj = new HashMap<Long, Integer>();
IDBHandler dbHandler = ServerConfigurationHardCoded.getInstance().getDBHandler();
Session session = dbHandler.getMiningSession();
Criteria criteria;
for(int i = 0; i < quizzes.size(); i++)
{
obj.put(quizzes.get(i), i);
}
criteria = session.createCriteria(IRatedLogObject.class, "log");
criteria.add(Restrictions.between("log.timestamp", startTime, endTime));
if(courses != null && courses.size() > 0)
criteria.add(Restrictions.in("log.course.id", courses));
if(users != null && users.size() > 0)
criteria.add(Restrictions.in("log.user.id", users));
ArrayList<IRatedLogObject> list = (ArrayList<IRatedLogObject>) criteria.list();
for(IRatedLogObject log : list)
{
if(obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId())) != null && log.getFinalgrade() != null &&
log.getMaxgrade() != null && log.getMaxgrade() > 0)
{
//Determine size of each interval
Double step = log.getMaxgrade() / resolution;
if(step > 0d)
{
//Determine interval for specific grade
int pos = (int) (log.getFinalgrade() / step);
if(pos > resolution - 1)
pos = resolution - 1;
//Increase count of specified interval
results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] = results[(resolution * obj.get(Long.valueOf(log.getPrefix() + "" + log.getLearnObjId()))) + pos] + 1;
}
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return new ResultListLongObject(Arrays.asList(results));
}
|
diff --git a/rms/org.eclipse.ptp.rm.lml.monitor.ui/src/org/eclipse/ptp/internal/rm/lml/monitor/ui/handlers/SuspendJobHandler.java b/rms/org.eclipse.ptp.rm.lml.monitor.ui/src/org/eclipse/ptp/internal/rm/lml/monitor/ui/handlers/SuspendJobHandler.java
index fff04ba5a..5003fa960 100644
--- a/rms/org.eclipse.ptp.rm.lml.monitor.ui/src/org/eclipse/ptp/internal/rm/lml/monitor/ui/handlers/SuspendJobHandler.java
+++ b/rms/org.eclipse.ptp.rm.lml.monitor.ui/src/org/eclipse/ptp/internal/rm/lml/monitor/ui/handlers/SuspendJobHandler.java
@@ -1,29 +1,29 @@
/*******************************************************************************
* Copyright (c) 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.rm.lml.monitor.ui.handlers;
import org.eclipse.ptp.core.jobs.IJobControl;
/**
* Suspend a job.
*/
public class SuspendJobHandler extends AbstractControlHandler {
/*
* (non-Javadoc)
*
* @see org.eclipse.ptp.internal.rm.lml.monitor.ui.handlers.AbstractControlHandler#getOperation()
*/
@Override
protected String getOperation() {
- return IJobControl.RESUME_OPERATION;
+ return IJobControl.SUSPEND_OPERATION;
}
}
| true | true | protected String getOperation() {
return IJobControl.RESUME_OPERATION;
}
| protected String getOperation() {
return IJobControl.SUSPEND_OPERATION;
}
|
diff --git a/src/plugins/KeyUtils/KeyExplorerUtils.java b/src/plugins/KeyUtils/KeyExplorerUtils.java
index 287e3cf..952b36c 100644
--- a/src/plugins/KeyUtils/KeyExplorerUtils.java
+++ b/src/plugins/KeyUtils/KeyExplorerUtils.java
@@ -1,498 +1,498 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.KeyUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
import com.db4o.ObjectContainer;
import freenet.client.ArchiveContext;
import freenet.client.ClientMetadata;
import freenet.client.FetchContext;
import freenet.client.FetchException;
import freenet.client.FetchResult;
import freenet.client.FetchWaiter;
import freenet.client.HighLevelSimpleClient;
import freenet.client.Metadata;
import freenet.client.MetadataParseException;
import freenet.client.InsertContext.CompatibilityMode;
import freenet.client.async.ClientContext;
import freenet.client.async.ClientGetState;
import freenet.client.async.ClientGetWorkerThread;
import freenet.client.async.ClientGetter;
import freenet.client.async.ManifestElement;
import freenet.client.async.GetCompletionCallback;
import freenet.client.async.KeyListenerConstructionException;
import freenet.client.async.SnoopBucket;
import freenet.client.async.SplitFileFetcher;
import freenet.client.async.StreamGenerator;
import freenet.client.filter.UnsafeContentTypeException;
import freenet.crypt.HashResult;
import freenet.keys.FreenetURI;
import freenet.node.RequestClient;
import freenet.node.RequestStarter;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Logger;
import freenet.support.OOMHandler;
import freenet.support.api.Bucket;
import freenet.support.api.BucketFactory;
import freenet.support.compress.CompressionOutputSizeException;
import freenet.support.compress.Compressor;
import freenet.support.compress.DecompressorThreadManager;
import freenet.support.compress.Compressor.COMPRESSOR_TYPE;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
public class KeyExplorerUtils {
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerClass(KeyExplorerUtils.class);
}
private static class SnoopGetter implements SnoopBucket {
private GetResult result;
private final BucketFactory _bf;
SnoopGetter (BucketFactory bf) {
_bf = bf;
}
@Override
public boolean snoopBucket(Bucket data, boolean isMetadata,
ObjectContainer container, ClientContext context) {
Bucket temp;
try {
temp = _bf.makeBucket(data.size());
BucketTools.copy(data, temp);
} catch (IOException e) {
Logger.error(this, "Bucket error, disk full?", e);
return true;
}
result = new GetResult(temp, isMetadata);
return true;
}
}
public static Metadata simpleManifestGet(PluginRespirator pr, FreenetURI uri) throws MetadataParseException, FetchException, IOException {
GetResult res = simpleGet(pr, uri);
if (!res.isMetaData()) {
throw new MetadataParseException("uri did not point to metadata " + uri);
}
return Metadata.construct(res.getData());
}
public static GetResult simpleGet(PluginRespirator pr, FreenetURI uri) throws FetchException {
SnoopGetter snooper = new SnoopGetter(pr.getNode().clientCore.tempBucketFactory);
FetchContext context = pr.getHLSimpleClient().getFetchContext();
FetchWaiter fw = new FetchWaiter();
ClientGetter get = new ClientGetter(fw, uri, context, RequestStarter.INTERACTIVE_PRIORITY_CLASS, (RequestClient)pr.getHLSimpleClient(), null, null, null);
get.setBucketSnoop(snooper);
try {
get.start(null, pr.getNode().clientCore.clientContext);
fw.waitForCompletion();
} catch (FetchException e) {
if (snooper.result == null) {
// really an error
Logger.error(KeyExplorerUtils.class, "pfehler", e);
throw e;
}
}
return snooper.result;
}
public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
- public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
+ public void onExpectedMIME(ClientMetadata metadata, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer, null);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
public static Metadata splitManifestGet(PluginRespirator pr, Metadata metadata) throws MetadataParseException, IOException, FetchException, KeyListenerConstructionException {
FetchResult res = splitGet(pr, metadata);
return Metadata.construct(res.asBucket());
}
public static Metadata zipManifestGet(PluginRespirator pr, FreenetURI uri) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
ZipInputStream zis = new ZipInputStream(fr.asBucket().getInputStream());
ZipEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (".metadata".equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive " + uri);
}
public static Metadata tarManifestGet(PluginRespirator pr, Metadata md, String metaName) throws FetchException, MetadataParseException, IOException {
FetchResult fr;
try {
fr = splitGet(pr, md);
} catch (KeyListenerConstructionException e) {
throw new FetchException(FetchException.INTERNAL_ERROR, e);
}
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata tarManifestGet(PluginRespirator pr, FreenetURI uri, String metaName) throws FetchException, MetadataParseException, IOException {
HighLevelSimpleClient hlsc = pr.getHLSimpleClient();
FetchContext fctx = hlsc.getFetchContext();
fctx.returnZIPManifests = true;
FetchWaiter fw = new FetchWaiter();
hlsc.fetch(uri, -1, (RequestClient) hlsc, fw, fctx);
FetchResult fr = fw.waitForCompletion();
return internalTarManifestGet(fr.asBucket(), metaName);
}
public static Metadata internalTarManifestGet(Bucket data, String metaName) throws IOException, MetadataParseException, FetchException {
TarInputStream zis = new TarInputStream(data.getInputStream());
TarEntry entry;
ByteArrayOutputStream bos;
while (true) {
entry = zis.getNextEntry();
if (entry == null)
break;
if (entry.isDirectory())
continue;
String name = entry.getName();
if (metaName.equals(name)) {
byte[] buf = new byte[32768];
bos = new ByteArrayOutputStream();
// Read the element
int readBytes;
while ((readBytes = zis.read(buf)) > 0) {
bos.write(buf, 0, readBytes);
}
bos.close();
return Metadata.construct(bos.toByteArray());
}
}
throw new FetchException(200, "impossible? no metadata in archive ");
}
public static HashMap<String, Object> parseMetadata(Metadata oldMetadata, FreenetURI oldUri) throws MalformedURLException {
return parseMetadata(oldMetadata.getDocuments(), oldUri, "");
}
private static HashMap<String, Object> parseMetadata(HashMap<String, Metadata> oldMetadata, FreenetURI oldUri, String prefix) throws MalformedURLException {
HashMap<String, Object> newMetadata = new HashMap<String, Object>();
for(Entry<String, Metadata> entry:oldMetadata.entrySet()) {
Metadata md = entry.getValue();
String name = entry.getKey();
if (md.isArchiveInternalRedirect()) {
String fname = prefix + name;
FreenetURI newUri = new FreenetURI(oldUri.toString(false, false) + "/"+ fname);
//System.err.println("NewURI: "+newUri.toString(false, false));
newMetadata.put(name, new ManifestElement(name, newUri, null));
} else if (md.isSingleFileRedirect()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else if (md.isSplitfile()) {
newMetadata.put(name, new ManifestElement(name, md.getSingleTarget(), null));
} else {
newMetadata.put(name, parseMetadata(md.getDocuments(), oldUri, prefix + name + "/"));
}
}
return newMetadata;
}
private byte[] doDownload(PluginRespirator pluginRespirator, List<String> errors, String key) {
if (errors.size() > 0) {
return null;
}
if (key == null || (key.trim().length() == 0)) {
errors.add("Are you jokingly? Empty URI");
return null;
}
try {
//FreenetURI furi = sanitizeURI(errors, key);
FreenetURI furi = new FreenetURI(key);
GetResult getresult = simpleGet(pluginRespirator, furi);
if (getresult.isMetaData()) {
return unrollMetadata(pluginRespirator, errors, Metadata.construct(getresult.getData()));
} else {
return BucketTools.toByteArray(getresult.getData());
}
} catch (MalformedURLException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (MetadataParseException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (FetchException e) {
errors.add(e.getMessage());
e.printStackTrace();
} catch (KeyListenerConstructionException e) {
errors.add(e.getMessage());
e.printStackTrace();
}
return null;
}
public static byte[] unrollMetadata(PluginRespirator pluginRespirator, List<String> errors, Metadata md) throws MalformedURLException, IOException, FetchException, MetadataParseException, KeyListenerConstructionException {
if (!md.isSplitfile()) {
errors.add("Unsupported Metadata: Not a Splitfile");
return null;
}
byte[] result = null;
result = BucketTools.toByteArray(splitGet(pluginRespirator, md).asBucket());
return result;
}
}
| true | true | public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedMIME(String mime, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer, null);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
| public static FetchResult splitGet(PluginRespirator pr, Metadata metadata) throws FetchException, MetadataParseException,
KeyListenerConstructionException {
if (!metadata.isSplitfile()) {
throw new MetadataParseException("uri did not point to splitfile");
}
final FetchWaiter fw = new FetchWaiter();
final FetchContext ctx = pr.getHLSimpleClient().getFetchContext();
GetCompletionCallback cb = new GetCompletionCallback() {
@Override
public void onBlockSetFinished(ClientGetState state, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedMIME(ClientMetadata metadata, ObjectContainer container, ClientContext context) {
}
@Override
public void onExpectedSize(long size, ObjectContainer container, ClientContext context) {
}
@Override
public void onFailure(FetchException e, ClientGetState state, ObjectContainer container, ClientContext context) {
fw.onFailure(e, null, container);
}
@Override
public void onFinalizedMetadata(ObjectContainer container) {
}
@Override
public void onTransition(ClientGetState oldState, ClientGetState newState, ObjectContainer container) {
}
@Override
public void onExpectedTopSize(long size, long compressed,
int blocksReq, int blocksTotal, ObjectContainer container,
ClientContext context) {
}
@Override
public void onHashes(HashResult[] hashes,
ObjectContainer container, ClientContext context) {
}
@Override
public void onSplitfileCompatibilityMode(CompatibilityMode min,
CompatibilityMode max, byte[] customSplitfileKey,
boolean compressed, boolean bottomLayer,
boolean definitiveAnyway, ObjectContainer container,
ClientContext context) {
}
@Override
public void onSuccess(StreamGenerator streamGenerator,
ClientMetadata clientMetadata,
List<? extends Compressor> decompressors,
ClientGetState state, ObjectContainer container,
ClientContext context) {
PipedOutputStream dataOutput = new PipedOutputStream();
PipedInputStream dataInput = new PipedInputStream();
OutputStream output = null;
DecompressorThreadManager decompressorManager = null;
ClientGetWorkerThread worker = null;
Bucket finalResult = null;
FetchResult result = null;
// FIXME use the two max lengths separately.
long maxLen = Math.max(ctx.maxTempLength, ctx.maxOutputLength);
try {
finalResult = context.getBucketFactory(false).makeBucket(maxLen);
dataOutput .connect(dataInput);
result = new FetchResult(clientMetadata, finalResult);
// Decompress
if(decompressors != null) {
if(logMINOR) Logger.minor(this, "Decompressing...");
decompressorManager = new DecompressorThreadManager(dataInput, decompressors, maxLen);
dataInput = decompressorManager.execute();
}
output = finalResult.getOutputStream();
worker = new ClientGetWorkerThread(dataInput, output, null, null, null, false, ctx.charset, ctx.prefetchHook, ctx.tagReplacer, null);
worker.start();
try {
streamGenerator.writeTo(dataOutput, container, context);
} catch(IOException e) {
//Check if the worker thread caught an exception
worker.getError();
//If not, throw the original error
throw e;
}
if(logMINOR) Logger.minor(this, "Size of written data: "+result.asBucket().size());
if(decompressorManager != null) {
if(logMINOR) Logger.minor(this, "Waiting for decompression to finalize");
decompressorManager.waitFinished();
}
if(logMINOR) Logger.minor(this, "Waiting for hashing, filtration, and writing to finish");
worker.waitFinished();
if(worker.getClientMetadata() != null) {
clientMetadata = worker.getClientMetadata();
result = new FetchResult(clientMetadata, finalResult);
}
dataOutput.close();
dataInput.close();
output.close();
} catch (OutOfMemoryError e) {
OOMHandler.handleOOM(e);
System.err.println("Failing above attempted fetch...");
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(UnsafeContentTypeException e) {
Logger.error(this, "Impossible, this piece of code does not filter", e);
onFailure(new FetchException(e.getFetchErrorCode(), e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(URISyntaxException e) {
//Impossible
Logger.error(this, "URISyntaxException converting a FreenetURI to a URI!: "+e, e);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, e), state/*Not really the state's fault*/, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(CompressionOutputSizeException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.TOO_BIG, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(IOException e) {
Logger.error(this, "Caught "+e, e);
onFailure(new FetchException(FetchException.BUCKET_ERROR, e), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(FetchException e) {
Logger.error(this, "Caught "+e, e);
onFailure(e, state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} catch(Throwable t) {
Logger.error(this, "Caught "+t, t);
onFailure(new FetchException(FetchException.INTERNAL_ERROR, t), state, container, context);
if(finalResult != null) {
finalResult.free();
}
Bucket data = result.asBucket();
data.free();
return;
} finally {
Closer.close(dataInput);
Closer.close(dataOutput);
Closer.close(output);
}
fw.onSuccess(result, null, container);
}
};
List<COMPRESSOR_TYPE> decompressors = new LinkedList<COMPRESSOR_TYPE>();
boolean deleteFetchContext = false;
ClientMetadata clientMetadata = null;
ArchiveContext actx = null;
int recursionLevel = 0;
Bucket returnBucket = null;
long token = 0;
if (metadata.isCompressed()) {
COMPRESSOR_TYPE codec = metadata.getCompressionCodec();
decompressors.add(codec);
}
VerySimpleGetter vsg = new VerySimpleGetter((short) 1, null, (RequestClient) pr.getHLSimpleClient());
SplitFileFetcher sf = new SplitFileFetcher(metadata, cb, vsg, ctx, deleteFetchContext, true, decompressors, clientMetadata, actx, recursionLevel, token,
false, (short) 0, null, pr.getNode().clientCore.clientContext);
// VerySimpleGetter vsg = new VerySimpleGetter((short) 1, uri,
// (RequestClient) pr.getHLSimpleClient());
// VerySimpleGet vs = new VerySimpleGet(ck, 0,
// pr.getHLSimpleClient().getFetchContext(), vsg);
sf.schedule(null, pr.getNode().clientCore.clientContext);
// fw.waitForCompletion();
return fw.waitForCompletion();
}
|
diff --git a/src/com/hexcore/cas/control/server/test/TestServerControl.java b/src/com/hexcore/cas/control/server/test/TestServerControl.java
index 632d626..6bf29f9 100644
--- a/src/com/hexcore/cas/control/server/test/TestServerControl.java
+++ b/src/com/hexcore/cas/control/server/test/TestServerControl.java
@@ -1,715 +1,723 @@
package com.hexcore.cas.control.server.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import junit.framework.TestCase;
import com.hexcore.cas.control.protocol.ByteNode;
import com.hexcore.cas.control.protocol.CAPMessageProtocol;
import com.hexcore.cas.control.protocol.DictNode;
import com.hexcore.cas.control.protocol.DoubleNode;
import com.hexcore.cas.control.protocol.IntNode;
import com.hexcore.cas.control.protocol.ListNode;
import com.hexcore.cas.control.protocol.Message;
import com.hexcore.cas.control.protocol.Node;
import com.hexcore.cas.control.server.ServerOverseer;
import com.hexcore.cas.math.Recti;
import com.hexcore.cas.math.Vector2i;
import com.hexcore.cas.model.Cell;
import com.hexcore.cas.model.Grid;
import com.hexcore.cas.model.HexagonGrid;
import com.hexcore.cas.model.RectangleGrid;
import com.hexcore.cas.model.ThreadWork;
import com.hexcore.cas.model.TriangleGrid;
import com.hexcore.cas.model.World;
import com.hexcore.cas.utilities.Log;
public class TestServerControl extends TestCase
{
public ServerOverseer server = null;
private static final String TAG = "Test";
public int genNum = 1;
private void testClientWork(ThreadWork[] cW)
{
Log.information(TAG, "Testing clientWork was set correctly");
assertEquals(4, cW.length);
assertEquals(0, cW[0].getID());
assertEquals(4, cW[0].getGrid().getWidth());
assertEquals(4, cW[0].getGrid().getHeight());
assertEquals(1.0, cW[0].getGrid().getCell(0, 0).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(1, 0).getValue(0));
assertEquals(0.0, cW[0].getGrid().getCell(2, 0).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(3, 0).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(0, 1).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(1, 1).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(2, 1).getValue(0));
assertEquals(0.0, cW[0].getGrid().getCell(3, 1).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(0, 2).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(1, 2).getValue(0));
assertEquals(0.0, cW[0].getGrid().getCell(2, 2).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(3, 2).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(0, 3).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(1, 3).getValue(0));
assertEquals(1.0, cW[0].getGrid().getCell(2, 3).getValue(0));
assertEquals(0.0, cW[0].getGrid().getCell(3, 3).getValue(0));
assertEquals(1, cW[0].getWorkableArea().getPosition().y);
assertEquals(1, cW[0].getWorkableArea().getPosition().x);
assertEquals(2, cW[0].getWorkableArea().getSize().y);
assertEquals(2, cW[0].getWorkableArea().getSize().x);
assertEquals(2, cW[2].getID());
assertEquals(4, cW[2].getGrid().getWidth());
assertEquals(4, cW[2].getGrid().getHeight());
assertEquals(1.0, cW[2].getGrid().getCell(0, 0).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(1, 0).getValue(0));
assertEquals(0.0, cW[2].getGrid().getCell(2, 0).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(3, 0).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(0, 1).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(1, 1).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(2, 1).getValue(0));
assertEquals(0.0, cW[2].getGrid().getCell(3, 1).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(0, 2).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(1, 2).getValue(0));
assertEquals(0.0, cW[2].getGrid().getCell(2, 2).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(3, 2).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(0, 3).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(1, 3).getValue(0));
assertEquals(1.0, cW[2].getGrid().getCell(2, 3).getValue(0));
assertEquals(0.0, cW[2].getGrid().getCell(3, 3).getValue(0));
assertEquals(1, cW[2].getWorkableArea().getPosition().y);
assertEquals(1, cW[2].getWorkableArea().getPosition().x);
assertEquals(2, cW[2].getWorkableArea().getSize().y);
assertEquals(2, cW[2].getWorkableArea().getSize().x);
assertEquals(1, cW[1].getID());
assertEquals(4, cW[1].getGrid().getWidth());
assertEquals(4, cW[1].getGrid().getHeight());
assertEquals(0.0, cW[1].getGrid().getCell(0, 0).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(1, 0).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(2, 0).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(3, 0).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(0, 1).getValue(0));
assertEquals(0.0, cW[1].getGrid().getCell(1, 1).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(2, 1).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(3, 1).getValue(0));
assertEquals(0.0, cW[1].getGrid().getCell(0, 2).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(1, 2).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(2, 2).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(3, 2).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(0, 3).getValue(0));
assertEquals(0.0, cW[1].getGrid().getCell(1, 3).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(2, 3).getValue(0));
assertEquals(1.0, cW[1].getGrid().getCell(3, 3).getValue(0));
assertEquals(1, cW[1].getWorkableArea().getPosition().y);
assertEquals(1, cW[1].getWorkableArea().getPosition().x);
assertEquals(2, cW[1].getWorkableArea().getSize().y);
assertEquals(2, cW[1].getWorkableArea().getSize().x);
assertEquals(3, cW[3].getID());
assertEquals(4, cW[3].getGrid().getWidth());
assertEquals(4, cW[3].getGrid().getHeight());
assertEquals(0.0, cW[3].getGrid().getCell(0, 0).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(1, 0).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(2, 0).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(3, 0).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(0, 1).getValue(0));
assertEquals(0.0, cW[3].getGrid().getCell(1, 1).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(2, 1).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(3, 1).getValue(0));
assertEquals(0.0, cW[3].getGrid().getCell(0, 2).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(1, 2).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(2, 2).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(3, 2).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(0, 3).getValue(0));
assertEquals(0.0, cW[3].getGrid().getCell(1, 3).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(2, 3).getValue(0));
assertEquals(1.0, cW[3].getGrid().getCell(3, 3).getValue(0));
assertEquals(1, cW[3].getWorkableArea().getPosition().y);
assertEquals(1, cW[3].getWorkableArea().getPosition().x);
assertEquals(2, cW[3].getWorkableArea().getSize().y);
assertEquals(2, cW[3].getWorkableArea().getSize().x);
Log.information(TAG, "SUCCESS - clientWork was set correctly");
}
private void testGridAfterFlips(Grid grid)
{
Log.information(TAG, "Testing grid was calculated and set correctly");
assertEquals('R', grid.getType());
assertEquals(4, grid.getWidth());
assertEquals(4, grid.getHeight());
assertEquals(1.0, grid.getCell(0, 0).getValue(0));
assertEquals(1.0, grid.getCell(1, 0).getValue(0));
assertEquals(0.0, grid.getCell(2, 0).getValue(0));
assertEquals(1.0, grid.getCell(3, 0).getValue(0));
assertEquals(1.0, grid.getCell(0, 1).getValue(0));
assertEquals(0.0, grid.getCell(1, 1).getValue(0));
assertEquals(1.0, grid.getCell(2, 1).getValue(0));
assertEquals(1.0, grid.getCell(3, 1).getValue(0));
assertEquals(1.0, grid.getCell(0, 2).getValue(0));
assertEquals(1.0, grid.getCell(1, 2).getValue(0));
assertEquals(0.0, grid.getCell(2, 2).getValue(0));
assertEquals(1.0, grid.getCell(3, 2).getValue(0));
assertEquals(1.0, grid.getCell(0, 3).getValue(0));
assertEquals(0.0, grid.getCell(1, 3).getValue(0));
assertEquals(1.0, grid.getCell(2, 3).getValue(0));
assertEquals(1.0, grid.getCell(3, 3).getValue(0));
Log.information(TAG, "SUCCESS - grid was calculated and set correctly");
}
private void testNameList(ArrayList<String> nameList)
{
Log.information(TAG, "Testing nameList was set correctly");
for(int i = 0; i < nameList.size(); i++)
assertEquals("localhost", nameList.get(i));
Log.information(TAG, "SUCCESS - nameList was set correctly");
}
private void testWorkables(Recti[] w, int NOC)
{
Log.information(TAG, "Testing workables was set correctly");
Log.information(TAG, "\tnumOfClients");
assertEquals(1, NOC);
Log.information(TAG, "\tclientWorkables");
assertEquals(0, w[0].getPosition().x);
assertEquals(0, w[0].getPosition().y);
assertEquals(2, w[0].getSize().x);
assertEquals(2, w[0].getSize().y);
assertEquals(2, w[1].getPosition().x);
assertEquals(0, w[1].getPosition().y);
assertEquals(2, w[1].getSize().x);
assertEquals(2, w[1].getSize().y);
assertEquals(0, w[2].getPosition().x);
assertEquals(2, w[2].getPosition().y);
assertEquals(2, w[2].getSize().x);
assertEquals(2, w[2].getSize().y);
assertEquals(2, w[3].getPosition().x);
assertEquals(2, w[3].getSize().x);
assertEquals(2, w[3].getSize().y);
Log.information(TAG, "SUCCESS - workables was set correctly");
}
public void testServer()
throws IOException
{
ClientThread client = new ClientThread();
client.create();
client.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
Log.information(TAG, "===============================================");
Log.information(TAG, "TESTING DISTRIBUTION SYSTEM WITH RECTANGLE GRID");
Log.information(TAG, "===============================================");
RectangleGrid g = new RectangleGrid(new Vector2i(4, 4), new Cell(1));
for(int y = 0; y < 4; y++)
for(int x = 0; x < 4; x++)
g.getCell(x, y).setValue(0, 0.0);
g.getCell(2, 0).setValue(0, 1.0);
g.getCell(1, 1).setValue(0, 1.0);
g.getCell(2, 2).setValue(0, 1.0);
g.getCell(1, 3).setValue(0, 1.0);
/*
* [0.0][0.0][1.0][0.0]
* [0.0][1.0][0.0][0.0]
* [0.0][0.0][1.0][0.0]
* [0.0][1.0][0.0][0.0]
*/
//================================== Creating ServerOverseer ==================================
World theWorld = new World();
server = new ServerOverseer(theWorld);
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("localhost");
server.setClientNames(nameList);
nameList = server.getClientNames();
testNameList(nameList);
server.start();
try
{
Thread.sleep(5000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
server.sendManualConnect(0);
try
{
Thread.sleep(2000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
server.requestStatuses();
try
{
Thread.sleep(2000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
server.simulate(g, genNum);
while(!server.isFinished())
{
try
{
Thread.sleep(2500);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Grid grid = server.getGrid();
testGridAfterFlips(grid);
int NOC = server.getNumberOfClients();
Recti[] w = server.getClientWorkables();
testWorkables(w, NOC);
ThreadWork[] cW = server.getClientWork();
testClientWork(cW);
Grid[] gens = theWorld.getWorld();
assertEquals(2, gens.length);
server.disconnect();
try
{
client.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Log.information(TAG, "Testing Distribution System complete");
}
private class ClientThread extends Thread
{
private CAPMessageProtocol capMP = null;
private boolean sentAccept = false;
private Grid grid = null;
private int ID = -1;
private static final int PROTOCOL_VERSION = 1;
private Recti workable = null;
private ServerSocket sock = null;
private static final String TAG = "ClientThread";
public void accept()
throws IOException
{
capMP = new CAPMessageProtocol(sock.accept());
capMP.start();
if(capMP != null)
Log.information(TAG, "Successfully made a connection to the server");
}
public void create()
{
try
{
sock = new ServerSocket(3119);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void run()
{
try
{
accept();
}
catch(IOException e)
{
e.printStackTrace();
}
Message message = null;
//Waiting for CONNECT message type.
message = null;
boolean displayed = false;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(header.has("VERSION"))
{
if(PROTOCOL_VERSION == ((IntNode)header.get("VERSION")).getIntValue())
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("ACCEPT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("CORES", new IntNode(2));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
sentAccept = true;
Log.information(TAG, "Accepted connection from server");
}
else
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("REJECT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("MSG", new ByteNode("VERSIONS INCOMPATIBLE"));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
Log.information(TAG, "Rejected connection from server");
}
}
else
capMP.sendState(2, "VERSION MISSING");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for CONNECT message type to raise error.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a second connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(sentAccept)
{
capMP.sendState(2, "CONNECT MESSAGE HAS ALREADY BEEN RECEIVED");
}
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for QUERY message type
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a query message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("QUERY"))
{
capMP.sendState(2, "TESTING QUERY MESSAGE TYPE - RECIEVED BY CLIENT");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE QUERY");
}
}
for(int a = 0; a < 4 * genNum; a++)
{
//Waiting for GRID message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for grid message number " + (a + 1));
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
DictNode body = (DictNode)message.getBody();
if(header.get("TYPE").toString().equals("GRID"))
{
Vector2i size = null;
Recti area = null;
int n = -1;
char type = 'X';
Grid grid = null;
int id = -1;
if(body == null)
{
capMP.sendState(2, "GRID MISSING A BODY");
}
else if(!body.has("SIZE"))
{
capMP.sendState(2, "GRID MISSING A SIZE");
}
else if(!body.has("AREA"))
{
capMP.sendState(2, "GRID MISSING AN AREA");
}
else if(!body.has("PROPERTIES"))
{
capMP.sendState(2, "GRID MISSING THE PROPERTY AMOUNT");
}
else if(!body.has("GRIDTYPE"))
{
capMP.sendState(2, "GRID MISSING THE GRID TYPE");
}
else if(!body.has("DATA"))
{
capMP.sendState(2, "GRID DATA MISSING");
}
else if(!body.has("ID"))
{
capMP.sendState(2, "GRID ID MISSING");
}
id = ((IntNode)body.get("ID")).getIntValue();
ArrayList<Node> sizeList = ((ListNode)body.get("SIZE")).getListValues();
size = new Vector2i(((IntNode)sizeList.get(0)).getIntValue(), ((IntNode)sizeList.get(1)).getIntValue());
ArrayList<Node> areaList2 = ((ListNode)body.get("AREA")).getListValues();
area = new Recti(new Vector2i(((IntNode)areaList2.get(0)).getIntValue(), ((IntNode)areaList2.get(1)).getIntValue()), new Vector2i(((IntNode)areaList2.get(2)).getIntValue(), ((IntNode)areaList2.get(3)).getIntValue()));
n = ((IntNode)body.get("PROPERTIES")).getIntValue();
type = body.get("GRIDTYPE").toString().charAt(0);
switch(type)
{
case 'h':
case 'H':
grid = new HexagonGrid(size, new Cell(n));
break;
case 't':
case 'T':
grid = new TriangleGrid(size, new Cell(n));
break;
case 'r':
case 'R':
grid = new RectangleGrid(size, new Cell(n));
break;
default:
capMP.sendState(2, "GRID TYPE INVALID");
return;
}
ArrayList<Node> rows2 = ((ListNode)body.get("DATA")).getListValues();
for(int y = 0; y < rows2.size(); y++)
{
ArrayList<Node> currRow2 = ((ListNode)rows2.get(y)).getListValues();
for(int x = 0; x < currRow2.size(); x++)
{
ArrayList<Node> currCell2 = ((ListNode)currRow2.get(x)).getListValues();
for(int i = 0; i < currCell2.size(); i++)
{
grid.getCell(x, y).setValue(i, ((DoubleNode)currCell2.get(i)).getDoubleValue());
}
}
}
this.grid = grid;
this.workable = area;
this.ID = id;
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE GRID");
}
}
//Create and send grid
for(int y = workable.getPosition().y; y < workable.getPosition().y + workable.getSize().y; y++)
{
for(int x = workable.getPosition().x; x < workable.getPosition().x + workable.getSize().x; x++)
{
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
int val = (grid.getCell(x, y).getValue(i) == 0) ? 1 : 0;
grid.getCell(x, y).setValue(i, val);
}
}
}
ListNode sizeNode = new ListNode();
sizeNode.addToList(new IntNode(grid.getWidth()));
sizeNode.addToList(new IntNode(grid.getHeight()));
ListNode rows = new ListNode();
for(int y = 0; y < grid.getHeight(); y++)
{
ListNode currRow = new ListNode();
for(int x = 0; x < grid.getWidth(); x++)
{
ListNode currCell = new ListNode();
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
currCell.addToList(new DoubleNode(grid.getCell(x, y).getValue(i)));
}
currRow.addToList(currCell);
}
rows.addToList(currRow);
}
ListNode areaList = new ListNode();
areaList.addToList(new IntNode(workable.getPosition().x));
areaList.addToList(new IntNode(workable.getPosition().y));
areaList.addToList(new IntNode(workable.getSize().x));
areaList.addToList(new IntNode(workable.getSize().y));
DictNode d = new DictNode();
d.addToDict("DATA", rows);
int val = (a <= (4 * genNum - 2)) ? 1 : 0;
d.addToDict("MORE", new IntNode(val));
d.addToDict("ID", new IntNode(ID));
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("RESULT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
Log.information(TAG, "Sending result");
Message msg = new Message(h, d);
try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
capMP.sendMessage(msg);
}
//Waiting for DISCONNECT message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a disconnect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
Log.debug(TAG, "Received disconnect message");
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("DISCONNECT"))
{
capMP.disconnect();
+ try
+ {
+ sock.close();
+ }
+ catch(IOException e)
+ {
+ e.printStackTrace();
+ }
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE DISCONNECT");
}
}
}
}
}
| true | true | public void run()
{
try
{
accept();
}
catch(IOException e)
{
e.printStackTrace();
}
Message message = null;
//Waiting for CONNECT message type.
message = null;
boolean displayed = false;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(header.has("VERSION"))
{
if(PROTOCOL_VERSION == ((IntNode)header.get("VERSION")).getIntValue())
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("ACCEPT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("CORES", new IntNode(2));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
sentAccept = true;
Log.information(TAG, "Accepted connection from server");
}
else
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("REJECT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("MSG", new ByteNode("VERSIONS INCOMPATIBLE"));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
Log.information(TAG, "Rejected connection from server");
}
}
else
capMP.sendState(2, "VERSION MISSING");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for CONNECT message type to raise error.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a second connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(sentAccept)
{
capMP.sendState(2, "CONNECT MESSAGE HAS ALREADY BEEN RECEIVED");
}
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for QUERY message type
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a query message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("QUERY"))
{
capMP.sendState(2, "TESTING QUERY MESSAGE TYPE - RECIEVED BY CLIENT");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE QUERY");
}
}
for(int a = 0; a < 4 * genNum; a++)
{
//Waiting for GRID message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for grid message number " + (a + 1));
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
DictNode body = (DictNode)message.getBody();
if(header.get("TYPE").toString().equals("GRID"))
{
Vector2i size = null;
Recti area = null;
int n = -1;
char type = 'X';
Grid grid = null;
int id = -1;
if(body == null)
{
capMP.sendState(2, "GRID MISSING A BODY");
}
else if(!body.has("SIZE"))
{
capMP.sendState(2, "GRID MISSING A SIZE");
}
else if(!body.has("AREA"))
{
capMP.sendState(2, "GRID MISSING AN AREA");
}
else if(!body.has("PROPERTIES"))
{
capMP.sendState(2, "GRID MISSING THE PROPERTY AMOUNT");
}
else if(!body.has("GRIDTYPE"))
{
capMP.sendState(2, "GRID MISSING THE GRID TYPE");
}
else if(!body.has("DATA"))
{
capMP.sendState(2, "GRID DATA MISSING");
}
else if(!body.has("ID"))
{
capMP.sendState(2, "GRID ID MISSING");
}
id = ((IntNode)body.get("ID")).getIntValue();
ArrayList<Node> sizeList = ((ListNode)body.get("SIZE")).getListValues();
size = new Vector2i(((IntNode)sizeList.get(0)).getIntValue(), ((IntNode)sizeList.get(1)).getIntValue());
ArrayList<Node> areaList2 = ((ListNode)body.get("AREA")).getListValues();
area = new Recti(new Vector2i(((IntNode)areaList2.get(0)).getIntValue(), ((IntNode)areaList2.get(1)).getIntValue()), new Vector2i(((IntNode)areaList2.get(2)).getIntValue(), ((IntNode)areaList2.get(3)).getIntValue()));
n = ((IntNode)body.get("PROPERTIES")).getIntValue();
type = body.get("GRIDTYPE").toString().charAt(0);
switch(type)
{
case 'h':
case 'H':
grid = new HexagonGrid(size, new Cell(n));
break;
case 't':
case 'T':
grid = new TriangleGrid(size, new Cell(n));
break;
case 'r':
case 'R':
grid = new RectangleGrid(size, new Cell(n));
break;
default:
capMP.sendState(2, "GRID TYPE INVALID");
return;
}
ArrayList<Node> rows2 = ((ListNode)body.get("DATA")).getListValues();
for(int y = 0; y < rows2.size(); y++)
{
ArrayList<Node> currRow2 = ((ListNode)rows2.get(y)).getListValues();
for(int x = 0; x < currRow2.size(); x++)
{
ArrayList<Node> currCell2 = ((ListNode)currRow2.get(x)).getListValues();
for(int i = 0; i < currCell2.size(); i++)
{
grid.getCell(x, y).setValue(i, ((DoubleNode)currCell2.get(i)).getDoubleValue());
}
}
}
this.grid = grid;
this.workable = area;
this.ID = id;
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE GRID");
}
}
//Create and send grid
for(int y = workable.getPosition().y; y < workable.getPosition().y + workable.getSize().y; y++)
{
for(int x = workable.getPosition().x; x < workable.getPosition().x + workable.getSize().x; x++)
{
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
int val = (grid.getCell(x, y).getValue(i) == 0) ? 1 : 0;
grid.getCell(x, y).setValue(i, val);
}
}
}
ListNode sizeNode = new ListNode();
sizeNode.addToList(new IntNode(grid.getWidth()));
sizeNode.addToList(new IntNode(grid.getHeight()));
ListNode rows = new ListNode();
for(int y = 0; y < grid.getHeight(); y++)
{
ListNode currRow = new ListNode();
for(int x = 0; x < grid.getWidth(); x++)
{
ListNode currCell = new ListNode();
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
currCell.addToList(new DoubleNode(grid.getCell(x, y).getValue(i)));
}
currRow.addToList(currCell);
}
rows.addToList(currRow);
}
ListNode areaList = new ListNode();
areaList.addToList(new IntNode(workable.getPosition().x));
areaList.addToList(new IntNode(workable.getPosition().y));
areaList.addToList(new IntNode(workable.getSize().x));
areaList.addToList(new IntNode(workable.getSize().y));
DictNode d = new DictNode();
d.addToDict("DATA", rows);
int val = (a <= (4 * genNum - 2)) ? 1 : 0;
d.addToDict("MORE", new IntNode(val));
d.addToDict("ID", new IntNode(ID));
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("RESULT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
Log.information(TAG, "Sending result");
Message msg = new Message(h, d);
try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
capMP.sendMessage(msg);
}
//Waiting for DISCONNECT message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a disconnect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
Log.debug(TAG, "Received disconnect message");
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("DISCONNECT"))
{
capMP.disconnect();
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE DISCONNECT");
}
}
}
| public void run()
{
try
{
accept();
}
catch(IOException e)
{
e.printStackTrace();
}
Message message = null;
//Waiting for CONNECT message type.
message = null;
boolean displayed = false;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(header.has("VERSION"))
{
if(PROTOCOL_VERSION == ((IntNode)header.get("VERSION")).getIntValue())
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("ACCEPT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("CORES", new IntNode(2));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
sentAccept = true;
Log.information(TAG, "Accepted connection from server");
}
else
{
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("REJECT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
DictNode b = new DictNode();
b.addToDict("MSG", new ByteNode("VERSIONS INCOMPATIBLE"));
Message msg = new Message(h, b);
capMP.sendMessage(msg);
Log.information(TAG, "Rejected connection from server");
}
}
else
capMP.sendState(2, "VERSION MISSING");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for CONNECT message type to raise error.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a second connect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("CONNECT"))
{
Log.debug(TAG, "Received connect message.");
if(sentAccept)
{
capMP.sendState(2, "CONNECT MESSAGE HAS ALREADY BEEN RECEIVED");
}
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE CONNECT");
}
}
//Waiting for QUERY message type
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a query message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("QUERY"))
{
capMP.sendState(2, "TESTING QUERY MESSAGE TYPE - RECIEVED BY CLIENT");
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE QUERY");
}
}
for(int a = 0; a < 4 * genNum; a++)
{
//Waiting for GRID message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for grid message number " + (a + 1));
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
DictNode header = message.getHeader();
DictNode body = (DictNode)message.getBody();
if(header.get("TYPE").toString().equals("GRID"))
{
Vector2i size = null;
Recti area = null;
int n = -1;
char type = 'X';
Grid grid = null;
int id = -1;
if(body == null)
{
capMP.sendState(2, "GRID MISSING A BODY");
}
else if(!body.has("SIZE"))
{
capMP.sendState(2, "GRID MISSING A SIZE");
}
else if(!body.has("AREA"))
{
capMP.sendState(2, "GRID MISSING AN AREA");
}
else if(!body.has("PROPERTIES"))
{
capMP.sendState(2, "GRID MISSING THE PROPERTY AMOUNT");
}
else if(!body.has("GRIDTYPE"))
{
capMP.sendState(2, "GRID MISSING THE GRID TYPE");
}
else if(!body.has("DATA"))
{
capMP.sendState(2, "GRID DATA MISSING");
}
else if(!body.has("ID"))
{
capMP.sendState(2, "GRID ID MISSING");
}
id = ((IntNode)body.get("ID")).getIntValue();
ArrayList<Node> sizeList = ((ListNode)body.get("SIZE")).getListValues();
size = new Vector2i(((IntNode)sizeList.get(0)).getIntValue(), ((IntNode)sizeList.get(1)).getIntValue());
ArrayList<Node> areaList2 = ((ListNode)body.get("AREA")).getListValues();
area = new Recti(new Vector2i(((IntNode)areaList2.get(0)).getIntValue(), ((IntNode)areaList2.get(1)).getIntValue()), new Vector2i(((IntNode)areaList2.get(2)).getIntValue(), ((IntNode)areaList2.get(3)).getIntValue()));
n = ((IntNode)body.get("PROPERTIES")).getIntValue();
type = body.get("GRIDTYPE").toString().charAt(0);
switch(type)
{
case 'h':
case 'H':
grid = new HexagonGrid(size, new Cell(n));
break;
case 't':
case 'T':
grid = new TriangleGrid(size, new Cell(n));
break;
case 'r':
case 'R':
grid = new RectangleGrid(size, new Cell(n));
break;
default:
capMP.sendState(2, "GRID TYPE INVALID");
return;
}
ArrayList<Node> rows2 = ((ListNode)body.get("DATA")).getListValues();
for(int y = 0; y < rows2.size(); y++)
{
ArrayList<Node> currRow2 = ((ListNode)rows2.get(y)).getListValues();
for(int x = 0; x < currRow2.size(); x++)
{
ArrayList<Node> currCell2 = ((ListNode)currRow2.get(x)).getListValues();
for(int i = 0; i < currCell2.size(); i++)
{
grid.getCell(x, y).setValue(i, ((DoubleNode)currCell2.get(i)).getDoubleValue());
}
}
}
this.grid = grid;
this.workable = area;
this.ID = id;
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE GRID");
}
}
//Create and send grid
for(int y = workable.getPosition().y; y < workable.getPosition().y + workable.getSize().y; y++)
{
for(int x = workable.getPosition().x; x < workable.getPosition().x + workable.getSize().x; x++)
{
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
int val = (grid.getCell(x, y).getValue(i) == 0) ? 1 : 0;
grid.getCell(x, y).setValue(i, val);
}
}
}
ListNode sizeNode = new ListNode();
sizeNode.addToList(new IntNode(grid.getWidth()));
sizeNode.addToList(new IntNode(grid.getHeight()));
ListNode rows = new ListNode();
for(int y = 0; y < grid.getHeight(); y++)
{
ListNode currRow = new ListNode();
for(int x = 0; x < grid.getWidth(); x++)
{
ListNode currCell = new ListNode();
for(int i = 0; i < grid.getCell(x, y).getValueCount(); i++)
{
currCell.addToList(new DoubleNode(grid.getCell(x, y).getValue(i)));
}
currRow.addToList(currCell);
}
rows.addToList(currRow);
}
ListNode areaList = new ListNode();
areaList.addToList(new IntNode(workable.getPosition().x));
areaList.addToList(new IntNode(workable.getPosition().y));
areaList.addToList(new IntNode(workable.getSize().x));
areaList.addToList(new IntNode(workable.getSize().y));
DictNode d = new DictNode();
d.addToDict("DATA", rows);
int val = (a <= (4 * genNum - 2)) ? 1 : 0;
d.addToDict("MORE", new IntNode(val));
d.addToDict("ID", new IntNode(ID));
DictNode h = new DictNode();
h.addToDict("TYPE", new ByteNode("RESULT"));
h.addToDict("VERSION", new IntNode(PROTOCOL_VERSION));
Log.information(TAG, "Sending result");
Message msg = new Message(h, d);
try
{
Thread.sleep(1000);
}
catch(Exception ex)
{
ex.printStackTrace();
}
capMP.sendMessage(msg);
}
//Waiting for DISCONNECT message type.
message = null;
while(true)
{
if(!displayed)
{
Log.debug(TAG, "Waiting for a disconnect message.");
displayed = true;
}
message = capMP.waitForMessage();
if(message != null)
{
displayed = false;
break;
}
}
if(message != null)
{
Log.debug(TAG, "Received disconnect message");
DictNode header = message.getHeader();
if(header.get("TYPE").toString().equals("DISCONNECT"))
{
capMP.disconnect();
try
{
sock.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
else
{
capMP.sendState(2, "MESSAGE TYPE IS NOT OF TYPE DISCONNECT");
}
}
}
|
diff --git a/src/main/java/net/mcft/copy/betterstorage/item/cardboard/CardboardEnchantmentRecipe.java b/src/main/java/net/mcft/copy/betterstorage/item/cardboard/CardboardEnchantmentRecipe.java
index ca353ff..5850b1b 100644
--- a/src/main/java/net/mcft/copy/betterstorage/item/cardboard/CardboardEnchantmentRecipe.java
+++ b/src/main/java/net/mcft/copy/betterstorage/item/cardboard/CardboardEnchantmentRecipe.java
@@ -1,109 +1,109 @@
package net.mcft.copy.betterstorage.item.cardboard;
import java.util.Collection;
import java.util.Map;
import net.mcft.copy.betterstorage.api.crafting.IRecipeInput;
import net.mcft.copy.betterstorage.api.crafting.StationCrafting;
import net.mcft.copy.betterstorage.api.crafting.IStationRecipe;
import net.mcft.copy.betterstorage.api.crafting.RecipeInputItemStack;
import net.mcft.copy.betterstorage.utils.StackUtils;
import net.mcft.copy.betterstorage.utils.StackUtils.StackEnchantment;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class CardboardEnchantmentRecipe implements IStationRecipe {
@Override
public StationCrafting checkMatch(ItemStack[] input) {
// Quick check if input matches the recipe.
boolean hasCardboardItems = false;
int bookIndex = -1;
ItemStack book = null;
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if (stack == null) continue;
if (stack.getItem() instanceof ICardboardItem)
hasCardboardItems = true;
else if ((book == null) && (stack.getItem() == Item.enchantedBook)) {
bookIndex = i;
book = stack;
} else return null;
}
if ((book == null) || !hasCardboardItems)
return null;
// Basic items match the recipe,
// do more expensive stuff now.
ItemStack[] output = new ItemStack[9];
int experienceCost = 0;
IRecipeInput[] requiredInput = new IRecipeInput[9];
Collection<StackEnchantment> bookEnchantments = StackUtils.getEnchantments(book).values();
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if ((stack == null) || !(stack.getItem() instanceof ICardboardItem))
continue;
ItemStack outputStack = stack.copy();
boolean canApply = false;
- Map<Integer, StackEnchantment> stackEnchants = StackUtils.getEnchantments(stack);
+ Map<Integer, StackEnchantment> stackEnchants = StackUtils.getEnchantments(outputStack);
int numEnchants = stackEnchants.size();
for (StackEnchantment bookEnch : bookEnchantments) {
if (!StackUtils.isEnchantmentCompatible(outputStack, stackEnchants.values(), bookEnch))
continue;
StackEnchantment stackEnch = stackEnchants.get(bookEnch.ench.effectId);
// Calculate enchantment cost.
int level = (bookEnch.getLevel() - ((stackEnch != null) ? stackEnch.getLevel() : 0));
experienceCost += calculateCost(bookEnch, (stackEnch == null), numEnchants);
// Set enchantment level of output item.
if (stackEnch != null) stackEnch.setLevel(bookEnch.getLevel());
else outputStack.addEnchantment(bookEnch.ench, bookEnch.getLevel());
canApply = true;
}
// If none of the enchantments on the book can
// be applied on the item, the recipe is invalid.
if (!canApply) return null;
output[i] = outputStack;
requiredInput[i] = new RecipeInputItemStack(StackUtils.copyStack(stack, 1), true);
}
requiredInput[bookIndex] = new RecipeInputItemStack(StackUtils.copyStack(book, 0, false));
return new StationCrafting(output, requiredInput, experienceCost);
}
// Utility functions
private int calculateCost(StackEnchantment ench, boolean hasEnchantment, int numEnchants) {
int weight = ench.ench.getWeight();
int costPerLevel;
if (weight > 8) costPerLevel = 1;
else if (weight > 6) costPerLevel = 2;
else if (weight > 3) costPerLevel = 3;
else if (weight > 1) costPerLevel = 4;
else costPerLevel = 6;
int cost = (costPerLevel * ench.getLevel()) - 1;
cost += CardboardRecipeHelper.getAdditionalEnchantmentCost(ench);
if (hasEnchantment)
cost += (numEnchants + 1) / 2;
return cost;
}
}
| true | true | public StationCrafting checkMatch(ItemStack[] input) {
// Quick check if input matches the recipe.
boolean hasCardboardItems = false;
int bookIndex = -1;
ItemStack book = null;
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if (stack == null) continue;
if (stack.getItem() instanceof ICardboardItem)
hasCardboardItems = true;
else if ((book == null) && (stack.getItem() == Item.enchantedBook)) {
bookIndex = i;
book = stack;
} else return null;
}
if ((book == null) || !hasCardboardItems)
return null;
// Basic items match the recipe,
// do more expensive stuff now.
ItemStack[] output = new ItemStack[9];
int experienceCost = 0;
IRecipeInput[] requiredInput = new IRecipeInput[9];
Collection<StackEnchantment> bookEnchantments = StackUtils.getEnchantments(book).values();
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if ((stack == null) || !(stack.getItem() instanceof ICardboardItem))
continue;
ItemStack outputStack = stack.copy();
boolean canApply = false;
Map<Integer, StackEnchantment> stackEnchants = StackUtils.getEnchantments(stack);
int numEnchants = stackEnchants.size();
for (StackEnchantment bookEnch : bookEnchantments) {
if (!StackUtils.isEnchantmentCompatible(outputStack, stackEnchants.values(), bookEnch))
continue;
StackEnchantment stackEnch = stackEnchants.get(bookEnch.ench.effectId);
// Calculate enchantment cost.
int level = (bookEnch.getLevel() - ((stackEnch != null) ? stackEnch.getLevel() : 0));
experienceCost += calculateCost(bookEnch, (stackEnch == null), numEnchants);
// Set enchantment level of output item.
if (stackEnch != null) stackEnch.setLevel(bookEnch.getLevel());
else outputStack.addEnchantment(bookEnch.ench, bookEnch.getLevel());
canApply = true;
}
// If none of the enchantments on the book can
// be applied on the item, the recipe is invalid.
if (!canApply) return null;
output[i] = outputStack;
requiredInput[i] = new RecipeInputItemStack(StackUtils.copyStack(stack, 1), true);
}
requiredInput[bookIndex] = new RecipeInputItemStack(StackUtils.copyStack(book, 0, false));
return new StationCrafting(output, requiredInput, experienceCost);
}
| public StationCrafting checkMatch(ItemStack[] input) {
// Quick check if input matches the recipe.
boolean hasCardboardItems = false;
int bookIndex = -1;
ItemStack book = null;
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if (stack == null) continue;
if (stack.getItem() instanceof ICardboardItem)
hasCardboardItems = true;
else if ((book == null) && (stack.getItem() == Item.enchantedBook)) {
bookIndex = i;
book = stack;
} else return null;
}
if ((book == null) || !hasCardboardItems)
return null;
// Basic items match the recipe,
// do more expensive stuff now.
ItemStack[] output = new ItemStack[9];
int experienceCost = 0;
IRecipeInput[] requiredInput = new IRecipeInput[9];
Collection<StackEnchantment> bookEnchantments = StackUtils.getEnchantments(book).values();
for (int i = 0; i < input.length; i++) {
ItemStack stack = input[i];
if ((stack == null) || !(stack.getItem() instanceof ICardboardItem))
continue;
ItemStack outputStack = stack.copy();
boolean canApply = false;
Map<Integer, StackEnchantment> stackEnchants = StackUtils.getEnchantments(outputStack);
int numEnchants = stackEnchants.size();
for (StackEnchantment bookEnch : bookEnchantments) {
if (!StackUtils.isEnchantmentCompatible(outputStack, stackEnchants.values(), bookEnch))
continue;
StackEnchantment stackEnch = stackEnchants.get(bookEnch.ench.effectId);
// Calculate enchantment cost.
int level = (bookEnch.getLevel() - ((stackEnch != null) ? stackEnch.getLevel() : 0));
experienceCost += calculateCost(bookEnch, (stackEnch == null), numEnchants);
// Set enchantment level of output item.
if (stackEnch != null) stackEnch.setLevel(bookEnch.getLevel());
else outputStack.addEnchantment(bookEnch.ench, bookEnch.getLevel());
canApply = true;
}
// If none of the enchantments on the book can
// be applied on the item, the recipe is invalid.
if (!canApply) return null;
output[i] = outputStack;
requiredInput[i] = new RecipeInputItemStack(StackUtils.copyStack(stack, 1), true);
}
requiredInput[bookIndex] = new RecipeInputItemStack(StackUtils.copyStack(book, 0, false));
return new StationCrafting(output, requiredInput, experienceCost);
}
|
diff --git a/odcleanstore/core/src/main/java/cz/cuni/mff/odcleanstore/data/DebugGraphFileLoader.java b/odcleanstore/core/src/main/java/cz/cuni/mff/odcleanstore/data/DebugGraphFileLoader.java
index 372ab828..9deb5360 100644
--- a/odcleanstore/core/src/main/java/cz/cuni/mff/odcleanstore/data/DebugGraphFileLoader.java
+++ b/odcleanstore/core/src/main/java/cz/cuni/mff/odcleanstore/data/DebugGraphFileLoader.java
@@ -1,166 +1,166 @@
package cz.cuni.mff.odcleanstore.data;
import java.io.InputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import virtuoso.jena.driver.VirtGraph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import cz.cuni.mff.odcleanstore.connection.JDBCConnectionCredentials;
import cz.cuni.mff.odcleanstore.connection.VirtuosoConnectionWrapper;
import cz.cuni.mff.odcleanstore.connection.exceptions.DatabaseException;
import cz.cuni.mff.odcleanstore.shared.UniqueGraphNameGenerator;
import de.fuberlin.wiwiss.ng4j.NamedGraph;
import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl;
/**
* Utility used to copy graphs into temporary graphs in dirty database
* @author Jakub Daniel
*/
public class DebugGraphFileLoader {
private static final Logger LOG = LoggerFactory.getLogger(DebugGraphFileLoader.class);
private static String markTemporaryGraph = "INSERT INTO DB.ODCLEANSTORE.TEMPORARY_GRAPHS (graphName) VALUES (?)";
private static String unmarkTemporaryGraph = "DELETE FROM DB.ODCLEANSTORE.TEMPORARY_GRAPHS WHERE graphName = ?";
private String temporaryGraphURIPrefix;
private JDBCConnectionCredentials connectionCredentials;
public DebugGraphFileLoader(URI temporaryGraphURIPrefix, JDBCConnectionCredentials connectionCredentials) {
this.temporaryGraphURIPrefix = temporaryGraphURIPrefix.toString();
this.connectionCredentials = connectionCredentials;
}
private static String getInputBaseURI(String temporaryGraphURIPrefix, String discriminator) {
return temporaryGraphURIPrefix + discriminator + "/input/";
}
public HashMap<String, String> load(InputStream input, String discriminator) throws Exception {
try {
return loadImpl(new MultipleFormatLoader().load(input, getInputBaseURI(this.temporaryGraphURIPrefix, discriminator)), discriminator);
} catch (Exception e) {
LOG.error("Could not finish loading debug graphs from input: {}", e.getMessage());
throw e;
}
}
private void markTemporaryGraph(String temporaryName) throws DatabaseException {
performUpdate(markTemporaryGraph, temporaryName);
}
private void unmarkTemporaryGraph(String temporaryName) throws DatabaseException {
performUpdate(unmarkTemporaryGraph, temporaryName);
}
private void performUpdate(String query, Object... objects) throws DatabaseException {
VirtuosoConnectionWrapper connection = null;
try {
connection = VirtuosoConnectionWrapper.createConnection(connectionCredentials);
connection.execute(query, objects);
} finally {
if (connection != null) {
try {
connection.close();
} catch (DatabaseException e) {
}
}
}
}
private HashMap<String, String> loadImpl(NamedGraphSetImpl namedGraphSet, String discriminator) throws Exception {
/**
* Copy them into unique graphs
*/
- UniqueGraphNameGenerator graphNameGen = new UniqueGraphNameGenerator(temporaryGraphURIPrefix + "/" + discriminator + "/debug/", connectionCredentials);
+ UniqueGraphNameGenerator graphNameGen = new UniqueGraphNameGenerator(temporaryGraphURIPrefix + discriminator + "/debug/", connectionCredentials);
HashMap<String, String> graphs = new HashMap<String, String>();
try {
Iterator<NamedGraph> it = namedGraphSet.listGraphs();
while (it.hasNext()) {
NamedGraph graph = it.next();
String name = graph.getGraphName().toString();
String temporaryName;
if (graphs.containsKey(name)) {
temporaryName = graphs.get(name);
} else {
temporaryName = graphNameGen.nextURI();
/**
* Make sure it is noted what graphs are temporarily in the database
*/
markTemporaryGraph(temporaryName);
graphs.put(name, temporaryName);
}
VirtGraph temporaryGraph = new VirtGraph(temporaryName,
connectionCredentials.getConnectionString(),
connectionCredentials.getUsername(),
connectionCredentials.getPassword());
ExtendedIterator<Triple> triples = graph.find(Node.ANY, Node.ANY, Node.ANY);
/**
* Copying contents into unique temporary destination graphs in dirty database
*/
while (triples.hasNext()) {
Triple triple = triples.next();
temporaryGraph.add(triple);
}
LOG.info("Input debug graph <{}> copied into <{}>", name, temporaryName);
}
} catch (Exception e) {
unload(graphs);
throw e;
}
return graphs;
}
public void unload(HashMap<String, String> graphs) {
Set<String> keys = graphs.keySet();
Iterator<String> it = keys.iterator();
/**
* Drop all graphs
*/
while (it.hasNext()) {
String key = it.next();
try {
VirtGraph temporaryGraph = new VirtGraph(graphs.get(key),
connectionCredentials.getConnectionString(),
connectionCredentials.getUsername(),
connectionCredentials.getPassword());
temporaryGraph.clear();
unmarkTemporaryGraph(graphs.get(key));
LOG.info("Temporary copy <{}> of input debug graph <{}> cleared", graphs.get(key), key);
} catch (Exception e) {
}
}
}
}
| true | true | private HashMap<String, String> loadImpl(NamedGraphSetImpl namedGraphSet, String discriminator) throws Exception {
/**
* Copy them into unique graphs
*/
UniqueGraphNameGenerator graphNameGen = new UniqueGraphNameGenerator(temporaryGraphURIPrefix + "/" + discriminator + "/debug/", connectionCredentials);
HashMap<String, String> graphs = new HashMap<String, String>();
try {
Iterator<NamedGraph> it = namedGraphSet.listGraphs();
while (it.hasNext()) {
NamedGraph graph = it.next();
String name = graph.getGraphName().toString();
String temporaryName;
if (graphs.containsKey(name)) {
temporaryName = graphs.get(name);
} else {
temporaryName = graphNameGen.nextURI();
/**
* Make sure it is noted what graphs are temporarily in the database
*/
markTemporaryGraph(temporaryName);
graphs.put(name, temporaryName);
}
VirtGraph temporaryGraph = new VirtGraph(temporaryName,
connectionCredentials.getConnectionString(),
connectionCredentials.getUsername(),
connectionCredentials.getPassword());
ExtendedIterator<Triple> triples = graph.find(Node.ANY, Node.ANY, Node.ANY);
/**
* Copying contents into unique temporary destination graphs in dirty database
*/
while (triples.hasNext()) {
Triple triple = triples.next();
temporaryGraph.add(triple);
}
LOG.info("Input debug graph <{}> copied into <{}>", name, temporaryName);
}
} catch (Exception e) {
unload(graphs);
throw e;
}
return graphs;
}
| private HashMap<String, String> loadImpl(NamedGraphSetImpl namedGraphSet, String discriminator) throws Exception {
/**
* Copy them into unique graphs
*/
UniqueGraphNameGenerator graphNameGen = new UniqueGraphNameGenerator(temporaryGraphURIPrefix + discriminator + "/debug/", connectionCredentials);
HashMap<String, String> graphs = new HashMap<String, String>();
try {
Iterator<NamedGraph> it = namedGraphSet.listGraphs();
while (it.hasNext()) {
NamedGraph graph = it.next();
String name = graph.getGraphName().toString();
String temporaryName;
if (graphs.containsKey(name)) {
temporaryName = graphs.get(name);
} else {
temporaryName = graphNameGen.nextURI();
/**
* Make sure it is noted what graphs are temporarily in the database
*/
markTemporaryGraph(temporaryName);
graphs.put(name, temporaryName);
}
VirtGraph temporaryGraph = new VirtGraph(temporaryName,
connectionCredentials.getConnectionString(),
connectionCredentials.getUsername(),
connectionCredentials.getPassword());
ExtendedIterator<Triple> triples = graph.find(Node.ANY, Node.ANY, Node.ANY);
/**
* Copying contents into unique temporary destination graphs in dirty database
*/
while (triples.hasNext()) {
Triple triple = triples.next();
temporaryGraph.add(triple);
}
LOG.info("Input debug graph <{}> copied into <{}>", name, temporaryName);
}
} catch (Exception e) {
unload(graphs);
throw e;
}
return graphs;
}
|
diff --git a/src/com/timsu/astrid/activities/TaskList.java b/src/com/timsu/astrid/activities/TaskList.java
index add1cf49d..4eb9138cf 100644
--- a/src/com/timsu/astrid/activities/TaskList.java
+++ b/src/com/timsu/astrid/activities/TaskList.java
@@ -1,417 +1,425 @@
package com.timsu.astrid.activities;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ViewFlipper;
import com.timsu.astrid.R;
import com.timsu.astrid.data.tag.TagController;
import com.timsu.astrid.data.task.TaskController;
import com.timsu.astrid.sync.Synchronizer;
import com.timsu.astrid.utilities.Constants;
import com.timsu.astrid.utilities.Preferences;
import com.timsu.astrid.utilities.StartupReceiver;
/**
* Main activity uses a ViewFlipper to flip between child views.
*
* @author Tim Su ([email protected])
*/
public class TaskList extends Activity {
/**
* Interface for views that are displayed from the main view page
*
* @author timsu
*/
abstract public static class SubActivity {
private TaskList parent;
private ActivityCode code;
private View view;
public SubActivity(TaskList parent, ActivityCode code, View view) {
this.parent = parent;
this.code = code;
this.view = view;
view.setTag(this);
}
// --- pass-through to activity listeners
/** Called when this subactivity is displayed to the user */
void onDisplay(Bundle variables) {
//
}
boolean onPrepareOptionsMenu(Menu menu) {
return false;
}
void onActivityResult(int requestCode, int resultCode, Intent data) {
//
}
boolean onMenuItemSelected(int featureId, MenuItem item) {
return false;
}
void onWindowFocusChanged(boolean hasFocus) {
//
}
boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
// --- pass-through to activity methods
public Resources getResources() {
return parent.getResources();
}
public View findViewById(int id) {
return view.findViewById(id);
}
public void startManagingCursor(Cursor c) {
parent.startManagingCursor(c);
}
public void setTitle(CharSequence title) {
parent.setTitle(title);
}
public void closeActivity() {
parent.finish();
}
public void launchActivity(Intent intent, int requestCode) {
parent.startActivityForResult(intent, requestCode);
}
// --- helper methods
public Activity getParent() {
return parent;
}
public TaskController getTaskController() {
return parent.taskController;
}
public TagController getTagController() {
return parent.tagController;
}
public View.OnTouchListener getGestureListener() {
return parent.gestureListener;
}
public void switchToActivity(ActivityCode activity, Bundle state) {
parent.switchToActivity(activity, state);
}
// --- internal methods
protected ActivityCode getActivityCode() {
return code;
}
protected View getView() {
return view;
}
}
/* ======================================================================
* ======================================================= internal stuff
* ====================================================================== */
public enum ActivityCode {
TASK_LIST,
TAG_LIST,
TASK_LIST_W_TAG
};
private static final String TAG_LAST_ACTIVITY = "l";
private static final String TAG_LAST_BUNDLE = "b";
private static final int FLING_DIST_THRESHOLD = 100;
private static final int FLING_VEL_THRESHOLD = 300;
// view components
private ViewFlipper viewFlipper;
private GestureDetector gestureDetector;
private View.OnTouchListener gestureListener;
private SubActivity taskList;
private SubActivity tagList;
private SubActivity taskListWTag;
private Bundle lastActivityBundle;
// animations
private Animation mInAnimationForward;
private Animation mOutAnimationForward;
private Animation mInAnimationBackward;
private Animation mOutAnimationBackward;
// data controllers
private TaskController taskController;
private TagController tagController;
// static variables
static boolean shouldCloseInstance = false;
@Override
/** Called when loading up the activity for the first time */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// open controllers & perform application startup rituals
StartupReceiver.onStartupApplication(this);
shouldCloseInstance = false;
taskController = new TaskController(this);
taskController.open();
tagController = new TagController(this);
tagController.open();
Synchronizer.setTagController(tagController);
Synchronizer.setTaskController(taskController);
setupUIComponents();
if(savedInstanceState != null && savedInstanceState.containsKey(TAG_LAST_ACTIVITY)) {
viewFlipper.setDisplayedChild(savedInstanceState.getInt(TAG_LAST_ACTIVITY));
Bundle variables = savedInstanceState.getBundle(TAG_LAST_BUNDLE);
getCurrentSubActivity().onDisplay(variables);
} else {
getCurrentSubActivity().onDisplay(null);
}
// auto sync if requested
Integer autoSyncHours = Preferences.autoSyncFrequency(this);
if(autoSyncHours != null) {
final Date lastSync = Preferences.getSyncLastSync(this);
if(lastSync == null || lastSync.getTime() +
1000L*3600*autoSyncHours < System.currentTimeMillis()) {
Synchronizer.synchronize(this, true, null);
}
}
}
/** Set up user interface components */
private void setupUIComponents() {
gestureDetector = new GestureDetector(new AstridGestureDetector());
viewFlipper = (ViewFlipper)findViewById(R.id.main);
taskList = new TaskListSubActivity(this, ActivityCode.TASK_LIST,
findViewById(R.id.tasklist_layout));
tagList = new TagListSubActivity(this, ActivityCode.TAG_LIST,
findViewById(R.id.taglist_layout));
taskListWTag = new TaskListSubActivity(this, ActivityCode.TASK_LIST_W_TAG,
findViewById(R.id.tasklistwtag_layout));
mInAnimationForward = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
mOutAnimationForward = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
mInAnimationBackward = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
mOutAnimationBackward = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
};
}
private class AstridGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
Log.i("astrid", "Got fling. X: " + (e2.getX() - e1.getX()) +
", vel: " + velocityX);
// flick R to L
if(e1.getX() - e2.getX() > FLING_DIST_THRESHOLD &&
Math.abs(velocityX) > FLING_VEL_THRESHOLD) {
switch(getCurrentSubActivity().getActivityCode()) {
case TASK_LIST:
switchToActivity(ActivityCode.TAG_LIST, null);
return true;
default:
return false;
}
}
// flick L to R
else if(e2.getX() - e1.getX() > FLING_DIST_THRESHOLD &&
Math.abs(velocityX) > FLING_VEL_THRESHOLD) {
switch(getCurrentSubActivity().getActivityCode()) {
case TASK_LIST_W_TAG:
switchToActivity(ActivityCode.TAG_LIST, null);
return true;
case TAG_LIST:
switchToActivity(ActivityCode.TASK_LIST, null);
return true;
default:
return false;
}
}
} catch (Exception e) {
// ignore!
}
return false;
}
}
/* ======================================================================
* ==================================================== subactivity stuff
* ====================================================================== */
private void switchToActivity(ActivityCode activity, Bundle variables) {
closeOptionsMenu();
// and flip to them
switch(getCurrentSubActivity().getActivityCode()) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
- viewFlipper.showNext();
- if(activity == ActivityCode.TASK_LIST_W_TAG)
- viewFlipper.showNext();
+ switch(activity) {
+ case TAG_LIST:
+ viewFlipper.showNext();
+ break;
+ case TASK_LIST_W_TAG:
+ viewFlipper.setDisplayedChild(taskListWTag.code.ordinal());
+ }
break;
case TAG_LIST:
switch(activity) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
viewFlipper.showPrevious();
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
viewFlipper.showNext();
break;
}
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
- viewFlipper.showPrevious();
- if(activity == ActivityCode.TASK_LIST_W_TAG)
- viewFlipper.showPrevious();
+ switch(activity) {
+ case TAG_LIST:
+ viewFlipper.showPrevious();
+ break;
+ case TASK_LIST:
+ viewFlipper.setDisplayedChild(taskList.code.ordinal());
+ }
break;
}
// initialize the components
switch(activity) {
case TASK_LIST:
taskList.onDisplay(variables);
break;
case TAG_LIST:
tagList.onDisplay(variables);
break;
case TASK_LIST_W_TAG:
taskListWTag.onDisplay(variables);
}
lastActivityBundle = variables;
}
private SubActivity getCurrentSubActivity() {
return (SubActivity)viewFlipper.getCurrentView().getTag();
}
/* ======================================================================
* ======================================================= event handling
* ====================================================================== */
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(TAG_LAST_ACTIVITY, getCurrentSubActivity().code.ordinal());
outState.putBundle(TAG_LAST_BUNDLE, lastActivityBundle);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(getCurrentSubActivity().onKeyDown(keyCode, event))
return true;
else
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
return getCurrentSubActivity().onPrepareOptionsMenu(menu);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Constants.RESULT_GO_HOME) {
switchToActivity(ActivityCode.TASK_LIST, null);
} else
getCurrentSubActivity().onActivityResult(requestCode, resultCode, data);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus && shouldCloseInstance) { // user wants to quit
finish();
} else
getCurrentSubActivity().onWindowFocusChanged(hasFocus);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if(getCurrentSubActivity().onMenuItemSelected(featureId, item))
return true;
else
return super.onMenuItemSelected(featureId, item);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event))
return true;
else
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
taskController.close();
tagController.close();
Synchronizer.setTagController(null);
Synchronizer.setTaskController(null);
}
}
| false | true | private void switchToActivity(ActivityCode activity, Bundle variables) {
closeOptionsMenu();
// and flip to them
switch(getCurrentSubActivity().getActivityCode()) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
viewFlipper.showNext();
if(activity == ActivityCode.TASK_LIST_W_TAG)
viewFlipper.showNext();
break;
case TAG_LIST:
switch(activity) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
viewFlipper.showPrevious();
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
viewFlipper.showNext();
break;
}
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
viewFlipper.showPrevious();
if(activity == ActivityCode.TASK_LIST_W_TAG)
viewFlipper.showPrevious();
break;
}
// initialize the components
switch(activity) {
case TASK_LIST:
taskList.onDisplay(variables);
break;
case TAG_LIST:
tagList.onDisplay(variables);
break;
case TASK_LIST_W_TAG:
taskListWTag.onDisplay(variables);
}
lastActivityBundle = variables;
}
| private void switchToActivity(ActivityCode activity, Bundle variables) {
closeOptionsMenu();
// and flip to them
switch(getCurrentSubActivity().getActivityCode()) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
switch(activity) {
case TAG_LIST:
viewFlipper.showNext();
break;
case TASK_LIST_W_TAG:
viewFlipper.setDisplayedChild(taskListWTag.code.ordinal());
}
break;
case TAG_LIST:
switch(activity) {
case TASK_LIST:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
viewFlipper.showPrevious();
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationForward);
viewFlipper.setOutAnimation(mOutAnimationForward);
viewFlipper.showNext();
break;
}
break;
case TASK_LIST_W_TAG:
viewFlipper.setInAnimation(mInAnimationBackward);
viewFlipper.setOutAnimation(mOutAnimationBackward);
switch(activity) {
case TAG_LIST:
viewFlipper.showPrevious();
break;
case TASK_LIST:
viewFlipper.setDisplayedChild(taskList.code.ordinal());
}
break;
}
// initialize the components
switch(activity) {
case TASK_LIST:
taskList.onDisplay(variables);
break;
case TAG_LIST:
tagList.onDisplay(variables);
break;
case TASK_LIST_W_TAG:
taskListWTag.onDisplay(variables);
}
lastActivityBundle = variables;
}
|
diff --git a/Dashboard/src/dashboard/util/Statistics.java b/Dashboard/src/dashboard/util/Statistics.java
index 8c5ca39..800163b 100644
--- a/Dashboard/src/dashboard/util/Statistics.java
+++ b/Dashboard/src/dashboard/util/Statistics.java
@@ -1,381 +1,381 @@
package dashboard.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import dashboard.model.*;
import dashboard.registry.StudentRegistry;
public class Statistics {
/**
* @param course
* the course you ant to get the time from
* @param moments
* the moments you want to use to get the time from
* @return
* the total time studied for that course in seconds
* | for(StudyMoment moment : moments))
* | if(moment.getCourse().getName().equals(course))
* | time += moment.getTime()
*/
public static long getTime(Course course, ArrayList<StudyMoment> moments){
long time = 0;
if(moments!=null){
for(StudyMoment moment : moments)
if(moment.getCourse().equals(course))
time += moment.getTime();
}
return time;
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* returns the total time the student has studied in seconds
* | for(StudyMoment moment : moments)
* | time += moment.getTime()
*/
public static long getTotalTime(ArrayList<StudyMoment> moments) {
long time = 0;
if(moments!=null){
for(StudyMoment moment : moments)
time += moment.getTime();
}
return time;
}
public static int getTotalPages(ArrayList<StudyMoment> moments){
int pages = 0;
for(StudyMoment moment : moments)
if(moment.getKind().equals("Theorie"))
pages += moment.getAmount();
return pages;
}
public static int getTotalExcercices(ArrayList<StudyMoment> moments){
int excercices = 0;
for(StudyMoment moment : moments)
if(moment.getKind().equals("Oefeningen"))
excercices += moment.getAmount();
return excercices;
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* an arrayList with the moments the student studied last week
*/
public static ArrayList<StudyMoment> getMomentsWeek(ArrayList<StudyMoment> moments) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.DAY_OF_WEEK,calendar.MONDAY);
Date start = calendar.getTime();
calendar.add(Calendar.WEEK_OF_YEAR,1);
Date end = calendar.getTime();
return getMomentsPeriod(moments, start, end);
}
/**
* @param moments
* the moments you want to use to get the time from
* @return
* an arrayList with the moments the student studied last week
*/
public static ArrayList<StudyMoment> getMomentsMonth(ArrayList<StudyMoment> moments) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND,0);
calendar.set(Calendar.DAY_OF_MONTH,1);
Date start = calendar.getTime();
calendar.add(calendar.MONTH,1);
Date end = calendar.getTime();
return getMomentsPeriod(moments, start, end);
}
public static ArrayList<StudyMoment> getMomentsPeriod(ArrayList<StudyMoment> moments, Date start,Date end){
ArrayList<StudyMoment> goodMoments = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments)
if(moment.getStart().before(end) &&
moment.getStart().after(start))
goodMoments.add(moment);
return goodMoments;
}
public static ArrayList<StudyMoment> getMomentsUntil(ArrayList<StudyMoment> moments,Date end){
ArrayList<StudyMoment> goodMoments = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments)
if(moment.getStart().before(end))
goodMoments.add(moment);
return goodMoments;
}
/**
* @param moments
* the moments of a student
* @param courses
* the courses of a student
* @return
* a hashmap filled with the courses and the percentage of time
* put into those courses based on total time
*/
public static HashMap<String,Long> getCourseTimes(ArrayList<StudyMoment> moments,ArrayList<CourseContract> courses){
HashMap<String,Long> result = new HashMap<String,Long>();
for(CourseContract course: courses){
long part = getTime(course.getCourse(), moments);
result.put(course.getCourse().getName(), part);
}
return result;
}
/**
* @param moments
* the moments of a student
* @param courses
* the courses of a student
* @return
* a hashmap filled with the courses and the percentage of time
* put into those courses based on total time
*/
public static HashMap<String,Long> getCoursePercents(ArrayList<StudyMoment> moments,ArrayList<CourseContract> courses){
HashMap<String,Long> result = new HashMap<String,Long>();
long totTime = getTotalTime(moments);
for(CourseContract course: courses){
long part = getTime(course.getCourse(), moments);
long resTime = (part/totTime)*100;
result.put(course.getCourse().getName(), resTime);
}
return result;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with days and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByDay(ArrayList<StudyMoment> moments){
HashMap<String, Long> results = new HashMap<String, Long>();
String dateString = "geen";
for(StudyMoment moment : moments){
String newDateString = moment.getStart().toString().substring(0, 10);
long time = moment.getTime();
if(dateString.equals(newDateString)){
time += results.get(newDateString);
results.remove(newDateString);
}
results.put(newDateString, time);
}
return results;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with locations and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByLoc(ArrayList<StudyMoment> moments,Student student){
HashMap<String,Long> ret = new HashMap<String,Long>();
Iterator<StudyMoment> it = moments.iterator();
while(it.hasNext()){
StudyMoment moment = it.next();
Integer amount = moment.getAmount();
String name;
if(moment.getLocation()==null)
name = "Geen data";
else{
Location match = student.matchStarredLocation(moment.getLocation(), 1000);
if(match==null)
name = "Overige";
else
name = match.getAlias();
}
if(ret.containsKey(name))
ret.put(name, amount+ret.get(name));
else
ret.put(name, amount.longValue());
}
return ret;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with days and the corresponding relative amount studied
*/
public static long[] getTimeByDayInWeek(ArrayList<StudyMoment> moments){
long[] results = new long[7];
for(StudyMoment moment : moments){
String dayString = moment.getStart().toString().substring(0,3);
if(dayString.equals("Mon"))
results[0] += moment.getTime();
else if(dayString.equals("Tue"))
results[1] += moment.getTime();
else if(dayString.equals("Wed"))
results[2] += moment.getTime();
else if(dayString.equals("Thu"))
results[3] += moment.getTime();
else if(dayString.equals("Fri"))
results[4] += moment.getTime();
else if(dayString.equals("Sat"))
results[5] += moment.getTime();
else if(dayString.equals("Sun"))
results[6] += moment.getTime();
}
return results;
}
/**
* @param moments
* the moments of a student
* @return
* a hashmap filled with months and the corresponding relative amount studied
*/
public static HashMap<String,Long> getTimeByMonth(ArrayList<StudyMoment> moments){
HashMap<String, Long> results = new HashMap<String, Long>();
String dateString = "geen";
for(StudyMoment moment : moments){
String newDateString = moment.getStart().toString().substring(4, 7) + moment.getStart().toString().substring(24, 28);
long time = moment.getTime();
if(dateString.equals(newDateString)){
time += results.get(newDateString);
results.remove(newDateString);
} else
dateString = newDateString;
results.put(newDateString, time);
}
return results;
}
/**
* @param moments
* the moments of a student
* @param course
* the course to search for
* @return
* an arraylist containing moments belonging to the course
*/
public static ArrayList<StudyMoment> filterMomentsByCourse(ArrayList<StudyMoment> moments,Course course){
ArrayList<StudyMoment> results = new ArrayList<StudyMoment>();
for(StudyMoment moment : moments){
if(moment.getCourse().equals(course))
results.add(moment);
}
return results;
}
/**
* @param course
* a course of the student
* @param student
* the student
* @return
* the progress in credits, assuming a credit requires 28 hours of work
*/
public static double creditProgress(Course course,Student student){
double done = getTime(course,student.getStudyMoments());
double exp = course.getCredit()*28*60*60;
double div = done/exp;
if(done<exp)
return div;
else
return 1;
}
/**
* @param course
* a course
* @return
* the average progress in credits, assuming a credit requires 28 hours of work
*/
public static double averageCreditProgress(Course course){
List<Student> allStudents = StudentRegistry.getUsers();
double all = 0;
long total = 0;
for(Student student: allStudents){
ArrayList<CourseContract> contracts = student.getCourses();
if(contracts!=null){
for(CourseContract contract : contracts){
if(contract.getCourse().equals(course)){
all += creditProgress(course,student);
total++;
break;
}
}
}
}
double div = all/total;
if(total==0)
return 0;
else
return div;
}
public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
- if(student.getCourses().contains(course)){
+ if(student.getCourseList().contains(course)){
long time = getTime(course, student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
public static long[][] getPeopleStats(int sections){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
long time = getTotalTime(student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
}
| true | true | public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
if(student.getCourses().contains(course)){
long time = getTime(course, student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
| public static long[][] getPeopleStatsCourse(int sections, Course course){
long[][] timeMatrix = new long[2][sections];
ArrayList<Long> times = new ArrayList<Long>();
long maxTime = 0;
for(Student student : StudentRegistry.getUsers()){
if(student.getCourseList().contains(course)){
long time = getTime(course, student.getStudyMoments());
times.add(time);
if(time > maxTime)
maxTime = time;
}
}
for(int i=0; i < sections; i++){
timeMatrix[0][i] = ((i+1)*maxTime)/sections;
timeMatrix[1][i] = 0;
}
for(long time : times){
for(int i=0; i < sections; i++){
if(time <= timeMatrix[0][i]){
timeMatrix[1][i]++;
break;
}
}
}
return timeMatrix;
}
|
diff --git a/src/net/rptools/maptool/model/SquareGrid.java b/src/net/rptools/maptool/model/SquareGrid.java
index b5f96c9e..639f484a 100644
--- a/src/net/rptools/maptool/model/SquareGrid.java
+++ b/src/net/rptools/maptool/model/SquareGrid.java
@@ -1,247 +1,248 @@
package net.rptools.maptool.model;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Area;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import javax.swing.SwingUtilities;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.maptool.client.AppState;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.ScreenPoint;
import net.rptools.maptool.client.ui.zone.ZoneRenderer;
import net.rptools.maptool.client.walker.ZoneWalker;
import net.rptools.maptool.client.walker.astar.AStarSquareEuclideanWalker;
public class SquareGrid extends Grid {
private static final Dimension CELL_OFFSET = new Dimension(0, 0);
private static BufferedImage pathHighlight;
private static List<TokenFootprint> footprintList;
static {
try {
pathHighlight = ImageUtil.getCompatibleImage("net/rptools/maptool/client/image/whiteBorder.png");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private static final GridCapabilities CAPABILITIES = new GridCapabilities() {
public boolean isPathingSupported() {return true;}
public boolean isSnapToGridSupported() {return true;}
public boolean isPathLineSupported() {return true;}
public boolean isSecondDimensionAdjustmentSupported() {return false;}
public boolean isCoordinatesSupported() {return true;}
};
private static final int[] FACING_ANGLES = new int[] {
-135, -90, -45, 0, 45, 90, 135, 180
};
public SquareGrid() {
super();
}
@Override
public void drawCoordinatesOverlay(Graphics2D g, ZoneRenderer renderer) {
Object oldAA = SwingUtil.useAntiAliasing(g);
- Font font = g.getFont().deriveFont(20f).deriveFont(Font.BOLD);
- g.setFont(font);
+ Font oldFont = g.getFont();
+ g.setFont(g.getFont().deriveFont(20f).deriveFont(Font.BOLD));
FontMetrics fm = g.getFontMetrics();
double cellSize = renderer.getScaledGridSize();
CellPoint topLeft = convert(new ScreenPoint(0, 0).convertToZone(renderer));
ScreenPoint sp = ScreenPoint.fromZonePoint(renderer, convert(topLeft));
Dimension size = renderer.getSize();
int startX = SwingUtilities.computeStringWidth(fm, "MMM") + 10;
double x = sp.x + cellSize/2; // Start at middle of the cell that's on screen
int nextAvailableSpace = -1;
while (x < size.width) {
String coord = Integer.toString(topLeft.x);
int strWidth = SwingUtilities.computeStringWidth(fm, coord);
int strX = (int)x - strWidth/2;
if (x > startX && strX > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, strX, fm.getHeight());
g.setColor(Color.orange);
g.drawString(coord, strX-1, fm.getHeight()-1);
nextAvailableSpace = strX + strWidth + 10;
}
x += cellSize;
topLeft.x ++;
}
double y = sp.y + cellSize/2; // Start at middle of the cell that's on screen
nextAvailableSpace = -1;
while (y < size.height) {
String coord = Integer.toString(topLeft.y);
int strY = (int)y + fm.getAscent()/2;
if (y > fm.getHeight() && strY > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, 10, strY);
g.setColor(Color.yellow);
g.drawString(coord, 10-1, strY-1);
nextAvailableSpace = strY + fm.getAscent()/2 + 10;
}
y += cellSize;
topLeft.y ++;
}
+ g.setFont(oldFont);
SwingUtil.restoreAntiAliasing(g, oldAA);
}
@Override
public List<TokenFootprint> getFootprints() {
if (footprintList == null) {
try {
footprintList = loadFootprints("net/rptools/maptool/model/squareGridFootprints.xml");
} catch (IOException ioe) {
ioe.printStackTrace();
MapTool.showError("Could not load square grid footprints");
}
}
return footprintList;
}
@Override
public Rectangle getBounds(CellPoint cp) {
return new Rectangle(cp.x * getSize(), cp.y * getSize(), getSize(), getSize());
}
@Override
public BufferedImage getCellHighlight() {
return pathHighlight;
}
@Override
protected Area createCellShape(int size) {
return new Area(new Rectangle(0, 0, size, size));
}
@Override
public Dimension getCellOffset() {
return CELL_OFFSET;
}
@Override
public double getCellHeight() {
return getSize();
}
@Override
public double getCellWidth() {
return getSize();
}
@Override
public int[] getFacingAngles() {
return FACING_ANGLES;
}
@Override
public CellPoint convert(ZonePoint zp) {
double calcX = (zp.x-getOffsetX()) / (float)getSize();
double calcY = (zp.y-getOffsetY()) / (float)getSize();
boolean exactCalcX = (zp.x-getOffsetX()) % getSize() == 0;
boolean exactCalcY = (zp.y-getOffsetY()) % getSize() == 0;
int newX = (int)(zp.x < 0 && !exactCalcX ? calcX-1 : calcX);
int newY = (int)(zp.y < 0 && !exactCalcY ? calcY-1 : calcY);
//System.out.format("%d / %d => %f, %f => %d, %d\n", zp.x, getSize(), calcX, calcY, newX, newY);
return new CellPoint(newX, newY);
}
@Override
public ZoneWalker createZoneWalker() {
return new AStarSquareEuclideanWalker(getZone());
}
@Override
public ZonePoint convert(CellPoint cp) {
return new ZonePoint((int)(cp.x * getSize() + getOffsetX()),
(int)(cp.y * getSize() + getOffsetY()));
}
@Override
public GridCapabilities getCapabilities() {
return CAPABILITIES;
}
@Override
public void draw(ZoneRenderer renderer, Graphics2D g, Rectangle bounds) {
double scale = renderer.getScale();
double gridSize = getSize() * scale;
g.setColor(new Color(getZone().getGridColor()));
int offX = (int)(renderer.getViewOffsetX() % gridSize + getOffsetX()*scale);
int offY = (int)(renderer.getViewOffsetY() % gridSize + getOffsetY()*scale);
int startCol = (int)((int)(bounds.x / gridSize) * gridSize);
int startRow = (int)((int)(bounds.y / gridSize) * gridSize);
for (double row = startRow; row < bounds.y + bounds.height + gridSize; row += gridSize) {
if (AppState.getGridSize() == 1) {
g.drawLine(bounds.x, (int)(row + offY), bounds.x+bounds.width, (int)(row + offY));
} else {
g.fillRect(bounds.x, (int)(row + offY - (AppState.getGridSize()/2)), bounds.width, AppState.getGridSize());
}
}
for (double col = startCol; col < bounds.x + bounds.width + gridSize; col += gridSize) {
if (AppState.getGridSize() == 1) {
g.drawLine((int)(col + offX), bounds.y, (int)(col + offX), bounds.y + bounds.height);
} else {
g.fillRect((int)(col + offX - (AppState.getGridSize()/2)), bounds.y, AppState.getGridSize(), bounds.height);
}
}
}
public ZonePoint getCenterPoint(CellPoint cellPoint) {
ZonePoint zp = convert(cellPoint);
zp.x += getCellWidth()/2;
zp.y += getCellHeight()/2;
return zp;
}
}
| false | true | public void drawCoordinatesOverlay(Graphics2D g, ZoneRenderer renderer) {
Object oldAA = SwingUtil.useAntiAliasing(g);
Font font = g.getFont().deriveFont(20f).deriveFont(Font.BOLD);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
double cellSize = renderer.getScaledGridSize();
CellPoint topLeft = convert(new ScreenPoint(0, 0).convertToZone(renderer));
ScreenPoint sp = ScreenPoint.fromZonePoint(renderer, convert(topLeft));
Dimension size = renderer.getSize();
int startX = SwingUtilities.computeStringWidth(fm, "MMM") + 10;
double x = sp.x + cellSize/2; // Start at middle of the cell that's on screen
int nextAvailableSpace = -1;
while (x < size.width) {
String coord = Integer.toString(topLeft.x);
int strWidth = SwingUtilities.computeStringWidth(fm, coord);
int strX = (int)x - strWidth/2;
if (x > startX && strX > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, strX, fm.getHeight());
g.setColor(Color.orange);
g.drawString(coord, strX-1, fm.getHeight()-1);
nextAvailableSpace = strX + strWidth + 10;
}
x += cellSize;
topLeft.x ++;
}
double y = sp.y + cellSize/2; // Start at middle of the cell that's on screen
nextAvailableSpace = -1;
while (y < size.height) {
String coord = Integer.toString(topLeft.y);
int strY = (int)y + fm.getAscent()/2;
if (y > fm.getHeight() && strY > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, 10, strY);
g.setColor(Color.yellow);
g.drawString(coord, 10-1, strY-1);
nextAvailableSpace = strY + fm.getAscent()/2 + 10;
}
y += cellSize;
topLeft.y ++;
}
SwingUtil.restoreAntiAliasing(g, oldAA);
}
| public void drawCoordinatesOverlay(Graphics2D g, ZoneRenderer renderer) {
Object oldAA = SwingUtil.useAntiAliasing(g);
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(20f).deriveFont(Font.BOLD));
FontMetrics fm = g.getFontMetrics();
double cellSize = renderer.getScaledGridSize();
CellPoint topLeft = convert(new ScreenPoint(0, 0).convertToZone(renderer));
ScreenPoint sp = ScreenPoint.fromZonePoint(renderer, convert(topLeft));
Dimension size = renderer.getSize();
int startX = SwingUtilities.computeStringWidth(fm, "MMM") + 10;
double x = sp.x + cellSize/2; // Start at middle of the cell that's on screen
int nextAvailableSpace = -1;
while (x < size.width) {
String coord = Integer.toString(topLeft.x);
int strWidth = SwingUtilities.computeStringWidth(fm, coord);
int strX = (int)x - strWidth/2;
if (x > startX && strX > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, strX, fm.getHeight());
g.setColor(Color.orange);
g.drawString(coord, strX-1, fm.getHeight()-1);
nextAvailableSpace = strX + strWidth + 10;
}
x += cellSize;
topLeft.x ++;
}
double y = sp.y + cellSize/2; // Start at middle of the cell that's on screen
nextAvailableSpace = -1;
while (y < size.height) {
String coord = Integer.toString(topLeft.y);
int strY = (int)y + fm.getAscent()/2;
if (y > fm.getHeight() && strY > nextAvailableSpace) {
g.setColor(Color.black);
g.drawString(coord, 10, strY);
g.setColor(Color.yellow);
g.drawString(coord, 10-1, strY-1);
nextAvailableSpace = strY + fm.getAscent()/2 + 10;
}
y += cellSize;
topLeft.y ++;
}
g.setFont(oldFont);
SwingUtil.restoreAntiAliasing(g, oldAA);
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java b/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
index ea1a32df..009a6062 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/halo/Halo.java
@@ -1,1178 +1,1192 @@
/*
* Copyright (C) 2013 ParanoidAndroid.
*
* 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.systemui.statusbar.halo;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.app.Notification;
import android.app.INotificationManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.animation.Keyframe;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.RemoteException;
import android.os.Vibrator;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.TranslateAnimation;
import android.animation.TimeInterpolator;
import android.view.Display;
import android.view.View;
import android.view.Gravity;
import android.view.GestureDetector;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.SoundEffectConstants;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.android.systemui.R;
import com.android.systemui.statusbar.BaseStatusBar.NotificationClicker;
import android.service.notification.StatusBarNotification;
import com.android.internal.statusbar.StatusBarIcon;
import com.android.systemui.statusbar.StatusBarIconView;
import com.android.systemui.statusbar.NotificationData;
import com.android.systemui.statusbar.BaseStatusBar;
import com.android.systemui.statusbar.phone.Ticker;
public class Halo extends FrameLayout implements Ticker.TickerCallback {
public static final String TAG = "HaloLauncher";
enum State {
IDLE,
HIDDEN,
SILENT,
DRAG,
GESTURES
}
enum Gesture {
NONE,
TASK,
UP1,
UP2,
DOWN1,
DOWN2
}
private Context mContext;
private PackageManager mPm;
private Handler mHandler;
private BaseStatusBar mBar;
private WindowManager mWindowManager;
private Display mDisplay;
private Vibrator mVibrator;
private LayoutInflater mInflater;
private INotificationManager mNotificationManager;
private SettingsObserver mSettingsObserver;
private GestureDetector mGestureDetector;
private KeyguardManager mKeyguardManager;
private HaloEffect mEffect;
private WindowManager.LayoutParams mTriggerPos;
private State mState = State.IDLE;
private Gesture mGesture = Gesture.NONE;
private View mRoot;
private View mContent, mHaloContent;
private NotificationData.Entry mLastNotificationEntry = null;
private NotificationData.Entry mCurrentNotficationEntry = null;
private NotificationClicker mContentIntent, mTaskIntent;
private NotificationData mNotificationData;
private String mNotificationText = "";
private Paint mPaintHoloBlue = new Paint();
private Paint mPaintWhite = new Paint();
private Paint mPaintHoloRed = new Paint();
private boolean mAttached = false;
private boolean isBeingDragged = false;
private boolean mHapticFeedback;
private boolean mHideTicker;
private boolean mFirstStart = true;
private boolean mInitialized = false;
private boolean mTickerLeft = true;
private boolean mIsNotificationNew = true;
private boolean mOverX = false;
private boolean mInteractionReversed = true;
private boolean hiddenState = false;
private int mIconSize, mIconHalfSize;
private int mScreenWidth, mScreenHeight;
private int mKillX, mKillY;
private int mMarkerIndex = -1;
private int oldIconIndex = -1;
private float initialX = 0;
private float initialY = 0;
// Halo dock position
SharedPreferences preferences;
private String KEY_HALO_POSITION_Y = "halo_position_y";
private String KEY_HALO_POSITION_X = "halo_position_x";
private final class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HALO_REVERSED), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HALO_HIDE), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.HAPTIC_FEEDBACK_ENABLED), false, this);
}
@Override
public void onChange(boolean selfChange) {
mInteractionReversed =
Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_REVERSED, 1) == 1;
mHideTicker =
Settings.System.getInt(mContext.getContentResolver(), Settings.System.HALO_HIDE, 0) == 1;
mHapticFeedback = Settings.System.getInt(mContext.getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 1) != 0;
if (!selfChange) {
mEffect.wake();
mEffect.ping(mPaintHoloBlue, HaloEffect.WAKE_TIME);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!mAttached) {
mAttached = true;
mSettingsObserver = new SettingsObserver(new Handler());
mSettingsObserver.observe();
mSettingsObserver.onChange(true);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {
mContext.getContentResolver().unregisterContentObserver(mSettingsObserver);
mAttached = false;
}
}
public Halo(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Halo(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
mPm = mContext.getPackageManager();
mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
mNotificationManager = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
mDisplay = mWindowManager.getDefaultDisplay();
mGestureDetector = new GestureDetector(mContext, new GestureListener());
mHandler = new Handler();
mRoot = this;
mKeyguardManager = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
// Init variables
BitmapDrawable bd = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.halo_bg);
mIconSize = bd.getBitmap().getWidth();
mIconHalfSize = mIconSize / 2;
mTriggerPos = getWMParams();
// Init colors
mPaintHoloBlue.setAntiAlias(true);
mPaintHoloBlue.setColor(0xff33b5e5);
mPaintWhite.setAntiAlias(true);
mPaintWhite.setColor(0xfff0f0f0);
mPaintHoloRed.setAntiAlias(true);
mPaintHoloRed.setColor(0xffcc0000);
// Create effect layer
mEffect = new HaloEffect(mContext);
mEffect.setLayerType (View.LAYER_TYPE_HARDWARE, null);
mEffect.pingMinRadius = mIconHalfSize;
mEffect.pingMaxRadius = (int)(mIconSize * 1.1f);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.LEFT|Gravity.TOP;
mWindowManager.addView(mEffect, lp);
}
private void initControl() {
if (mInitialized) return;
mInitialized = true;
// Get actual screen size
mScreenWidth = mEffect.getWidth();
mScreenHeight = mEffect.getHeight();
// Halo dock position
preferences = mContext.getSharedPreferences("Halo", 0);
int msavePositionX = preferences.getInt(KEY_HALO_POSITION_X, 0);
int msavePositionY = preferences.getInt(KEY_HALO_POSITION_Y, mScreenHeight / 2 - mIconHalfSize);
mKillX = mScreenWidth / 2;
mKillY = mIconHalfSize;
if (!mFirstStart) {
if (msavePositionY < 0) mEffect.setHaloY(0);
float mTmpHaloY = (float) msavePositionY / mScreenWidth * (mScreenHeight);
if (msavePositionY > mScreenHeight-mIconSize) {
mEffect.setHaloY((int)mTmpHaloY);
} else {
mEffect.setHaloY(isLandscapeMod() ? msavePositionY : (int)mTmpHaloY);
}
if (mState == State.HIDDEN || mState == State.SILENT) {
mEffect.setHaloX((int)(mTickerLeft ? -mIconSize*0.8f : mScreenWidth - mIconSize*0.2f));
final int triggerWidth = (int)(mTickerLeft ? -mIconSize*0.7f : mScreenWidth - mIconSize*0.3f);
updateTriggerPosition(triggerWidth, mEffect.mHaloY);
} else {
mEffect.nap(500);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
} else {
// Do the startup animations only once
mFirstStart = false;
// Halo dock position
mTickerLeft = msavePositionX == 0 ? true : false;
updateTriggerPosition(msavePositionX, msavePositionY);
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
mEffect.setHaloX(msavePositionX);
mEffect.setHaloY(msavePositionY);
mEffect.nap(500);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
}
private boolean isLandscapeMod() {
return mScreenWidth < mScreenHeight;
}
private void updateTriggerPosition(int x, int y) {
try {
mTriggerPos.x = x;
mTriggerPos.y = y;
mWindowManager.updateViewLayout(mRoot, mTriggerPos);
} catch(Exception e) {
// Probably some animation still looking to move stuff around
}
}
private void loadLastNotification(boolean includeCurrentDismissable) {
if (mNotificationData.size() > 0) {
//oldEntry = mLastNotificationEntry;
mLastNotificationEntry = mNotificationData.get(mNotificationData.size() - 1);
// If the current notification is dismissable we might want to skip it if so desired
if (!includeCurrentDismissable) {
if (mNotificationData.size() > 1 && mLastNotificationEntry != null &&
mLastNotificationEntry.notification == mCurrentNotficationEntry.notification) {
boolean cancel = (mLastNotificationEntry.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) mLastNotificationEntry = mNotificationData.get(mNotificationData.size() - 2);
} else if (mNotificationData.size() == 1) {
boolean cancel = (mLastNotificationEntry.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
// We have one notification left and it is dismissable, clear it...
clearTicker();
return;
}
}
}
if (mLastNotificationEntry.notification != null
&& mLastNotificationEntry.notification.notification != null
&& mLastNotificationEntry.notification.notification.tickerText != null) {
mNotificationText = mLastNotificationEntry.notification.notification.tickerText.toString();
}
tick(mLastNotificationEntry, "", 0, 0);
} else {
clearTicker();
}
}
public void setStatusBar(BaseStatusBar bar) {
mBar = bar;
if (mBar.getTicker() != null) mBar.getTicker().setUpdateEvent(this);
mNotificationData = mBar.getNotificationData();
loadLastNotification(true);
}
void launchTask(NotificationClicker intent) {
// Do not launch tasks in hidden state or protected lock screen
if (mState == State.HIDDEN || mState == State.SILENT
|| (mKeyguardManager.isKeyguardLocked() && mKeyguardManager.isKeyguardSecure())) return;
try {
ActivityManagerNative.getDefault().resumeAppSwitches();
ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
} catch (RemoteException e) {
// ...
}
if (intent!= null) {
intent.onClick(mRoot);
}
}
class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapUp (MotionEvent event) {
playSoundEffect(SoundEffectConstants.CLICK);
return true;
}
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
if (mState != State.DRAG) {
launchTask(mContentIntent);
}
return true;
}
@Override
public boolean onDoubleTap(MotionEvent event) {
if (!mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
// Move
mState = State.DRAG;
mEffect.intro();
}
return true;
}
}
void resetIcons() {
final float originalAlpha = mContext.getResources().getFraction(R.dimen.status_bar_icon_drawing_alpha, 1, 1);
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
entry.icon.setAlpha(originalAlpha);
}
}
void setIcon(int index) {
float originalAlpha = mContext.getResources().getFraction(R.dimen.status_bar_icon_drawing_alpha, 1, 1);
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
entry.icon.setAlpha(index == i ? 1f : originalAlpha);
}
}
private boolean verticalGesture() {
return (mGesture == Gesture.UP1
|| mGesture == Gesture.DOWN1
|| mGesture == Gesture.UP2
|| mGesture == Gesture.DOWN2);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
- loadLastNotification(true);
+ mCurrentNotficationEntry = null;
+ if (mNotificationData.size() > 0) {
+ if (mNotificationData.size() > 0) {
+ for (int i = mNotificationData.size() - 1; i >= 0; i--) {
+ NotificationData.Entry item = mNotificationData.get(i);
+ if (!((item.notification.notification.flags &
+ Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL)) {
+ tick(item, "", 0, 0);
+ break;
+ }
+ }
+ }
+ }
+ if (mCurrentNotficationEntry == null) clearTicker();
+ mLastNotificationEntry = null;
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
public void cleanUp() {
// Remove pending tasks, if we can
mEffect.unscheduleSleep();
mHandler.removeCallbacksAndMessages(null);
// Kill callback
mBar.getTicker().setUpdateEvent(null);
// Flag tasker
mBar.setHaloTaskerActive(false, false);
// Kill the effect layer
if (mEffect != null) mWindowManager.removeView(mEffect);
// Remove resolver
mContext.getContentResolver().unregisterContentObserver(mSettingsObserver);
}
class HaloEffect extends HaloProperties {
public static final int WAKE_TIME = 300;
public static final int SNAP_TIME = 300;
public static final int NAP_TIME = 1000;
public static final int SLEEP_TIME = 2000;
public static final int PING_TIME = 1500;
public static final int PULSE_TIME = 1500;
public static final int TICKER_HIDE_TIME = 2500;
public static final int NAP_DELAY = 4500;
public static final int SLEEP_DELAY = 6500;
private Context mContext;
private Paint mPingPaint;
private int pingRadius = 0;
private int mPingX, mPingY;
protected int pingMinRadius = 0;
protected int pingMaxRadius = 0;
private boolean mPingAllowed = true;
private Bitmap mMarker, mMarkerT, mMarkerB;
private Bitmap mBigRed;
private Paint mMarkerPaint = new Paint();
private Paint xPaint = new Paint();
CustomObjectAnimator xAnimator = new CustomObjectAnimator(this);
CustomObjectAnimator tickerAnimator = new CustomObjectAnimator(this);
public HaloEffect(Context context) {
super(context);
mContext = context;
setWillNotDraw(false);
setDrawingCacheEnabled(false);
mBigRed = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_bigred);
mMarker = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker);
mMarkerT = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker_t);
mMarkerB = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.halo_marker_b);
mMarkerPaint.setAntiAlias(true);
mMarkerPaint.setAlpha(0);
xPaint.setAntiAlias(true);
xPaint.setAlpha(0);
updateResources();
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
onConfigurationChanged(null);
}
@Override
public void onConfigurationChanged(Configuration newConfiguration) {
// This will reset the initialization flag
mInitialized = false;
// Generate a new content bubble
updateResources();
}
@Override
protected void onLayout (boolean changed, int left, int top, int right, int bottom) {
super.onLayout (changed, left, top, right, bottom);
// We have our effect-layer, now let's kickstart HALO
initControl();
}
public void killTicker() {
tickerAnimator.animate(ObjectAnimator.ofFloat(this, "haloContentAlpha", 0f).setDuration(250),
new DecelerateInterpolator(), null);
}
public void ticker(String tickerText, int delay, int startDuration) {
if (tickerText == null || tickerText.isEmpty()) {
killTicker();
return;
}
mHaloTextViewR.setText(tickerText);
mHaloTextViewL.setText(tickerText);
float total = TICKER_HIDE_TIME + startDuration + 1000;
PropertyValuesHolder tickerUpFrames = PropertyValuesHolder.ofKeyframe("haloContentAlpha",
Keyframe.ofFloat(0f, mHaloTextViewL.getAlpha()),
Keyframe.ofFloat(startDuration / total, 1f),
Keyframe.ofFloat((TICKER_HIDE_TIME + startDuration) / total, 1f),
Keyframe.ofFloat(1f, 0f));
tickerAnimator.animate(ObjectAnimator.ofPropertyValuesHolder(this, tickerUpFrames).setDuration((int)total),
new DecelerateInterpolator(), null, delay, null);
}
public void ping(final Paint paint, final long delay) {
if ((!mPingAllowed && paint != mPaintHoloRed)
&& mGesture != Gesture.TASK) return;
mHandler.postDelayed(new Runnable() {
public void run() {
mPingAllowed = false;
mPingX = mHaloX + mIconHalfSize;
mPingY = mHaloY + mIconHalfSize;
;
mPingPaint = paint;
CustomObjectAnimator pingAnimator = new CustomObjectAnimator(mEffect);
pingAnimator.animate(ObjectAnimator.ofInt(mPingPaint, "alpha", 200, 0).setDuration(PING_TIME),
new DecelerateInterpolator(), new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
pingRadius = (int)((pingMaxRadius - pingMinRadius) *
animation.getAnimatedFraction()) + pingMinRadius;
invalidate();
}});
// prevent ping spam
mHandler.postDelayed(new Runnable() {
public void run() {
mPingAllowed = true;
}}, PING_TIME / 2);
}}, delay);
}
public void intro() {
xAnimator.animate(ObjectAnimator.ofInt(xPaint, "alpha", 255).setDuration(PING_TIME / 3),
new DecelerateInterpolator(), null);
}
public void outro() {
xAnimator.animate(ObjectAnimator.ofInt(xPaint, "alpha", 0).setDuration(PING_TIME / 3),
new AccelerateInterpolator(), null);
}
CustomObjectAnimator snapAnimator = new CustomObjectAnimator(this);
public void wake() {
unscheduleSleep();
if (mState == State.HIDDEN || mState == State.SILENT) mState = State.IDLE;
int newPos = mTickerLeft ? 0 : mScreenWidth - mIconSize;
updateTriggerPosition(newPos, mHaloY);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(WAKE_TIME),
new DecelerateInterpolator(), null);
}
public void snap(long delay) {
int newPos = mTickerLeft ? 0 : mScreenWidth - mIconSize;
updateTriggerPosition(newPos, mHaloY);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(SNAP_TIME),
new DecelerateInterpolator(), null, delay, null);
}
public void nap(long delay) {
final int newPos = mTickerLeft ? -mIconHalfSize : mScreenWidth - mIconHalfSize;
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(NAP_TIME),
new DecelerateInterpolator(), null, delay, new Runnable() {
public void run() {
updateTriggerPosition(newPos, mHaloY);
}});
}
public void sleep(long delay, int speed, final boolean silent) {
final int newPos = (int)(mTickerLeft ? -mIconSize*0.8f : mScreenWidth - mIconSize*0.2f);
snapAnimator.animate(ObjectAnimator.ofInt(this, "haloX", newPos).setDuration(speed),
new DecelerateInterpolator(), null, delay, new Runnable() {
public void run() {
mState = silent ? State.SILENT : State.HIDDEN;
final int triggerWidth = (int)(mTickerLeft ? -mIconSize*0.7f : mScreenWidth - mIconSize*0.3f);
updateTriggerPosition(triggerWidth, mHaloY);
}});
}
public void unscheduleSleep() {
snapAnimator.cancel(true);
}
@Override
protected void onDraw(Canvas canvas) {
int state;
// Ping
if (mPingPaint != null) {
canvas.drawCircle(mPingX, mPingY, pingRadius, mPingPaint);
}
// Content
state = canvas.save();
int ch = mHaloTickerContent.getMeasuredHeight();
int cw = mHaloTickerContent.getMeasuredWidth();
int y = mHaloY + mIconHalfSize - ch / 2;
if (y < 0) y = 0;
int x = mHaloX + mIconSize;
if (!mTickerLeft) {
x = mHaloX - cw;
}
state = canvas.save();
canvas.translate(x, y);
mHaloContentView.draw(canvas);
canvas.restoreToCount(state);
// X
float fraction = 1 - ((float)xPaint.getAlpha()) / 255;
int killyPos = (int)(mKillY - mBigRed.getWidth() / 2 - mIconSize * fraction);
canvas.drawBitmap(mBigRed, mKillX - mBigRed.getWidth() / 2, killyPos, xPaint);
// Horizontal Marker
if (mGesture == Gesture.TASK) {
if (y > 0 && mNotificationData != null && mNotificationData.size() > 0) {
int pulseY = (int)(mHaloY - mIconSize * 0.1f);
int items = mNotificationData.size();
int indexLength = (mScreenWidth - mIconSize * 2) / items;
for (int i = 0; i < items; i++) {
float pulseX = mTickerLeft ? (mIconSize * 1.15f + indexLength * i)
: (mScreenWidth - mIconSize * 1.15f - indexLength * i - mMarker.getWidth());
boolean markerState = mTickerLeft ? mMarkerIndex >= 0 && i < items-mMarkerIndex : i <= mMarkerIndex;
mMarkerPaint.setAlpha(markerState ? 255 : 100);
canvas.drawBitmap(mMarker, pulseX, pulseY, mMarkerPaint);
}
}
}
// Vertical Markers
if (verticalGesture()) {
int xPos = mHaloX + mIconHalfSize - mMarkerT.getWidth() / 2;
mMarkerPaint.setAlpha(mGesture == Gesture.UP1 ? 255 : 100);
int yTop = (int)(mHaloY + mIconHalfSize - mIconSize - mMarkerT.getHeight() / 2);
canvas.drawBitmap(mMarkerT, xPos, yTop, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.UP2 ? 255 : 100);
yTop = yTop - (int)(mIconSize * 0.6f);
canvas.drawBitmap(mMarkerT, xPos, yTop, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.DOWN1 ? 255 : 100);
int yButtom = (int)(mHaloY + mIconHalfSize + mIconSize - mMarkerT.getHeight() / 2);
canvas.drawBitmap(mMarkerB, xPos, yButtom, mMarkerPaint);
mMarkerPaint.setAlpha(mGesture == Gesture.DOWN2 ? 255 : 100);
yButtom = yButtom + (int)(mIconSize * 0.6f);
canvas.drawBitmap(mMarkerB, xPos, yButtom, mMarkerPaint);
}
// Bubble
state = canvas.save();
canvas.translate(mHaloX, mHaloY);
mHaloBubble.draw(canvas);
canvas.restoreToCount(state);
// Number
if (mState == State.IDLE || mState == State.GESTURES && !verticalGesture()) {
state = canvas.save();
canvas.translate(mTickerLeft ? mHaloX + mIconSize - mHaloNumber.getMeasuredWidth() : mHaloX, mHaloY);
mHaloNumberView.draw(canvas);
canvas.restoreToCount(state);
}
}
}
public WindowManager.LayoutParams getWMParams() {
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
mIconSize,
mIconSize,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
lp.gravity = Gravity.LEFT|Gravity.TOP;
return lp;
}
void clearTicker() {
mEffect.mHaloIcon.setImageDrawable(null);
mEffect.mHaloNumber.setAlpha(0f);
mContentIntent = null;
mCurrentNotficationEntry = null;
mEffect.killTicker();
mEffect.updateResources();
mEffect.invalidate();
}
void tick(NotificationData.Entry entry, String text, int delay, int duration) {
if (entry == null) {
clearTicker();
return;
}
StatusBarNotification notification = entry.notification;
Notification n = notification.notification;
// Deal with the intent
mContentIntent = entry.getFloatingIntent();
mCurrentNotficationEntry = entry;
// set the avatar
mEffect.mHaloIcon.setImageDrawable(new BitmapDrawable(mContext.getResources(), entry.getRoundIcon()));
// Set Number
if (n.number > 0) {
mEffect.mHaloNumber.setText((n.number < 100) ? String.valueOf(n.number) : "+");
mEffect.mHaloNumber.setAlpha(1f);
} else {
mEffect.mHaloNumber.setAlpha(0f);
}
// Set text
if (mState != State.SILENT) mEffect.ticker(text, delay, duration);
mEffect.updateResources();
mEffect.invalidate();
}
// This is the android ticker callback
public void updateTicker(StatusBarNotification notification, String text) {
boolean allowed = false; // default off
try {
allowed = mNotificationManager.isPackageAllowedForHalo(notification.pkg);
} catch (android.os.RemoteException ex) {
// System is dead
}
for (int i = 0; i < mNotificationData.size(); i++) {
NotificationData.Entry entry = mNotificationData.get(i);
if (entry.notification == notification) {
// No intent, no tick ...
if (entry.notification.notification.contentIntent == null) return;
mIsNotificationNew = true;
if (mLastNotificationEntry != null && notification == mLastNotificationEntry.notification) {
// Ok, this is the same notification
// Let's give it a chance though, if the text has changed we allow it
mIsNotificationNew = !mNotificationText.equals(text);
}
if (mIsNotificationNew) {
mNotificationText = text;
mLastNotificationEntry = entry;
if (allowed) {
tick(entry, text, HaloEffect.WAKE_TIME, 1000);
// Pop while not tasking, only if notification is certified fresh
if (mGesture != Gesture.TASK && mState != State.SILENT) mEffect.ping(mPaintHoloBlue, HaloEffect.WAKE_TIME);
if (mState == State.IDLE || mState == State.HIDDEN) {
mEffect.wake();
mEffect.nap(HaloEffect.NAP_DELAY);
if (mHideTicker) mEffect.sleep(HaloEffect.SLEEP_DELAY, HaloEffect.SLEEP_TIME, false);
}
}
}
break;
}
}
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
loadLastNotification(true);
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
| public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
final int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
// Stop HALO from moving around, unschedule sleeping patterns
if (mState != State.GESTURES) mEffect.unscheduleSleep();
mMarkerIndex = -1;
oldIconIndex = -1;
mGesture = Gesture.NONE;
hiddenState = (mState == State.HIDDEN || mState == State.SILENT);
if (hiddenState) {
mEffect.wake();
if (mHideTicker) {
mEffect.sleep(2500, HaloEffect.SLEEP_TIME, false);
} else {
mEffect.nap(2500);
}
return true;
}
initialX = event.getRawX();
initialY = event.getRawY();
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (hiddenState) break;
resetIcons();
mBar.setHaloTaskerActive(false, true);
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
updateTriggerPosition(mEffect.getHaloX(), mEffect.getHaloY());
mEffect.outro();
mEffect.killTicker();
mEffect.unscheduleSleep();
// Do we erase ourselves?
if (mOverX) {
Settings.System.putInt(mContext.getContentResolver(),
Settings.System.HALO_ACTIVE, 0);
return true;
}
// Halo dock position
float mTmpHaloY = (float) mEffect.mHaloY / mScreenHeight * mScreenWidth;
preferences.edit().putInt(KEY_HALO_POSITION_X, mTickerLeft ?
0 : mScreenWidth - mIconSize).putInt(KEY_HALO_POSITION_Y, isLandscapeMod() ?
mEffect.mHaloY : (int)mTmpHaloY).apply();
if (mGesture == Gesture.TASK) {
// Launch tasks
if (mTaskIntent != null) {
playSoundEffect(SoundEffectConstants.CLICK);
launchTask(mTaskIntent);
}
mEffect.nap(0);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 1500, HaloEffect.SLEEP_TIME, false);
} else if (mGesture == Gesture.DOWN2) {
// Hide & silence
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, true);
} else if (mGesture == Gesture.DOWN1) {
// Hide from sight
playSoundEffect(SoundEffectConstants.CLICK);
mEffect.sleep(0, HaloEffect.NAP_TIME / 2, false);
} else if (mGesture == Gesture.UP2) {
// Clear all notifications
playSoundEffect(SoundEffectConstants.CLICK);
try {
mBar.getService().onClearAllNotifications();
} catch (RemoteException ex) {
// system process is dead if we're here.
}
mCurrentNotficationEntry = null;
if (mNotificationData.size() > 0) {
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (!((item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL)) {
tick(item, "", 0, 0);
break;
}
}
}
}
if (mCurrentNotficationEntry == null) clearTicker();
mLastNotificationEntry = null;
} else if (mGesture == Gesture.UP1) {
// Dismiss notification
playSoundEffect(SoundEffectConstants.CLICK);
if (mContentIntent != null) {
try {
mBar.getService().onNotificationClear(mContentIntent.mPkg, mContentIntent.mTag, mContentIntent.mId);
} catch (RemoteException ex) {
// system process is dead if we're here.
}
}
// Find next entry
NotificationData.Entry entry = null;
if (mNotificationData.size() > 0) {
for (int i = mNotificationData.size() - 1; i >= 0; i--) {
NotificationData.Entry item = mNotificationData.get(i);
if (mCurrentNotficationEntry != null
&& mCurrentNotficationEntry.notification == item.notification) {
continue;
}
boolean cancel = (item.notification.notification.flags &
Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
if (cancel) {
entry = item;
break;
}
}
}
// When no entry was found, take the last one
if (entry == null && mNotificationData.size() > 0) {
loadLastNotification(false);
} else {
tick(entry, "", 0, 0);
}
mEffect.nap(1500);
if (mHideTicker) mEffect.sleep(HaloEffect.NAP_TIME + 3000, HaloEffect.SLEEP_TIME, false);
} else {
// No gesture, just snap HALO
mEffect.snap(0);
mEffect.nap(HaloEffect.SNAP_TIME + 1000);
if (mHideTicker) mEffect.sleep(HaloEffect.SNAP_TIME + HaloEffect.NAP_TIME + 2500, HaloEffect.SLEEP_TIME, false);
}
mState = State.IDLE;
mGesture = Gesture.NONE;
break;
case MotionEvent.ACTION_MOVE:
if (hiddenState) break;
float distanceX = mKillX-event.getRawX();
float distanceY = mKillY-event.getRawY();
float distanceToKill = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
distanceX = initialX-event.getRawX();
distanceY = initialY-event.getRawY();
float initialDistance = (float)Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));
if (mState != State.GESTURES) {
// Check kill radius
if (distanceToKill < mIconSize) {
// Magnetize X
mEffect.setHaloX((int)mKillX - mIconHalfSize);
mEffect.setHaloY((int)(mKillY - mIconHalfSize));
if (!mOverX) {
if (mHapticFeedback) mVibrator.vibrate(25);
mEffect.ping(mPaintHoloRed, 0);
mEffect.setHaloOverlay(HaloProperties.Overlay.BLACK_X, 1f);
mOverX = true;
}
return false;
} else {
if (mOverX) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mOverX = false;
}
// Drag
if (mState != State.DRAG) {
if (initialDistance > mIconSize * 0.7f) {
if (mInteractionReversed) {
mState = State.GESTURES;
mEffect.wake();
mBar.setHaloTaskerActive(true, true);
} else {
mState = State.DRAG;
mEffect.intro();
if (mHapticFeedback) mVibrator.vibrate(25);
}
}
} else {
int posX = (int)event.getRawX() - mIconHalfSize;
int posY = (int)event.getRawY() - mIconHalfSize;
if (posX < 0) posX = 0;
if (posY < 0) posY = 0;
if (posX > mScreenWidth-mIconSize) posX = mScreenWidth-mIconSize;
if (posY > mScreenHeight-mIconSize) posY = mScreenHeight-mIconSize;
mEffect.setHaloX(posX);
mEffect.setHaloY(posY);
// Update resources when the side changes
boolean oldTickerPos = mTickerLeft;
mTickerLeft = (posX + mIconHalfSize < mScreenWidth / 2);
if (oldTickerPos != mTickerLeft) {
mEffect.updateResources();
mEffect.mHaloTextViewL.setVisibility(mTickerLeft ? View.VISIBLE : View.GONE);
mEffect.mHaloTextViewR.setVisibility(mTickerLeft ? View.GONE : View.VISIBLE);
}
}
} else {
// We have three basic gestures, one horizontal for switching through tasks and
// two vertical for dismissing tasks or making HALO fall asleep
int deltaX = (int)(mTickerLeft ? event.getRawX() : mScreenWidth - event.getRawX());
int deltaY = (int)(mEffect.getHaloY() - event.getRawY() + mIconSize);
int horizontalThreshold = (int)(mIconSize * 1.5f);
int verticalThreshold = mIconHalfSize;
int verticalSteps = (int)(mIconSize * 0.6f);
String gestureText = mNotificationText;
// Switch icons
if (deltaX > horizontalThreshold) {
if (mGesture != Gesture.TASK) mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
mGesture = Gesture.TASK;
deltaX -= horizontalThreshold;
if (mNotificationData != null && mNotificationData.size() > 0) {
int items = mNotificationData.size();
// This will be the lenght we are going to use
int indexLength = (mScreenWidth - mIconSize * 2) / items;
// Calculate index
mMarkerIndex = mTickerLeft ? (items - deltaX / indexLength) - 1 : (deltaX / indexLength);
// Watch out for margins!
if (mMarkerIndex >= items) mMarkerIndex = items - 1;
if (mMarkerIndex < 0) mMarkerIndex = 0;
}
// Up & down gestures
} else if (Math.abs(deltaY) > verticalThreshold) {
mMarkerIndex = -1;
boolean gestureChanged = false;
final int deltaIndex = (Math.abs(deltaY) - verticalThreshold) / verticalSteps;
if (deltaY > 0) {
if (deltaIndex < 2 && mGesture != Gesture.UP1) {
mGesture = Gesture.UP1;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.DISMISS, 1f);
gestureText = mContext.getResources().getString(R.string.halo_dismiss);
} else if (deltaIndex > 1 && mGesture != Gesture.UP2) {
mGesture = Gesture.UP2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.CLEAR_ALL, 1f);
gestureText = mContext.getResources().getString(R.string.halo_clear_all);
}
} else {
if (deltaIndex < 2 && mGesture != Gesture.DOWN1) {
mGesture = Gesture.DOWN1;
gestureChanged = true;
mEffect.setHaloOverlay(mTickerLeft ? HaloProperties.Overlay.BACK_LEFT
: HaloProperties.Overlay.BACK_RIGHT, 1f);
gestureText = mContext.getResources().getString(R.string.halo_hide);
} else if (deltaIndex > 1 && mGesture != Gesture.DOWN2) {
mGesture = Gesture.DOWN2;
gestureChanged = true;
mEffect.setHaloOverlay(HaloProperties.Overlay.SILENCE, 1f);
gestureText = mContext.getResources().getString(R.string.halo_silence);
}
}
if (gestureChanged) {
mMarkerIndex = -1;
// Tasking hasn't changed, we can tick the message here
if (mMarkerIndex == oldIconIndex) {
mEffect.ticker(gestureText, 0, 250);
mEffect.updateResources();
mEffect.invalidate();
}
if (mHapticFeedback) mVibrator.vibrate(10);
}
} else {
mMarkerIndex = -1;
if (mGesture != Gesture.NONE) {
mEffect.setHaloOverlay(HaloProperties.Overlay.NONE, 0f);
if (verticalGesture()) mEffect.killTicker();
}
mGesture = Gesture.NONE;
}
// If the marker index changed, tick
if (mMarkerIndex != oldIconIndex) {
oldIconIndex = mMarkerIndex;
// Make a tiny pop if not so many icons are present
if (mHapticFeedback && mNotificationData.size() < 10) mVibrator.vibrate(1);
try {
if (mMarkerIndex == -1) {
mTaskIntent = null;
resetIcons();
tick(mLastNotificationEntry, gestureText, 0, 250);
// Ping to notify the user we're back where we started
mEffect.ping(mPaintHoloBlue, 0);
} else {
setIcon(mMarkerIndex);
NotificationData.Entry entry = mNotificationData.get(mMarkerIndex);
String text = "";
if (entry.notification.notification.tickerText != null) {
text = entry.notification.notification.tickerText.toString();
}
tick(entry, text, 0, 250);
mTaskIntent = entry.getFloatingIntent();
}
} catch (Exception e) {
// IndexOutOfBoundsException
}
}
}
mEffect.invalidate();
break;
}
return false;
}
|
diff --git a/src/main/ed/util/MailUtil.java b/src/main/ed/util/MailUtil.java
index 70ad18ed0..1331caedc 100644
--- a/src/main/ed/util/MailUtil.java
+++ b/src/main/ed/util/MailUtil.java
@@ -1,19 +1,19 @@
// MailUtil.java
package ed.util;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class MailUtil {
public static Session createSession( final Properties props , final String user , final String pass ){
- return Session.getDefaultInstance( props , new javax.mail.Authenticator() {
+ return Session.getInstance( props , new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( user , pass );
}
});
}
}
| true | true | public static Session createSession( final Properties props , final String user , final String pass ){
return Session.getDefaultInstance( props , new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( user , pass );
}
});
}
| public static Session createSession( final Properties props , final String user , final String pass ){
return Session.getInstance( props , new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( user , pass );
}
});
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
index d7bb3df7..78782368 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
@@ -1,143 +1,145 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.ec2.dynamicstorage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.FileUtils;
import org.cloudifysource.quality.iTests.framework.utils.AssertUtils;
import org.cloudifysource.quality.iTests.framework.utils.Ec2StorageApiForRegionHelper;
import org.cloudifysource.quality.iTests.framework.utils.IOUtils;
import org.cloudifysource.quality.iTests.framework.utils.LogUtils;
import org.cloudifysource.quality.iTests.framework.utils.ScriptUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.NewAbstractCloudTest;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.ec2.Ec2CloudService;
import org.jclouds.ec2.domain.Volume;
import org.jclouds.ec2.domain.Volume.Status;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public abstract class AbstractDynamicStorageTest extends NewAbstractCloudTest {
private static final long VOLUME_WAIT_TIMEOUT = 3 * 60 * 1000;
private static final String PATH_TO_SERVICE = CommandTestUtils.getPath("/src/main/resources/apps/USM/usm/dynamicstorage/");;
protected static final String SERVICE_NAME = "groovy";
protected Ec2StorageApiForRegionHelper storageHelper;
public abstract void doTest() throws Exception ;
public abstract String getServiceFolder();
@Override
protected void bootstrap() throws Exception {
super.bootstrap();
Ec2CloudService ec2CloudService = (Ec2CloudService)getService();
this.storageHelper = new Ec2StorageApiForRegionHelper(ec2CloudService.getRegion(), ec2CloudService.getComputeServiceContext());
}
@BeforeMethod
public void prepareService() throws IOException {
String buildRecipesServicesPath = ScriptUtils.getBuildRecipesServicesPath();
File serviceFolder = new File(buildRecipesServicesPath, getServiceFolder());
if (serviceFolder.exists()) {
FileUtils.deleteDirectory(serviceFolder);
}
FileUtils.copyDirectoryToDirectory( new File(PATH_TO_SERVICE + "/" + getServiceFolder()), new File(buildRecipesServicesPath));
}
public void testUbuntu() throws Exception {
setTemplate("SMALL_UBUNTU", false);
doTest();
}
public void testLinux(final boolean useManagement) throws Exception {
setTemplate("SMALL_LINUX", useManagement);
doTest();
}
public void testLinux() throws Exception {
testLinux(true);
}
@Override
protected void customizeCloud() throws Exception {
super.customizeCloud();
((Ec2CloudService)getService()).getAdditionalPropsToReplace().put("cloudify-storage-volume", System.getProperty("user.name") + "-" + this.getClass().getSimpleName().toLowerCase());
}
public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
- LogUtils.log("Found a leaking volume " + volumeByName);
+ LogUtils.log("Found a leaking volume " + volumeByName + ". status is " + volumeByName.getStatus());
+ LogUtils.log("Volume attachments are : " + volumeByName.getAttachments());
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
+ waitForVolumeStatus(volumeByName, Status.AVAILABLE);
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
}
}
if (!volumesByName.isEmpty()) {
AssertUtils.assertFail("Found leaking volumes after test ended :" + volumesByName);
}
}
public void scanForLeakedVolumesCreatedViaTemplate(final String templateName) throws TimeoutException {
final String name = getService().getCloud().getCloudStorage().getTemplates().get(templateName).getNamePrefix();
scanForLeakedVolumes(name);
}
private void waitForVolumeStatus(final Volume vol, final Status status) throws TimeoutException {
final long end = System.currentTimeMillis() + VOLUME_WAIT_TIMEOUT;
while (System.currentTimeMillis() < end) {
Volume volume = storageHelper.getVolumeById(vol.getId());
if (volume.getStatus().equals(status)) {
return;
} else {
try {
LogUtils.log("Waiting for volume " + vol.getId()
+ " to reach status " + status + " . current status is : " + volume.getStatus());
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
throw new TimeoutException("Timed out waiting for volume " + vol + " to reach status " + status);
}
@AfterMethod
public void deleteService() throws IOException {
FileUtils.deleteDirectory(new File(ScriptUtils.getBuildRecipesServicesPath() + "/" + getServiceFolder()));
}
protected void setTemplate(final String computeTemplateName, boolean useManagement) throws Exception {
File serviceFile = new File(ScriptUtils.getBuildRecipesServicesPath() + "/" + getServiceFolder(), SERVICE_NAME + "-service.groovy");
Map<String, String> props = new HashMap<String,String>();
props.put("ENTER_TEMPLATE", computeTemplateName);
if (!useManagement) {
props.put("useManagement true", "useManagement false");
}
IOUtils.replaceTextInFile(serviceFile.getAbsolutePath(), props);
}
}
| false | true | public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
LogUtils.log("Found a leaking volume " + volumeByName);
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
}
}
if (!volumesByName.isEmpty()) {
AssertUtils.assertFail("Found leaking volumes after test ended :" + volumesByName);
}
}
| public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
LogUtils.log("Found a leaking volume " + volumeByName + ". status is " + volumeByName.getStatus());
LogUtils.log("Volume attachments are : " + volumeByName.getAttachments());
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
}
}
if (!volumesByName.isEmpty()) {
AssertUtils.assertFail("Found leaking volumes after test ended :" + volumesByName);
}
}
|
diff --git a/cometd-javascript/common-test/src/main/java/org/cometd/javascript/jquery/JQueryTestProvider.java b/cometd-javascript/common-test/src/main/java/org/cometd/javascript/jquery/JQueryTestProvider.java
index 5d6c1122c..df9702cc7 100644
--- a/cometd-javascript/common-test/src/main/java/org/cometd/javascript/jquery/JQueryTestProvider.java
+++ b/cometd-javascript/common-test/src/main/java/org/cometd/javascript/jquery/JQueryTestProvider.java
@@ -1,62 +1,62 @@
/*
* Copyright (c) 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cometd.javascript.jquery;
import java.net.URL;
import org.cometd.javascript.TestProvider;
import org.cometd.javascript.ThreadModel;
public class JQueryTestProvider implements TestProvider
{
public void provideCometD(ThreadModel threadModel, String contextURL) throws Exception
{
// Order of the script evaluation is important, as they depend one from the other
threadModel.evaluate(new URL(contextURL + "/env.js"));
threadModel.evaluate("window_location", "window.location = '" + contextURL + "'");
- threadModel.evaluate(new URL(contextURL + "/jquery/jquery-1.6.1.js"));
+ threadModel.evaluate(new URL(contextURL + "/jquery/jquery-1.6.2.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/json2.js"));
threadModel.evaluate(new URL(contextURL + "/org/cometd.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd.js"));
threadModel.evaluate("cometd", "var cometd = $.cometd;");
}
public void provideMessageAcknowledgeExtension(ThreadModel threadModel, String contextURL) throws Exception
{
threadModel.evaluate(new URL(contextURL + "/org/cometd/AckExtension.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd-ack.js"));
}
public void provideReloadExtension(ThreadModel threadModel, String contextURL) throws Exception
{
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cookie.js"));
threadModel.evaluate(new URL(contextURL + "/org/cometd/ReloadExtension.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd-reload.js"));
}
public void provideTimestampExtension(ThreadModel threadModel, String contextURL) throws Exception
{
threadModel.evaluate(new URL(contextURL + "/org/cometd/TimeStampExtension.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd-timestamp.js"));
}
public void provideTimesyncExtension(ThreadModel threadModel, String contextURL) throws Exception
{
threadModel.evaluate(new URL(contextURL + "/org/cometd/TimeSyncExtension.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd-timesync.js"));
}
}
| true | true | public void provideCometD(ThreadModel threadModel, String contextURL) throws Exception
{
// Order of the script evaluation is important, as they depend one from the other
threadModel.evaluate(new URL(contextURL + "/env.js"));
threadModel.evaluate("window_location", "window.location = '" + contextURL + "'");
threadModel.evaluate(new URL(contextURL + "/jquery/jquery-1.6.1.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/json2.js"));
threadModel.evaluate(new URL(contextURL + "/org/cometd.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd.js"));
threadModel.evaluate("cometd", "var cometd = $.cometd;");
}
| public void provideCometD(ThreadModel threadModel, String contextURL) throws Exception
{
// Order of the script evaluation is important, as they depend one from the other
threadModel.evaluate(new URL(contextURL + "/env.js"));
threadModel.evaluate("window_location", "window.location = '" + contextURL + "'");
threadModel.evaluate(new URL(contextURL + "/jquery/jquery-1.6.2.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/json2.js"));
threadModel.evaluate(new URL(contextURL + "/org/cometd.js"));
threadModel.evaluate(new URL(contextURL + "/jquery/jquery.cometd.js"));
threadModel.evaluate("cometd", "var cometd = $.cometd;");
}
|
diff --git a/APS-Libraries/APSWebTools/src/main/java/se/natusoft/osgi/aps/tools/web/APSAdminWebLoginHandler.java b/APS-Libraries/APSWebTools/src/main/java/se/natusoft/osgi/aps/tools/web/APSAdminWebLoginHandler.java
index 40cdc93e..234adfea 100644
--- a/APS-Libraries/APSWebTools/src/main/java/se/natusoft/osgi/aps/tools/web/APSAdminWebLoginHandler.java
+++ b/APS-Libraries/APSWebTools/src/main/java/se/natusoft/osgi/aps/tools/web/APSAdminWebLoginHandler.java
@@ -1,131 +1,133 @@
/*
*
* PROJECT
* Name
* APS Web Tools
*
* Code Version
* 0.9.0
*
* Description
* This provides some utility classes for web applications.
*
* COPYRIGHTS
* Copyright (C) 2012 by Natusoft AB All rights reserved.
*
* LICENSE
* Apache 2.0 (Open Source)
*
* 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.
*
* AUTHORS
* Tommy Svensson ([email protected])
* Changes:
* 2013-02-03: Created!
*
*/
package se.natusoft.osgi.aps.tools.web;
import org.osgi.framework.BundleContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This is a login handler to use by any admin web registering with the APSAdminWeb to validate
* that there is a valid login available.
*/
public class APSAdminWebLoginHandler extends APSLoginHandler implements APSLoginHandler.HandlerInfo {
//
// Private Members
//
/** The current APSSession id. */
private String sessionId = null;
//
// Constructors
//
/**
* Creates a new APSAdminWebLoginHandler.
*
* @param context The bundle context.
*/
public APSAdminWebLoginHandler(BundleContext context) {
super(context, null);
setHandlerInfo(this);
}
//
// Methods
//
/**
* Sets the session id from a cookie in the specified request.
*
* @param request The request to get the session id cookie from.
*/
public void setSessionIdFromRequestCookie(HttpServletRequest request) {
- String sessId = CookieTool.getCookie(request.getCookies(), "aps-adminweb-session-id");
- if (sessId != null) {
- this.sessionId = sessId;
+ if (request.getCookies() != null) {
+ String sessId = CookieTool.getCookie(request.getCookies(), "aps-adminweb-session-id");
+ if (sessId != null) {
+ this.sessionId = sessId;
+ }
}
}
/**
* Saves the current session id on the specified response.
*
* @param response The response to save the session id cookie on.
*/
public void saveSessionIdOnResponse(HttpServletResponse response) {
if (this.sessionId != null) {
CookieTool.setCookie(response, "aps-adminweb-session-id", this.sessionId, 3600 * 24, "/");
}
}
/**
* @return An id to an APSSessionService session.
*/
@Override
public String getSessionId() {
return this.sessionId;
}
/**
* Sets a new session id.
*
* @param sessionId The session id to set.
*/
@Override
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
/**
* @return The name of the session data containing the logged in user if any.
*/
@Override
public String getUserSessionName() {
return "aps-admin-user";
}
/**
* @return The required role of the user for it to be considered logged in.
*/
@Override
public String getRequiredRole() {
return "apsadmin";
}
}
| true | true | public void setSessionIdFromRequestCookie(HttpServletRequest request) {
String sessId = CookieTool.getCookie(request.getCookies(), "aps-adminweb-session-id");
if (sessId != null) {
this.sessionId = sessId;
}
}
| public void setSessionIdFromRequestCookie(HttpServletRequest request) {
if (request.getCookies() != null) {
String sessId = CookieTool.getCookie(request.getCookies(), "aps-adminweb-session-id");
if (sessId != null) {
this.sessionId = sessId;
}
}
}
|
diff --git a/develop/src/org/eclipse/xtext/GenerateAllLanguages.java b/develop/src/org/eclipse/xtext/GenerateAllLanguages.java
index 5121376a2..24f858f13 100644
--- a/develop/src/org/eclipse/xtext/GenerateAllLanguages.java
+++ b/develop/src/org/eclipse/xtext/GenerateAllLanguages.java
@@ -1,30 +1,30 @@
/*******************************************************************************
* Copyright (c) 2008 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext;
/**
* Generates all test and example languages.
*
* @author Jan K�hnlein - Initial contribution and API
*/
public class GenerateAllLanguages {
public static void main(String[] args) {
try {
org.eclipse.xtext.GenerateAllTestGrammars.main("../org.eclipse.xtext.generator.tests/");
org.eclipse.xtext.ui.common.GenerateAllTestGrammarsWithUiConfig.main("../org.eclipse.xtext.ui.common.tests/");
- org.eclipse.xtext.ui.integration.GenerateAllTestGrammars.main("../org.eclipse.xtext.ui.core.tests");
+ org.eclipse.xtext.ui.integration.GenerateAllTestGrammars.main("../org.eclipse.xtext.ui.integration.tests");
org.eclipse.emf.mwe.di.mwe.main("../org.eclipse.emf.mwe.di");
xtext.example.GenerateGrammar.main("../org.eclipse.xtext.example.domainmodel");
org.eclipse.xtext.example.FowlerDsl.main("../org.eclipse.xtext.example.fowlerdsl");
org.eclipse.xtext.reference.ReferenceGrammar.main("../org.eclipse.xtext.reference");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
try {
org.eclipse.xtext.GenerateAllTestGrammars.main("../org.eclipse.xtext.generator.tests/");
org.eclipse.xtext.ui.common.GenerateAllTestGrammarsWithUiConfig.main("../org.eclipse.xtext.ui.common.tests/");
org.eclipse.xtext.ui.integration.GenerateAllTestGrammars.main("../org.eclipse.xtext.ui.core.tests");
org.eclipse.emf.mwe.di.mwe.main("../org.eclipse.emf.mwe.di");
xtext.example.GenerateGrammar.main("../org.eclipse.xtext.example.domainmodel");
org.eclipse.xtext.example.FowlerDsl.main("../org.eclipse.xtext.example.fowlerdsl");
org.eclipse.xtext.reference.ReferenceGrammar.main("../org.eclipse.xtext.reference");
}
catch (Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
try {
org.eclipse.xtext.GenerateAllTestGrammars.main("../org.eclipse.xtext.generator.tests/");
org.eclipse.xtext.ui.common.GenerateAllTestGrammarsWithUiConfig.main("../org.eclipse.xtext.ui.common.tests/");
org.eclipse.xtext.ui.integration.GenerateAllTestGrammars.main("../org.eclipse.xtext.ui.integration.tests");
org.eclipse.emf.mwe.di.mwe.main("../org.eclipse.emf.mwe.di");
xtext.example.GenerateGrammar.main("../org.eclipse.xtext.example.domainmodel");
org.eclipse.xtext.example.FowlerDsl.main("../org.eclipse.xtext.example.fowlerdsl");
org.eclipse.xtext.reference.ReferenceGrammar.main("../org.eclipse.xtext.reference");
}
catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/core/src/main/java/org/icepush/SequenceTaggingServer.java b/core/src/main/java/org/icepush/SequenceTaggingServer.java
index dab708b..ec02fce 100644
--- a/core/src/main/java/org/icepush/SequenceTaggingServer.java
+++ b/core/src/main/java/org/icepush/SequenceTaggingServer.java
@@ -1,117 +1,117 @@
/*
* Copyright 2004-2013 ICEsoft Technologies Canada Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icepush;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.icepush.http.Request;
import org.icepush.http.Response;
import org.icepush.http.ResponseHandler;
import org.icepush.http.Server;
import org.icepush.http.standard.RequestProxy;
import org.icepush.util.Slot;
public class SequenceTaggingServer implements Server {
private static final Logger LOGGER = Logger.getLogger(SequenceTaggingServer.class.getName());
private Server server;
private Slot sequenceNo;
private List<String> participatingPushIDList = new ArrayList<String>();
private boolean participatingPushIDsChanged;
public SequenceTaggingServer(Slot sequenceNo, Server server) {
this.sequenceNo = sequenceNo;
this.server = server;
}
public void service(Request request) throws Exception {
List<String> currentParticipatingPushIDList =
Arrays.asList(request.getParameterAsStrings("ice.pushid"));
participatingPushIDsChanged =
!participatingPushIDList.containsAll(currentParticipatingPushIDList) ||
!currentParticipatingPushIDList.containsAll(participatingPushIDList);
if (participatingPushIDsChanged) {
participatingPushIDList = currentParticipatingPushIDList;
}
server.service(new TaggingRequest(request));
}
public void shutdown() {
server.shutdown();
}
public class TaggingRequest extends RequestProxy {
public TaggingRequest(Request request) {
super(request);
}
public void respondWith(final ResponseHandler handler) throws Exception {
request.respondWith(new TaggingResponseHandler(handler));
}
private class TaggingResponseHandler implements ResponseHandler {
private final ResponseHandler handler;
public TaggingResponseHandler(ResponseHandler handler) {
this.handler = handler;
}
public void respond(Response response) throws Exception {
try {
long previousSequenceNo;
try {
previousSequenceNo = request.getHeaderAsLong("ice.push.sequence");
if (previousSequenceNo >= sequenceNo.getLongValue()) {
sequenceNo.setLongValue(previousSequenceNo + 1);
} else if (participatingPushIDsChanged) {
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
} else {
- if (LOGGER.isLoggable(Level.WARNING)) {
+ if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(
- Level.WARNING,
+ Level.FINE,
"Request's 'ice.push.sequence' [" + previousSequenceNo + "] is less than " +
"the server-side sequence number [" + sequenceNo.getLongValue() + "].");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
} catch (RuntimeException e) {
// No sequence number found.
if (sequenceNo.getLongValue() == 0) {
// Start with sequence number
sequenceNo.setLongValue((long)1);
} else {
- if (LOGGER.isLoggable(Level.WARNING)) {
+ if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(
- Level.WARNING,
+ Level.FINE,
"Request's 'ice.push.sequence' header is missing, " +
"while server-side sequence number is '" + sequenceNo.getLongValue() + "'.");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
}
response.setHeader("ice.push.sequence", sequenceNo.getLongValue());
} finally {
handler.respond(response);
}
}
}
}
}
| false | true | public void respond(Response response) throws Exception {
try {
long previousSequenceNo;
try {
previousSequenceNo = request.getHeaderAsLong("ice.push.sequence");
if (previousSequenceNo >= sequenceNo.getLongValue()) {
sequenceNo.setLongValue(previousSequenceNo + 1);
} else if (participatingPushIDsChanged) {
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
} else {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(
Level.WARNING,
"Request's 'ice.push.sequence' [" + previousSequenceNo + "] is less than " +
"the server-side sequence number [" + sequenceNo.getLongValue() + "].");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
} catch (RuntimeException e) {
// No sequence number found.
if (sequenceNo.getLongValue() == 0) {
// Start with sequence number
sequenceNo.setLongValue((long)1);
} else {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.log(
Level.WARNING,
"Request's 'ice.push.sequence' header is missing, " +
"while server-side sequence number is '" + sequenceNo.getLongValue() + "'.");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
}
response.setHeader("ice.push.sequence", sequenceNo.getLongValue());
} finally {
handler.respond(response);
}
}
| public void respond(Response response) throws Exception {
try {
long previousSequenceNo;
try {
previousSequenceNo = request.getHeaderAsLong("ice.push.sequence");
if (previousSequenceNo >= sequenceNo.getLongValue()) {
sequenceNo.setLongValue(previousSequenceNo + 1);
} else if (participatingPushIDsChanged) {
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(
Level.FINE,
"Request's 'ice.push.sequence' [" + previousSequenceNo + "] is less than " +
"the server-side sequence number [" + sequenceNo.getLongValue() + "].");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
} catch (RuntimeException e) {
// No sequence number found.
if (sequenceNo.getLongValue() == 0) {
// Start with sequence number
sequenceNo.setLongValue((long)1);
} else {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(
Level.FINE,
"Request's 'ice.push.sequence' header is missing, " +
"while server-side sequence number is '" + sequenceNo.getLongValue() + "'.");
}
sequenceNo.setLongValue(sequenceNo.getLongValue() + 1);
}
}
response.setHeader("ice.push.sequence", sequenceNo.getLongValue());
} finally {
handler.respond(response);
}
}
|
diff --git a/src/org/fasttether/AirplaneModeSwitch.java b/src/org/fasttether/AirplaneModeSwitch.java
index 84ac44c..087743d 100644
--- a/src/org/fasttether/AirplaneModeSwitch.java
+++ b/src/org/fasttether/AirplaneModeSwitch.java
@@ -1,66 +1,66 @@
package org.fasttether;
import android.content.ContextWrapper;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
/**
* Switch for Airplane mode.
*
* <p>
* uses-permission
* <ul>
* <li>android.permission.WRITE_SETTINGS</li>
* </ul>
* </p>
*
* @author takayuki hirota
*/
public class AirplaneModeSwitch {
private static final String TAG = "AirplaneModeSwitch";
private final ContextWrapper contextWrapper;
public AirplaneModeSwitch(final ContextWrapper contextWrapper) {
this.contextWrapper = contextWrapper;
}
/**
* turn on airplane mode.
*/
public void enable() {
setMode(true);
}
/**
* turn off airplane mode.
*/
public void disable() {
setMode(false);
}
private boolean getCurrentMode() {
final boolean result = Settings.System.getInt(
contextWrapper.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
Log.i(TAG, "airplaneMode: " + result);
return result;
}
private void setMode(final boolean after) {
final boolean before = getCurrentMode();
if (before == after) {
Log.i(TAG, "airplaneMode alreay "
- + (before ? "enabled" : "diabled"));
+ + (before ? "enabled" : "disabled"));
return;
}
Settings.System.putInt(contextWrapper.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, after ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", after);
contextWrapper.sendBroadcast(intent);
}
}
| true | true | private void setMode(final boolean after) {
final boolean before = getCurrentMode();
if (before == after) {
Log.i(TAG, "airplaneMode alreay "
+ (before ? "enabled" : "diabled"));
return;
}
Settings.System.putInt(contextWrapper.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, after ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", after);
contextWrapper.sendBroadcast(intent);
}
| private void setMode(final boolean after) {
final boolean before = getCurrentMode();
if (before == after) {
Log.i(TAG, "airplaneMode alreay "
+ (before ? "enabled" : "disabled"));
return;
}
Settings.System.putInt(contextWrapper.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, after ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", after);
contextWrapper.sendBroadcast(intent);
}
|
diff --git a/src/com/vividsolutions/jump/workbench/ui/renderer/ImageCachingRenderer.java b/src/com/vividsolutions/jump/workbench/ui/renderer/ImageCachingRenderer.java
index b74afae1..4724cb07 100644
--- a/src/com/vividsolutions/jump/workbench/ui/renderer/ImageCachingRenderer.java
+++ b/src/com/vividsolutions/jump/workbench/ui/renderer/ImageCachingRenderer.java
@@ -1,108 +1,112 @@
/*
* The Unified Mapping Platform (JUMP) is an extensible, interactive GUI
* for visualizing and manipulating spatial features with geometry and attributes.
*
* Copyright (C) 2003 Vivid Solutions
*
* 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.
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jump.workbench.ui.renderer;
import java.awt.Graphics2D;
import javax.swing.SwingUtilities;
import com.vividsolutions.jump.workbench.ui.LayerViewPanel;
import com.vividsolutions.jump.workbench.ui.WorkbenchFrame;
public abstract class ImageCachingRenderer implements Renderer {
protected volatile boolean cancelled = false;
private Object contentID;
protected volatile ThreadSafeImage image = null;
protected LayerViewPanel panel;
protected volatile boolean rendering = false;
public ImageCachingRenderer(Object contentID, LayerViewPanel panel) {
this.contentID = contentID;
this.panel = panel;
}
public void clearImageCache() {
image = null;
}
public boolean isRendering() {
return rendering;
}
public Object getContentID() {
return contentID;
}
protected ThreadSafeImage getImage() {
return image;
}
public void copyTo(Graphics2D graphics) {
//Some subclasses override #getImage [Jon Aquino]
if (getImage() == null) {
return;
}
getImage().copyTo(graphics, null);
}
public Runnable createRunnable() {
if (image != null) {
return null;
}
//Rendering starts as soon as the #createRunnable request is made,
//to get the animated clock icons going. [Jon Aquino]
- rendering = true;
+ //rendering = true;
cancelled = false;
return new Runnable() {
public void run() {
+ //Rendering starts when the thread actually starts
+ //In some situations, setting rendering=true before starting
+ //Runnable could create infinite loops (see bug id 3564039)
+ rendering = true;
try {
if (cancelled) {
//This short-circuit exit made a big speed increase
// (21 March 2003). [Jon Aquino]
return;
}
image = new ThreadSafeImage(panel);
try {
renderHook(image);
} catch (Throwable t) {
panel.getContext()
.warnUser(WorkbenchFrame.toMessage(t));
t.printStackTrace(System.err);
return;
}
//Don't wait for the RenderingManager's 1-second
// repaint-timer. [Jon Aquino]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
panel.superRepaint();
}
});
} finally {
rendering = false;
}
}
};
}
protected abstract void renderHook(ThreadSafeImage image) throws Exception;
public void cancel() {
cancelled = true;
}
}
| false | true | public Runnable createRunnable() {
if (image != null) {
return null;
}
//Rendering starts as soon as the #createRunnable request is made,
//to get the animated clock icons going. [Jon Aquino]
rendering = true;
cancelled = false;
return new Runnable() {
public void run() {
try {
if (cancelled) {
//This short-circuit exit made a big speed increase
// (21 March 2003). [Jon Aquino]
return;
}
image = new ThreadSafeImage(panel);
try {
renderHook(image);
} catch (Throwable t) {
panel.getContext()
.warnUser(WorkbenchFrame.toMessage(t));
t.printStackTrace(System.err);
return;
}
//Don't wait for the RenderingManager's 1-second
// repaint-timer. [Jon Aquino]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
panel.superRepaint();
}
});
} finally {
rendering = false;
}
}
};
}
| public Runnable createRunnable() {
if (image != null) {
return null;
}
//Rendering starts as soon as the #createRunnable request is made,
//to get the animated clock icons going. [Jon Aquino]
//rendering = true;
cancelled = false;
return new Runnable() {
public void run() {
//Rendering starts when the thread actually starts
//In some situations, setting rendering=true before starting
//Runnable could create infinite loops (see bug id 3564039)
rendering = true;
try {
if (cancelled) {
//This short-circuit exit made a big speed increase
// (21 March 2003). [Jon Aquino]
return;
}
image = new ThreadSafeImage(panel);
try {
renderHook(image);
} catch (Throwable t) {
panel.getContext()
.warnUser(WorkbenchFrame.toMessage(t));
t.printStackTrace(System.err);
return;
}
//Don't wait for the RenderingManager's 1-second
// repaint-timer. [Jon Aquino]
SwingUtilities.invokeLater(new Runnable() {
public void run() {
panel.superRepaint();
}
});
} finally {
rendering = false;
}
}
};
}
|
diff --git a/src/story/book/view/StoryFragmentListActivity.java b/src/story/book/view/StoryFragmentListActivity.java
index 83f8334..6cbb691 100644
--- a/src/story/book/view/StoryFragmentListActivity.java
+++ b/src/story/book/view/StoryFragmentListActivity.java
@@ -1,328 +1,327 @@
/* CMPUT301F13T06-Adventure Club: A choose-your-own-adventure story platform
* Copyright (C) 2013 Alexander Cheung, Jessica Surya, Vina Nguyen, Anthony Ou,
* Nancy Pham-Nguyen
*
* 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
* 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 story.book.view;
import java.util.ArrayList;
import java.util.HashMap;
import story.book.view.R;
import story.book.controller.StoryCreationController;
import story.book.model.Story;
import story.book.model.StoryFragment;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.SearchView;
/**
* StoryFragmentListActivity displays all story fragments contained
* in the story that is currently open. Selecting a story fragment
* will allow user to:
* 1. Edit the story fragment
* 2. Set the story fragment as the starting fragment
* 3. Delete the story fragment from the story
*
* @author Jessica Surya
* @author Vina Nguyen
*/
public class StoryFragmentListActivity extends Activity implements StoryView, RequestingActivity {
ActionBar actionBar;
ArrayList<StoryFragment> SFL;
ArrayAdapter<StoryFragment> adapter;
StoryCreationController SCC;
int pos;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story_fragment_read_activity);
SCC = new StoryCreationController();
SFL = new ArrayList<StoryFragment>();
SCC.getStory().addView(this);
return;
}
@Override
public void onStart() {
super.onStart();
Log.d(String.valueOf(
SFL.isEmpty()), "DEBUG: SFL is empty");
getFragmentTitles();
}
@Override
public void onDestroy() {
super.onDestroy();
Story s = SCC.getStory();
SCC.saveStory();
s.deleteView(this);
for (StoryFragment f: SFL) {
f.deleteView(this);
}
}
/**
* getFragmentTitles() loads fragment titles from the story using the
* <code>StoryCreationController</code> and displays them in the list
* by calling <code>updateFragmentList()</code> method
*/
private void getFragmentTitles() {
SFL = new ArrayList<StoryFragment>();
HashMap<Integer, StoryFragment> map = SCC.getFragments();
for (Integer key : map.keySet()){
StoryFragment f = map.get(key);
SFL.add(f);
f.addView(this);
}
updateFragmentList();
}
/**
* updateFragmentList() displays a story fragment titles in the list
*/
private void updateFragmentList() {
String title = SCC.getStory().getStoryInfo().getTitle();
actionBar = getActionBar();
actionBar.setTitle(title);
adapter = new ArrayAdapter<StoryFragment>(this, android.R.layout.simple_list_item_1,
SFL);
ListView listview = new ListView(this);
listview.setBackgroundColor(Color.WHITE);
listview.setAdapter(adapter);
setContentView(listview);
registerForContextMenu(listview);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
pos = position;
Intent i = new Intent(parent.getContext(), StoryFragmentEditActivity.class);
i.putExtra("FID", SFL.get(pos).getFragmentID());
startActivity(i);
}
});
}
/**
* editFragment() passes the FragmentID from the selected story fragment in the list
* and starts a new <code>StoryFragmentEditActivity</code> for edit the contents of
* the fragment
*
* @param FragmentID (FID) which will be passed to <code>StoryFragmentEditActivity</code>
*/
private void editFragment(int FID) {
Intent i = new Intent(this, StoryFragmentEditActivity.class);
i.putExtra("FID", FID);
startActivity(i);
}
/**
* changeFragmentTitle() adds a new fragment to the current story.
*/
private void changeFragmentTitle() {
DialogFragment newFragment = new RequestTextDialog();
((RequestTextDialog)newFragment).setParent(this);
((RequestTextDialog)newFragment).setHeader(this.getString(R.string.add_fragment_title));
((RequestTextDialog)newFragment).setWarning(this.getString(R.string.bad_frag_title_msg));
newFragment.show(getFragmentManager(), "addFragment");
}
public void onUserSelectValue(String title) {
if (title != null) {
if (pos != - 1) {
//Update fragment title
SCC.changeFragmentTitle(SFL.get(pos), title);
} else
{
//Create fragment with this title
StoryFragment fragment = SCC.newFragment(title);
//Open fragment for editing
editFragment(fragment.getFragmentID());
}
}
}
/**
* doMySearch() takes a query from the search bar, passes it to
* <code>StoryCreationController</code>, and display the set of results
* returned by the controller in the listView
*
* @param query returned by SearchView (search bar)
*/
private void doMySearch(String query) {
SFL = new ArrayList<StoryFragment>();
//show the list with just the search results
HashMap<Integer, StoryFragment> map = SCC.searchFragments(query);
for (Integer key : map.keySet()){
SFL.add(map.get(key));
}
updateFragmentList();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.search_bar, menu);
inflater.inflate(R.menu.fragment_list_menu, menu);
inflater.inflate(R.menu.standard_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
- SearchView searchView = (SearchView) menu.findItem(R.id.search_bar).getActionView();
+ SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSubmitButtonEnabled(true);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
- searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
+ searchView.setIconifiedByDefault(true); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(String.valueOf(query), "DEBUG: Query entered");
doMySearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText.isEmpty()) {
Log.d("Close", "DEBUG: Search closed");
SFL = new ArrayList<StoryFragment>();
getFragmentTitles();
return true;
}
else {
return false;
}
}
});
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
Intent intent;
switch (item.getItemId()) {
case R.id.title_activity_dashboard:
intent = new Intent(this, Dashboard.class);
startActivity(intent);
finish();
return true;
case R.id.add_fragment:
pos = -1;
changeFragmentTitle();
return true;
case R.id.publish:
if (StoryApplication.checkInternetConnected()) {
SCC.publishStory();
} else {
SimpleWarningDialog.getWarningDialog(this.getString(R.string.no_internet), this);
}
return true;
case R.id.change_info:
intent = new Intent(this, EditStoryInformationActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select an Option:");
menu.add(0, v.getId(), 1, "Edit");
menu.add(0, v.getId(), 2, "Change Fragment Title");
menu.add(0, v.getId(), 3, "Set as Starting Story Fragment");
menu.add(0, v.getId(), 4, "Delete");
menu.add(0, v.getId(), 5, "Cancel");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
pos = info.position;
switch (item.getOrder()) {
case 1:
// Edit story fragment
editFragment(SFL.get(pos).getFragmentID());
break;
case 2:
// Edit story fragment title
changeFragmentTitle();
break;
case 3:
// Set as starting story fragment
SCC.setStartingFragment(SFL.get(pos).getFragmentID());
break;
case 4:
//Delete
int FID = SFL.get(pos).getFragmentID();
if (FID == SCC.getStartingFragment()) {
SimpleWarningDialog.getWarningDialog(this.getString(R.string.bad_frag_delete_msg), this);
} else {
SCC.deleteFragment(FID);
}
getFragmentTitles();
break;
case 5:
// Cancel options
return false;
}
return true;
}
@Override
public void update(Object model) {
// TODO Auto-generated method stub
getFragmentTitles();
}
}
| false | true | public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_bar, menu);
inflater.inflate(R.menu.fragment_list_menu, menu);
inflater.inflate(R.menu.standard_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search_bar).getActionView();
searchView.setSubmitButtonEnabled(true);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(String.valueOf(query), "DEBUG: Query entered");
doMySearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText.isEmpty()) {
Log.d("Close", "DEBUG: Search closed");
SFL = new ArrayList<StoryFragment>();
getFragmentTitles();
return true;
}
else {
return false;
}
}
});
return super.onCreateOptionsMenu(menu);
}
| public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fragment_list_menu, menu);
inflater.inflate(R.menu.standard_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSubmitButtonEnabled(true);
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Log.d(String.valueOf(query), "DEBUG: Query entered");
doMySearch(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
if (newText.isEmpty()) {
Log.d("Close", "DEBUG: Search closed");
SFL = new ArrayList<StoryFragment>();
getFragmentTitles();
return true;
}
else {
return false;
}
}
});
return super.onCreateOptionsMenu(menu);
}
|
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/AntBuilder.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/AntBuilder.java
index 270df899..5dd01739 100644
--- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/AntBuilder.java
+++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/builders/AntBuilder.java
@@ -1,391 +1,391 @@
/********************************************************************************
* CruiseControl, a Continuous Integration Toolkit
* Copyright (c) 2001, ThoughtWorks, Inc.
* 651 W Washington Ave. Suite 600
* Chicago, IL 60661 USA
* 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 ThoughtWorks, Inc., CruiseControl, 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 REGENTS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
package net.sourceforge.cruisecontrol.builders;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sourceforge.cruisecontrol.Builder;
import net.sourceforge.cruisecontrol.CruiseControlException;
import net.sourceforge.cruisecontrol.util.EmptyElementFilter;
import net.sourceforge.cruisecontrol.util.Util;
import net.sourceforge.cruisecontrol.util.ValidationHelper;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.XMLFilter;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* we often see builds that fail because the previous build is still holding on to some resource.
* we can avoid this by just building in a different process which will completely die after every
* build.
*/
public class AntBuilder extends Builder {
protected static final String DEFAULT_LOGGER = "org.apache.tools.ant.XmlLogger";
private static final Logger LOG = Logger.getLogger(AntBuilder.class);
private String antWorkingDir = null;
private String buildFile = "build.xml";
private String target = "";
private String tempFileName = "log.xml";
private String antScript;
private String antHome;
private boolean useLogger;
private List args = new ArrayList();
private List properties = new ArrayList();
private boolean useDebug = false;
private boolean useQuiet = false;
private String loggerClassName = DEFAULT_LOGGER;
private File saveLogDir = null;
private long timeout = ScriptRunner.NO_TIMEOUT;
public void validate() throws CruiseControlException {
super.validate();
ValidationHelper.assertIsSet(buildFile, "buildfile", this.getClass());
ValidationHelper.assertIsSet(target, "target", this.getClass());
ValidationHelper.assertFalse(useDebug && useQuiet,
"'useDebug' and 'useQuiet' can't be used together");
if (!useLogger && (useDebug || useQuiet)) {
LOG.warn("usedebug and usequiet are ignored if uselogger is not set to 'true'!");
}
if (antScript != null && !args.isEmpty()) {
LOG.warn("jvmargs will be ignored if you specify your own antscript!");
}
if (saveLogDir != null) {
ValidationHelper.assertTrue(saveLogDir.isDirectory(), "'saveLogDir' must exist and be a directory");
}
ValidationHelper.assertFalse(antScript != null && antHome != null,
"'antHome' and 'antscript' cannot both be set");
if (antHome != null) {
final File antHomeFile = new File(antHome);
ValidationHelper.assertTrue(antHomeFile.exists() && antHomeFile.isDirectory(),
"'antHome' must exist and be a directory. Expected to find "
+ antHomeFile.getAbsolutePath());
final File antScriptInAntHome = new File(findAntScript(Util.isWindows()));
ValidationHelper.assertTrue(antScriptInAntHome.exists() && antScriptInAntHome.isFile(),
"'antHome' must contain an ant execution script. Expected to find "
+ antScriptInAntHome.getAbsolutePath());
antScript = antScriptInAntHome.getAbsolutePath();
}
}
/**
* build and return the results via xml. debug status can be determined
* from log4j category once we get all the logging in place.
*/
public Element build(Map buildProperties) throws CruiseControlException {
AntScript script = new AntScript();
script.setBuildProperties(buildProperties);
script.setProperties(properties);
script.setUseLogger(useLogger);
script.setUseScript(antScript != null);
script.setWindows(Util.isWindows());
script.setAntScript(antScript);
script.setArgs(args);
script.setBuildFile(buildFile);
script.setTarget(target);
script.setLoggerClassName(loggerClassName);
script.setTempFileName(tempFileName);
script.setUseDebug(useDebug);
script.setUseQuiet(useQuiet);
script.setSystemClassPath(getSystemClassPath());
File workingDir = antWorkingDir != null ? new File(antWorkingDir) : null;
ScriptRunner scriptRunner = new ScriptRunner();
boolean scriptCompleted = scriptRunner.runScript(workingDir, script, timeout);
File logFile = new File(antWorkingDir, tempFileName);
Element buildLogElement;
if (!scriptCompleted) {
LOG.warn("Build timeout timer of " + timeout + " seconds has expired");
buildLogElement = new Element("build");
buildLogElement.setAttribute("error", "build timeout");
- // although log file is most certainly empy, let's try to preserve it
+ // although log file is most certainly empty, let's try to preserve it
// somebody should really fix ant's XmlLogger
if (logFile.exists()) {
try {
buildLogElement.setText(Util.readFileToString(logFile));
} catch (IOException likely) {
}
}
} else {
//read in log file as element, return it
buildLogElement = getAntLogAsElement(logFile);
saveAntLog(logFile);
logFile.delete();
}
return buildLogElement;
}
/**
* Set the location to which the ant log will be saved before Cruise
* Control merges the file into its log.
*
* @param dir
* the absolute path to the directory where the ant log will be
* saved or relative path to where you started CruiseControl
*/
public void setSaveLogDir(String dir) {
saveLogDir = null;
if (dir != null && !dir.trim().equals("")) {
saveLogDir = new File(dir.trim());
}
}
void saveAntLog(File logFile) {
if (saveLogDir == null) {
return;
}
try {
File newAntLogFile = new File(saveLogDir, tempFileName);
newAntLogFile.createNewFile();
FileInputStream in = new FileInputStream(logFile);
FileOutputStream out = new FileOutputStream(newAntLogFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException ioe) {
LOG.error(ioe);
LOG.error("Unable to create file: " + new File(saveLogDir, tempFileName));
}
}
/**
* Set the working directory where Ant will be invoked. This parameter gets
* set in the XML file via the antWorkingDir attribute. The directory can
* be relative (to the cruisecontrol current working directory) or absolute.
*
* @param dir
* the directory to make the current working directory.
*/
public void setAntWorkingDir(String dir) {
antWorkingDir = dir;
}
/**
* Sets the Script file to be invoked (in place of calling the Ant class
* directly). This is a platform dependent script file.
*
* @param antScript the name of the script file
*/
public void setAntScript(String antScript) {
this.antScript = antScript;
}
/**
* If set CC will use the platform specific script provided by Ant
*
* @param antHome the path to ANT_HOME
*/
public void setAntHome(String antHome) {
this.antHome = antHome;
}
/**
* If the anthome attribute is set, then this method returns the correct shell script
* to use for a specific environment.
*/
protected String findAntScript(boolean isWindows) throws CruiseControlException {
if (antHome == null) {
throw new CruiseControlException("anthome attribute not set.");
}
if (isWindows) {
return antHome + "\\bin\\ant.bat";
} else {
return antHome + "/bin/ant";
}
}
/**
* Set the name of the temporary file used to capture output.
*
* @param tempFileName
*/
public void setTempFile(String tempFileName) {
this.tempFileName = tempFileName;
}
/**
* Set the Ant target(s) to invoke.
*
* @param target the target(s) name.
*/
public void setTarget(String target) {
this.target = target;
}
/**
* Used to invoke the builder via JMX with a different target.
*/
protected void overrideTarget(String target) {
setTarget(target);
}
/**
* Sets the name of the build file that Ant will use. The Ant default is
* build.xml, use this to override it.
*
* @param buildFile the name of the build file.
*/
public void setBuildFile(String buildFile) {
this.buildFile = buildFile;
}
/**
* Sets whether Ant will use the custom loggers.
*
* @param useLogger
*/
public void setUseLogger(boolean useLogger) {
this.useLogger = useLogger;
}
public Object createJVMArg() {
JVMArg arg = new JVMArg();
args.add(arg);
return arg;
}
public Property createProperty() {
Property property = new Property();
properties.add(property);
return property;
}
protected String getSystemClassPath() {
return System.getProperty("java.class.path");
}
protected static Element getAntLogAsElement(File file) throws CruiseControlException {
if (!file.exists()) {
throw new CruiseControlException("ant logfile " + file.getAbsolutePath() + " does not exist.");
}
try {
SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
// old Ant-versions contain a bug in the XmlLogger that outputs
// an invalid PI containing the target "xml:stylesheet"
// instead of "xml-stylesheet": fix this
XMLFilter piFilter = new XMLFilterImpl() {
public void processingInstruction(String target, String data) throws SAXException {
if (target.equals("xml:stylesheet")) { target = "xml-stylesheet"; }
super.processingInstruction(target, data);
}
};
// get rid of empty <task>- and <message>-elements created by Ant's XmlLogger
XMLFilter emptyTaskFilter = new EmptyElementFilter("task");
emptyTaskFilter.setParent(piFilter);
XMLFilter emptyMessageFilter = new EmptyElementFilter("message");
emptyMessageFilter.setParent(emptyTaskFilter);
builder.setXMLFilter(emptyMessageFilter);
return builder.build(file).getRootElement();
} catch (Exception ee) {
if (ee instanceof CruiseControlException) {
throw (CruiseControlException) ee;
}
File saveFile = new File(file.getParentFile(), System.currentTimeMillis() + file.getName());
file.renameTo(saveFile);
throw new CruiseControlException("Error reading : " + file.getAbsolutePath()
+ ". Saved as : " + saveFile.getAbsolutePath(), ee);
}
}
public void setUseDebug(boolean debug) {
useDebug = debug;
}
public void setUseQuiet(boolean quiet) {
useQuiet = quiet;
}
public String getLoggerClassName() {
return loggerClassName;
}
public void setLoggerClassName(String string) {
loggerClassName = string;
}
public class JVMArg {
private String arg;
public void setArg(String arg) {
this.arg = arg;
}
public String getArg() {
return arg;
}
}
/**
* @param timeout The timeout to set.
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
}
| true | true | public Element build(Map buildProperties) throws CruiseControlException {
AntScript script = new AntScript();
script.setBuildProperties(buildProperties);
script.setProperties(properties);
script.setUseLogger(useLogger);
script.setUseScript(antScript != null);
script.setWindows(Util.isWindows());
script.setAntScript(antScript);
script.setArgs(args);
script.setBuildFile(buildFile);
script.setTarget(target);
script.setLoggerClassName(loggerClassName);
script.setTempFileName(tempFileName);
script.setUseDebug(useDebug);
script.setUseQuiet(useQuiet);
script.setSystemClassPath(getSystemClassPath());
File workingDir = antWorkingDir != null ? new File(antWorkingDir) : null;
ScriptRunner scriptRunner = new ScriptRunner();
boolean scriptCompleted = scriptRunner.runScript(workingDir, script, timeout);
File logFile = new File(antWorkingDir, tempFileName);
Element buildLogElement;
if (!scriptCompleted) {
LOG.warn("Build timeout timer of " + timeout + " seconds has expired");
buildLogElement = new Element("build");
buildLogElement.setAttribute("error", "build timeout");
// although log file is most certainly empy, let's try to preserve it
// somebody should really fix ant's XmlLogger
if (logFile.exists()) {
try {
buildLogElement.setText(Util.readFileToString(logFile));
} catch (IOException likely) {
}
}
} else {
//read in log file as element, return it
buildLogElement = getAntLogAsElement(logFile);
saveAntLog(logFile);
logFile.delete();
}
return buildLogElement;
}
| public Element build(Map buildProperties) throws CruiseControlException {
AntScript script = new AntScript();
script.setBuildProperties(buildProperties);
script.setProperties(properties);
script.setUseLogger(useLogger);
script.setUseScript(antScript != null);
script.setWindows(Util.isWindows());
script.setAntScript(antScript);
script.setArgs(args);
script.setBuildFile(buildFile);
script.setTarget(target);
script.setLoggerClassName(loggerClassName);
script.setTempFileName(tempFileName);
script.setUseDebug(useDebug);
script.setUseQuiet(useQuiet);
script.setSystemClassPath(getSystemClassPath());
File workingDir = antWorkingDir != null ? new File(antWorkingDir) : null;
ScriptRunner scriptRunner = new ScriptRunner();
boolean scriptCompleted = scriptRunner.runScript(workingDir, script, timeout);
File logFile = new File(antWorkingDir, tempFileName);
Element buildLogElement;
if (!scriptCompleted) {
LOG.warn("Build timeout timer of " + timeout + " seconds has expired");
buildLogElement = new Element("build");
buildLogElement.setAttribute("error", "build timeout");
// although log file is most certainly empty, let's try to preserve it
// somebody should really fix ant's XmlLogger
if (logFile.exists()) {
try {
buildLogElement.setText(Util.readFileToString(logFile));
} catch (IOException likely) {
}
}
} else {
//read in log file as element, return it
buildLogElement = getAntLogAsElement(logFile);
saveAntLog(logFile);
logFile.delete();
}
return buildLogElement;
}
|
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index 964dd99c..2c39eba5 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,2087 +1,2089 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.compat.CompatUtils;
import com.android.inputmethod.compat.EditorInfoCompatUtils;
import com.android.inputmethod.compat.InputConnectionCompatUtils;
import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
import com.android.inputmethod.compat.InputMethodServiceCompatWrapper;
import com.android.inputmethod.compat.InputTypeCompatUtils;
import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
import com.android.inputmethod.deprecated.VoiceProxy;
import com.android.inputmethod.deprecated.recorrection.Recorrection;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.LatinKeyboard;
import com.android.inputmethod.keyboard.LatinKeyboardView;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.InputConnection;
import android.widget.LinearLayout;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean PERF_DEBUG = false;
private static final boolean TRACE = false;
private static boolean DEBUG = LatinImeLogger.sDBG;
/**
* The private IME option used to indicate that no microphone should be
* shown for a given text field. For instance, this is specified by the
* search dialog when the dialog is already showing a voice search button.
*
* @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed.
*/
@SuppressWarnings("dep-ann")
public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm";
/**
* The private IME option used to indicate that no microphone should be
* shown for a given text field. For instance, this is specified by the
* search dialog when the dialog is already showing a voice search button.
*/
public static final String IME_OPTION_NO_MICROPHONE = "noMicrophoneKey";
/**
* The private IME option used to indicate that no settings key should be
* shown for a given text field.
*/
public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey";
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
/**
* The name of the scheme used by the Package Manager to warn of a new package installation,
* replacement or removal.
*/
private static final String SCHEME_PACKAGE = "package";
private int mSuggestionVisibility;
private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE
= R.string.prefs_suggestion_visibility_show_value;
private static final int SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE
= R.string.prefs_suggestion_visibility_show_only_portrait_value;
private static final int SUGGESTION_VISIBILILTY_HIDE_VALUE
= R.string.prefs_suggestion_visibility_hide_value;
private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] {
SUGGESTION_VISIBILILTY_SHOW_VALUE,
SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE,
SUGGESTION_VISIBILILTY_HIDE_VALUE
};
private Settings.Values mSettingsValues;
private View mCandidateViewContainer;
private int mCandidateStripHeight;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private AlertDialog mOptionsDialog;
private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
private String mInputMethodId;
private KeyboardSwitcher mKeyboardSwitcher;
private SubtypeSwitcher mSubtypeSwitcher;
private VoiceProxy mVoiceProxy;
private Recorrection mRecorrection;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
// TODO: Create an inner class to group options and pseudo-options to improve readability.
// These variables are initialized according to the {@link EditorInfo#inputType}.
private boolean mShouldInsertMagicSpace;
private boolean mInputTypeNoAutoCorrect;
private boolean mIsSettingsSuggestionStripOn;
private boolean mApplicationSpecifiedCompletionOn;
private final StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private CharSequence mBestWord;
private boolean mHasUncommittedTypedChars;
private boolean mHasDictionary;
// Magic space: a space that should disappear on space/apostrophe insertion, move after the
// punctuation on punctuation insertion, and become a real space on alpha char insertion.
private boolean mJustAddedMagicSpace; // This indicates whether the last char is a magic space.
private int mCorrectionMode;
private int mCommittedLength;
private int mOrientation;
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private int mDeleteCount;
private long mLastKeyTime;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private static final float FX_VOLUME = -1.0f;
private boolean mSilentModeOn; // System-wide current configuration
// TODO: Move this flag to VoiceProxy
private boolean mConfigurationChanging;
// Object for reacting to adding/removing a dictionary pack.
private BroadcastReceiver mDictionaryPackInstallReceiver =
new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
public final UIHandler mHandler = new UIHandler();
public class UIHandler extends Handler {
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 4;
private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 5;
private static final int MSG_SPACE_TYPED = 6;
private static final int MSG_SET_BIGRAM_PREDICTIONS = 7;
@Override
public void handleMessage(Message msg) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final LatinKeyboardView inputView = switcher.getInputView();
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
mRecorrection.setRecorrectionSuggestions(mVoiceProxy, mCandidateView, mSuggest,
mKeyboardSwitcher, mWord, mHasUncommittedTypedChars, mLastSelectionStart,
mLastSelectionEnd, mSettingsValues.mWordSeparators);
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
case MSG_SET_BIGRAM_PREDICTIONS:
updateBigramPredictions();
break;
case MSG_VOICE_RESULTS:
mVoiceProxy.handleVoiceResults(preferCapitalization()
|| (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked()));
break;
case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR:
if (inputView != null) {
inputView.setSpacebarTextFadeFactor(
(1.0f + mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar) / 2,
(LatinKeyboard)msg.obj);
}
sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj),
mSettingsValues.mDurationOfFadeoutLanguageOnSpacebar);
break;
case MSG_DISMISS_LANGUAGE_ON_SPACEBAR:
if (inputView != null) {
inputView.setSpacebarTextFadeFactor(
mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar,
(LatinKeyboard)msg.obj);
}
break;
}
}
public void postUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTIONS);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS),
mSettingsValues.mDelayUpdateSuggestions);
}
public void cancelUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTIONS);
}
public boolean hasPendingUpdateSuggestions() {
return hasMessages(MSG_UPDATE_SUGGESTIONS);
}
public void postUpdateOldSuggestions() {
removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
sendMessageDelayed(obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS),
mSettingsValues.mDelayUpdateOldSuggestions);
}
public void cancelUpdateOldSuggestions() {
removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
}
public void postUpdateShiftKeyState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE),
mSettingsValues.mDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
public void postUpdateBigramPredictions() {
removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS),
mSettingsValues.mDelayUpdateSuggestions);
}
public void cancelUpdateBigramPredictions() {
removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
}
public void updateVoiceResults() {
sendMessage(obtainMessage(MSG_VOICE_RESULTS));
}
public void startDisplayLanguageOnSpacebar(boolean localeChanged) {
removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR);
removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR);
final LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
final LatinKeyboard keyboard = mKeyboardSwitcher.getLatinKeyboard();
// The language is always displayed when the delay is negative.
final boolean needsToDisplayLanguage = localeChanged
|| mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar < 0;
// The language is never displayed when the delay is zero.
if (mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar != 0) {
inputView.setSpacebarTextFadeFactor(needsToDisplayLanguage ? 1.0f
: mSettingsValues.mFinalFadeoutFactorOfLanguageOnSpacebar, keyboard);
}
// The fadeout animation will start when the delay is positive.
if (localeChanged && mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar > 0) {
sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard),
mSettingsValues.mDelayBeforeFadeoutLanguageOnSpacebar);
}
}
}
public void startDoubleSpacesTimer() {
removeMessages(MSG_SPACE_TYPED);
sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED),
mSettingsValues.mDoubleSpacesTurnIntoPeriodTimeout);
}
public void cancelDoubleSpacesTimer() {
removeMessages(MSG_SPACE_TYPED);
}
public boolean isAcceptingDoubleSpaces() {
return hasMessages(MSG_SPACE_TYPED);
}
}
@Override
public void onCreate() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
LanguageSwitcherProxy.init(this, prefs);
SubtypeSwitcher.init(this, prefs);
KeyboardSwitcher.init(this, prefs);
Recorrection.init(this, prefs);
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance(this);
mInputMethodId = Utils.getInputMethodId(mImm, getPackageName());
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mRecorrection = Recorrection.getInstance();
loadSettings();
final Resources res = getResources();
mResources = res;
Utils.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest();
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e);
}
}
mOrientation = res.getConfiguration().orientation;
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
mVoiceProxy = VoiceProxy.init(this, prefs, mHandler);
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageFilter.addDataScheme(SCHEME_PACKAGE);
registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
final IntentFilter newDictFilter = new IntentFilter();
newDictFilter.addAction(
DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
}
// Has to be package-visible for unit tests
/* package */ void loadSettings() {
if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
if (null == mSubtypeSwitcher) mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mSettingsValues = new Settings.Values(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr());
}
private void initSuggest() {
final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
final Locale keyboardLocale = new Locale(localeStr);
final Resources res = mResources;
final Locale savedLocale = Utils.setSystemLocale(res, keyboardLocale);
if (mSuggest != null) {
mSuggest.close();
}
int mainDicResId = Utils.getMainDictionaryResourceId(res);
mSuggest = new Suggest(this, mainDicResId, keyboardLocale);
if (mSettingsValues.mAutoCorrectEnabled) {
mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold);
}
updateAutoTextEnabled();
mUserDictionary = new UserDictionary(this, localeStr);
mSuggest.setUserDictionary(mUserDictionary);
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
mSuggest.setContactsDictionary(mContactsDictionary);
mAutoDictionary = new AutoDictionary(this, this, localeStr, Suggest.DIC_AUTO);
mSuggest.setAutoDictionary(mAutoDictionary);
mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
updateCorrectionMode();
Utils.setSystemLocale(res, savedLocale);
}
/* package private */ void resetSuggestMainDict() {
final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
final Locale keyboardLocale = new Locale(localeStr);
int mainDicResId = Utils.getMainDictionaryResourceId(mResources);
mSuggest.resetMainDict(this, mainDicResId, keyboardLocale);
}
@Override
public void onDestroy() {
if (mSuggest != null) {
mSuggest.close();
mSuggest = null;
}
unregisterReceiver(mReceiver);
unregisterReceiver(mDictionaryPackInstallReceiver);
mVoiceProxy.destroy();
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
mSubtypeSwitcher.onConfigurationChanged(conf);
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
if (isShowingOptionDialog())
mOptionsDialog.dismiss();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
mVoiceProxy.onConfigurationChanged(conf);
mConfigurationChanging = false;
// This will work only when the subtype is not supported.
LanguageSwitcherProxy.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
return mKeyboardSwitcher.onCreateInputView();
}
@Override
public View onCreateCandidatesView() {
LayoutInflater inflater = getLayoutInflater();
LinearLayout container = (LinearLayout)inflater.inflate(R.layout.candidates, null);
mCandidateViewContainer = container;
mCandidateStripHeight = (int)mResources.getDimension(R.dimen.candidate_strip_height);
mCandidateView = (CandidateView) container.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return container;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
LatinKeyboardView inputView = switcher.getInputView();
if (DEBUG) {
Log.d(TAG, "onStartInputView: " + inputView);
}
// In landscape mode, this method gets called without the input view being created.
if (inputView == null) {
return;
}
mSubtypeSwitcher.updateParametersOnStartInputView();
TextEntryState.reset();
// Most such things we decide below in initializeInputAttributesAndGetMode, but we need to
// know now whether this is a password text field, because we need to know now whether we
// want to enable the voice button.
final VoiceProxy voiceIme = mVoiceProxy;
voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(attribute.inputType)
|| InputTypeCompatUtils.isVisiblePasswordInputType(attribute.inputType));
initializeInputAttributes(attribute);
inputView.closing();
mEnteredText = null;
mComposing.setLength(0);
mHasUncommittedTypedChars = false;
mDeleteCount = 0;
mJustAddedMagicSpace = false;
loadSettings();
updateCorrectionMode();
updateAutoTextEnabled();
updateSuggestionVisibility(mPrefs, mResources);
if (mSuggest != null && mSettingsValues.mAutoCorrectEnabled) {
mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold);
}
mVoiceProxy.loadSettings(attribute, mPrefs);
// This will work only when the subtype is not supported.
LanguageSwitcherProxy.loadSettings();
if (mSubtypeSwitcher.isKeyboardMode()) {
switcher.loadKeyboard(attribute,
mSubtypeSwitcher.isShortcutImeEnabled() && voiceIme.isVoiceButtonEnabled(),
voiceIme.isVoiceButtonOnPrimary());
switcher.updateShiftState();
}
setCandidatesViewShownInternal(isCandidateStripVisible(), false /* needsInputViewShown */ );
// Delay updating suggestions because keyboard input view may not be shown at this point.
mHandler.postUpdateSuggestions();
updateCorrectionMode();
inputView.setKeyPreviewPopupEnabled(mSettingsValues.mKeyPreviewPopupOn,
mSettingsValues.mKeyPreviewPopupDismissDelay);
inputView.setProximityCorrectionEnabled(true);
// If we just entered a text field, maybe it has some old text that requires correction
mRecorrection.checkRecorrectionOnStart();
inputView.setForeground(true);
voiceIme.onStartInputView(inputView.getWindowToken());
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
private void initializeInputAttributes(EditorInfo attribute) {
if (attribute == null)
return;
final int inputType = attribute.inputType;
final int variation = inputType & InputType.TYPE_MASK_VARIATION;
mShouldInsertMagicSpace = false;
mInputTypeNoAutoCorrect = false;
mIsSettingsSuggestionStripOn = false;
mApplicationSpecifiedCompletionOn = false;
mApplicationSpecifiedCompletions = null;
if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
mIsSettingsSuggestionStripOn = true;
// Make sure that passwords are not displayed in candidate view
if (InputTypeCompatUtils.isPasswordInputType(inputType)
|| InputTypeCompatUtils.isVisiblePasswordInputType(inputType)) {
mIsSettingsSuggestionStripOn = false;
}
if (InputTypeCompatUtils.isEmailVariation(variation)
|| variation == InputType.TYPE_TEXT_VARIATION_PERSON_NAME) {
mShouldInsertMagicSpace = false;
} else {
mShouldInsertMagicSpace = true;
}
if (InputTypeCompatUtils.isEmailVariation(variation)) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_URI) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((inputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mIsSettingsSuggestionStripOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0
&& (inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mIsSettingsSuggestionStripOn = false;
mApplicationSpecifiedCompletionOn = isFullscreenMode();
}
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
mKeyboardSwitcher.onAutoCorrectionStateChanged(false);
mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging);
KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) inputView.closing();
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onFinishInputView(boolean finishingInput) {
super.onFinishInputView(finishingInput);
KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) inputView.setForeground(false);
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestions();
mHandler.cancelUpdateOldSuggestions();
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
mVoiceProxy.showPunctuationHintIfNecessary();
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", lss=" + mLastSelectionStart
+ ", lse=" + mLastSelectionEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart);
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
final boolean selectionChanged = (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart;
final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1;
if (((mComposing.length() > 0 && mHasUncommittedTypedChars)
|| mVoiceProxy.isVoiceInputHighlighted())
&& (selectionChanged || candidatesCleared)) {
if (candidatesCleared) {
// If the composing span has been cleared, save the typed word in the history for
// recorrection before we reset the candidate strip. Then, we'll be able to show
// suggestions for recorrection right away.
mRecorrection.saveRecorrectionSuggestion(mWord, mComposing);
}
mComposing.setLength(0);
mHasUncommittedTypedChars = false;
if (isCursorTouchingWord()) {
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
} else {
setPunctuationSuggestions();
}
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceProxy.setVoiceInputHighlighted(false);
} else if (!mHasUncommittedTypedChars && !mJustAccepted) {
if (TextEntryState.isAcceptedDefault() || TextEntryState.isSpaceAfterPicked()) {
if (TextEntryState.isAcceptedDefault())
TextEntryState.reset();
mJustAddedMagicSpace = false; // The user moved the cursor.
}
}
mJustAccepted = false;
mHandler.postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
mRecorrection.updateRecorrectionSelection(mKeyboardSwitcher,
mCandidateView, candidatesStart, candidatesEnd, newSelStart,
newSelEnd, oldSelStart, mLastSelectionStart,
mLastSelectionEnd, mHasUncommittedTypedChars);
}
public void setLastSelection(int start, int end) {
mLastSelectionStart = start;
mLastSelectionEnd = end;
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the candidates view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
mKeyboardSwitcher.onAutoCorrectionStateChanged(false);
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
mVoiceProxy.hideVoiceWindow(mConfigurationChanging);
mRecorrection.clearWordsInHistory();
super.hideWindow();
}
@Override
public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) {
if (DEBUG) {
Log.i(TAG, "Received completions:");
if (applicationSpecifiedCompletions != null) {
for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]);
}
}
}
if (mApplicationSpecifiedCompletionOn) {
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestions();
return;
}
SuggestedWords.Builder builder = new SuggestedWords.Builder()
.setApplicationSpecifiedCompletions(applicationSpecifiedCompletions)
.setTypedWordValid(true)
.setHasMinimalSuggestion(true);
// When in fullscreen mode, show completions generated by the application
setSuggestions(builder.build());
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
// TODO: Modify this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
final boolean shouldShowCandidates = shown
&& (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true);
if (isExtractViewShown()) {
// No need to have extra space to show the key preview.
mCandidateViewContainer.setMinimumHeight(0);
super.setCandidatesViewShown(shown);
} else {
// We must control the visibility of the suggestion strip in order to avoid clipped
// key previews, even when we don't show the suggestion strip.
mCandidateViewContainer.setVisibility(
shouldShowCandidates ? View.VISIBLE : View.INVISIBLE);
super.setCandidatesViewShown(true);
}
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
final KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView == null)
return;
final int containerHeight = mCandidateViewContainer.getHeight();
int touchY = containerHeight;
// Need to set touchable region only if input view is being shown
if (mKeyboardSwitcher.isInputViewShown()) {
if (mCandidateViewContainer.getVisibility() == View.VISIBLE) {
touchY -= mCandidateStripHeight;
}
final int touchWidth = inputView.getWidth();
final int touchHeight = inputView.getHeight() + containerHeight
// Extend touchable region below the keyboard.
+ EXTENDED_TOUCHABLE_REGION_HEIGHT;
if (DEBUG) {
Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth
+ " height=" + touchHeight);
}
setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight);
}
outInsets.contentTopInsets = touchY;
outInsets.visibleTopInsets = touchY;
}
@Override
public boolean onEvaluateFullscreenMode() {
final Resources res = mResources;
DisplayMetrics dm = res.getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen mode
float dimen = res.getDimension(R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
}
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Enable shift key and DPAD to do selections
if (mKeyboardSwitcher.isInputViewShown()
&& mKeyboardSwitcher.isShiftedOrShiftLocked()) {
KeyEvent newEvent = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null)
ic.sendKeyEvent(newEvent);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
public void commitTyped(InputConnection inputConnection) {
if (mHasUncommittedTypedChars) {
mHasUncommittedTypedChars = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
addToAutoAndUserBigramDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
public boolean getCurrentAutoCapsState() {
InputConnection ic = getCurrentInputConnection();
EditorInfo ei = getCurrentInputEditorInfo();
if (mSettingsValues.mAutoCap && ic != null && ei != null
&& ei.inputType != InputType.TYPE_NULL) {
return ic.getCursorCapsMode(ei.inputType) != 0;
}
return false;
}
private void swapSwapperAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
// It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
}
}
private void maybeDoubleSpace() {
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE
&& mHandler.isAcceptingDoubleSpaces()) {
mHandler.cancelDoubleSpacesTimer();
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
} else {
mHandler.startDoubleSpacesTimer();
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_PERIOD
&& text.charAt(0) == Keyboard.CODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word to the
// user dictionary
mHandler.postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void onSettingsKeyPressed() {
if (!isShowingOptionDialog()) {
if (!mSettingsValues.mEnableShowSubtypeSettings) {
showSubtypeSelectorAndSettings();
} else if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
showOptionsMenu();
} else {
launchSettings();
}
}
}
private void onSettingsKeyLongPressed() {
if (!isShowingOptionDialog()) {
if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
mImm.showInputMethodPicker();
} else {
launchSettings();
}
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
KeyboardSwitcher switcher = mKeyboardSwitcher;
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.CODE_DELETE:
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.CODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
switcher.toggleShift();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
switcher.changeKeyboardMode();
break;
case Keyboard.CODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case Keyboard.CODE_SETTINGS:
onSettingsKeyPressed();
break;
case Keyboard.CODE_SETTINGS_LONGPRESS:
onSettingsKeyLongPressed();
break;
case LatinKeyboard.CODE_NEXT_LANGUAGE:
toggleLanguage(true);
break;
case LatinKeyboard.CODE_PREV_LANGUAGE:
toggleLanguage(false);
break;
case Keyboard.CODE_CAPSLOCK:
switcher.toggleCapsLock();
break;
case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME();
break;
case Keyboard.CODE_TAB:
handleTab();
break;
default:
if (mSettingsValues.isWordSeparator(primaryCode)) {
handleSeparator(primaryCode, x, y);
} else {
handleCharacter(primaryCode, keyCodes, x, y);
}
}
switcher.onKey(primaryCode);
// Reset after any single keystroke
mEnteredText = null;
}
@Override
public void onTextInput(CharSequence text) {
mVoiceProxy.commitVoiceInput();
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
mRecorrection.abortRecorrection(false);
ic.beginBatchEdit();
commitTyped(ic);
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onKey(Keyboard.CODE_DUMMY);
mJustAddedMagicSpace = false;
mEnteredText = text;
}
@Override
public void onCancelInput() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace() {
if (mVoiceProxy.logAndRevertVoiceInput()) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
mVoiceProxy.handleBackspace();
boolean deleteChar = false;
if (mHasUncommittedTypedChars) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mHasUncommittedTypedChars = false;
}
if (1 == length) {
// 1 == length means we are about to erase the last character of the word,
// so we can show bigrams.
mHandler.postUpdateBigramPredictions();
} else {
// length > 1, so we still have letters to deduce a suggestion from.
mHandler.postUpdateSuggestions();
}
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
mHandler.postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.isUndoCommit()) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
}
if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Touch again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
ic.endBatchEdit();
}
private void handleTab() {
final int imeOptions = getCurrentInputEditorInfo().imeOptions;
if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
&& !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
return;
}
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
// True if keyboard is in either chording shift or manual temporary upper case mode.
final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase();
if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
&& !isManualTemporaryUpperCase) {
EditorInfoCompatUtils.performEditorActionNext(ic);
ic.performEditorAction(EditorInfo.IME_ACTION_NEXT);
} else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)
&& isManualTemporaryUpperCase) {
EditorInfoCompatUtils.performEditorActionPrevious(ic);
}
}
private void handleCharacter(int primaryCode, int[] keyCodes, int x, int y) {
mVoiceProxy.handleCharacter();
if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceStripper(primaryCode)) {
removeTrailingSpace();
}
if (mLastSelectionStart == mLastSelectionEnd) {
mRecorrection.abortRecorrection(false);
}
int code = primaryCode;
if (isAlphabet(code) && isSuggestionsRequested() && !isCursorTouchingWord()) {
if (!mHasUncommittedTypedChars) {
mHasUncommittedTypedChars = true;
mComposing.setLength(0);
mRecorrection.saveRecorrectionSuggestion(mWord, mBestWord);
mWord.reset();
clearSuggestions();
}
}
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (switcher.isShiftedOrShiftLocked()) {
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
code = keyCodes[0];
if (switcher.isAlphabetMode() && Character.isLowerCase(code)) {
int upperCaseCode = Character.toUpperCase(code);
if (upperCaseCode != code) {
code = upperCaseCode;
} else {
// Some keys, such as [eszett], have upper case as multi-characters.
String upperCase = new String(new int[] {code}, 0, 1).toUpperCase();
onTextInput(upperCase);
return;
}
}
}
if (mHasUncommittedTypedChars) {
if (mComposing.length() == 0 && switcher.isAlphabetMode()
&& switcher.isShiftedOrShiftLocked()) {
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) code);
mWord.add(code, keyCodes, x, y);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(getCurrentAutoCapsState());
}
ic.setComposingText(mComposing, 1);
}
mHandler.postUpdateSuggestions();
} else {
sendKeyChar((char)code);
}
if (mJustAddedMagicSpace && mSettingsValues.isMagicSpaceSwapper(primaryCode)) {
swapSwapperAndSpace();
} else {
mJustAddedMagicSpace = false;
}
switcher.updateShiftState();
if (LatinIME.PERF_DEBUG) measureCps();
TextEntryState.typedCharacter((char) code, mSettingsValues.isWordSeparator(code), x, y);
}
private void handleSeparator(int primaryCode, int x, int y) {
mVoiceProxy.handleSeparator();
// Should dismiss the "Touch again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
final InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
mRecorrection.abortRecorrection(false);
}
if (mHasUncommittedTypedChars) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
final boolean shouldAutoCorrect =
(mSettingsValues.mAutoCorrectEnabled || mSettingsValues.mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
if (shouldAutoCorrect && primaryCode != Keyboard.CODE_SINGLE_QUOTE) {
pickedDefault = pickDefaultSuggestion(primaryCode);
} else {
commitTyped(ic);
}
}
if (mJustAddedMagicSpace) {
if (mSettingsValues.isMagicSpaceSwapper(primaryCode)) {
sendKeyChar((char)primaryCode);
swapSwapperAndSpace();
} else {
if (mSettingsValues.isMagicSpaceStripper(primaryCode)) removeTrailingSpace();
sendKeyChar((char)primaryCode);
mJustAddedMagicSpace = false;
}
} else {
sendKeyChar((char)primaryCode);
}
if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) {
maybeDoubleSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true, x, y);
if (pickedDefault) {
CharSequence typedWord = mWord.getTypedWord();
TextEntryState.backToAcceptedDefault(typedWord);
if (!TextUtils.isEmpty(typedWord) && !typedWord.equals(mBestWord)) {
InputConnectionCompatUtils.commitCorrection(
ic, mLastSelectionEnd - typedWord.length(), typedWord, mBestWord);
if (mCandidateView != null)
mCandidateView.onAutoCorrectionInverted(mBestWord);
}
}
if (Keyboard.CODE_SPACE == primaryCode) {
if (!isCursorTouchingWord()) {
mHandler.cancelUpdateSuggestions();
mHandler.cancelUpdateOldSuggestions();
mHandler.postUpdateBigramPredictions();
}
} else {
// Set punctuation right away. onUpdateSelection will fire but tests whether it is
// already displayed or not, so it's okay.
setPunctuationSuggestions();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
mVoiceProxy.handleClose();
requestHideSelf(0);
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null)
inputView.closing();
}
public boolean isSuggestionsRequested() {
return mIsSettingsSuggestionStripOn
&& (mCorrectionMode > 0 || isShowingSuggestionsStrip());
}
public boolean isShowingPunctuationList() {
return mSettingsValues.mSuggestPuncList == mCandidateView.getSuggestions();
}
public boolean isShowingSuggestionsStrip() {
return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE)
|| (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE
&& mOrientation == Configuration.ORIENTATION_PORTRAIT);
}
public boolean isCandidateStripVisible() {
if (mCandidateView == null)
return false;
if (mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isRecorrecting())
return true;
if (!isShowingSuggestionsStrip())
return false;
if (mApplicationSpecifiedCompletionOn)
return true;
return isSuggestionsRequested();
}
public void switchToKeyboardView() {
if (DEBUG) {
Log.d(TAG, "Switch to keyboard view.");
}
View v = mKeyboardSwitcher.getInputView();
if (v != null) {
// Confirms that the keyboard view doesn't have parent view.
ViewParent p = v.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup) p).removeView(v);
}
setInputView(v);
}
setCandidatesViewShown(isCandidateStripVisible());
updateInputViewShown();
mHandler.postUpdateSuggestions();
}
public void clearSuggestions() {
setSuggestions(SuggestedWords.EMPTY);
}
public void setSuggestions(SuggestedWords words) {
if (mVoiceProxy.getAndResetIsShowingHint()) {
setCandidatesView(mCandidateViewContainer);
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(words);
if (mCandidateView.isConfigCandidateHighlightFontColorEnabled()) {
mKeyboardSwitcher.onAutoCorrectionStateChanged(
words.hasWordAboveAutoCorrectionScoreThreshold());
}
}
}
public void updateSuggestions() {
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isSuggestionsRequested())
&& !mVoiceProxy.isVoiceInputHighlighted()) {
return;
}
if (!mHasUncommittedTypedChars) {
setPunctuationSuggestions();
return;
}
showSuggestions(mWord);
}
private void showSuggestions(WordComposer word) {
// TODO: May need a better way of retrieving previous word
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
mSettingsValues.mWordSeparators);
SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
mKeyboardSwitcher.getInputView(), word, prevWord);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection();
final CharSequence typedWord = word.getTypedWord();
// Here, we want to promote a whitelisted word if exists.
final boolean typedWordValid = AutoCorrection.isValidWordForAutoCorrection(
mSuggest.getUnigramDictionaries(), typedWord, preferCapitalization());
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isRecorrecting();
// Basically, we update the suggestion strip only when suggestion count > 1. However,
// there is an exception: We update the suggestion strip whenever typed word's length
// is 1 or typed word is found in dictionary, regardless of suggestion count. Actually,
// in most cases, suggestion count is 1 when typed word's length is 1, but we do always
// need to clear the previous state when the user starts typing a word (i.e. typed word's
// length == 1).
if (typedWord != null) {
if (builder.size() > 1 || typedWord.length() == 1 || typedWordValid
|| mCandidateView.isShowingAddToDictionaryHint()) {
builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(
correctionAvailable);
} else {
final SuggestedWords previousSuggestions = mCandidateView.getSuggestions();
if (previousSuggestions == mSettingsValues.mSuggestPuncList)
return;
builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions);
}
}
showSuggestions(builder.build(), typedWord);
}
public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) {
setSuggestions(suggestedWords);
if (suggestedWords.size() > 0) {
if (Utils.shouldBlockedBySafetyNetForAutoCorrection(suggestedWords, mSuggest)) {
mBestWord = typedWord;
} else if (suggestedWords.hasAutoCorrectionWord()) {
mBestWord = suggestedWords.getWord(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible());
}
private boolean pickDefaultSuggestion(int separatorCode) {
// Complete any pending candidate query first
if (mHandler.hasPendingUpdateSuggestions()) {
mHandler.cancelUpdateSuggestions();
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord, separatorCode);
mJustAccepted = true;
pickSuggestion(mBestWord);
// Add the word to the auto dictionary if it's not a known word
addToAutoAndUserBigramDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion,
mSettingsValues.mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0))
|| mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
- final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0);
+ final CharSequence beforeText = ic.getTextBeforeCursor(1, 0);
+ final int toLeft = (ic == null || TextUtils.isEmpty(beforeText))
+ ? 0 : beforeText.charAt(0);
final boolean oldMagicSpace = mJustAddedMagicSpace;
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
* @param suggestion the suggestion picked by the user to be committed to
* the text field
*/
private void pickSuggestion(CharSequence suggestion) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (!switcher.isKeyboardAvailable())
return;
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
mVoiceProxy.rememberReplacedWord(suggestion, mSettingsValues.mWordSeparators);
ic.commitText(suggestion, 1);
}
mRecorrection.saveRecorrectionSuggestion(mWord, suggestion);
mHasUncommittedTypedChars = false;
mCommittedLength = suggestion.length();
}
private static final WordComposer sEmptyWordComposer = new WordComposer();
private void updateBigramPredictions() {
if (mSuggest == null || !isSuggestionsRequested())
return;
if (!mSettingsValues.mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(),
mSettingsValues.mWordSeparators);
SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
mKeyboardSwitcher.getInputView(), sEmptyWordComposer, prevWord);
if (builder.size() > 0) {
// Explicitly supply an empty typed word (the no-second-arg version of
// showSuggestions will retrieve the word near the cursor, we don't want that here)
showSuggestions(builder.build(), "");
} else {
if (!isShowingPunctuationList()) setPunctuationSuggestions();
}
}
public void setPunctuationSuggestions() {
setSuggestions(mSettingsValues.mSuggestPuncList);
setCandidatesViewShown(isCandidateStripVisible());
}
private void addToAutoAndUserBigramDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToOnlyBigramDictionary(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
* @param selectedANotTypedWord true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta,
boolean selectedANotTypedWord) {
if (suggestion == null || suggestion.length() < 1) return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
final boolean selectedATypedWordAndItsInAutoDic =
!selectedANotTypedWord && mAutoDictionary.isValidWord(suggestion);
final boolean isValidWord = AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true);
final boolean needsToAddToAutoDictionary = selectedATypedWordAndItsInAutoDic
|| !isValidWord;
if (needsToAddToAutoDictionary) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
// We don't want to register as bigrams words separated by a separator.
// For example "I will, and you too" : we don't want the pair ("will" "and") to be
// a bigram.
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
mSettingsValues.mWordSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
public boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !mSettingsValues.isWordSeparator(toLeft.charAt(0))
&& !mSettingsValues.isSuggestedPunctuation(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !mSettingsValues.isWordSeparator(toRight.charAt(0))
&& !mSettingsValues.isSuggestedPunctuation(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mHasUncommittedTypedChars && length > 0) {
final InputConnection ic = getCurrentInputConnection();
final CharSequence punctuation = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
final CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (!TextUtils.isEmpty(toTheLeft)
&& mSettingsValues.isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
// Re-insert punctuation only when the deleted character was word separator and the
// composing text wasn't equal to the auto-corrected text.
if (deleteChar
&& !TextUtils.isEmpty(punctuation)
&& mSettingsValues.isWordSeparator(punctuation.charAt(0))
&& !TextUtils.equals(mComposing, toTheLeft)) {
ic.commitText(mComposing, 1);
TextEntryState.acceptedTyped(mComposing);
ic.commitText(punctuation, 1);
TextEntryState.typedCharacter(punctuation.charAt(0), true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// Clear composing text
mComposing.setLength(0);
} else {
mHasUncommittedTypedChars = true;
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
}
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
public boolean isWordSeparator(int code) {
return mSettingsValues.isWordSeparator(code);
}
private void sendMagicSpace() {
sendKeyChar((char)Keyboard.CODE_SPACE);
mJustAddedMagicSpace = true;
mKeyboardSwitcher.updateShiftState();
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
// Notify that language or mode have been changed and toggleLanguage will update KeyboardID
// according to new language or mode.
public void onRefreshKeyboard() {
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(),
mSubtypeSwitcher.isShortcutImeEnabled() && mVoiceProxy.isVoiceButtonEnabled(),
mVoiceProxy.isVoiceButtonOnPrimary());
initSuggest();
loadSettings();
mKeyboardSwitcher.updateShiftState();
}
// "reset" and "next" are used only for USE_SPACEBAR_LANGUAGE_SWITCHER.
private void toggleLanguage(boolean next) {
if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()) {
mSubtypeSwitcher.toggleLanguage(next);
}
// The following is necessary because on API levels < 10, we don't get notified when
// subtype changes.
onRefreshKeyboard();
}
@Override
public void onSwipeDown() {
if (mSettingsValues.mSwipeDownDismissKeyboardEnabled)
handleClose();
}
@Override
public void onPress(int primaryCode, boolean withSliding) {
if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) {
vibrate();
playKeyClick(primaryCode);
}
KeyboardSwitcher switcher = mKeyboardSwitcher;
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) {
switcher.onPressShift(withSliding);
} else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
switcher.onPressSymbol();
} else {
switcher.onOtherKeyPressed();
}
}
@Override
public void onRelease(int primaryCode, boolean withSliding) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
// Reset any drag flags in the keyboard
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) {
switcher.onReleaseShift(withSliding);
} else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
switcher.onReleaseSymbol();
}
}
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
updateRingerMode();
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
}
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (isSoundOn()) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.CODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case Keyboard.CODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case Keyboard.CODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
public void vibrate() {
if (!mSettingsValues.mVibrateOn) {
return;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
public void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
public WordComposer getCurrentWord() {
return mWord;
}
boolean isSoundOn() {
return mSettingsValues.mSoundOn && !mSilentModeOn;
}
private void updateCorrectionMode() {
// TODO: cleanup messy flags
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
final boolean shouldAutoCorrect = (mSettingsValues.mAutoCorrectEnabled
|| mSettingsValues.mQuickFixes) && !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (shouldAutoCorrect && mSettingsValues.mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (shouldAutoCorrect ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
mCorrectionMode = (mSettingsValues.mBigramSuggestionEnabled && shouldAutoCorrect
&& mSettingsValues.mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled() {
if (mSuggest == null) return;
mSuggest.setQuickFixesEnabled(mSettingsValues.mQuickFixes
&& SubtypeSwitcher.getInstance().isSystemLanguageSameAsInputLanguage());
}
private void updateSuggestionVisibility(final SharedPreferences prefs, final Resources res) {
final String suggestionVisiblityStr = prefs.getString(
Settings.PREF_SHOW_SUGGESTIONS_SETTING,
res.getString(R.string.prefs_suggestion_visibility_default_value));
for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) {
if (suggestionVisiblityStr.equals(res.getString(visibility))) {
mSuggestionVisibility = visibility;
break;
}
}
}
protected void launchSettings() {
launchSettings(Settings.class);
}
public void launchDebugSettings() {
launchSettings(DebugSettings.class);
}
protected void launchSettings(Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
// TODO: Should use new string "Select active input modes".
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
mInputMethodId, Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case 1:
launchSettings();
break;
}
}
};
showOptionsMenuInternal(title, items, listener);
}
private void showOptionsMenu() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
getString(R.string.selectInputMethod),
getString(R.string.english_ime_settings),
};
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
mImm.showInputMethodPicker();
break;
case 1:
launchSettings();
break;
}
}
};
showOptionsMenuInternal(title, items, listener);
}
private void showOptionsMenuInternal(CharSequence title, CharSequence[] items,
DialogInterface.OnClickListener listener) {
final IBinder windowToken = mKeyboardSwitcher.getInputView().getWindowToken();
if (windowToken == null) return;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setItems(items, listener);
builder.setTitle(title);
mOptionsDialog = builder.create();
mOptionsDialog.setCanceledOnTouchOutside(true);
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
@Override
protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mComposing=" + mComposing.toString());
p.println(" mIsSuggestionsRequested=" + mIsSettingsSuggestionStripOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mHasUncommittedTypedChars=" + mHasUncommittedTypedChars);
p.println(" mAutoCorrectEnabled=" + mSettingsValues.mAutoCorrectEnabled);
p.println(" mShouldInsertMagicSpace=" + mShouldInsertMagicSpace);
p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSettingsValues.mSoundOn);
p.println(" mVibrateOn=" + mSettingsValues.mVibrateOn);
p.println(" mKeyPreviewPopupOn=" + mSettingsValues.mKeyPreviewPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
}
| true | true | public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion,
mSettingsValues.mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0))
|| mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0);
final boolean oldMagicSpace = mJustAddedMagicSpace;
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
| public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion,
mSettingsValues.mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0))
|| mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
final CharSequence beforeText = ic.getTextBeforeCursor(1, 0);
final int toLeft = (ic == null || TextUtils.isEmpty(beforeText))
? 0 : beforeText.charAt(0);
final boolean oldMagicSpace = mJustAddedMagicSpace;
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
}
if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
|
diff --git a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
index 1b8ed54..d7b7dd2 100644
--- a/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
+++ b/src/com/wolvencraft/prison/mines/cmd/EditCommand.java
@@ -1,316 +1,316 @@
package com.wolvencraft.prison.mines.cmd;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.material.MaterialData;
import com.wolvencraft.prison.PrisonSuite;
import com.wolvencraft.prison.hooks.TimedTask;
import com.wolvencraft.prison.mines.CommandManager;
import com.wolvencraft.prison.mines.PrisonMine;
import com.wolvencraft.prison.mines.mine.Mine;
import com.wolvencraft.prison.mines.settings.Language;
import com.wolvencraft.prison.mines.settings.MineData;
import com.wolvencraft.prison.mines.util.Message;
import com.wolvencraft.prison.mines.util.Util;
import com.wolvencraft.prison.mines.util.data.MineBlock;
public class EditCommand implements BaseCommand {
public boolean run(String[] args) {
if(args.length == 1
&& !args[0].equalsIgnoreCase("none")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
getHelp();
return true;
}
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
}
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1]));
return false;
}
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
List<MineBlock> blocks = curMine.getBlocks();
if(blocks.size() == 0) blocks.add(new MineBlock(new MaterialData(Material.AIR), 1));
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) {
Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1]));
return false;
}
if(block.equals(air.getBlock())) {
Message.sendFormattedError(language.ERROR_FUCKIGNNOOB);
return false;
}
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
}
else percent = percentAvailable;
if(percent <= 0) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if((percentAvailable - percent) < 0) {
Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages");
return false;
}
else percentAvailable -= percent;
air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) blocks.add(new MineBlock(block, percent));
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.round(percent) + " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) {
Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'");
return false;
}
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.equals(air)) {
Message.sendFormattedError("This value is calculated automatically");
return false;
}
double percent;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try {
percent = Double.parseDouble(args[2].replace("%", ""));
}
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.round(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
List<MineBlock> blocks = curMine.getBlocks();
air.setChance(air.getChance() + blockData.getChance());
blocks.remove(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length > 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args.length == 1) {
curMine = PrisonMine.getCurMine();
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
}
else {
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length < 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("toggle")) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else {
try {
int seconds = Util.parseTime(args[1]);
if(seconds == -1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(seconds));
}
catch (NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
}
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
return curMine.saveFile();
}
if(Mine.get(args[1]) == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
if(args[1].equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("You cannot set mine's parent to itself, silly");
return false;
}
if(Mine.get(args[1]).getParent() != null && Mine.get(args[1]).getSuperParent().getId().equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("Infinite loop detected in timers!");
return false;
}
curMine.setParent(args[1]);
- Message.sendFormattedMine("Mine will is now linked to " + ChatColor.GREEN + args[1]);
+ Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
public void getHelp() {
Message.formatHeader(20, "Editing");
Message.formatHelp("edit", "<id>", "Selects a mine to edit its properties");
Message.formatHelp("name", "<name>", "Sets a display name for a mine");
Message.formatHelp("+", "<block> [percentage]", "Adds a block type to the mine");
Message.formatHelp("-", "<block> [percentage]", "Removes the block from the mine");
Message.formatHelp("delete", "[id]", "Deletes all the mine data");
Message.formatHelp("setparent", "<id>", "Links the timers of two mines");
Message.formatHelp("cooldown toggle", "", "Toggles the reset cooldown");
Message.formatHelp("cooldown <time>", "", "Sets the cooldown time");
Message.formatHelp("setwarp", "", "Sets the teleportation point for the mine");
return;
}
public void getHelpLine() { Message.formatHelp("edit", "", "Shows a help page on mine atribute editing", "prison.mine.edit"); }
}
| true | true | public boolean run(String[] args) {
if(args.length == 1
&& !args[0].equalsIgnoreCase("none")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
getHelp();
return true;
}
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
}
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1]));
return false;
}
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
List<MineBlock> blocks = curMine.getBlocks();
if(blocks.size() == 0) blocks.add(new MineBlock(new MaterialData(Material.AIR), 1));
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) {
Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1]));
return false;
}
if(block.equals(air.getBlock())) {
Message.sendFormattedError(language.ERROR_FUCKIGNNOOB);
return false;
}
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
}
else percent = percentAvailable;
if(percent <= 0) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if((percentAvailable - percent) < 0) {
Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages");
return false;
}
else percentAvailable -= percent;
air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) blocks.add(new MineBlock(block, percent));
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.round(percent) + " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) {
Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'");
return false;
}
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.equals(air)) {
Message.sendFormattedError("This value is calculated automatically");
return false;
}
double percent;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try {
percent = Double.parseDouble(args[2].replace("%", ""));
}
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.round(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
List<MineBlock> blocks = curMine.getBlocks();
air.setChance(air.getChance() + blockData.getChance());
blocks.remove(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length > 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args.length == 1) {
curMine = PrisonMine.getCurMine();
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
}
else {
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length < 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("toggle")) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else {
try {
int seconds = Util.parseTime(args[1]);
if(seconds == -1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(seconds));
}
catch (NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
}
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
return curMine.saveFile();
}
if(Mine.get(args[1]) == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
if(args[1].equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("You cannot set mine's parent to itself, silly");
return false;
}
if(Mine.get(args[1]).getParent() != null && Mine.get(args[1]).getSuperParent().getId().equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("Infinite loop detected in timers!");
return false;
}
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine will is now linked to " + ChatColor.GREEN + args[1]);
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
| public boolean run(String[] args) {
if(args.length == 1
&& !args[0].equalsIgnoreCase("none")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
getHelp();
return true;
}
Language language = PrisonMine.getLanguage();
Mine curMine = PrisonMine.getCurMine();
if(curMine == null
&& !args[0].equalsIgnoreCase("edit")
&& !args[0].equalsIgnoreCase("delete")
&& !args[0].equalsIgnoreCase("generator")) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
if(args[0].equalsIgnoreCase("edit")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedSuccess(language.MINE_DESELECTED);
PrisonMine.setCurMine(null);
return true;
}
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME.replace("<ID>", args[1]));
return false;
}
PrisonMine.setCurMine(curMine);
Message.sendFormattedSuccess(language.MINE_SELECTED);
return true;
} else if(args[0].equalsIgnoreCase("add") || args[0].equalsIgnoreCase("+")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
List<MineBlock> blocks = curMine.getBlocks();
if(blocks.size() == 0) blocks.add(new MineBlock(new MaterialData(Material.AIR), 1));
MaterialData block = Util.getBlock(args[1]);
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(block == null) {
Message.sendFormattedError(language.ERROR_NOSUCHBLOCK.replaceAll("<BLOCK>", args[1]));
return false;
}
if(block.equals(air.getBlock())) {
Message.sendFormattedError(language.ERROR_FUCKIGNNOOB);
return false;
}
double percent, percentAvailable = air.getChance();
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try { percent = Double.parseDouble(args[2].replace("%", "")); }
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
}
else percent = percentAvailable;
if(percent <= 0) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if((percentAvailable - percent) < 0) {
Message.sendFormattedError("Invalid percentage. Use /mine info " + curMine.getId() + " to review the percentages");
return false;
}
else percentAvailable -= percent;
air.setChance(percentAvailable);
MineBlock index = curMine.getBlock(block);
if(index == null) blocks.add(new MineBlock(block, percent));
else index.setChance(index.getChance() + percent);
Message.sendFormattedMine(Util.round(percent) + " of " + block.getItemType().toString().toLowerCase().replace("_", " ") + " added to the mine");
Message.sendFormattedMine("Reset the mine for the changes to take effect");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("remove") || args[0].equalsIgnoreCase("-")) {
if(args.length != 2 && args.length != 3) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
MineBlock blockData = curMine.getBlock(Util.getBlock(args[1]));
if(blockData == null) {
Message.sendFormattedError("There is no " + ChatColor.RED + args[1] + ChatColor.WHITE + " in mine '" + curMine.getId() + "'");
return false;
}
MineBlock air = curMine.getBlock(new MaterialData(Material.AIR));
if(blockData.equals(air)) {
Message.sendFormattedError("This value is calculated automatically");
return false;
}
double percent;
if(args.length == 3) {
if(Util.isNumeric(args[2])) percent = Double.parseDouble(args[2]);
else {
Message.debug("Argument is not numeric, attempting to parse");
try {
percent = Double.parseDouble(args[2].replace("%", ""));
}
catch(NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
}
percent = percent / 100;
Message.debug("Chance value is " + percent);
if(percent > blockData.getChance()) percent = blockData.getChance();
air.setChance(air.getChance() + percent);
blockData.setChance(blockData.getChance() - percent);
Message.sendFormattedMine(Util.round(percent) + " of " + args[1] + " was successfully removed from the mine");
}
else {
List<MineBlock> blocks = curMine.getBlocks();
air.setChance(air.getChance() + blockData.getChance());
blocks.remove(blockData);
Message.sendFormattedMine(args[1] + " was successfully removed from the mine");
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("del")) {
if(args.length > 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args.length == 1) {
curMine = PrisonMine.getCurMine();
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENOTSELECTED);
return false;
}
}
else {
curMine = Mine.get(args[1]);
if(curMine == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
}
for(Mine child : curMine.getChildren()) { child.setParent(null); }
for(TimedTask task : PrisonSuite.getLocalTasks()) {
if(task.getName().endsWith(curMine.getId())) task.cancel();
}
PrisonMine.removeMine(curMine);
Message.sendFormattedMine("Mine successfully deleted");
PrisonMine.setCurMine(null);
curMine.deleteFile();
MineData.saveAll();
return true;
} else if(args[0].equalsIgnoreCase("name")) {
if(args.length < 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
String name = args[1];
for(int i = 2; i < args.length; i++) name = name + " " + args[i];
curMine.setName(name);
Message.sendFormattedMine("Mine now has a display name '" + ChatColor.GOLD + name + ChatColor.WHITE + "'");
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("cooldown")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("toggle")) {
if(curMine.getCooldown()) {
curMine.setCooldownEnabled(false);
Message.sendFormattedMine("Reset cooldown " + ChatColor.RED + "disabled");
}
else {
curMine.setCooldownEnabled(true);
Message.sendFormattedMine("Reset cooldown " + ChatColor.GREEN + "enabled");
}
} else {
try {
int seconds = Util.parseTime(args[1]);
if(seconds == -1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setCooldownPeriod(seconds);
Message.sendFormattedMine("Reset cooldown set to " + ChatColor.GREEN + Util.parseSeconds(seconds));
}
catch (NumberFormatException nfe) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
}
}
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setparent") || args[0].equalsIgnoreCase("link")) {
if(args.length != 2) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
if(args[1].equalsIgnoreCase("none")) {
Message.sendFormattedMine("Mine is no longer linked to " + ChatColor.RED + curMine.getParent());
curMine.setParent(null);
return curMine.saveFile();
}
if(Mine.get(args[1]) == null) {
Message.sendFormattedError(language.ERROR_MINENAME);
return false;
}
if(args[1].equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("You cannot set mine's parent to itself, silly");
return false;
}
if(Mine.get(args[1]).getParent() != null && Mine.get(args[1]).getSuperParent().getId().equalsIgnoreCase(curMine.getId())) {
Message.sendFormattedError("Infinite loop detected in timers!");
return false;
}
curMine.setParent(args[1]);
Message.sendFormattedMine("Mine is now linked to " + ChatColor.GREEN + args[1]);
return curMine.saveFile();
} else if(args[0].equalsIgnoreCase("setwarp")) {
if(args.length != 1) {
Message.sendFormattedError(language.ERROR_ARGUMENTS);
return false;
}
curMine.setTpPoint(((Player) CommandManager.getSender()).getLocation());
Message.sendFormattedMine("Mine tp point is set to your current location");
return true;
} else {
Message.sendFormattedError(language.ERROR_COMMAND);
return false;
}
}
|
diff --git a/plugins/org.teiid.designer.webservice/rest_war_resources/webapps/WEB-INF/classes/org/teiid/rest/services/TeiidRSProviderPost.java b/plugins/org.teiid.designer.webservice/rest_war_resources/webapps/WEB-INF/classes/org/teiid/rest/services/TeiidRSProviderPost.java
index 2813f1912..ce95a4048 100644
--- a/plugins/org.teiid.designer.webservice/rest_war_resources/webapps/WEB-INF/classes/org/teiid/rest/services/TeiidRSProviderPost.java
+++ b/plugins/org.teiid.designer.webservice/rest_war_resources/webapps/WEB-INF/classes/org/teiid/rest/services/TeiidRSProviderPost.java
@@ -1,188 +1,187 @@
/*
* JBoss, Home of Professional Open Source.
*
* See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
*
* See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
*/
package org.teiid.rest.services;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLXML;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.xml.ws.WebServiceContext;
import org.teiid.core.types.BlobType;
import org.teiid.core.types.TransformationException;
import org.teiid.core.types.XMLType;
import org.teiid.core.util.ReaderInputStream;
import org.teiid.query.sql.symbol.XMLSerialize;
import org.teiid.query.function.source.XMLSystemFunctions;
import org.teiid.rest.RestPlugin;
public class TeiidRSProviderPost {
protected WebServiceContext webServiceContext;
private static Logger logger = Logger.getLogger("org.teiid.rest"); //$NON-NLS-1$
@javax.annotation.Resource
protected void setWebServiceContext( WebServiceContext wsc ) {
webServiceContext = wsc;
}
public DataSource getDataSource(String jndiName) throws NamingException {
InitialContext ctx;
DataSource ds = null;
ctx = new InitialContext();
ds = (DataSource)ctx.lookup(jndiName); //$NON-NLS-1$
return ds;
}
public InputStream execute( String procedureName,
Map<String, String> parameterMap, String charSet, Properties properties) throws WebApplicationException {
Connection conn = null;
PreparedStatement statement = null;
- ResultSet set = null;
Object result = null;
InputStream resultStream = null;
String responseString = null;
try {
DataSource ds = getDataSource(properties.getProperty("jndiName"));
conn = ds.getConnection();
boolean noParm = false;
if (parameterMap.isEmpty()) {
noParm = true;
}
final String executeStatement = "call " + procedureName + (noParm ? "()" : createParmString(parameterMap)) + ";"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
statement = conn.prepareStatement(executeStatement);
if (!noParm) {
int i = 1;
for (Object value : parameterMap.values()) {
statement.setString(i++, (String)value);
}
}
final boolean hasResultSet = statement.execute();
if (hasResultSet) {
ResultSet rs = statement.getResultSet();
if (rs.next()) {
result = rs.getObject(1);
} else {
logger.log(Level.WARNING, RestPlugin.Util.getString("TeiidRSProvider.8") //$NON-NLS-1$
+ procedureName);
createWebApplicationException(new Exception(RestPlugin.Util.getString("TeiidRSProvider.2")), //$NON-NLS-1$
RestPlugin.Util.getString("TeiidRSProvider.2")); //$NON-NLS-1$
}
- set.close();
+ rs.close();
}
statement.close();
resultStream = handleResult(charSet, result);
} catch (SQLException e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} catch (Exception e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
/*
* In this case, we do not return an exception to the
* customer. We simply log this problem. If we do
* a return from the finally block, we will override the
* return in the try/catch that will either return the
* 'true' error or return a valid result document. Either
* way we do not want to return an exception just because
* closing the connection failed.
*/
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return resultStream;
}
private InputStream handleResult(String charSet, Object result) throws SQLException, UnsupportedEncodingException {
if (result == null) {
return null;
}
if (result instanceof SQLXML) {
if (charSet != null) {
XMLSerialize serialize = new XMLSerialize();
serialize.setTypeString("blob"); //$NON-NLS-1$
serialize.setDeclaration(true);
serialize.setEncoding(charSet);
serialize.setDocument(true);
try {
return ((BlobType)XMLSystemFunctions.serialize(serialize, new XMLType((SQLXML)result))).getBinaryStream();
} catch (TransformationException e) {
throw new SQLException(e);
}
}
return ((SQLXML)result).getBinaryStream();
}
else if (result instanceof Blob) {
return ((Blob)result).getBinaryStream();
}
else if (result instanceof Clob) {
return new ReaderInputStream(((Clob)result).getCharacterStream(), Charset.forName(charSet));
}
return new ByteArrayInputStream(result.toString().getBytes(charSet));
}
protected String createParmString( Map<String, String> parameterMap ) {
StringBuilder sb = new StringBuilder();
sb.append("(?"); //$NON-NLS-1$
for (int i = 1; i < parameterMap.size(); i++) {
sb.append(","); //$NON-NLS-1$
sb.append("?"); //$NON-NLS-1$
}
sb.append(")"); //$NON-NLS-1$
return sb.toString();
}
protected void createWebApplicationException( final Exception e,
final String faultSoapPluginString ) throws WebApplicationException {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
| false | true | public InputStream execute( String procedureName,
Map<String, String> parameterMap, String charSet, Properties properties) throws WebApplicationException {
Connection conn = null;
PreparedStatement statement = null;
ResultSet set = null;
Object result = null;
InputStream resultStream = null;
String responseString = null;
try {
DataSource ds = getDataSource(properties.getProperty("jndiName"));
conn = ds.getConnection();
boolean noParm = false;
if (parameterMap.isEmpty()) {
noParm = true;
}
final String executeStatement = "call " + procedureName + (noParm ? "()" : createParmString(parameterMap)) + ";"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
statement = conn.prepareStatement(executeStatement);
if (!noParm) {
int i = 1;
for (Object value : parameterMap.values()) {
statement.setString(i++, (String)value);
}
}
final boolean hasResultSet = statement.execute();
if (hasResultSet) {
ResultSet rs = statement.getResultSet();
if (rs.next()) {
result = rs.getObject(1);
} else {
logger.log(Level.WARNING, RestPlugin.Util.getString("TeiidRSProvider.8") //$NON-NLS-1$
+ procedureName);
createWebApplicationException(new Exception(RestPlugin.Util.getString("TeiidRSProvider.2")), //$NON-NLS-1$
RestPlugin.Util.getString("TeiidRSProvider.2")); //$NON-NLS-1$
}
set.close();
}
statement.close();
resultStream = handleResult(charSet, result);
} catch (SQLException e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} catch (Exception e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
/*
* In this case, we do not return an exception to the
* customer. We simply log this problem. If we do
* a return from the finally block, we will override the
* return in the try/catch that will either return the
* 'true' error or return a valid result document. Either
* way we do not want to return an exception just because
* closing the connection failed.
*/
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return resultStream;
}
| public InputStream execute( String procedureName,
Map<String, String> parameterMap, String charSet, Properties properties) throws WebApplicationException {
Connection conn = null;
PreparedStatement statement = null;
Object result = null;
InputStream resultStream = null;
String responseString = null;
try {
DataSource ds = getDataSource(properties.getProperty("jndiName"));
conn = ds.getConnection();
boolean noParm = false;
if (parameterMap.isEmpty()) {
noParm = true;
}
final String executeStatement = "call " + procedureName + (noParm ? "()" : createParmString(parameterMap)) + ";"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
statement = conn.prepareStatement(executeStatement);
if (!noParm) {
int i = 1;
for (Object value : parameterMap.values()) {
statement.setString(i++, (String)value);
}
}
final boolean hasResultSet = statement.execute();
if (hasResultSet) {
ResultSet rs = statement.getResultSet();
if (rs.next()) {
result = rs.getObject(1);
} else {
logger.log(Level.WARNING, RestPlugin.Util.getString("TeiidRSProvider.8") //$NON-NLS-1$
+ procedureName);
createWebApplicationException(new Exception(RestPlugin.Util.getString("TeiidRSProvider.2")), //$NON-NLS-1$
RestPlugin.Util.getString("TeiidRSProvider.2")); //$NON-NLS-1$
}
rs.close();
}
statement.close();
resultStream = handleResult(charSet, result);
} catch (SQLException e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} catch (Exception e) {
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
createWebApplicationException(e, e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
/*
* In this case, we do not return an exception to the
* customer. We simply log this problem. If we do
* a return from the finally block, we will override the
* return in the try/catch that will either return the
* 'true' error or return a valid result document. Either
* way we do not want to return an exception just because
* closing the connection failed.
*/
String msg = RestPlugin.Util.getString("TeiidRSProvider.1"); //$NON-NLS-1$
logger.logrb(Level.SEVERE, "TeiidRSProvider", "execute", RestPlugin.PLUGIN_ID, msg, new Throwable(e)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
return resultStream;
}
|
diff --git a/src/main/java/RSLBench/Algorithms/BMS/RSLBenchCommunicationAdapter.java b/src/main/java/RSLBench/Algorithms/BMS/RSLBenchCommunicationAdapter.java
index f8409f0..bdb7a36 100644
--- a/src/main/java/RSLBench/Algorithms/BMS/RSLBenchCommunicationAdapter.java
+++ b/src/main/java/RSLBench/Algorithms/BMS/RSLBenchCommunicationAdapter.java
@@ -1,88 +1,88 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package RSLBench.Algorithms.BMS;
import RSLBench.Constants;
import es.csic.iiia.maxsum.CommunicationAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import rescuecore2.config.Config;
import rescuecore2.misc.Pair;
/**
*
* @author Marc Pujol <[email protected]>
*/
public class RSLBenchCommunicationAdapter implements CommunicationAdapter<NodeID> {
private static final Logger Logger = LogManager.getLogger(RSLBenchCommunicationAdapter.class);
/** Threshold below which messages are considered equal. */
public static final double EPSILON = 1e-5;
/** The damping factor to use when sending messages */
private final double DAMPING_FACTOR;
private ArrayList<BinaryMaxSumMessage> outgoingMessages;
private Map<Pair<NodeID,NodeID>, Double> oldMessages;
private boolean converged;
public RSLBenchCommunicationAdapter(Config config) {
DAMPING_FACTOR = config.getFloatValue(BinaryMaxSum.KEY_MAXSUM_DAMPING);
outgoingMessages = new ArrayList<>();
oldMessages = new HashMap<>();
converged = true;
}
public Collection<BinaryMaxSumMessage> flushMessages() {
Collection<BinaryMaxSumMessage> result = outgoingMessages;
outgoingMessages = new ArrayList<>();
converged = true;
return result;
}
@Override
public void send(double message, NodeID sender, NodeID recipient) {
Logger.trace("Message from {} to {} : {}", new Object[]{sender, recipient, message});
if (Double.isNaN(message)) {
Logger.warn("Factor {} tried to send {} to factor {}!", new Object[]{sender, message, recipient});
throw new RuntimeException("Invalid message sent!");
}
// The algorithm has converged unless there is at least one message
// different from the previous iteration
Pair<NodeID, NodeID> sr = new Pair<>(sender, recipient);
Double oldMessage = oldMessages.get(sr);
- if (oldMessage != null) {
+ if (oldMessage != null && !Double.isInfinite(message)) {
message = oldMessage * DAMPING_FACTOR + message * (1 - DAMPING_FACTOR);
}
if (oldMessage == null || isDifferent(oldMessage, message)) {
converged = false;
}
oldMessages.put(sr, message);
outgoingMessages.add(new BinaryMaxSumMessage(message, sender, recipient));
}
/**
* Returns true if all the messages sent in the current iteration are
* <em>equal</em> to the messages sent in the previous one.
*
* @see #EPSILON
* @return true if the algorithm has converged, or false otherwise.
*/
public boolean isConverged() {
return converged;
}
private boolean isDifferent(double m1, double m2) {
return Math.abs(m1 - m2) > EPSILON;
}
}
| true | true | public void send(double message, NodeID sender, NodeID recipient) {
Logger.trace("Message from {} to {} : {}", new Object[]{sender, recipient, message});
if (Double.isNaN(message)) {
Logger.warn("Factor {} tried to send {} to factor {}!", new Object[]{sender, message, recipient});
throw new RuntimeException("Invalid message sent!");
}
// The algorithm has converged unless there is at least one message
// different from the previous iteration
Pair<NodeID, NodeID> sr = new Pair<>(sender, recipient);
Double oldMessage = oldMessages.get(sr);
if (oldMessage != null) {
message = oldMessage * DAMPING_FACTOR + message * (1 - DAMPING_FACTOR);
}
if (oldMessage == null || isDifferent(oldMessage, message)) {
converged = false;
}
oldMessages.put(sr, message);
outgoingMessages.add(new BinaryMaxSumMessage(message, sender, recipient));
}
| public void send(double message, NodeID sender, NodeID recipient) {
Logger.trace("Message from {} to {} : {}", new Object[]{sender, recipient, message});
if (Double.isNaN(message)) {
Logger.warn("Factor {} tried to send {} to factor {}!", new Object[]{sender, message, recipient});
throw new RuntimeException("Invalid message sent!");
}
// The algorithm has converged unless there is at least one message
// different from the previous iteration
Pair<NodeID, NodeID> sr = new Pair<>(sender, recipient);
Double oldMessage = oldMessages.get(sr);
if (oldMessage != null && !Double.isInfinite(message)) {
message = oldMessage * DAMPING_FACTOR + message * (1 - DAMPING_FACTOR);
}
if (oldMessage == null || isDifferent(oldMessage, message)) {
converged = false;
}
oldMessages.put(sr, message);
outgoingMessages.add(new BinaryMaxSumMessage(message, sender, recipient));
}
|
diff --git a/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfoGroup.java b/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfoGroup.java
index d2083e8..a298b6b 100644
--- a/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfoGroup.java
+++ b/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfoGroup.java
@@ -1,20 +1,20 @@
package edu.wpi.first.wpilibj.templates.debugging;
/**
* This is a group of Debug Info. You can use RobotDebugger.push() to deal with
* it if you find yourself with one.
*/
public class DebugInfoGroup extends DebugOutput {
private DebugInfo[] infos;
public DebugInfoGroup(DebugInfo[] listOfInfo) {
infos = listOfInfo;
}
protected void debug() {
for (int i = 0; i < infos.length; i++) {
- RobotDebugger.push(infos[i]);
+ RobotDebugger.pushInfo(infos[i]);
}
}
}
| true | true | protected void debug() {
for (int i = 0; i < infos.length; i++) {
RobotDebugger.push(infos[i]);
}
}
| protected void debug() {
for (int i = 0; i < infos.length; i++) {
RobotDebugger.pushInfo(infos[i]);
}
}
|
diff --git a/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java b/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
index 6cf619f..9e9964d 100644
--- a/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
+++ b/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
@@ -1,57 +1,58 @@
package com.abudko.reseller.huuto.mvc.item;
import static com.abudko.reseller.huuto.mvc.list.SearchControllerConstants.SEARCH_PARAMS_ATTRIBUTE;
import static com.abudko.reseller.huuto.mvc.list.SearchControllerConstants.SEARCH_RESULTS_ATTRIBUTE;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.abudko.reseller.huuto.mvc.list.SearchController;
import com.abudko.reseller.huuto.order.ItemOrder;
import com.abudko.reseller.huuto.query.html.item.ItemInfo;
import com.abudko.reseller.huuto.query.html.item.ItemResponse;
import com.abudko.reseller.huuto.query.service.item.QueryItemService;
@Controller
@SessionAttributes({ SEARCH_RESULTS_ATTRIBUTE, SEARCH_PARAMS_ATTRIBUTE })
public class QueryItemController {
private Logger log = LoggerFactory.getLogger(getClass());
@Resource
private QueryItemService queryItemService;
@RequestMapping(value = "/item", method = RequestMethod.GET)
- public String extractItem(@RequestParam String url, Model model) {
+ public String extractItem(@RequestParam String url, @RequestParam String brand, @RequestParam String size,
+ @RequestParam String newPrice, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
- //setInfo(response, brand, size, newPrice);
+ setInfo(response, brand, size, newPrice);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
SearchController.setEnumConstantsToRequest(model);
return "order/order";
}
private void setInfo(ItemResponse response, String brand, String size, String newPrice) {
ItemInfo itemInfo = new ItemInfo(brand, size, newPrice);
response.setItemInfo(itemInfo);
}
private ItemOrder createItemOrderFor(ItemResponse response) {
ItemOrder order = new ItemOrder();
order.setItemResponse(response);
return order;
}
}
| false | true | public String extractItem(@RequestParam String url, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
//setInfo(response, brand, size, newPrice);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
SearchController.setEnumConstantsToRequest(model);
return "order/order";
}
| public String extractItem(@RequestParam String url, @RequestParam String brand, @RequestParam String size,
@RequestParam String newPrice, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
setInfo(response, brand, size, newPrice);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
SearchController.setEnumConstantsToRequest(model);
return "order/order";
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java
index cddb00145..9cdf1e6d8 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCat.java
@@ -1,114 +1,116 @@
package org.tmatesoft.svn.core.internal.wc2.ng;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.util.SVNDate;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslator;
import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslatorInputStream;
import org.tmatesoft.svn.core.internal.wc17.SVNStatusEditor17;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext.PristineContentsInfo;
import org.tmatesoft.svn.core.internal.wc17.db.Structure;
import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc2.SvnCat;
import org.tmatesoft.svn.core.wc2.SvnStatus;
import org.tmatesoft.svn.util.SVNLogType;
public class SvnNgCat extends SvnNgOperationRunner<Long, SvnCat> {
@Override
protected Long run(SVNWCContext context) throws SVNException {
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNRevision revision = getOperation().getRevision();
SVNProperties properties;
InputStream source = null;
boolean localModifications = false;
try {
if (revision != SVNRevision.WORKING) {
PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false);
source = info.stream;
properties = context.getPristineProps(getFirstTarget());
} else {
source = SVNFileUtil.openFileForReading(getFirstTarget());
properties = context.getDb().readProperties(getFirstTarget());
SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget());
localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL;
}
if (properties == null) {
properties = new SVNProperties();
}
String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE);
String keywords = properties.getStringValue(SVNProperty.KEYWORDS);
boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null;
long lastModified = 0;
if (localModifications && !special) {
lastModified = getFirstTarget().lastModified();
} else {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime);
lastModified = info.lng(NodeInfo.recordedTime) / 1000;
info.release();
}
Map<?, ?> keywordsMap = null;
if (keywords != null && getOperation().isExpandKeywords()) {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor);
SVNURL url = context.getNodeUrl(getFirstTarget());
String rev = Long.toString(info.lng(NodeInfo.changedRev));
String author = info.get(NodeInfo.changedAuthor);
info.release();
if (localModifications) {
rev = rev + "M";
author = "(local)";
}
String date = SVNDate.formatDate(new Date(lastModified));
keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions());
}
if (keywordsMap != null || eolStyle != null) {
source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()),
false, keywordsMap, true);
}
- try {
- SVNTranslator.copy(source, getOperation().getOutput());
- } catch (IOException e) {
- SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e);
- SVNErrorManager.error(err, SVNLogType.WC);
+ if (source != null && getOperation().getOutput() != null) {
+ try {
+ SVNTranslator.copy(source, getOperation().getOutput());
+ } catch (IOException e) {
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e);
+ SVNErrorManager.error(err, SVNLogType.WC);
+ }
}
} finally {
SVNFileUtil.closeFile(source);
}
return null;
}
}
| true | true | protected Long run(SVNWCContext context) throws SVNException {
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNRevision revision = getOperation().getRevision();
SVNProperties properties;
InputStream source = null;
boolean localModifications = false;
try {
if (revision != SVNRevision.WORKING) {
PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false);
source = info.stream;
properties = context.getPristineProps(getFirstTarget());
} else {
source = SVNFileUtil.openFileForReading(getFirstTarget());
properties = context.getDb().readProperties(getFirstTarget());
SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget());
localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL;
}
if (properties == null) {
properties = new SVNProperties();
}
String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE);
String keywords = properties.getStringValue(SVNProperty.KEYWORDS);
boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null;
long lastModified = 0;
if (localModifications && !special) {
lastModified = getFirstTarget().lastModified();
} else {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime);
lastModified = info.lng(NodeInfo.recordedTime) / 1000;
info.release();
}
Map<?, ?> keywordsMap = null;
if (keywords != null && getOperation().isExpandKeywords()) {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor);
SVNURL url = context.getNodeUrl(getFirstTarget());
String rev = Long.toString(info.lng(NodeInfo.changedRev));
String author = info.get(NodeInfo.changedAuthor);
info.release();
if (localModifications) {
rev = rev + "M";
author = "(local)";
}
String date = SVNDate.formatDate(new Date(lastModified));
keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions());
}
if (keywordsMap != null || eolStyle != null) {
source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()),
false, keywordsMap, true);
}
try {
SVNTranslator.copy(source, getOperation().getOutput());
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e);
SVNErrorManager.error(err, SVNLogType.WC);
}
} finally {
SVNFileUtil.closeFile(source);
}
return null;
}
| protected Long run(SVNWCContext context) throws SVNException {
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_IS_DIRECTORY, "''{0}'' refers to a directory", getFirstTarget().getAbsolutePath());
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNRevision revision = getOperation().getRevision();
SVNProperties properties;
InputStream source = null;
boolean localModifications = false;
try {
if (revision != SVNRevision.WORKING) {
PristineContentsInfo info = context.getPristineContents(getFirstTarget(), true, false);
source = info.stream;
properties = context.getPristineProps(getFirstTarget());
} else {
source = SVNFileUtil.openFileForReading(getFirstTarget());
properties = context.getDb().readProperties(getFirstTarget());
SvnStatus status = SVNStatusEditor17.internalStatus(context, getFirstTarget());
localModifications = status.getTextStatus() != SVNStatusType.STATUS_NORMAL;
}
if (properties == null) {
properties = new SVNProperties();
}
String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE);
String keywords = properties.getStringValue(SVNProperty.KEYWORDS);
boolean special = properties.getStringValue(SVNProperty.SPECIAL) != null;
long lastModified = 0;
if (localModifications && !special) {
lastModified = getFirstTarget().lastModified();
} else {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.recordedTime);
lastModified = info.lng(NodeInfo.recordedTime) / 1000;
info.release();
}
Map<?, ?> keywordsMap = null;
if (keywords != null && getOperation().isExpandKeywords()) {
Structure<NodeInfo> info = context.getDb().readInfo(getFirstTarget(), NodeInfo.changedRev, NodeInfo.changedAuthor);
SVNURL url = context.getNodeUrl(getFirstTarget());
String rev = Long.toString(info.lng(NodeInfo.changedRev));
String author = info.get(NodeInfo.changedAuthor);
info.release();
if (localModifications) {
rev = rev + "M";
author = "(local)";
}
String date = SVNDate.formatDate(new Date(lastModified));
keywordsMap = SVNTranslator.computeKeywords(keywords, url.toString(), author, date, rev, getOperation().getOptions());
}
if (keywordsMap != null || eolStyle != null) {
source = new SVNTranslatorInputStream(source, SVNTranslator.getEOL(eolStyle, getOperation().getOptions()),
false, keywordsMap, true);
}
if (source != null && getOperation().getOutput() != null) {
try {
SVNTranslator.copy(source, getOperation().getOutput());
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
} finally {
SVNFileUtil.closeFile(source);
}
return null;
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/nio/ssl/BasicSSLContextFactory.java b/hazelcast/src/main/java/com/hazelcast/nio/ssl/BasicSSLContextFactory.java
index f617b17b62..ba51ace49b 100644
--- a/hazelcast/src/main/java/com/hazelcast/nio/ssl/BasicSSLContextFactory.java
+++ b/hazelcast/src/main/java/com/hazelcast/nio/ssl/BasicSSLContextFactory.java
@@ -1,97 +1,97 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.nio.ssl;
import com.hazelcast.nio.IOUtil;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Properties;
public class BasicSSLContextFactory implements SSLContextFactory {
private static final String JAVA_NET_SSL_PREFIX = "javax.net.ssl.";
private SSLContext sslContext;
public BasicSSLContextFactory() {
}
public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
if (keyStore == null || keyStorePassword == null) {
throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
}
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
- String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", "SunX509");
- String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", "SunX509");
+ String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
+ String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm",TrustManagerFactory.getDefaultAlgorithm());
String protocol = properties.getProperty("protocol", "TLS");
final char[] keyStorePassPhrase = keyStorePassword.toCharArray();
loadKeyStore(ks, keyStorePassPhrase, keyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
kmf.init(ks, keyStorePassPhrase);
loadKeyStore(ts, trustStorePassword.toCharArray(), trustStore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ts);
sslContext = SSLContext.getInstance(protocol);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
private void loadKeyStore(KeyStore ks, char[] passPhrase, String keyStoreFile) throws IOException, NoSuchAlgorithmException, CertificateException {
final InputStream in = new FileInputStream(keyStoreFile);
try {
ks.load(in, passPhrase);
} finally {
IOUtil.closeResource(in);
}
}
private static String getProperty(Properties properties, String property) {
String value = properties.getProperty(property);
if (value == null) {
value = properties.getProperty(JAVA_NET_SSL_PREFIX + property);
}
if (value == null) {
value = System.getProperty(JAVA_NET_SSL_PREFIX + property);
}
return value;
}
private static String getProperty(Properties properties, String property, String defaultValue) {
String value = getProperty(properties, property);
return value != null ? value : defaultValue;
}
public SSLContext getSSLContext() {
return sslContext;
}
}
| true | true | public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
if (keyStore == null || keyStorePassword == null) {
throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
}
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", "SunX509");
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", "SunX509");
String protocol = properties.getProperty("protocol", "TLS");
final char[] keyStorePassPhrase = keyStorePassword.toCharArray();
loadKeyStore(ks, keyStorePassPhrase, keyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
kmf.init(ks, keyStorePassPhrase);
loadKeyStore(ts, trustStorePassword.toCharArray(), trustStore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ts);
sslContext = SSLContext.getInstance(protocol);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
| public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
if (keyStore == null || keyStorePassword == null) {
throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
}
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm",TrustManagerFactory.getDefaultAlgorithm());
String protocol = properties.getProperty("protocol", "TLS");
final char[] keyStorePassPhrase = keyStorePassword.toCharArray();
loadKeyStore(ks, keyStorePassPhrase, keyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
kmf.init(ks, keyStorePassPhrase);
loadKeyStore(ts, trustStorePassword.toCharArray(), trustStore);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ts);
sslContext = SSLContext.getInstance(protocol);
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.