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/com.piece_framework.makegood.aspect.org.eclipse.php.core/src/com/piece_framework/makegood/aspect/org/eclipse/php/core/MakeGoodGoalEvaluatorFactory.java b/com.piece_framework.makegood.aspect.org.eclipse.php.core/src/com/piece_framework/makegood/aspect/org/eclipse/php/core/MakeGoodGoalEvaluatorFactory.java
index 1ed16c53..bfecae78 100644
--- a/com.piece_framework.makegood.aspect.org.eclipse.php.core/src/com/piece_framework/makegood/aspect/org/eclipse/php/core/MakeGoodGoalEvaluatorFactory.java
+++ b/com.piece_framework.makegood.aspect.org.eclipse.php.core/src/com/piece_framework/makegood/aspect/org/eclipse/php/core/MakeGoodGoalEvaluatorFactory.java
@@ -1,25 +1,24 @@
/**
* Copyright (c) 2010 MATSUFUJI Hideharu <[email protected]>,
* All rights reserved.
*
* This file is part of MakeGood.
*
* 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 com.piece_framework.makegood.aspect.org.eclipse.php.core;
import org.eclipse.dltk.ti.IGoalEvaluatorFactory;
import org.eclipse.dltk.ti.goals.GoalEvaluator;
import org.eclipse.dltk.ti.goals.IGoal;
public class MakeGoodGoalEvaluatorFactory implements IGoalEvaluatorFactory {
@Override
public GoalEvaluator createEvaluator(IGoal goal) {
- FragmentWeavingProcess process = new FragmentWeavingProcess();
- process.process();
+ new FragmentWeavingProcess().earlyStartup();
return null;
}
}
| true | true | public GoalEvaluator createEvaluator(IGoal goal) {
FragmentWeavingProcess process = new FragmentWeavingProcess();
process.process();
return null;
}
| public GoalEvaluator createEvaluator(IGoal goal) {
new FragmentWeavingProcess().earlyStartup();
return null;
}
|
diff --git a/src/com/github/kenji0717/a3cs/CarBattleImpl.java b/src/com/github/kenji0717/a3cs/CarBattleImpl.java
index 6689ac5..6ab9c0b 100644
--- a/src/com/github/kenji0717/a3cs/CarBattleImpl.java
+++ b/src/com/github/kenji0717/a3cs/CarBattleImpl.java
@@ -1,133 +1,138 @@
package com.github.kenji0717.a3cs;
import java.awt.BorderLayout;
import jp.sourceforge.acerola3d.a3.*;
import javax.swing.*;
import javax.vecmath.Vector3d;
import com.bulletphysics.linearmath.Transform;
class CarBattleImpl implements Runnable, CollisionListener {
PhysicalWorld pw;
String carClass1;
String carClass2;
CarBase car1;
CarBase car2;
JFrame f;
A3Canvas mainCanvas;
A3SubCanvas car1Canvas;
A3SubCanvas car2Canvas;
CarBattleImpl(String args[]) {
- carClass1 = args[0];
- carClass2 = args[1];
+ if (args.length==2) {
+ carClass1 = args[0];
+ carClass2 = args[1];
+ } else {
+ carClass1 = "test.TestCar02";
+ carClass2 = "test.TestCar02";
+ }
pw = new PhysicalWorld();
pw.addCollisionListener(this);
f = new JFrame("CarBattle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
HBox baseBox = new HBox();
f.add(baseBox,BorderLayout.CENTER);
mainCanvas = A3Canvas.createA3Canvas(400,400);
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
pw.setMainCanvas(mainCanvas);
baseBox.myAdd(mainCanvas,1);
VBox subBox = new VBox();
baseBox.myAdd(subBox,0);
car1Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car1Canvas);
subBox.myAdd(car1Canvas,1);
car2Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car2Canvas);
subBox.myAdd(car2Canvas,1);
f.pack();
f.setVisible(true);
MyGround2 g = new MyGround2(pw);
pw.add(g);
//MyGround g = new MyGround(pw);
//pw.add(g);
initCars();
Thread t = new Thread(this);
t.start();
}
void initCars() {
try {
ClassLoader cl = this.getClass().getClassLoader();
Class<?> theClass = cl.loadClass(carClass1);
Class<? extends CarBase> tClass = theClass.asSubclass(CarBase.class);
car1 = tClass.newInstance();
theClass = cl.loadClass(carClass2);
tClass = theClass.asSubclass(CarBase.class);
car2 = tClass.newInstance();
} catch(Exception e) {
System.out.println("Class Load Error!!!");
}
car1.init(new Vector3d( 1,2,-10),new Vector3d(),"x-res:///res/stk_tux.a3",pw);
car2.init(new Vector3d(-1,2,10),new Vector3d(0,3.14,0),"x-res:///res/stk_tux.a3",pw);
pw.add(car1.car);
pw.add(car2.car);
Vector3d lookAt = new Vector3d(0.0,0.0,6.0);
Vector3d camera = new Vector3d(0.0,3.0,-6.0);
Vector3d up = new Vector3d(0.0,1.0,0.0);
car1Canvas.setAvatar(car1.car.a3);
car1Canvas.setNavigationMode(A3CanvasInterface.NaviMode.CHASE,lookAt,camera,up,10.0);
car2Canvas.setAvatar(car2.car.a3);
car2Canvas.setNavigationMode(A3CanvasInterface.NaviMode.CHASE,lookAt,camera,up,10.0);
}
public void run() {
while (true) {
car1.exec();
car2.exec();
try{Thread.sleep(33);}catch(Exception e){;}
}
}
@Override
public void collided(A3CollisionObject a, A3CollisionObject b) {
if ((a instanceof MyBullet)||(b instanceof MyBullet)) {
MyBullet bullet = null;
A3CollisionObject other = null;
if (a instanceof MyBullet) {
bullet = (MyBullet)a;
other = b;
} else {
bullet = (MyBullet)b;
other = a;
}
if (other instanceof MyBullet) {
pw.del(other);
pw.del(bullet);
} else if (other instanceof MyCar) {
((MyCar)other).carBase.hit();
pw.del(bullet);
} else if (other instanceof MyGround2){
//なぜか、当ってないと思うのに地面と衝突していると判定される。
//pw.del(bullet);
}
/*
System.out.println("gaha bullet:"+bullet.a3.getUserData()+" other:"+other.a3.getUserData());
Transform t = new Transform();
bullet.body.getWorldTransform(t);
System.out.println("gaha loc:"+t.origin);
*/
}
//System.out.println("gaha a:"+a.a3.getUserData()+" b:"+b.a3.getUserData());
}
}
| true | true | CarBattleImpl(String args[]) {
carClass1 = args[0];
carClass2 = args[1];
pw = new PhysicalWorld();
pw.addCollisionListener(this);
f = new JFrame("CarBattle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
HBox baseBox = new HBox();
f.add(baseBox,BorderLayout.CENTER);
mainCanvas = A3Canvas.createA3Canvas(400,400);
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
pw.setMainCanvas(mainCanvas);
baseBox.myAdd(mainCanvas,1);
VBox subBox = new VBox();
baseBox.myAdd(subBox,0);
car1Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car1Canvas);
subBox.myAdd(car1Canvas,1);
car2Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car2Canvas);
subBox.myAdd(car2Canvas,1);
f.pack();
f.setVisible(true);
MyGround2 g = new MyGround2(pw);
pw.add(g);
//MyGround g = new MyGround(pw);
//pw.add(g);
initCars();
Thread t = new Thread(this);
t.start();
}
| CarBattleImpl(String args[]) {
if (args.length==2) {
carClass1 = args[0];
carClass2 = args[1];
} else {
carClass1 = "test.TestCar02";
carClass2 = "test.TestCar02";
}
pw = new PhysicalWorld();
pw.addCollisionListener(this);
f = new JFrame("CarBattle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
HBox baseBox = new HBox();
f.add(baseBox,BorderLayout.CENTER);
mainCanvas = A3Canvas.createA3Canvas(400,400);
mainCanvas.setCameraLocImmediately(0.0,150.0,0.0);
mainCanvas.setCameraLookAtPointImmediately(-50.0,0.0,1.0);
mainCanvas.setNavigationMode(A3CanvasInterface.NaviMode.SIMPLE,150.0);
pw.setMainCanvas(mainCanvas);
baseBox.myAdd(mainCanvas,1);
VBox subBox = new VBox();
baseBox.myAdd(subBox,0);
car1Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car1Canvas);
subBox.myAdd(car1Canvas,1);
car2Canvas = A3SubCanvas.createA3SubCanvas(200,200);
pw.addSubCanvas(car2Canvas);
subBox.myAdd(car2Canvas,1);
f.pack();
f.setVisible(true);
MyGround2 g = new MyGround2(pw);
pw.add(g);
//MyGround g = new MyGround(pw);
//pw.add(g);
initCars();
Thread t = new Thread(this);
t.start();
}
|
diff --git a/src/test/java/com/example/helloworld/HelloWorldTest.java b/src/test/java/com/example/helloworld/HelloWorldTest.java
index 50a97c3..f7016bf 100644
--- a/src/test/java/com/example/helloworld/HelloWorldTest.java
+++ b/src/test/java/com/example/helloworld/HelloWorldTest.java
@@ -1,15 +1,15 @@
package com.example.helloworld;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class HelloWorldTest {
@Test
public void greetResultsInHello() {
World world = new World();
- assertEquals("Hello world", world.greet());
+ assertEquals("Hello world!", world.greet());
}
}
| true | true | public void greetResultsInHello() {
World world = new World();
assertEquals("Hello world", world.greet());
}
| public void greetResultsInHello() {
World world = new World();
assertEquals("Hello world!", world.greet());
}
|
diff --git a/benchmark/src/main/java/info/gehrels/diplomarbeit/neo4j/Neo4jStronglyConnectedComponents.java b/benchmark/src/main/java/info/gehrels/diplomarbeit/neo4j/Neo4jStronglyConnectedComponents.java
index 2c8fc92..679662f 100644
--- a/benchmark/src/main/java/info/gehrels/diplomarbeit/neo4j/Neo4jStronglyConnectedComponents.java
+++ b/benchmark/src/main/java/info/gehrels/diplomarbeit/neo4j/Neo4jStronglyConnectedComponents.java
@@ -1,94 +1,96 @@
package info.gehrels.diplomarbeit.neo4j;
import com.google.common.base.Stopwatch;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.tooling.GlobalGraphOperations;
import java.util.Iterator;
public class Neo4jStronglyConnectedComponents extends AbstractStronglyConnectedComponentsCalculator<GraphDatabaseService, Node> {
public static void main(String... args) throws Exception {
Stopwatch stopwatch = new Stopwatch().start();
new Neo4jStronglyConnectedComponents(args[0]).calculateStronglyConnectedComponents();
stopwatch.stop();
System.out.println(stopwatch);
}
public Neo4jStronglyConnectedComponents(String dbPath) {
super(Neo4jHelper.createNeo4jDatabase(dbPath));
}
@Override
protected Iterable<Node> getAllNodes() {
final Iterator<Node> iterator = GlobalGraphOperations.at(graphDB).getAllNodes().iterator();
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
public Node next;
@Override
public boolean hasNext() {
ensureNextIsFetched();
return next != null;
}
private void ensureNextIsFetched() {
if (next == null && iterator.hasNext()) {
next = iterator.next();
}
- if (next.getId() == 0) {
+ if (next != null && next.getId() == 0) {
next = null;
ensureNextIsFetched();
}
}
@Override
public Node next() {
ensureNextIsFetched();
- return next;
+ Node nodeToReturn = next;
+ next = null;
+ return nodeToReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
protected long getNodeName(Node endNode) {
return (Long) endNode.getProperty(Neo4jImporter.NAME_KEY);
}
protected Iterable<Node> getOutgoingIncidentNodes(Node node) {
final Iterator<Relationship> relationships = node.getRelationships(Direction.OUTGOING).iterator();
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
@Override
public boolean hasNext() {
return relationships.hasNext();
}
@Override
public Node next() {
return relationships.next().getEndNode();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
| false | true | protected Iterable<Node> getAllNodes() {
final Iterator<Node> iterator = GlobalGraphOperations.at(graphDB).getAllNodes().iterator();
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
public Node next;
@Override
public boolean hasNext() {
ensureNextIsFetched();
return next != null;
}
private void ensureNextIsFetched() {
if (next == null && iterator.hasNext()) {
next = iterator.next();
}
if (next.getId() == 0) {
next = null;
ensureNextIsFetched();
}
}
@Override
public Node next() {
ensureNextIsFetched();
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
| protected Iterable<Node> getAllNodes() {
final Iterator<Node> iterator = GlobalGraphOperations.at(graphDB).getAllNodes().iterator();
return new Iterable<Node>() {
@Override
public Iterator<Node> iterator() {
return new Iterator<Node>() {
public Node next;
@Override
public boolean hasNext() {
ensureNextIsFetched();
return next != null;
}
private void ensureNextIsFetched() {
if (next == null && iterator.hasNext()) {
next = iterator.next();
}
if (next != null && next.getId() == 0) {
next = null;
ensureNextIsFetched();
}
}
@Override
public Node next() {
ensureNextIsFetched();
Node nodeToReturn = next;
next = null;
return nodeToReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
|
diff --git a/maven-project-builder/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java b/maven-project-builder/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java
index 248cf9f3e..192f32159 100644
--- a/maven-project-builder/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java
+++ b/maven-project-builder/src/main/java/org/apache/maven/project/builder/ArtifactModelContainerFactory.java
@@ -1,229 +1,229 @@
package org.apache.maven.project.builder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.shared.model.ModelContainer;
import org.apache.maven.shared.model.ModelContainerAction;
import org.apache.maven.shared.model.ModelContainerFactory;
import org.apache.maven.shared.model.ModelProperty;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public final class ArtifactModelContainerFactory
implements ModelContainerFactory
{
private static final Collection<String> uris = Collections.unmodifiableList( Arrays.asList(
ProjectUri.DependencyManagement.Dependencies.Dependency.xUri, ProjectUri.Dependencies.Dependency.xUri,
ProjectUri.Reporting.Plugins.Plugin.xUri,
ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri,
ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.xUri,
ProjectUri.Build.Plugins.Plugin.xUri, ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.xUri,
ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.Exclusions.Exclusion.xUri,
ProjectUri.Build.Extensions.Extension.xUri
) );
public Collection<String> getUris()
{
return uris;
}
public ModelContainer create( List<ModelProperty> modelProperties )
{
if ( modelProperties == null || modelProperties.size() == 0 )
{
throw new IllegalArgumentException( "modelProperties: null or empty" );
}
return new ArtifactModelContainer( modelProperties );
}
private static class ArtifactModelContainer
implements ModelContainer
{
private String groupId;
private String artifactId;
private String version;
private String type;
private String scope;
private String classifier;
private List<ModelProperty> properties;
private static String findBaseUriFrom( List<ModelProperty> modelProperties )
{
String baseUri = null;
for ( ModelProperty mp : modelProperties )
{
if ( baseUri == null || mp.getUri().length() < baseUri.length() )
{
baseUri = mp.getUri();
}
}
return baseUri;
}
private ArtifactModelContainer( List<ModelProperty> properties )
{
this.properties = new ArrayList<ModelProperty>( properties );
this.properties = Collections.unmodifiableList( this.properties );
String uri = findBaseUriFrom( this.properties );
for ( ModelProperty mp : this.properties )
{
if ( version == null && mp.getUri().equals( uri + "/version" ) )
{
this.version = mp.getResolvedValue();
}
else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) )
{
this.artifactId = mp.getResolvedValue();
}
else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) )
{
this.groupId = mp.getResolvedValue();
}
else if ( scope == null && mp.getUri().equals( uri + "/scope" ) )
{
this.scope = mp.getResolvedValue();
}
else if ( classifier == null && mp.getUri().equals( uri + "/classifier" ) )
{
this.classifier = mp.getResolvedValue();
}
else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type )
|| mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type))
{
this.type = mp.getResolvedValue();
}
}
if ( groupId == null )
{
- groupId = "org.apache.maven.plugins";
- /* FIXME: This was meant to fix MNG-3863 but it's been reported to break Nexus/Mercury build so needs review
if ( ProjectUri.Build.Plugins.Plugin.xUri.equals( uri )
+ || ProjectUri.Profiles.Profile.Build.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri.equals( uri )
- || ProjectUri.Reporting.Plugins.Plugin.xUri.equals( uri ) )
+ || ProjectUri.Profiles.Profile.Build.PluginManagement.Plugins.Plugin.xUri.equals( uri )
+ || ProjectUri.Reporting.Plugins.Plugin.xUri.equals( uri )
+ || ProjectUri.Profiles.Profile.Reporting.Plugins.Plugin.xUri.equals( uri ))
{
groupId = "org.apache.maven.plugins";
}
else
{
throw new IllegalArgumentException( "Properties do not contain group id. Artifact ID = "
+ artifactId + ", Version = " + version );
}
- */
}
if ( artifactId == null )
{
StringBuffer sb = new StringBuffer();
for ( ModelProperty mp : properties )
{
sb.append( mp ).append( "\r\n" );
}
throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId +
", Version = " + version + ", Base = " + uri + ":\r\n" + sb );
}
if ( version == null )
{
version = "";
}
if ( type == null )
{
type = "jar";
}
if ( classifier == null )
{
classifier = "";
}
if ( scope == null || scope.equals("provided"))
{
scope = "compile";
}
}
public ModelContainerAction containerAction( ModelContainer modelContainer )
{
if ( modelContainer == null )
{
throw new IllegalArgumentException( "modelContainer: null" );
}
if ( !( modelContainer instanceof ArtifactModelContainer ) )
{
throw new IllegalArgumentException( "modelContainer: wrong type" );
}
ArtifactModelContainer c = (ArtifactModelContainer) modelContainer;
if ( c.groupId.equals( groupId ) && c.artifactId.equals( artifactId ) && c.type.equals( type )
&& c.classifier.equals( classifier ))
{
if ( c.version.equals( version ) )
{
return ModelContainerAction.JOIN;
}
else
{
return ModelContainerAction.DELETE;
}
}
return ModelContainerAction.NOP;
}
public ModelContainer createNewInstance( List<ModelProperty> modelProperties )
{
return new ArtifactModelContainer( modelProperties );
}
public List<ModelProperty> getProperties()
{
return properties;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append( "Group ID = " ).append( groupId ).append( ", Artifact ID = " ).append( artifactId )
.append( ", Version" ).append( version ).append( "\r\n" );
for ( ModelProperty mp : properties )
{
sb.append( mp ).append( "\r\n" );
}
return sb.toString();
}
}
}
| false | true | private ArtifactModelContainer( List<ModelProperty> properties )
{
this.properties = new ArrayList<ModelProperty>( properties );
this.properties = Collections.unmodifiableList( this.properties );
String uri = findBaseUriFrom( this.properties );
for ( ModelProperty mp : this.properties )
{
if ( version == null && mp.getUri().equals( uri + "/version" ) )
{
this.version = mp.getResolvedValue();
}
else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) )
{
this.artifactId = mp.getResolvedValue();
}
else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) )
{
this.groupId = mp.getResolvedValue();
}
else if ( scope == null && mp.getUri().equals( uri + "/scope" ) )
{
this.scope = mp.getResolvedValue();
}
else if ( classifier == null && mp.getUri().equals( uri + "/classifier" ) )
{
this.classifier = mp.getResolvedValue();
}
else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type )
|| mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type))
{
this.type = mp.getResolvedValue();
}
}
if ( groupId == null )
{
groupId = "org.apache.maven.plugins";
/* FIXME: This was meant to fix MNG-3863 but it's been reported to break Nexus/Mercury build so needs review
if ( ProjectUri.Build.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Reporting.Plugins.Plugin.xUri.equals( uri ) )
{
groupId = "org.apache.maven.plugins";
}
else
{
throw new IllegalArgumentException( "Properties do not contain group id. Artifact ID = "
+ artifactId + ", Version = " + version );
}
*/
}
if ( artifactId == null )
{
StringBuffer sb = new StringBuffer();
for ( ModelProperty mp : properties )
{
sb.append( mp ).append( "\r\n" );
}
throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId +
", Version = " + version + ", Base = " + uri + ":\r\n" + sb );
}
if ( version == null )
{
version = "";
}
if ( type == null )
{
type = "jar";
}
if ( classifier == null )
{
classifier = "";
}
if ( scope == null || scope.equals("provided"))
{
scope = "compile";
}
}
| private ArtifactModelContainer( List<ModelProperty> properties )
{
this.properties = new ArrayList<ModelProperty>( properties );
this.properties = Collections.unmodifiableList( this.properties );
String uri = findBaseUriFrom( this.properties );
for ( ModelProperty mp : this.properties )
{
if ( version == null && mp.getUri().equals( uri + "/version" ) )
{
this.version = mp.getResolvedValue();
}
else if ( artifactId == null && mp.getUri().equals( uri + "/artifactId" ) )
{
this.artifactId = mp.getResolvedValue();
}
else if ( groupId == null && mp.getUri().equals( uri + "/groupId" ) )
{
this.groupId = mp.getResolvedValue();
}
else if ( scope == null && mp.getUri().equals( uri + "/scope" ) )
{
this.scope = mp.getResolvedValue();
}
else if ( classifier == null && mp.getUri().equals( uri + "/classifier" ) )
{
this.classifier = mp.getResolvedValue();
}
else if ( type == null && mp.getUri().equals( ProjectUri.Dependencies.Dependency.type )
|| mp.getUri().equals(ProjectUri.DependencyManagement.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.PluginManagement.Plugins.Plugin.Dependencies.Dependency.type)
|| mp.getUri().equals(ProjectUri.Build.Plugins.Plugin.Dependencies.Dependency.type))
{
this.type = mp.getResolvedValue();
}
}
if ( groupId == null )
{
if ( ProjectUri.Build.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Profiles.Profile.Build.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Build.PluginManagement.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Profiles.Profile.Build.PluginManagement.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Reporting.Plugins.Plugin.xUri.equals( uri )
|| ProjectUri.Profiles.Profile.Reporting.Plugins.Plugin.xUri.equals( uri ))
{
groupId = "org.apache.maven.plugins";
}
else
{
throw new IllegalArgumentException( "Properties do not contain group id. Artifact ID = "
+ artifactId + ", Version = " + version );
}
}
if ( artifactId == null )
{
StringBuffer sb = new StringBuffer();
for ( ModelProperty mp : properties )
{
sb.append( mp ).append( "\r\n" );
}
throw new IllegalArgumentException( "Properties does not contain artifact id. Group ID = " + groupId +
", Version = " + version + ", Base = " + uri + ":\r\n" + sb );
}
if ( version == null )
{
version = "";
}
if ( type == null )
{
type = "jar";
}
if ( classifier == null )
{
classifier = "";
}
if ( scope == null || scope.equals("provided"))
{
scope = "compile";
}
}
|
diff --git a/src_lib/yang/graphics/skeletons/defaults/JointGridCreator.java b/src_lib/yang/graphics/skeletons/defaults/JointGridCreator.java
index 1e0b2ee5..a992be2d 100644
--- a/src_lib/yang/graphics/skeletons/defaults/JointGridCreator.java
+++ b/src_lib/yang/graphics/skeletons/defaults/JointGridCreator.java
@@ -1,175 +1,175 @@
package yang.graphics.skeletons.defaults;
import yang.graphics.buffers.IndexedVertexBuffer;
import yang.graphics.defaults.DefaultGraphics;
import yang.graphics.defaults.geometrycreators.grids.GridCreator;
import yang.graphics.model.FloatColor;
import yang.graphics.textures.TextureCoordinatesQuad;
import yang.math.objects.YangMatrix;
import yang.physics.massaggregation.MassAggregation;
import yang.physics.massaggregation.constraints.ColliderConstraint;
import yang.physics.massaggregation.elements.Joint;
import yang.physics.massaggregation.elements.JointConnection;
public class JointGridCreator {
public float mJointMass = 1.5f;
public MassAggregation mMassAggregation;
public String mJointNamePrefix = "grid_";
public String mBoneNamePrefix = "grid_";
public Joint[][] mJoints;
public float mStrength = 40;
public float mFriction = 0.98f;
public float mJointRadius = 0.1f;
//Drawing
public GridCreator<?> mGridDrawer;
private int mColCount,mRowCount;
private float mRatio;
public MassAggregation create(int countX,int countY,YangMatrix transform) {
if(transform==null)
transform = YangMatrix.IDENTITY;
mColCount = countX;
mRowCount = countY;
mJoints = new Joint[countY][countX];
if(countX<2 || countY<2)
throw new RuntimeException("countX and countY must be larger or equal 2.");
if(mMassAggregation==null) {
mMassAggregation = new MassAggregation();
mMassAggregation.mLowerLimit = -128;
}
- mRatio = (float)countX/countY;
+ mRatio = (float)(countX-1)/(countY-1);
for(int j=0;j<countY;j++) {
float y = (float)j/(countY-1);
Joint prevJoint = null;
for(int i=0;i<countX;i++) {
Joint newJoint = new Joint(mJointNamePrefix+j+"-"+i);
float x = (float)i/(countX-1) * mRatio;
transform.apply3D(x,y,0, newJoint);
newJoint.setInitialValues();
mJoints[j][i] = newJoint;
newJoint.mRadius = mJointRadius;
mMassAggregation.addJoint(newJoint);
JointConnection boneX = null;
JointConnection boneY = null;
if(i>0)
boneX = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+j+"-"+(i-1)+"_"+j+"-"+i, prevJoint,newJoint), mStrength);
if(j>0)
boneY = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+i, mJoints[j-1][i],newJoint), mStrength);
if(i>0 && j>0) {
// GridConstraint gridConstraint = new GridConstraint(boneX,boneY);
// mMassAggregation.addConstraint(gridConstraint);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+(i-1)+"_"+j+"-"+i, mJoints[j-1][i-1],newJoint), mStrength);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+(i-1), mJoints[j-1][i],mJoints[j][i-1]), mStrength);
}
prevJoint = newJoint;
newJoint.mFriction = mFriction;
}
}
return mMassAggregation;
}
public Joint getJoint(int indexX,int indexY) {
return mJoints[indexY][indexX];
}
public int getColumnCount() {
return mColCount;
}
public int getRowCount() {
return mRowCount;
}
public void addCollider(Joint collJoint) {
for(Joint[] row:mJoints) {
for(Joint joint:row) {
mMassAggregation.addConstraint(new ColliderConstraint(collJoint,joint));
}
}
}
public void setRowFixed(float row,boolean fixed) {
int rowId = normToRow(row);
Joint[] jointRow = mJoints[rowId];
for(Joint joint:jointRow) {
joint.mFixed = fixed;
}
}
public void setColumnFixed(float column,boolean fixed) {
int colId = normToColumn(column);
for(int i=0;i<mRowCount;i++) {
mJoints[i][colId].mFixed = fixed;
}
}
public int normToRow(float normRow) {
return (int)(normRow*(mRowCount-1)+0.5f);
}
public int normToColumn(float normColumn) {
return (int)(normColumn*(mColCount-1)+0.5f);
}
public float rowToNorm(int rowIndex) {
return (float)rowIndex/(mColCount-1);
}
public float columnToNorm(int columnIndex) {
return (float)columnIndex/(mColCount-1)*mRatio;
}
public float getRatio() {
return mRatio;
}
//--------DRAWING--------
public int getVertexCount() {
return mColCount*mRowCount;
}
public void initGraphics(DefaultGraphics<?> graphics) {
mGridDrawer = new GridCreator<DefaultGraphics<?>>(graphics);
mGridDrawer.init(mColCount,mRowCount, 1,1);
}
public void putPositions() {
if(mGridDrawer==null)
throw new RuntimeException("Graphics not initialized");
IndexedVertexBuffer vBuffer = mGridDrawer.mGraphics.mCurrentVertexBuffer;
for(Joint[] row:mJoints) {
for(Joint joint:row) {
vBuffer.putVec3(DefaultGraphics.ID_POSITIONS, joint.mWorldPosition);
}
}
}
public void drawDefault(FloatColor color,TextureCoordinatesQuad texCoords) {
if(texCoords==null)
texCoords = TextureCoordinatesQuad.FULL_TEXTURE;
mGridDrawer.beginDraw();
mGridDrawer.putIndices();
putPositions();
mGridDrawer.putGridColor(color.mValues);
mGridDrawer.putGridSuppData(FloatColor.BLACK.mValues);
mGridDrawer.putGridTextureRect(texCoords);
mGridDrawer.putNormals();
}
public void drawDefault() {
drawDefault(FloatColor.WHITE,TextureCoordinatesQuad.FULL_TEXTURE);
}
public Joint pickJoint(float normColumn,float normRow) {
return mJoints[normToRow(normRow)][normToColumn(normColumn)];
}
}
| true | true | public MassAggregation create(int countX,int countY,YangMatrix transform) {
if(transform==null)
transform = YangMatrix.IDENTITY;
mColCount = countX;
mRowCount = countY;
mJoints = new Joint[countY][countX];
if(countX<2 || countY<2)
throw new RuntimeException("countX and countY must be larger or equal 2.");
if(mMassAggregation==null) {
mMassAggregation = new MassAggregation();
mMassAggregation.mLowerLimit = -128;
}
mRatio = (float)countX/countY;
for(int j=0;j<countY;j++) {
float y = (float)j/(countY-1);
Joint prevJoint = null;
for(int i=0;i<countX;i++) {
Joint newJoint = new Joint(mJointNamePrefix+j+"-"+i);
float x = (float)i/(countX-1) * mRatio;
transform.apply3D(x,y,0, newJoint);
newJoint.setInitialValues();
mJoints[j][i] = newJoint;
newJoint.mRadius = mJointRadius;
mMassAggregation.addJoint(newJoint);
JointConnection boneX = null;
JointConnection boneY = null;
if(i>0)
boneX = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+j+"-"+(i-1)+"_"+j+"-"+i, prevJoint,newJoint), mStrength);
if(j>0)
boneY = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+i, mJoints[j-1][i],newJoint), mStrength);
if(i>0 && j>0) {
// GridConstraint gridConstraint = new GridConstraint(boneX,boneY);
// mMassAggregation.addConstraint(gridConstraint);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+(i-1)+"_"+j+"-"+i, mJoints[j-1][i-1],newJoint), mStrength);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+(i-1), mJoints[j-1][i],mJoints[j][i-1]), mStrength);
}
prevJoint = newJoint;
newJoint.mFriction = mFriction;
}
}
return mMassAggregation;
}
| public MassAggregation create(int countX,int countY,YangMatrix transform) {
if(transform==null)
transform = YangMatrix.IDENTITY;
mColCount = countX;
mRowCount = countY;
mJoints = new Joint[countY][countX];
if(countX<2 || countY<2)
throw new RuntimeException("countX and countY must be larger or equal 2.");
if(mMassAggregation==null) {
mMassAggregation = new MassAggregation();
mMassAggregation.mLowerLimit = -128;
}
mRatio = (float)(countX-1)/(countY-1);
for(int j=0;j<countY;j++) {
float y = (float)j/(countY-1);
Joint prevJoint = null;
for(int i=0;i<countX;i++) {
Joint newJoint = new Joint(mJointNamePrefix+j+"-"+i);
float x = (float)i/(countX-1) * mRatio;
transform.apply3D(x,y,0, newJoint);
newJoint.setInitialValues();
mJoints[j][i] = newJoint;
newJoint.mRadius = mJointRadius;
mMassAggregation.addJoint(newJoint);
JointConnection boneX = null;
JointConnection boneY = null;
if(i>0)
boneX = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+j+"-"+(i-1)+"_"+j+"-"+i, prevJoint,newJoint), mStrength);
if(j>0)
boneY = mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+i, mJoints[j-1][i],newJoint), mStrength);
if(i>0 && j>0) {
// GridConstraint gridConstraint = new GridConstraint(boneX,boneY);
// mMassAggregation.addConstraint(gridConstraint);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+(i-1)+"_"+j+"-"+i, mJoints[j-1][i-1],newJoint), mStrength);
mMassAggregation.addSpringBone(new JointConnection(mBoneNamePrefix+(j-1)+"-"+i+"_"+j+"-"+(i-1), mJoints[j-1][i],mJoints[j][i-1]), mStrength);
}
prevJoint = newJoint;
newJoint.mFriction = mFriction;
}
}
return mMassAggregation;
}
|
diff --git a/jsf/components/component/src/org/icefaces/mobi/component/button/CommandButtonRenderer.java b/jsf/components/component/src/org/icefaces/mobi/component/button/CommandButtonRenderer.java
index c35e30e0d..ad0cd20e2 100644
--- a/jsf/components/component/src/org/icefaces/mobi/component/button/CommandButtonRenderer.java
+++ b/jsf/components/component/src/org/icefaces/mobi/component/button/CommandButtonRenderer.java
@@ -1,237 +1,241 @@
/*
* Copyright 2004-2012 ICEsoft Technologies Canada Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icefaces.mobi.component.button;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.ClientBehaviorHolder;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.ActionEvent;
import org.icefaces.mobi.component.panelconfirmation.PanelConfirmationRenderer;
import org.icefaces.mobi.component.submitnotification.SubmitNotificationRenderer;
import org.icefaces.mobi.renderkit.CoreRenderer;
import org.icefaces.mobi.utils.HTML;
import org.icefaces.mobi.utils.JSFUtils;
import org.icefaces.mobi.utils.MobiJSFUtils;
public class CommandButtonRenderer extends CoreRenderer {
private static Logger logger = Logger.getLogger(CommandButtonRenderer.class.getName());
List <UIParameter> uiParamChildren;
public void decode(FacesContext facesContext, UIComponent uiComponent) {
Map requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
CommandButton commandButton = (CommandButton) uiComponent;
String source = String.valueOf(requestParameterMap.get("ice.event.captured"));
String clientId = commandButton.getClientId();
// logger.info("source = "+source);
if (clientId.equals(source)) {
try {
if (!commandButton.isDisabled()) {
uiComponent.queueEvent(new ActionEvent(uiComponent));
decodeBehaviors(facesContext, uiComponent);
}
} catch (Exception e) {
logger.warning("Error queuing CommandButton event");
}
}
}
public void encodeBegin(FacesContext facesContext, UIComponent uiComponent)
throws IOException {
CommandButton commandButton = (CommandButton) uiComponent;
// apply button type style classes
StringBuilder baseClass = new StringBuilder(CommandButton.BASE_STYLE_CLASS);
String buttonType = commandButton.getButtonType();
String styleClass = commandButton.getStyleClass();
if (styleClass != null) {
baseClass.append(" ").append(styleClass);
}
// apply selected state if any
if (commandButton.isSelected()) {
baseClass.append(CommandButton.SELECTED_STYLE_CLASS);
}
// apply disabled style state if specified.
if (commandButton.isDisabled()) {
baseClass.append(" ").append(CommandButton.DISABLED_STYLE_CLASS);
}
String style = commandButton.getStyle();
if( style != null ){
style = style.trim();
if( style.length() == 0){
style = null;
}
}
// assign button type
if (CommandButton.BUTTON_TYPE_DEFAULT.equals(buttonType)) {
baseClass.append(CommandButton.DEFAULT_STYLE_CLASS);
} else if (CommandButton.BUTTON_TYPE_BACK.equals(buttonType)) {
baseClass.append(CommandButton.BACK_STYLE_CLASS);
} else if (CommandButton.BUTTON_TYPE_ATTENTION.equals(buttonType)) {
baseClass.append(CommandButton.ATTENTION_STYLE_CLASS);
} else if (CommandButton.BUTTON_TYPE_IMPORTANT.equals(buttonType)) {
baseClass.append(CommandButton.IMPORTANT_STYLE_CLASS);
} else if (logger.isLoggable(Level.FINER)) {
baseClass.append(CommandButton.DEFAULT_STYLE_CLASS);
}
String type = commandButton.getType();
// button type for styling purposes, otherwise use pass through value.
if (type == null){
type = "button";
}
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = uiComponent.getClientId(facesContext);
if (CommandButton.BUTTON_TYPE_BACK.equals(buttonType)){
writer.startElement(HTML.DIV_ELEM, commandButton);
writer.writeAttribute(HTML.ID_ATTR, clientId+"_ctr", HTML.ID_ATTR);
writer.writeAttribute(HTML.CLASS_ATTR, baseClass.toString(), null);
// should be auto base though
if (style != null ) {
writer.writeAttribute(HTML.STYLE_ATTR, style, HTML.STYLE_ATTR);
}
writer.startElement(HTML.SPAN_ELEM, commandButton);
writer.endElement(HTML.SPAN_ELEM);
}
writer.startElement(HTML.INPUT_ELEM, uiComponent);
writer.writeAttribute(HTML.ID_ATTR, clientId, HTML.ID_ATTR);
//style and class written to ctr div when back button
if (!CommandButton.BUTTON_TYPE_BACK.equals(buttonType)){
writer.writeAttribute(HTML.CLASS_ATTR, baseClass.toString(), null);
// should be auto base though
if (style != null ) {
writer.writeAttribute(HTML.STYLE_ATTR, style, HTML.STYLE_ATTR);
}
}
writer.writeAttribute(HTML.TYPE_ATTR, type, null);
writer.writeAttribute(HTML.NAME_ATTR, clientId, null);
String value = type;
Object oVal = commandButton.getValue();
if (null != oVal) {
value = oVal.toString();
}
writer.writeAttribute(HTML.VALUE_ATTR, value, HTML.VALUE_ATTR);
}
public void encodeEnd(FacesContext facesContext, UIComponent uiComponent)
throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = uiComponent.getClientId(facesContext);
CommandButton commandButton = (CommandButton) uiComponent;
uiParamChildren = JSFUtils.captureParameters( commandButton );
if (commandButton.isDisabled()) {
writer.writeAttribute("disabled", "disabled", null);
writer.endElement(HTML.INPUT_ELEM);
+ //end ctr div for back button
+ if (CommandButton.BUTTON_TYPE_BACK.equals(commandButton.getButtonType())){
+ writer.endElement(HTML.DIV_ELEM);
+ }
return;
}
boolean singleSubmit = commandButton.isSingleSubmit();
String idAndparams = "'"+clientId+"'";
String params="";
if (uiParamChildren != null) {
params = MobiJSFUtils.asParameterString(uiParamChildren);
idAndparams += ","+ params;
}
ClientBehaviorHolder cbh = (ClientBehaviorHolder)uiComponent;
boolean hasBehaviors = !cbh.getClientBehaviors().isEmpty();
StringBuilder seCall = new StringBuilder("ice.se(event, ").append(idAndparams).append(");");
StringBuilder sCall = new StringBuilder("ice.s(event, ").append(idAndparams).append(");");
/**
* panelConfirmation? Then no singleSubmit
* then add the confirmation panel ID. panelConfrmation confirm will
* submitNotification?
* if no panelConfirmation then just display it when commandButton does submit
* have behaviors? , ice.se or ice.s doesn't matter.
*
*
*
*/
StringBuilder builder = new StringBuilder(255);
String panelConfId=commandButton.getPanelConfirmation();
String subNotId = commandButton.getSubmitNotification();
String submitNotificationId = null;
// builder.append("{ elVal: this");
builder.append("{ event: event");
if (singleSubmit){
builder.append(", singleSubmit:").append(singleSubmit);
}
if (null != subNotId && subNotId.length()> 0) {
submitNotificationId = SubmitNotificationRenderer.findSubmitNotificationId(uiComponent,subNotId);
if (null != submitNotificationId ){
builder.append(",snId: '").append(submitNotificationId).append("'");
} else {
logger.warning("no submitNotification id found for commandButton id="+clientId);
}
}
if (uiParamChildren != null){
//include params for button
builder.append(",params: ").append(params);
}
if (null != panelConfId && panelConfId.length()>0){
///would never use this with singleSubmit so always false when using with panelConfirmation
//panelConf either has ajax request behaviors or regular ice.submit.
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
builder.append(behaviors);
}
StringBuilder pcBuilder = PanelConfirmationRenderer.renderOnClickString(uiComponent, builder );
if (null != pcBuilder){
//has panelConfirmation and it is found
writer.writeAttribute(HTML.ONCLICK_ATTR, pcBuilder.toString(),HTML.ONCLICK_ATTR);
} else { //no panelConfirmation found so commandButton does the job
logger.warning("panelConfirmation of "+panelConfId+" NOT FOUND:- resorting to standard ajax form submit");
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
noPanelConf.append("});"); ///this is the cfg if commandButton does the submit
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
} else { //no panelConfirmation requested so button does job
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
noPanelConf.append(behaviors);
}
noPanelConf.append("});");
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
writer.endElement(HTML.INPUT_ELEM);
//end ctr div for back button
if (CommandButton.BUTTON_TYPE_BACK.equals(commandButton.getButtonType())){
writer.endElement(HTML.DIV_ELEM);
}
}
private StringBuilder getCall(String clientId, String builder ) {
StringBuilder noPanelConf = new StringBuilder("mobi.button.select('").append(clientId).append("',");
noPanelConf.append(builder);
return noPanelConf;
}
}
| true | true | public void encodeEnd(FacesContext facesContext, UIComponent uiComponent)
throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = uiComponent.getClientId(facesContext);
CommandButton commandButton = (CommandButton) uiComponent;
uiParamChildren = JSFUtils.captureParameters( commandButton );
if (commandButton.isDisabled()) {
writer.writeAttribute("disabled", "disabled", null);
writer.endElement(HTML.INPUT_ELEM);
return;
}
boolean singleSubmit = commandButton.isSingleSubmit();
String idAndparams = "'"+clientId+"'";
String params="";
if (uiParamChildren != null) {
params = MobiJSFUtils.asParameterString(uiParamChildren);
idAndparams += ","+ params;
}
ClientBehaviorHolder cbh = (ClientBehaviorHolder)uiComponent;
boolean hasBehaviors = !cbh.getClientBehaviors().isEmpty();
StringBuilder seCall = new StringBuilder("ice.se(event, ").append(idAndparams).append(");");
StringBuilder sCall = new StringBuilder("ice.s(event, ").append(idAndparams).append(");");
/**
* panelConfirmation? Then no singleSubmit
* then add the confirmation panel ID. panelConfrmation confirm will
* submitNotification?
* if no panelConfirmation then just display it when commandButton does submit
* have behaviors? , ice.se or ice.s doesn't matter.
*
*
*
*/
StringBuilder builder = new StringBuilder(255);
String panelConfId=commandButton.getPanelConfirmation();
String subNotId = commandButton.getSubmitNotification();
String submitNotificationId = null;
// builder.append("{ elVal: this");
builder.append("{ event: event");
if (singleSubmit){
builder.append(", singleSubmit:").append(singleSubmit);
}
if (null != subNotId && subNotId.length()> 0) {
submitNotificationId = SubmitNotificationRenderer.findSubmitNotificationId(uiComponent,subNotId);
if (null != submitNotificationId ){
builder.append(",snId: '").append(submitNotificationId).append("'");
} else {
logger.warning("no submitNotification id found for commandButton id="+clientId);
}
}
if (uiParamChildren != null){
//include params for button
builder.append(",params: ").append(params);
}
if (null != panelConfId && panelConfId.length()>0){
///would never use this with singleSubmit so always false when using with panelConfirmation
//panelConf either has ajax request behaviors or regular ice.submit.
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
builder.append(behaviors);
}
StringBuilder pcBuilder = PanelConfirmationRenderer.renderOnClickString(uiComponent, builder );
if (null != pcBuilder){
//has panelConfirmation and it is found
writer.writeAttribute(HTML.ONCLICK_ATTR, pcBuilder.toString(),HTML.ONCLICK_ATTR);
} else { //no panelConfirmation found so commandButton does the job
logger.warning("panelConfirmation of "+panelConfId+" NOT FOUND:- resorting to standard ajax form submit");
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
noPanelConf.append("});"); ///this is the cfg if commandButton does the submit
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
} else { //no panelConfirmation requested so button does job
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
noPanelConf.append(behaviors);
}
noPanelConf.append("});");
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
writer.endElement(HTML.INPUT_ELEM);
//end ctr div for back button
if (CommandButton.BUTTON_TYPE_BACK.equals(commandButton.getButtonType())){
writer.endElement(HTML.DIV_ELEM);
}
}
| public void encodeEnd(FacesContext facesContext, UIComponent uiComponent)
throws IOException {
ResponseWriter writer = facesContext.getResponseWriter();
String clientId = uiComponent.getClientId(facesContext);
CommandButton commandButton = (CommandButton) uiComponent;
uiParamChildren = JSFUtils.captureParameters( commandButton );
if (commandButton.isDisabled()) {
writer.writeAttribute("disabled", "disabled", null);
writer.endElement(HTML.INPUT_ELEM);
//end ctr div for back button
if (CommandButton.BUTTON_TYPE_BACK.equals(commandButton.getButtonType())){
writer.endElement(HTML.DIV_ELEM);
}
return;
}
boolean singleSubmit = commandButton.isSingleSubmit();
String idAndparams = "'"+clientId+"'";
String params="";
if (uiParamChildren != null) {
params = MobiJSFUtils.asParameterString(uiParamChildren);
idAndparams += ","+ params;
}
ClientBehaviorHolder cbh = (ClientBehaviorHolder)uiComponent;
boolean hasBehaviors = !cbh.getClientBehaviors().isEmpty();
StringBuilder seCall = new StringBuilder("ice.se(event, ").append(idAndparams).append(");");
StringBuilder sCall = new StringBuilder("ice.s(event, ").append(idAndparams).append(");");
/**
* panelConfirmation? Then no singleSubmit
* then add the confirmation panel ID. panelConfrmation confirm will
* submitNotification?
* if no panelConfirmation then just display it when commandButton does submit
* have behaviors? , ice.se or ice.s doesn't matter.
*
*
*
*/
StringBuilder builder = new StringBuilder(255);
String panelConfId=commandButton.getPanelConfirmation();
String subNotId = commandButton.getSubmitNotification();
String submitNotificationId = null;
// builder.append("{ elVal: this");
builder.append("{ event: event");
if (singleSubmit){
builder.append(", singleSubmit:").append(singleSubmit);
}
if (null != subNotId && subNotId.length()> 0) {
submitNotificationId = SubmitNotificationRenderer.findSubmitNotificationId(uiComponent,subNotId);
if (null != submitNotificationId ){
builder.append(",snId: '").append(submitNotificationId).append("'");
} else {
logger.warning("no submitNotification id found for commandButton id="+clientId);
}
}
if (uiParamChildren != null){
//include params for button
builder.append(",params: ").append(params);
}
if (null != panelConfId && panelConfId.length()>0){
///would never use this with singleSubmit so always false when using with panelConfirmation
//panelConf either has ajax request behaviors or regular ice.submit.
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
builder.append(behaviors);
}
StringBuilder pcBuilder = PanelConfirmationRenderer.renderOnClickString(uiComponent, builder );
if (null != pcBuilder){
//has panelConfirmation and it is found
writer.writeAttribute(HTML.ONCLICK_ATTR, pcBuilder.toString(),HTML.ONCLICK_ATTR);
} else { //no panelConfirmation found so commandButton does the job
logger.warning("panelConfirmation of "+panelConfId+" NOT FOUND:- resorting to standard ajax form submit");
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
noPanelConf.append("});"); ///this is the cfg if commandButton does the submit
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
} else { //no panelConfirmation requested so button does job
StringBuilder noPanelConf = this.getCall(clientId, builder.toString());
if (hasBehaviors){
String behaviors = this.encodeClientBehaviors(facesContext, cbh, "click").toString();
behaviors = behaviors.replace("\"", "\'");
noPanelConf.append(behaviors);
}
noPanelConf.append("});");
writer.writeAttribute(HTML.ONCLICK_ATTR, noPanelConf.toString(), HTML.ONCLICK_ATTR);
}
writer.endElement(HTML.INPUT_ELEM);
//end ctr div for back button
if (CommandButton.BUTTON_TYPE_BACK.equals(commandButton.getButtonType())){
writer.endElement(HTML.DIV_ELEM);
}
}
|
diff --git a/MetroBike/src/com/HuskySoft/metrobike/ui/utility/HistoryItem.java b/MetroBike/src/com/HuskySoft/metrobike/ui/utility/HistoryItem.java
index 97b326a..2cfdcfd 100644
--- a/MetroBike/src/com/HuskySoft/metrobike/ui/utility/HistoryItem.java
+++ b/MetroBike/src/com/HuskySoft/metrobike/ui/utility/HistoryItem.java
@@ -1,59 +1,58 @@
package com.HuskySoft.metrobike.ui.utility;
/**
* This class is immutable to store the history details.
*/
public class HistoryItem {
/**
* The position index of this item.
*/
private int index;
/**
* The address starting from.
*/
private String from;
/**
* The address going to.
*/
private String to;
/**
* Constructor to initialize those field. Once this object is created, it
* will not be changed.
*
* @param indexPos
* the position index
* @param fromAddress
* the starting address
* @param endAddress
* the ending address
*/
public HistoryItem(final int indexPos, final String fromAddress,
final String endAddress) {
- super();
this.index = indexPos;
this.from = fromAddress;
this.to = endAddress;
}
/**
* @return int index where the position of this item.
*/
public final int getIndex() {
return index;
}
/**
* @return String from where the starting address.
*/
public final String getFrom() {
return from;
}
/**
* @return String to where the ending address.
*/
public final String getTo() {
return to;
}
}
| true | true | public HistoryItem(final int indexPos, final String fromAddress,
final String endAddress) {
super();
this.index = indexPos;
this.from = fromAddress;
this.to = endAddress;
}
| public HistoryItem(final int indexPos, final String fromAddress,
final String endAddress) {
this.index = indexPos;
this.from = fromAddress;
this.to = endAddress;
}
|
diff --git a/src/org/openstreetmap/josm/io/GpxReader.java b/src/org/openstreetmap/josm/io/GpxReader.java
index eeb52d20..565df194 100644
--- a/src/org/openstreetmap/josm/io/GpxReader.java
+++ b/src/org/openstreetmap/josm/io/GpxReader.java
@@ -1,334 +1,334 @@
//License: GPL. Copyright 2007 by Immanuel Scholz and others
//TODO: this is far from complete, but can emulate old RawGps behaviour
package org.openstreetmap.josm.io;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.openstreetmap.josm.data.coor.LatLon;
import org.openstreetmap.josm.data.gpx.GpxData;
import org.openstreetmap.josm.data.gpx.GpxLink;
import org.openstreetmap.josm.data.gpx.GpxRoute;
import org.openstreetmap.josm.data.gpx.GpxTrack;
import org.openstreetmap.josm.data.gpx.WayPoint;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Read a gpx file. Bounds are not read, as we caluclate them. @see GpxData.recalculateBounds()
* @author imi, ramack
*/
public class GpxReader {
// TODO: implement GPX 1.0 parsing
/**
* The resulting gpx data
*/
public GpxData data;
public enum state { init, metadata, wpt, rte, trk, ext, author, link, trkseg, copyright}
private class Parser extends DefaultHandler {
private GpxData currentData;
private GpxTrack currentTrack;
private Collection<WayPoint> currentTrackSeg;
private GpxRoute currentRoute;
private WayPoint currentWayPoint;
private state currentState = state.init;
private GpxLink currentLink;
private Stack<state> states;
private StringBuffer accumulator = new StringBuffer();
@Override public void startDocument() {
accumulator = new StringBuffer();
states = new Stack<state>();
currentData = new GpxData();
}
private double parseCoord(String s) {
try {
return Double.parseDouble(s);
} catch (NumberFormatException ex) {
return Double.NaN;
}
}
private LatLon parseLatLon(Attributes atts) {
return new LatLon(
parseCoord(atts.getValue("lat")),
parseCoord(atts.getValue("lon")));
}
@Override public void startElement(String namespaceURI, String qName, String rqName, Attributes atts) throws SAXException {
switch(currentState) {
case init:
if (qName.equals("metadata")) {
states.push(currentState);
currentState = state.metadata;
} else if (qName.equals("wpt")) {
states.push(currentState);
currentState = state.wpt;
currentWayPoint = new WayPoint(parseLatLon(atts));
} else if (qName.equals("rte")) {
states.push(currentState);
currentState = state.rte;
currentRoute = new GpxRoute();
} else if (qName.equals("trk")) {
states.push(currentState);
currentState = state.trk;
currentTrack = new GpxTrack();
} else if (qName.equals("extensions")) {
states.push(currentState);
currentState = state.ext;
}
break;
case author:
if (qName.equals("link")) {
states.push(currentState);
currentState = state.link;
currentLink = new GpxLink(atts.getValue("href"));
} else if (qName.equals("email")) {
currentData.attr.put(GpxData.META_AUTHOR_EMAIL, atts.getValue("id") + "@" + atts.getValue("domain"));
}
break;
case trk:
if (qName.equals("trkseg")) {
states.push(currentState);
currentState = state.trkseg;
currentTrackSeg = new ArrayList<WayPoint>();
} else if (qName.equals("link")) {
states.push(currentState);
currentState = state.link;
currentLink = new GpxLink(atts.getValue("href"));
} else if (qName.equals("extensions")) {
states.push(currentState);
currentState = state.ext;
}
break;
case metadata:
if (qName.equals("author")) {
states.push(currentState);
currentState = state.author;
} else if (qName.equals("extensions")) {
states.push(currentState);
currentState = state.ext;
} else if (qName.equals("copyright")) {
states.push(currentState);
currentState = state.copyright;
currentData.attr.put(GpxData.META_COPYRIGHT_AUTHOR, atts.getValue("author"));
} else if (qName.equals("link")) {
states.push(currentState);
currentState = state.link;
currentLink = new GpxLink(atts.getValue("href"));
}
break;
case trkseg:
if (qName.equals("trkpt")) {
states.push(currentState);
currentState = state.wpt;
currentWayPoint = new WayPoint(parseLatLon(atts));
}
break;
case wpt:
if (qName.equals("link")) {
states.push(currentState);
currentState = state.link;
currentLink = new GpxLink(atts.getValue("href"));
} else if (qName.equals("extensions")) {
states.push(currentState);
currentState = state.ext;
}
break;
case rte:
if (qName.equals("link")) {
states.push(currentState);
currentState = state.link;
currentLink = new GpxLink(atts.getValue("href"));
} else if (qName.equals("rtept")) {
states.push(currentState);
currentState = state.wpt;
currentWayPoint = new WayPoint(parseLatLon(atts));
} else if (qName.equals("extensions")) {
states.push(currentState);
currentState = state.ext;
}
break;
default:
}
accumulator.setLength(0);
}
@Override public void characters(char[] ch, int start, int length) {
accumulator.append(ch, start, length);
}
private Map<String, Object> getAttr() {
switch (currentState) {
case rte: return currentRoute.attr;
case metadata: return currentData.attr;
case wpt: return currentWayPoint.attr;
case trk: return currentTrack.attr;
default: return null;
}
}
@Override public void endElement(String namespaceURI, String qName, String rqName) {
switch (currentState) {
case metadata:
if (qName.equals("name")) {
currentData.attr.put(GpxData.META_NAME, accumulator.toString());
} else if (qName.equals("desc")) {
currentData.attr.put(GpxData.META_DESC, accumulator.toString());
} else if (qName.equals("time")) {
currentData.attr.put(GpxData.META_TIME, accumulator.toString());
} else if (qName.equals("keywords")) {
currentData.attr.put(GpxData.META_KEYWORDS, accumulator.toString());
} else if (qName.equals("metadata")) {
currentState = states.pop();
}
//TODO: parse bounds, extensions
break;
case author:
if (qName.equals("author")) {
currentState = states.pop();
} else if (qName.equals("name")) {
currentData.attr.put(GpxData.META_AUTHOR_NAME, accumulator.toString());
} else if (qName.equals("email")) {
// do nothing, has been parsed on startElement
} else if (qName.equals("link")) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
}
break;
case copyright:
if (qName.equals("copyright")) {
currentState = states.pop();
} else if (qName.equals("year")) {
currentData.attr.put(GpxData.META_COPYRIGHT_YEAR, accumulator.toString());
} else if (qName.equals("license")) {
currentData.attr.put(GpxData.META_COPYRIGHT_LICENSE, accumulator.toString());
}
break;
case link:
if (qName.equals("text")) {
currentLink.text = accumulator.toString();
} else if (qName.equals("type")) {
currentLink.type = accumulator.toString();
} else if (qName.equals("link")) {
currentState = states.pop();
}
if (currentState == state.author) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
- } else if (currentState == state.metadata) {
+ } else if (currentState != state.link) {
Map<String, Object> attr = getAttr();
if (!attr.containsKey(GpxData.META_LINKS)) {
attr.put(GpxData.META_LINKS, new LinkedList<GpxLink>());
}
((Collection<GpxLink>) attr.get(GpxData.META_LINKS)).add(currentLink);
}
break;
case wpt:
if ( qName.equals("ele") || qName.equals("magvar")
|| qName.equals("name") || qName.equals("geoidheight")
|| qName.equals("type") || qName.equals("sym")) {
currentWayPoint.attr.put(qName, accumulator.toString());
} else if(qName.equals("hdop") /*|| qName.equals("vdop") ||
qName.equals("pdop")*/) {
try {
currentWayPoint.attr.put(qName, Float.parseFloat(accumulator.toString()));
} catch(Exception e) {
currentWayPoint.attr.put(qName, new Float(0));
}
} else if (qName.equals("time")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setTime();
} else if (qName.equals("cmt") || qName.equals("desc")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setGarminCommentTime(qName);
} else if (qName.equals("rtept")) {
currentState = states.pop();
currentRoute.routePoints.add(currentWayPoint);
} else if (qName.equals("trkpt")) {
currentState = states.pop();
currentTrackSeg.add(currentWayPoint);
} else if (qName.equals("wpt")) {
currentState = states.pop();
currentData.waypoints.add(currentWayPoint);
}
break;
case trkseg:
if (qName.equals("trkseg")) {
currentState = states.pop();
currentTrack.trackSegs.add(currentTrackSeg);
}
break;
case trk:
if (qName.equals("trk")) {
currentState = states.pop();
currentData.tracks.add(currentTrack);
} else if (qName.equals("name") || qName.equals("cmt")
|| qName.equals("desc") || qName.equals("src")
|| qName.equals("type") || qName.equals("number")) {
currentTrack.attr.put(qName, accumulator.toString());
}
break;
case ext:
if (qName.equals("extensions")) {
currentState = states.pop();
}
break;
default:
if (qName.equals("wpt")) {
currentState = states.pop();
} else if (qName.equals("rte")) {
currentState = states.pop();
currentData.routes.add(currentRoute);
}
}
}
@Override public void endDocument() throws SAXException {
if (!states.empty()) {
throw new SAXException(tr("Parse error: invalid document structure for gpx document"));
}
data = currentData;
}
}
/**
* Parse the input stream and store the result in trackData and markerData
*
* @param relativeMarkerPath The directory to use as relative path for all <wpt>
* marker tags. Maybe <code>null</code>, in which case no relative urls are constructed for the markers.
*/
public GpxReader(InputStream source, File relativeMarkerPath) throws SAXException, IOException {
Parser parser = new Parser();
InputSource inputSource = new InputSource(new InputStreamReader(source, "UTF-8"));
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.newSAXParser().parse(inputSource, parser);
} catch (ParserConfigurationException e) {
e.printStackTrace(); // broken SAXException chaining
throw new SAXException(e);
}
}
}
| true | true | @Override public void endElement(String namespaceURI, String qName, String rqName) {
switch (currentState) {
case metadata:
if (qName.equals("name")) {
currentData.attr.put(GpxData.META_NAME, accumulator.toString());
} else if (qName.equals("desc")) {
currentData.attr.put(GpxData.META_DESC, accumulator.toString());
} else if (qName.equals("time")) {
currentData.attr.put(GpxData.META_TIME, accumulator.toString());
} else if (qName.equals("keywords")) {
currentData.attr.put(GpxData.META_KEYWORDS, accumulator.toString());
} else if (qName.equals("metadata")) {
currentState = states.pop();
}
//TODO: parse bounds, extensions
break;
case author:
if (qName.equals("author")) {
currentState = states.pop();
} else if (qName.equals("name")) {
currentData.attr.put(GpxData.META_AUTHOR_NAME, accumulator.toString());
} else if (qName.equals("email")) {
// do nothing, has been parsed on startElement
} else if (qName.equals("link")) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
}
break;
case copyright:
if (qName.equals("copyright")) {
currentState = states.pop();
} else if (qName.equals("year")) {
currentData.attr.put(GpxData.META_COPYRIGHT_YEAR, accumulator.toString());
} else if (qName.equals("license")) {
currentData.attr.put(GpxData.META_COPYRIGHT_LICENSE, accumulator.toString());
}
break;
case link:
if (qName.equals("text")) {
currentLink.text = accumulator.toString();
} else if (qName.equals("type")) {
currentLink.type = accumulator.toString();
} else if (qName.equals("link")) {
currentState = states.pop();
}
if (currentState == state.author) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
} else if (currentState == state.metadata) {
Map<String, Object> attr = getAttr();
if (!attr.containsKey(GpxData.META_LINKS)) {
attr.put(GpxData.META_LINKS, new LinkedList<GpxLink>());
}
((Collection<GpxLink>) attr.get(GpxData.META_LINKS)).add(currentLink);
}
break;
case wpt:
if ( qName.equals("ele") || qName.equals("magvar")
|| qName.equals("name") || qName.equals("geoidheight")
|| qName.equals("type") || qName.equals("sym")) {
currentWayPoint.attr.put(qName, accumulator.toString());
} else if(qName.equals("hdop") /*|| qName.equals("vdop") ||
qName.equals("pdop")*/) {
try {
currentWayPoint.attr.put(qName, Float.parseFloat(accumulator.toString()));
} catch(Exception e) {
currentWayPoint.attr.put(qName, new Float(0));
}
} else if (qName.equals("time")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setTime();
} else if (qName.equals("cmt") || qName.equals("desc")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setGarminCommentTime(qName);
} else if (qName.equals("rtept")) {
currentState = states.pop();
currentRoute.routePoints.add(currentWayPoint);
} else if (qName.equals("trkpt")) {
currentState = states.pop();
currentTrackSeg.add(currentWayPoint);
} else if (qName.equals("wpt")) {
currentState = states.pop();
currentData.waypoints.add(currentWayPoint);
}
break;
case trkseg:
if (qName.equals("trkseg")) {
currentState = states.pop();
currentTrack.trackSegs.add(currentTrackSeg);
}
break;
case trk:
if (qName.equals("trk")) {
currentState = states.pop();
currentData.tracks.add(currentTrack);
} else if (qName.equals("name") || qName.equals("cmt")
|| qName.equals("desc") || qName.equals("src")
|| qName.equals("type") || qName.equals("number")) {
currentTrack.attr.put(qName, accumulator.toString());
}
break;
case ext:
if (qName.equals("extensions")) {
currentState = states.pop();
}
break;
default:
if (qName.equals("wpt")) {
currentState = states.pop();
} else if (qName.equals("rte")) {
currentState = states.pop();
currentData.routes.add(currentRoute);
}
}
}
| @Override public void endElement(String namespaceURI, String qName, String rqName) {
switch (currentState) {
case metadata:
if (qName.equals("name")) {
currentData.attr.put(GpxData.META_NAME, accumulator.toString());
} else if (qName.equals("desc")) {
currentData.attr.put(GpxData.META_DESC, accumulator.toString());
} else if (qName.equals("time")) {
currentData.attr.put(GpxData.META_TIME, accumulator.toString());
} else if (qName.equals("keywords")) {
currentData.attr.put(GpxData.META_KEYWORDS, accumulator.toString());
} else if (qName.equals("metadata")) {
currentState = states.pop();
}
//TODO: parse bounds, extensions
break;
case author:
if (qName.equals("author")) {
currentState = states.pop();
} else if (qName.equals("name")) {
currentData.attr.put(GpxData.META_AUTHOR_NAME, accumulator.toString());
} else if (qName.equals("email")) {
// do nothing, has been parsed on startElement
} else if (qName.equals("link")) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
}
break;
case copyright:
if (qName.equals("copyright")) {
currentState = states.pop();
} else if (qName.equals("year")) {
currentData.attr.put(GpxData.META_COPYRIGHT_YEAR, accumulator.toString());
} else if (qName.equals("license")) {
currentData.attr.put(GpxData.META_COPYRIGHT_LICENSE, accumulator.toString());
}
break;
case link:
if (qName.equals("text")) {
currentLink.text = accumulator.toString();
} else if (qName.equals("type")) {
currentLink.type = accumulator.toString();
} else if (qName.equals("link")) {
currentState = states.pop();
}
if (currentState == state.author) {
currentData.attr.put(GpxData.META_AUTHOR_LINK, currentLink);
} else if (currentState != state.link) {
Map<String, Object> attr = getAttr();
if (!attr.containsKey(GpxData.META_LINKS)) {
attr.put(GpxData.META_LINKS, new LinkedList<GpxLink>());
}
((Collection<GpxLink>) attr.get(GpxData.META_LINKS)).add(currentLink);
}
break;
case wpt:
if ( qName.equals("ele") || qName.equals("magvar")
|| qName.equals("name") || qName.equals("geoidheight")
|| qName.equals("type") || qName.equals("sym")) {
currentWayPoint.attr.put(qName, accumulator.toString());
} else if(qName.equals("hdop") /*|| qName.equals("vdop") ||
qName.equals("pdop")*/) {
try {
currentWayPoint.attr.put(qName, Float.parseFloat(accumulator.toString()));
} catch(Exception e) {
currentWayPoint.attr.put(qName, new Float(0));
}
} else if (qName.equals("time")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setTime();
} else if (qName.equals("cmt") || qName.equals("desc")) {
currentWayPoint.attr.put(qName, accumulator.toString());
currentWayPoint.setGarminCommentTime(qName);
} else if (qName.equals("rtept")) {
currentState = states.pop();
currentRoute.routePoints.add(currentWayPoint);
} else if (qName.equals("trkpt")) {
currentState = states.pop();
currentTrackSeg.add(currentWayPoint);
} else if (qName.equals("wpt")) {
currentState = states.pop();
currentData.waypoints.add(currentWayPoint);
}
break;
case trkseg:
if (qName.equals("trkseg")) {
currentState = states.pop();
currentTrack.trackSegs.add(currentTrackSeg);
}
break;
case trk:
if (qName.equals("trk")) {
currentState = states.pop();
currentData.tracks.add(currentTrack);
} else if (qName.equals("name") || qName.equals("cmt")
|| qName.equals("desc") || qName.equals("src")
|| qName.equals("type") || qName.equals("number")) {
currentTrack.attr.put(qName, accumulator.toString());
}
break;
case ext:
if (qName.equals("extensions")) {
currentState = states.pop();
}
break;
default:
if (qName.equals("wpt")) {
currentState = states.pop();
} else if (qName.equals("rte")) {
currentState = states.pop();
currentData.routes.add(currentRoute);
}
}
}
|
diff --git a/src/main/java/eu/vilaca/keystore/Database.java b/src/main/java/eu/vilaca/keystore/Database.java
index 04843b3..4e13b55 100644
--- a/src/main/java/eu/vilaca/keystore/Database.java
+++ b/src/main/java/eu/vilaca/keystore/Database.java
@@ -1,229 +1,226 @@
/**
*
*/
package eu.vilaca.keystore;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author vilaca
*
*/
public class Database {
static final Logger logger = LogManager.getLogger(Database.class.getName());
// TODO make this a singleton to avoid statics?
// hash map to URL
// TODO can be optimized, only one MAP is needed
final static Map<HashKey, String> hash2Url = new HashMap<HashKey, String>();
final static Map<String, HashKey> url2Hash = new HashMap<String, HashKey>();
static BufferedWriter resumeLog;
/**
* private c'tor to forbid instantiation
*/
private Database() {
}
public static void start(String folder) throws IOException {
// fix database path
if (folder == null) {
// default to base directory
folder = "";
} else if (!folder.endsWith(System.getProperty("file.separator"))) {
folder += System.getProperty("file.separator");
}
logger.trace("Resuming from folder: " + folder);
// get all files sorted
final File[] files = new File(folder).listFiles();
final int next;
if (files != null && files.length > 0) {
logger.trace("Found " + files.length + " old files.");
// read old data
readSerializedData(files);
// get most recent file ( last in array )
Arrays.sort(files);
final File latest = files[files.length - 1];
next = Integer.parseInt(latest.getName()) + 1;
} else {
next = 0;
}
final String filename = folder + String.format("%05d", next);
logger.info("Next (resume) file: " + filename);
resumeLog = new BufferedWriter(new FileWriter(filename));
}
public static void stop() throws IOException {
logger.trace("Stopping database.");
resumeLog.flush();
resumeLog.close();
}
/**
* @param files
*/
private static void readSerializedData(final File[] files) {
// load all data from each file
for (final File file : files) {
try (final FileReader fr = new FileReader(file.getAbsolutePath());
final BufferedReader br = new BufferedReader(fr);) {
logger.trace("Reading from Resume file: " + file.getName());
// read all lines in file
String line = br.readLine();
while (line != null) {
// fields are comma separated [hashkey,url]
final String fields[] = line.split(",");
final HashKey hk = new HashKey(fields[0].getBytes());
final String url = fields[1];
// store data
hash2Url.put(hk, url);
url2Hash.put(url, hk);
line = br.readLine();
}
} catch (IOException e) {
logger.error("Error reading: " + file.getAbsolutePath());
}
}
}
public static byte[] add(String url) {
// trim whitespace
url = url.trim();
// only continue if its a valid Url
if (!new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
return null;
}
// normalize Url ending
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
// remove http:// but keep https://
if (url.startsWith("http://")) {
url = url.substring("http://".length());
}
// lookup database to see if URL is already there
HashKey base64hash = url2Hash.get(url);
if (base64hash != null) {
return base64hash.getBytes();
}
// TODO check granularity, may add a random value to avoid too many
// repeats in case of hash collision
int tries = 0;
HashKey hk;
do {
tries++;
if (tries > 10) {
// give up
logger.warn("Giving up rehashing " + url);
return null;
} else if (tries > 1) {
logger.warn("Rehashing " + url + " / " + tries + "try.");
}
- // create a base64 hash based on system timer
- final long ticks = hash2Url.hashCode() ^ System.currentTimeMillis()
- * url2Hash.hashCode();
- hk = new HashKey(ticks * tries);
+ hk = new HashKey();
// loop if hash already being used
} while (hash2Url.containsKey(hk));
hash2Url.put(hk, url);
url2Hash.put(url, hk);
try {
resumeLog.write(hk.toString() + "," + url
+ System.getProperty("line.separator"));
resumeLog.flush();
} catch (IOException e) {
logger.error("Could not write to the resume log :(");
hash2Url.remove(hk);
url2Hash.remove(url);
return null;
}
return hk.getBytes();
}
public static String get(final HashKey key) {
final String url = hash2Url.get(key);
if (url == null) {
return null;
}
if (url.startsWith("http")) {
return url;
}
return "http://" + url;
}
}
| true | true | public static byte[] add(String url) {
// trim whitespace
url = url.trim();
// only continue if its a valid Url
if (!new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
return null;
}
// normalize Url ending
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
// remove http:// but keep https://
if (url.startsWith("http://")) {
url = url.substring("http://".length());
}
// lookup database to see if URL is already there
HashKey base64hash = url2Hash.get(url);
if (base64hash != null) {
return base64hash.getBytes();
}
// TODO check granularity, may add a random value to avoid too many
// repeats in case of hash collision
int tries = 0;
HashKey hk;
do {
tries++;
if (tries > 10) {
// give up
logger.warn("Giving up rehashing " + url);
return null;
} else if (tries > 1) {
logger.warn("Rehashing " + url + " / " + tries + "try.");
}
// create a base64 hash based on system timer
final long ticks = hash2Url.hashCode() ^ System.currentTimeMillis()
* url2Hash.hashCode();
hk = new HashKey(ticks * tries);
// loop if hash already being used
} while (hash2Url.containsKey(hk));
hash2Url.put(hk, url);
url2Hash.put(url, hk);
try {
resumeLog.write(hk.toString() + "," + url
+ System.getProperty("line.separator"));
resumeLog.flush();
} catch (IOException e) {
logger.error("Could not write to the resume log :(");
hash2Url.remove(hk);
url2Hash.remove(url);
return null;
}
return hk.getBytes();
}
| public static byte[] add(String url) {
// trim whitespace
url = url.trim();
// only continue if its a valid Url
if (!new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
return null;
}
// normalize Url ending
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
// remove http:// but keep https://
if (url.startsWith("http://")) {
url = url.substring("http://".length());
}
// lookup database to see if URL is already there
HashKey base64hash = url2Hash.get(url);
if (base64hash != null) {
return base64hash.getBytes();
}
// TODO check granularity, may add a random value to avoid too many
// repeats in case of hash collision
int tries = 0;
HashKey hk;
do {
tries++;
if (tries > 10) {
// give up
logger.warn("Giving up rehashing " + url);
return null;
} else if (tries > 1) {
logger.warn("Rehashing " + url + " / " + tries + "try.");
}
hk = new HashKey();
// loop if hash already being used
} while (hash2Url.containsKey(hk));
hash2Url.put(hk, url);
url2Hash.put(url, hk);
try {
resumeLog.write(hk.toString() + "," + url
+ System.getProperty("line.separator"));
resumeLog.flush();
} catch (IOException e) {
logger.error("Could not write to the resume log :(");
hash2Url.remove(hk);
url2Hash.remove(url);
return null;
}
return hk.getBytes();
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/plot2/BasicTicker.java b/ttools/src/main/uk/ac/starlink/ttools/plot2/BasicTicker.java
index f7dc62a9e..8dd20db1d 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/plot2/BasicTicker.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/plot2/BasicTicker.java
@@ -1,800 +1,797 @@
package uk.ac.starlink.ttools.plot2;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Partial Ticker implementation based on a rule defining a sequence of ticks.
* Concrete subclasses must implement a method to create a Rule
* suitable for a given range, and this is used to provide suitable
* ticks for particular circumstances, including avoiding label overlap.
*
* @author Mark Taylor
* @since 17 Oct 2013
*/
public abstract class BasicTicker implements Ticker {
private final boolean logFlag_;
/** Ticker for linear axes. */
public static final BasicTicker LINEAR = new BasicTicker( false ) {
public Rule createRule( double dlo, double dhi,
double approxMajorCount, int adjust ) {
return new CheckRule( createRawRule( dlo, dhi, approxMajorCount,
adjust, false ) ) {
boolean checkLabel( String label, double value ) {
return Math.abs( Double.parseDouble( label ) - value )
< 1e-10;
}
};
}
};
/** Ticker for logarithmic axes. */
public static final BasicTicker LOG = new BasicTicker( true ) {
public Rule createRule( double dlo, double dhi,
double approxMajorCount, int adjust ) {
if ( dlo <= 0 || dhi <= 0 ) {
throw new IllegalArgumentException( "Negative log range?" );
}
return new CheckRule( createRawRule( dlo, dhi, approxMajorCount,
adjust, true ) ) {
boolean checkLabel( String label, double value ) {
return Math.abs( Double.parseDouble( label ) / value - 1 )
< 1e-10;
}
};
}
};
/**
* Constructor.
*
* @param logFlag true for logarithmic axis, false for linear
*/
protected BasicTicker( boolean logFlag ) {
logFlag_ = logFlag;
}
/**
* Returns a new rule for labelling an axis in a given range.
* The tick density is determined by two parameters,
* <code>approxMajorCount</code>, which gives a baseline value for
* the number of ticks required over the given range, and
* <code>adjust</code>.
* Increasing <code>adjust</code> will give more major ticks, and
* decreasing it will give fewer ticks.
* Each value of adjust should result in a different tick count.
*
* @param dlo minimum axis data value
* @param dhi maximum axis data value
* @param approxMajorCount guide value for number of major ticks
* in range
* @param adjust adjusts density of major ticks, zero is normal
*/
public abstract Rule createRule( double dlo, double dhi,
double approxMajorCount, int adjust );
public Tick[] getTicks( double dlo, double dhi, boolean withMinor,
Captioner captioner, Orientation orient, int npix,
double crowding ) {
Rule rule = getRule( dlo, dhi, captioner, orient, npix, crowding );
return withMinor
? PlotUtil.arrayConcat( getMajorTicks( rule, dlo, dhi ),
getMinorTicks( rule, dlo, dhi ) )
: getMajorTicks( rule, dlo, dhi );
}
/**
* Returns a Rule suitable for a given axis labelling job.
* This starts off by generating ticks at roughly a standard separation,
* guided by the crowding parameter. However, if the resulting ticks
* are so close as to overlap, it backs off until it finds a set of
* ticks that can be displayed in a tidy fashion.
*
* @param dlo minimum axis data value
* @param dhi maximum axis data value
* @param captioner caption painter
* @param orient label orientation
* @param npix number of pixels along the axis
* @param crowding 1 for normal tick density on the axis,
* lower for fewer labels, higher for more
* @return basic tick generation rule
*/
public Rule getRule( double dlo, double dhi,
Captioner captioner, Orientation orient,
int npix, double crowding ) {
if ( dhi <= dlo ) {
throw new IllegalArgumentException( "Bad range: "
+ dlo + " .. " + dhi );
}
/* Work out approximately how many major ticks are requested. */
double approxMajorCount = Math.max( 1, npix / 80 ) * crowding;
/* Acquire a suitable rule and use it to generate the major ticks.
* When we have the ticks, check that they are not so crowded as
* to generate overlapping tick labels. If they are, back off
* to lower tick crowding levels until we have something suitable. */
Axis axis = Axis.createAxis( 0, npix, dlo, dhi, logFlag_, false );
int adjust = 0;
Rule rule;
Tick[] majors;
do {
rule = createRule( dlo, dhi, approxMajorCount, adjust );
majors = getMajorTicks( rule, dlo, dhi );
} while ( overlaps( majors, axis, captioner, orient )
&& adjust-- > -5 );
return rule;
}
/**
* Use a given rule to generate major ticks in a given range of
* coordinates.
*
* @param rule tick generation rule
* @param dlo minimum axis data value
* @param dhi maximum axis data value
* @return array of major ticks
*/
public static Tick[] getMajorTicks( Rule rule, double dlo, double dhi ) {
List<Tick> list = new ArrayList<Tick>();
for ( long index = rule.floorIndex( dlo );
rule.indexToValue( index ) <= dhi; index++ ) {
double major = rule.indexToValue( index );
if ( major >= dlo && major <= dhi ) {
String label = rule.indexToLabel( index );
list.add( new Tick( major, label ) );
}
}
return list.toArray( new Tick[ 0 ] );
}
/**
* Use a given rule to generate minor ticks in a given range of
* coordinates.
*
* @param rule tick generation rule
* @param dlo minimum axis data value
* @param dhi maximum axis data value
* @return array of minor ticks
*/
public static Tick[] getMinorTicks( Rule rule, double dlo, double dhi ) {
List<Tick> list = new ArrayList<Tick>();
for ( long index = rule.floorIndex( dlo );
rule.indexToValue( index ) <= dhi; index++ ) {
double[] minors = rule.getMinors( index );
for ( int imin = 0; imin < minors.length; imin++ ) {
double minor = minors[ imin ];
if ( minor >= dlo && minor <= dhi ) {
list.add( new Tick( minor ) );
}
}
}
return list.toArray( new Tick[ 0 ] );
}
/**
* Acquire a rule for labelling a linear or logarithmic axis.
* The tick density is determined by two parameters,
* <code>approxMajorCount</code>, which gives a baseline value for
* the number of ticks required over the given range, and
* <code>adjust</code>.
* Increasing <code>adjust</code> will give more major ticks, and
* decreasing it will give fewer ticks.
*
* @param dlo minimum axis data value
* @param dhi maximum axis data value
* @param approxMajorCount guide value for number of major ticks
* in range
* @param adjust adjusts density of major ticks
* @param log true for logarithmic, false for linear
* @return tick generation rule
*/
private static Rule createRawRule( double dlo, double dhi,
double approxMajorCount, int adjust,
final boolean log ) {
/* Use specifically logarithmic labelling only if the axes are
* logarithmic and the range is greater than a factor of ten. */
if ( log && Math.log10( dhi / dlo ) > 1 ) {
double approxMajorFactor =
Math.pow( dhi / dlo, 1. / approxMajorCount );
LogSpacer[] spacers = LogSpacer.SPACERS;
assert spacers.length == 2;
/* Work out how many decades a single major tick interval covers. */
double nDecade = Math.log10( approxMajorFactor );
int iSpacer;
/* If it's more than about 1, ticks will all be 10**n. */
if ( nDecade >= 1 ) {
iSpacer = - (int) nDecade;
}
/* Otherwise use a log rule with custom spacing. */
else if ( nDecade >= 0.5 ) {
iSpacer = 0;
}
else if ( nDecade >= 0.2 ) {
iSpacer = 1;
}
else {
iSpacer = 2;
}
/* Apply adjustment. */
iSpacer += adjust;
/* If a log rule is indicated, return it here. */
if ( iSpacer < 0 ) {
return new DecadeLogRule( -iSpacer );
}
else if ( iSpacer < 2 ) {
return new SpacerLogRule( spacers[ iSpacer ] );
}
/* Otherwise fall back to linear tick marks. This is probably
* more dense, though it might not work well for large ranges.
* Won't happen often though. */
}
/* Linear tick marks. */
double approxMajorInterval = ( dhi - dlo ) / approxMajorCount;
int exp = (int) Math.floor( Math.log10( approxMajorInterval ) );
double oversize = approxMajorInterval / exp10( exp );
assert oversize >= 1 && oversize < 10;
final int maxLevel = LinearSpacer.SPACERS.length;
int num = exp * maxLevel
+ LinearSpacer.getSpacerIndex( oversize ) - adjust;
int[] div = divFloor( num, maxLevel );
return new LinearRule( div[ 0 ], LinearSpacer.SPACERS[ div[ 1 ] ] );
}
/**
* Generates a major tick mark label suitable for use with linear axes.
* Some care is required assembling the label, to make sure we
* avoid rounding issues (like 0.999999999999).
* Double.toString() is not good enough.
*
* @param mantissa multiplier
* @param exp power of 10
* @return tick label text
*/
private static String linearLabel( long mantissa, int exp ) {
boolean minus = mantissa < 0;
String sign = minus ? "-" : "";
String digits = Long.toString( minus ? -mantissa : mantissa );
int ndigit = digits.length();
int sciLimit = 3;
if ( mantissa == 0 ) {
return "0";
}
else if ( exp >= 0 && exp <= sciLimit ) {
return new StringBuffer()
.append( sign )
.append( digits )
.append( zeros( exp ) )
.toString();
}
else if ( exp < 0 && exp >= -sciLimit ) {
int pointPos = ndigit + exp;
if ( pointPos <= 0 ) {
return new StringBuffer()
.append( sign )
.append( "0." )
.append( zeros( -pointPos ) )
.append( digits )
.toString();
}
else {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.substring( 0, pointPos ) );
if ( pointPos < ndigit ) {
sbuf.append( "." )
.append( digits.substring( pointPos ) );
}
return sbuf.toString();
}
}
else if ( exp > sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.charAt( 0 ) );
int postDigit = ndigit - 1;
if ( postDigit > 0 ) {
sbuf.append( "." )
.append( digits.substring( 1 ) );
}
int pexp = exp + postDigit;
if ( pexp > sciLimit ) {
sbuf.append( "e" )
.append( Integer.toString( pexp ) );
}
else {
sbuf.append( zeros( pexp ) );
}
return sbuf.toString();
}
else if ( exp < -sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign );
int pexp = exp + ndigit;
- if ( pexp == 0 ) {
- sbuf.append( digits );
- }
- else if ( pexp > 0 ) {
+ if ( pexp > 0 ) {
sbuf.append( digits.substring( 0, pexp ) )
.append( "." )
.append( digits.substring( pexp ) );
}
- else if ( pexp < 0 && pexp >= -sciLimit ) {
+ else if ( pexp <= 0 && pexp >= -sciLimit ) {
sbuf.append( "0." )
.append( zeros( -pexp ) )
.append( digits );
}
else if ( pexp < -sciLimit ) {
sbuf.append( digits.charAt( 0 ) )
.append( "." )
.append( digits.substring( 1 ) )
.append( "e" )
.append( Integer.toString( pexp - 1 ) );
}
else {
assert false;
sbuf.append( "??" );
}
return sbuf.toString();
}
else {
assert false;
return "??";
}
}
/**
* Generates a major tick mark label suitable for use with logarithmic axes.
*
* @param mantissa multiplier in range 1-9 (inclusive)
* @param exponent power of 10
* @return tick label text
*/
private static String logLabel( long mantissa, int exponent ) {
assert mantissa > 0 && mantissa < 10;
double value = mantissa * exp10( exponent );
/* Some care is required assembling the label, to make sure we
* avoid rounding issues (like 0.999999999999).
* Double.toString() is not good enough. */
String smantissa = Long.toString( mantissa );
if ( exponent == 0 ) {
return smantissa;
}
else if ( exponent > -4 && exponent < 0 ) {
return "0." + zeros( - exponent - 1 ) + smantissa;
}
else if ( exponent < 4 && exponent > 0 ) {
return smantissa + zeros( exponent );
}
else {
return smantissa + "e" + exponent;
}
}
/**
* Determines whether the labels for a set of tick marks
* would overlap when painted on a given axis.
*
* @param ticks major tick marks
* @param axis axis on which the ticks will be drawn
* @param captioner caption painter
* @param orient label orientation
* @return true iff some of the ticks are so close to each other that
* their labels will overlap
*/
public static boolean overlaps( Tick[] ticks, Axis axis,
Captioner captioner, Orientation orient ) {
int cpad = captioner.getPad();
Rectangle lastBox = null;
for ( int i = 0; i < ticks.length; i++ ) {
Tick tick = ticks[ i ];
String label = tick.getLabel();
if ( label != null ) {
int gx = axis.dataToGraphics( tick.getValue() );
Rectangle cbounds = captioner.getCaptionBounds( label );
AffineTransform oTrans =
orient.captionTransform( cbounds, cpad );
Rectangle box =
oTrans.createTransformedShape( cbounds ).getBounds();
box.translate( gx, 0 );
box.width += cpad;
if ( lastBox != null && box.intersects( lastBox ) ) {
return true;
}
lastBox = box;
}
}
return false;
}
/**
* Integer division with remainder which rounds towards minus infinity.
* This is unlike the <code>/</code> operator which rounds towards zero.
*
* @param numerator value to divide
* @param divisor value to divide by
* @return 2-element array: (result of integer division rounded down,
* positive remainder)
*/
private static int[] divFloor( int numerator, int divisor ) {
int whole = numerator / divisor;
int part = numerator % divisor;
if ( part < 0 ) {
part += divisor;
whole -= 1;
}
assert whole * divisor + part == numerator;
return new int[] { whole, part };
}
/**
* Power of ten.
*
* @param exp exponent
* @return <code>pow(10,exp)</code>
*/
private static double exp10( int exp ) {
return Math.pow( 10, exp );
}
/**
* Returns a string which is a given number of zeros.
*
* @param n number of zeros
* @return zero-filled string of length <code>n</code>
*/
private static String zeros( int n ) {
StringBuffer sbuf = new StringBuffer( n );
for ( int i = 0; i < n; i++ ) {
sbuf.append( '0' );
}
return sbuf.toString();
}
/**
* Defines a specific rule for generating major and minor axis tick marks.
* The major tick marks defined by this rule are labelled by a
* contiguous sequence of long integer indices, which increase in the
* direction of axis value increase.
*/
public interface Rule {
/**
* Returns the largest major tick mark index value that identifies
* an axis value less than or equal to a supplied axis value.
*
* @param value axis reference value
* @return major tick index for an axis point equal to
* or just less than <code>value</code>
*/
long floorIndex( double value );
/**
* Returns the axis values for minor tickmarks that fall between the
* a given major tick mark and the next one.
*
* @param index major tick mark index
* @return minor tick mark axis values between the axis values
* for major ticks <code>index</code> and <code>index+1</code>
*/
double[] getMinors( long index );
/**
* Returns the axis value identified by a given major tick mark index.
*
* @param index major tick index
* @return axis value for major tick
*/
double indexToValue( long index );
/**
* Returns a text string to label the major tick identified by
* a given index.
*
* @param index major tick index
* @return label string for major tick
*/
String indexToLabel( long index );
}
/**
* Defines how to split up an interval of approximately unit extent
* into major and minor divisions of equal linear size.
*/
private static class LinearSpacer {
private final double thresh_;
private final int major_;
private final double[] minors_;
/** Known instances, in order. */
public static final LinearSpacer[] SPACERS = new LinearSpacer[] {
new LinearSpacer( 2.5, 1, 0.1 ),
new LinearSpacer( 4.5, 2, 0.25 ),
new LinearSpacer( 7.5, 5, 1 ),
};
/**
* Constructor.
*
* @param oversizeThresh selection threshold, in range 1..10
* @param major interval between major ticks
* @param minor interval between minor ticks
*/
LinearSpacer( double oversizeThresh, int major, double minor ) {
thresh_ = oversizeThresh;
major_ = major;
int nminor = (int) Math.round( major / minor );
minors_ = new double[ nminor - 1 ];
for ( int i = 1; i < nminor; i++ ) {
minors_[ i - 1 ] = minor * i;
}
}
/**
* Returns the index into SPACERS of the spacer appropriate
* for a given oversize value.
*
* @param oversize factor by which ten is too large for the
* major tick interval; in range 1..10
* @return index into SPACERS, or SPACERS.length if too big
*/
public static int getSpacerIndex( double oversize ) {
for ( int i = 0; i < SPACERS.length; i++ ) {
if ( oversize <= SPACERS[ i ].thresh_ ) {
return i;
}
}
return SPACERS.length;
}
}
/**
* Defines how to split up an interval of approximately a factor of 10
* into major an minor divisions of approximately equal logarithmic size.
*/
private static class LogSpacer {
private final int[] majors_;
private final double[][] minors_;
/** Known instances, in order. */
public static final LogSpacer[] SPACERS = new LogSpacer[] {
new LogSpacer( new int[] { 1, 2, 5, },
new double[][] { { 1.1, 1.2, 1.3, 1.4, 1.5, },
{ 2.5, 3.0, 3.5, 4.0, 4.5, },
{ 6.0, 7.0, 8.0, 9.0, }, } ),
new LogSpacer( new int[] { 1, 2, 3, 4, 5 },
new double[][] { { 1.2, 1.4, 1.6, 1.8, },
{ 2.2, 2.4, 2.6, 2.8, },
{ 3.2, 3.4, 3.6, 3.8, },
{ 4.2, 4.4, 4.6, 4.8, },
{ 6.0, 7.0, 8.0, 9.0, }, } ),
};
/**
* Constructor.
*
* @param major tick marks between 1 and 10
* @param minors array for each major of minor tick marks
*/
public LogSpacer( int[] majors, double[][] minors ) {
majors_ = majors;
minors_ = minors;
}
}
/**
* Rule instance that works with a LinearSpacer.
*/
private static class LinearRule implements Rule {
private final int exp_;
private final LinearSpacer spacer_;
private final double mult_;
/**
* Constructor.
*
* @param log to base 10 of multiplication factor
* @param spacer splits up a decade into round intervals
*/
LinearRule( int exp, LinearSpacer spacer ) {
exp_ = exp;
spacer_ = spacer;
mult_ = exp10( exp ) * spacer.major_;
}
public long floorIndex( double value ) {
return (long) Math.floor( value / mult_ );
}
public double indexToValue( long index ) {
return index * mult_;
}
public double[] getMinors( long index ) {
double major = indexToValue( index );
double[] minors = new double[ spacer_.minors_.length ];
for ( int i = 0; i < minors.length; i++ ) {
minors[ i ] = major + exp10( exp_ ) * spacer_.minors_[ i ];
}
return minors;
}
public String indexToLabel( long index ) {
long mantissa = index * spacer_.major_;
return linearLabel( mantissa, exp_ );
}
}
/**
* Rule instance for logarithmic intervals in which each major tick
* represents one or more decades.
*/
private static class DecadeLogRule implements Rule {
private final int nDecade_;
private final double[] minors_;
/**
* Constructor.
*
* @param nDecade number of decades per major tick
*/
public DecadeLogRule( int nDecade ) {
nDecade_ = nDecade;
if ( nDecade == 1 ) {
minors_ = new double[] { 2, 3, 4, 5, 6, 7, 8, 9 };
}
else if ( nDecade == 2 ) {
minors_ = new double[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, };
}
else if ( nDecade <= 10 ) {
minors_ = new double[ nDecade_ - 1 ];
for ( int i = 1; i < nDecade_; i++ ) {
minors_[ i - 1 ] = exp10( i );
}
}
else {
// no minor ticks; for these very large factors I should
// really restrict nDecade to some multiple of a
// round number N and put minor ticks every N decades.
minors_ = new double[ 0 ];
}
}
public long floorIndex( double value ) {
return (long) Math.floor( Math.log10( value ) / nDecade_ );
}
public double indexToValue( long index ) {
return exp10( (int) index * nDecade_ );
}
public double[] getMinors( long index ) {
double[] minors = new double[ minors_.length ];
double major = indexToValue( index );
for ( int i = 0; i < minors.length; i++ ) {
minors[ i ] = major * minors_[ i ];
}
return minors;
}
public String indexToLabel( long index ) {
return logLabel( 1, (int) index * nDecade_ );
}
}
/**
* Rule instance that works with a LogSpacer.
*/
private static class SpacerLogRule implements Rule {
private final int[] majors_;
private final double[][] minors_;
/**
* Constructor.
*
* @param spacer splits up a decade into round intervals
*/
public SpacerLogRule( LogSpacer spacer ) {
majors_ = spacer.majors_;
minors_ = spacer.minors_;
}
public long floorIndex( double value ) {
int expFloor = (int) Math.floor( Math.log10( value ) );
double mult = value / exp10( expFloor );
int ik = 0;
for ( int i = 0; i < majors_.length; i++ ) {
if ( mult >= majors_[ i ] ) {
ik = i;
}
}
return expFloor * majors_.length + ik;
}
public double indexToValue( long index ) {
int[] div = divFloor( (int) index, majors_.length );
int exp = div[ 0 ];
int ik = div[ 1 ];
return majors_[ ik ] * exp10( exp );
}
public double[] getMinors( long index ) {
int[] div = divFloor( (int) index, majors_.length );
int exp = div[ 0 ];
int ik = div[ 1 ];
double base = exp10( exp );
double[] kminors = minors_[ ik ];
double[] minors = new double[ kminors.length ];
for ( int i = 0; i < kminors.length; i++ ) {
minors[ i ] = base * kminors[ i ];
}
return minors;
}
public String indexToLabel( long index ) {
int[] div = divFloor( (int) index, majors_.length );
int exp = div[ 0 ];
int ik = div[ 1 ];
return logLabel( majors_[ ik ], exp );
}
}
/**
* Decorates a rule with assertions.
* It's easy to get the tick mark labelling wrong, and easy not
* to notice it if it happens, so this check is worth doing.
*/
private static abstract class CheckRule implements Rule {
private final Rule base_;
/**
* Constructor.
*
* @param base rule instance to be decorated
*/
CheckRule( Rule base ) {
base_ = base;
}
/**
* Tests whether the label text matches the value.
*
* @param label major tick label text
* @param value major tick value
* @return true iff the label correctly represents the value
*/
abstract boolean checkLabel( String label, double value );
public String indexToLabel( long index ) {
String label = base_.indexToLabel( index );
assert checkLabel( label, base_.indexToValue( index ) )
: '"' + label + '"' + " != " + base_.indexToValue( index );
return label;
}
public long floorIndex( double value ) {
return base_.floorIndex( value );
}
public double[] getMinors( long index ) {
return base_.getMinors( index );
}
public double indexToValue( long index ) {
return base_.indexToValue( index );
}
}
}
| false | true | private static String linearLabel( long mantissa, int exp ) {
boolean minus = mantissa < 0;
String sign = minus ? "-" : "";
String digits = Long.toString( minus ? -mantissa : mantissa );
int ndigit = digits.length();
int sciLimit = 3;
if ( mantissa == 0 ) {
return "0";
}
else if ( exp >= 0 && exp <= sciLimit ) {
return new StringBuffer()
.append( sign )
.append( digits )
.append( zeros( exp ) )
.toString();
}
else if ( exp < 0 && exp >= -sciLimit ) {
int pointPos = ndigit + exp;
if ( pointPos <= 0 ) {
return new StringBuffer()
.append( sign )
.append( "0." )
.append( zeros( -pointPos ) )
.append( digits )
.toString();
}
else {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.substring( 0, pointPos ) );
if ( pointPos < ndigit ) {
sbuf.append( "." )
.append( digits.substring( pointPos ) );
}
return sbuf.toString();
}
}
else if ( exp > sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.charAt( 0 ) );
int postDigit = ndigit - 1;
if ( postDigit > 0 ) {
sbuf.append( "." )
.append( digits.substring( 1 ) );
}
int pexp = exp + postDigit;
if ( pexp > sciLimit ) {
sbuf.append( "e" )
.append( Integer.toString( pexp ) );
}
else {
sbuf.append( zeros( pexp ) );
}
return sbuf.toString();
}
else if ( exp < -sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign );
int pexp = exp + ndigit;
if ( pexp == 0 ) {
sbuf.append( digits );
}
else if ( pexp > 0 ) {
sbuf.append( digits.substring( 0, pexp ) )
.append( "." )
.append( digits.substring( pexp ) );
}
else if ( pexp < 0 && pexp >= -sciLimit ) {
sbuf.append( "0." )
.append( zeros( -pexp ) )
.append( digits );
}
else if ( pexp < -sciLimit ) {
sbuf.append( digits.charAt( 0 ) )
.append( "." )
.append( digits.substring( 1 ) )
.append( "e" )
.append( Integer.toString( pexp - 1 ) );
}
else {
assert false;
sbuf.append( "??" );
}
return sbuf.toString();
}
else {
assert false;
return "??";
}
}
| private static String linearLabel( long mantissa, int exp ) {
boolean minus = mantissa < 0;
String sign = minus ? "-" : "";
String digits = Long.toString( minus ? -mantissa : mantissa );
int ndigit = digits.length();
int sciLimit = 3;
if ( mantissa == 0 ) {
return "0";
}
else if ( exp >= 0 && exp <= sciLimit ) {
return new StringBuffer()
.append( sign )
.append( digits )
.append( zeros( exp ) )
.toString();
}
else if ( exp < 0 && exp >= -sciLimit ) {
int pointPos = ndigit + exp;
if ( pointPos <= 0 ) {
return new StringBuffer()
.append( sign )
.append( "0." )
.append( zeros( -pointPos ) )
.append( digits )
.toString();
}
else {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.substring( 0, pointPos ) );
if ( pointPos < ndigit ) {
sbuf.append( "." )
.append( digits.substring( pointPos ) );
}
return sbuf.toString();
}
}
else if ( exp > sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign )
.append( digits.charAt( 0 ) );
int postDigit = ndigit - 1;
if ( postDigit > 0 ) {
sbuf.append( "." )
.append( digits.substring( 1 ) );
}
int pexp = exp + postDigit;
if ( pexp > sciLimit ) {
sbuf.append( "e" )
.append( Integer.toString( pexp ) );
}
else {
sbuf.append( zeros( pexp ) );
}
return sbuf.toString();
}
else if ( exp < -sciLimit ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( sign );
int pexp = exp + ndigit;
if ( pexp > 0 ) {
sbuf.append( digits.substring( 0, pexp ) )
.append( "." )
.append( digits.substring( pexp ) );
}
else if ( pexp <= 0 && pexp >= -sciLimit ) {
sbuf.append( "0." )
.append( zeros( -pexp ) )
.append( digits );
}
else if ( pexp < -sciLimit ) {
sbuf.append( digits.charAt( 0 ) )
.append( "." )
.append( digits.substring( 1 ) )
.append( "e" )
.append( Integer.toString( pexp - 1 ) );
}
else {
assert false;
sbuf.append( "??" );
}
return sbuf.toString();
}
else {
assert false;
return "??";
}
}
|
diff --git a/hedwig-server/src/main/java/org/apache/hedwig/server/persistence/ReadAheadCache.java b/hedwig-server/src/main/java/org/apache/hedwig/server/persistence/ReadAheadCache.java
index 10d22de6..0ee4f1ca 100644
--- a/hedwig-server/src/main/java/org/apache/hedwig/server/persistence/ReadAheadCache.java
+++ b/hedwig-server/src/main/java/org/apache/hedwig/server/persistence/ReadAheadCache.java
@@ -1,865 +1,871 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hedwig.server.persistence;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hedwig.protocol.PubSubProtocol;
import org.apache.hedwig.server.netty.ServerStats;
import org.apache.hedwig.server.stats.HedwigServerStatsLogger;
import org.apache.hedwig.server.stats.ServerStatsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.protobuf.ByteString;
import org.apache.bookkeeper.util.MathUtils;
import org.apache.bookkeeper.util.OrderedSafeExecutor;
import org.apache.bookkeeper.util.SafeRunnable;
import org.apache.hedwig.exceptions.PubSubException;
import org.apache.hedwig.exceptions.PubSubException.ServerNotResponsibleForTopicException;
import org.apache.hedwig.protocol.PubSubProtocol.Message;
import org.apache.hedwig.protocol.PubSubProtocol.MessageSeqId;
import org.apache.hedwig.protoextensions.MessageIdUtils;
import org.apache.hedwig.server.common.ServerConfiguration;
import org.apache.hedwig.server.common.UnexpectedError;
import org.apache.hedwig.server.jmx.HedwigJMXService;
import org.apache.hedwig.server.jmx.HedwigMBeanInfo;
import org.apache.hedwig.server.jmx.HedwigMBeanRegistry;
import org.apache.hedwig.server.persistence.ReadAheadCacheBean;
import org.apache.hedwig.util.Callback;
public class ReadAheadCache implements PersistenceManager, HedwigJMXService {
static Logger logger = LoggerFactory.getLogger(ReadAheadCache.class);
protected interface CacheRequest {
public void performRequest();
}
/**
* The underlying persistence manager that will be used for persistence and
* scanning below the cache
*/
protected PersistenceManagerWithRangeScan realPersistenceManager;
/**
* The structure for the cache
*/
protected ConcurrentMap<CacheKey, CacheValue> cache =
new ConcurrentHashMap<CacheKey, CacheValue>();
/**
* We also want to track the entries in seq-id order so that we can clean up
* entries after the last subscriber
*/
protected ConcurrentMap<ByteString, SortedSet<Long>> orderedIndexOnSeqId =
new ConcurrentHashMap<ByteString, SortedSet<Long>>();
/**
* Partition Cache into Serveral Segments for simplify synchronization.
* Each segment maintains its time index and segment size.
*/
static class CacheSegment {
/**
* We want to keep track of when entries were added in the cache, so that we
* can remove them in a FIFO fashion
*/
protected SortedMap<Long, Set<CacheKey>> timeIndexOfAddition = new TreeMap<Long, Set<CacheKey>>();
/**
* We maintain an estimate of the current size of each cache segment,
* so that the thread know when to evict entries from cache segment.
*/
protected AtomicLong presentSegmentSize = new AtomicLong(0);
}
/**
* We maintain an estimate of the current size of the cache, so that we know
* when to evict entries.
*/
protected AtomicLong presentCacheSize = new AtomicLong(0);
/**
* Num pending requests.
*/
protected AtomicInteger numPendingRequests = new AtomicInteger(0);
/**
* Cache segment for different threads
*/
protected final ThreadLocal<CacheSegment> cacheSegment =
new ThreadLocal<CacheSegment>() {
@Override
protected CacheSegment initialValue() {
return new CacheSegment();
}
};
/**
* One instance of a callback that we will pass to the underlying
* persistence manager when asking it to persist messages
*/
protected PersistCallback persistCallbackInstance = new PersistCallback();
/**
* 2 kinds of exceptions that we will use to signal error from readahead
*/
protected NoSuchSeqIdException noSuchSeqIdExceptionInstance = new NoSuchSeqIdException();
protected ReadAheadException readAheadExceptionInstance = new ReadAheadException();
protected ServerConfiguration cfg;
// Boolean indicating if this thread should continue running. This is used
// when we want to stop the thread during a PubSubServer shutdown.
protected volatile boolean keepRunning = true;
protected final OrderedSafeExecutor cacheWorkers;
protected final int numCacheWorkers;
protected volatile long maxSegmentSize;
protected volatile long cacheEntryTTL;
// JMX Beans
ReadAheadCacheBean jmxCacheBean = null;
/**
* Constructor. Starts the cache maintainer thread
*
* @param realPersistenceManager
*/
public ReadAheadCache(PersistenceManagerWithRangeScan realPersistenceManager, ServerConfiguration cfg) {
this.realPersistenceManager = realPersistenceManager;
this.cfg = cfg;
numCacheWorkers = cfg.getNumReadAheadCacheThreads();
cacheWorkers = new OrderedSafeExecutor(numCacheWorkers);
reloadConf(cfg);
}
/**
* Reload configuration
*
* @param conf
* Server configuration object
*/
protected void reloadConf(ServerConfiguration cfg) {
maxSegmentSize = cfg.getMaximumCacheSize() / numCacheWorkers;
cacheEntryTTL = cfg.getCacheEntryTTL();
}
public ReadAheadCache start() {
return this;
}
/**
* ========================================================================
* Methods of {@link PersistenceManager} that we will pass straight down to
* the real persistence manager.
*/
public long getSeqIdAfterSkipping(ByteString topic, long seqId, int skipAmount) {
return realPersistenceManager.getSeqIdAfterSkipping(topic, seqId, skipAmount);
}
public MessageSeqId getCurrentSeqIdForTopic(ByteString topic) throws ServerNotResponsibleForTopicException {
return realPersistenceManager.getCurrentSeqIdForTopic(topic);
}
/**
* ========================================================================
* Other methods of {@link PersistenceManager} that the cache needs to take
* some action on.
*
* 1. Persist: We pass it through to the real persistence manager but insert
* our callback on the return path
*
*/
public void persistMessage(PersistRequest request) {
// make a new PersistRequest object so that we can insert our own
// callback in the middle. Assign the original request as the context
// for the callback.
PersistRequest newRequest = new PersistRequest(request.getTopic(), request.getMessage(),
persistCallbackInstance, request);
realPersistenceManager.persistMessage(newRequest);
}
/**
* The callback that we insert on the persist request return path. The
* callback simply forms a {@link PersistResponse} object and inserts it in
* the request queue to be handled serially by the cache maintainer thread.
*
*/
public class PersistCallback implements Callback<PubSubProtocol.MessageSeqId> {
/**
* In case there is a failure in persisting, just pass it to the
* original callback
*/
public void operationFailed(Object ctx, PubSubException exception) {
PersistRequest originalRequest = (PersistRequest) ctx;
Callback<PubSubProtocol.MessageSeqId> originalCallback = originalRequest.getCallback();
Object originalContext = originalRequest.getCtx();
originalCallback.operationFailed(originalContext, exception);
}
/**
* When the persist finishes, we first notify the original callback of
* success, and then opportunistically treat the message as if it just
* came in through a scan
*/
public void operationFinished(Object ctx, PubSubProtocol.MessageSeqId resultOfOperation) {
PersistRequest originalRequest = (PersistRequest) ctx;
// Lets call the original callback first so that the publisher can
// hear success
originalRequest.getCallback().operationFinished(originalRequest.getCtx(), resultOfOperation);
// Original message that was persisted didn't have the local seq-id.
// Lets add that in
Message messageWithLocalSeqId = MessageIdUtils.mergeLocalSeqId(originalRequest.getMessage(),
resultOfOperation.getLocalComponent());
// Now enqueue a request to add this newly persisted message to our
// cache
CacheKey cacheKey = new CacheKey(originalRequest.getTopic(), resultOfOperation.getLocalComponent());
enqueueWithoutFailureByTopic(cacheKey.getTopic(),
new ScanResponse(cacheKey, messageWithLocalSeqId));
}
}
protected void enqueueWithoutFailureByTopic(ByteString topic, final CacheRequest obj) {
if (!keepRunning) {
return;
}
try {
numPendingRequests.incrementAndGet();
cacheWorkers.submitOrdered(topic, new SafeRunnable() {
@Override
public void safeRun() {
numPendingRequests.decrementAndGet();
obj.performRequest();
}
});
} catch (RejectedExecutionException ree) {
logger.error("Failed to submit cache request for topic " + topic.toStringUtf8() + " : ", ree);
}
}
/**
* Another method from {@link PersistenceManager}.
*
* 2. Scan - Since the scan needs to touch the cache, we will just enqueue
* the scan request and let the cache maintainer thread handle it.
*/
public void scanSingleMessage(ScanRequest request) {
// Let the scan requests be serialized through the queue
enqueueWithoutFailureByTopic(request.getTopic(),
new ScanRequestWrapper(request));
}
/**
* Another method from {@link PersistenceManager}.
*
* 3. Enqueue the request so that the cache maintainer thread can delete all
* message-ids older than the one specified
*/
public void deliveredUntil(ByteString topic, Long seqId) {
enqueueWithoutFailureByTopic(topic, new DeliveredUntil(topic, seqId));
}
/**
* Another method from {@link PersistenceManager}.
*
* Since this is a cache layer on top of an underlying persistence manager,
* we can just call the consumedUntil method there. The messages older than
* the latest one passed here won't be accessed anymore so they should just
* get aged out of the cache eventually. For now, there is no need to
* proactively remove those entries from the cache.
*/
public void consumedUntil(ByteString topic, Long seqId) {
realPersistenceManager.consumedUntil(topic, seqId);
}
public void setMessageBound(ByteString topic, Integer bound) {
realPersistenceManager.setMessageBound(topic, bound);
}
public void clearMessageBound(ByteString topic) {
realPersistenceManager.clearMessageBound(topic);
}
public void consumeToBound(ByteString topic) {
realPersistenceManager.consumeToBound(topic);
}
/**
* Stop the readahead cache.
*/
public void stop() {
try {
keepRunning = false;
cacheWorkers.shutdown();
} catch (Exception e) {
logger.warn("Failed to shut down cache workers : ", e);
}
}
/**
* The readahead policy is simple: We check if an entry already exists for
* the message being requested. If an entry exists, it means that either
* that message is already in the cache, or a read for that message is
* outstanding. In that case, we look a little ahead (by readAheadCount/2)
* and issue a range read of readAheadCount/2 messages. The idea is to
* ensure that the next readAheadCount messages are always available.
*
* @return the range scan that should be issued for read ahead
*/
protected RangeScanRequest doReadAhead(ScanRequest request) {
ByteString topic = request.getTopic();
Long seqId = request.getStartSeqId();
int readAheadCount = cfg.getReadAheadCount();
// To prevent us from getting screwed by bad configuration
readAheadCount = Math.max(1, readAheadCount);
RangeScanRequest readAheadRequest = doReadAheadStartingFrom(topic, seqId, readAheadCount);
if (readAheadRequest != null) {
return readAheadRequest;
}
// start key was already there in the cache so no readahead happened,
// lets look a little beyond
seqId = realPersistenceManager.getSeqIdAfterSkipping(topic, seqId, readAheadCount / 2);
readAheadRequest = doReadAheadStartingFrom(topic, seqId, readAheadCount / 2);
return readAheadRequest;
}
/**
* This method just checks if the provided seq-id already exists in the
* cache. If not, a range read of the specified amount is issued.
*
* @param topic
* @param seqId
* @param readAheadCount
* @return The range read that should be issued
*/
protected RangeScanRequest doReadAheadStartingFrom(ByteString topic, long seqId, int readAheadCount) {
long startSeqId = seqId;
Queue<CacheKey> installedStubs = new LinkedList<CacheKey>();
int i = 0;
for (; i < readAheadCount; i++) {
CacheKey cacheKey = new CacheKey(topic, seqId);
// Even if a stub exists, it means that a scan for that is
// outstanding
if (cache.containsKey(cacheKey)) {
break;
}
CacheValue cacheValue = new CacheValue();
if (null != cache.putIfAbsent(cacheKey, cacheValue)) {
logger.warn("It is unexpected that more than one threads are adding message to cache key {}"
+" at the same time.", cacheKey);
}
logger.debug("Adding cache stub for: {}", cacheKey);
installedStubs.add(cacheKey);
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHE_STUBS).inc();
seqId = realPersistenceManager.getSeqIdAfterSkipping(topic, seqId, 1);
}
// so how many did we decide to readahead
if (i == 0) {
// no readahead, hence return false
return null;
}
long readAheadSizeLimit = cfg.getReadAheadSizeBytes();
ReadAheadScanCallback callback = new ReadAheadScanCallback(installedStubs, topic);
RangeScanRequest rangeScanRequest = new RangeScanRequest(topic, startSeqId, i, readAheadSizeLimit, callback,
null);
return rangeScanRequest;
}
/**
* This is the callback that is used for the range scans.
*/
protected class ReadAheadScanCallback implements ScanCallback {
Queue<CacheKey> installedStubs;
ByteString topic;
/**
* Constructor
*
* @param installedStubs
* The list of stubs that were installed for this range scan
* @param topic
*/
public ReadAheadScanCallback(Queue<CacheKey> installedStubs, ByteString topic) {
this.installedStubs = installedStubs;
this.topic = topic;
}
public void messageScanned(Object ctx, Message message) {
// Any message we read is potentially useful for us, so lets first
// enqueue it
CacheKey cacheKey = new CacheKey(topic, message.getMsgId().getLocalComponent());
enqueueWithoutFailureByTopic(topic, new ScanResponse(cacheKey, message));
// Now lets see if this message is the one we were expecting
CacheKey expectedKey = installedStubs.peek();
if (expectedKey == null) {
// Was not expecting any more messages to come in, but they came
// in so we will keep them
return;
}
if (expectedKey.equals(cacheKey)) {
// what we got is what we expected, dequeue it so we get the
// next expected one
installedStubs.poll();
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHE_STUBS).dec();
return;
}
// If reached here, what we scanned was not what we were expecting.
// This means that we have wrong stubs installed in the cache. We
// should remove them, so that whoever is waiting on them can retry.
// This shouldn't be happening usually
logger.warn("Unexpected message seq-id: " + message.getMsgId().getLocalComponent() + " on topic: "
+ topic.toStringUtf8() + " from readahead scan, was expecting seq-id: " + expectedKey.seqId
+ " topic: " + expectedKey.topic.toStringUtf8() + " installedStubs: " + installedStubs);
enqueueDeleteOfRemainingStubs(noSuchSeqIdExceptionInstance);
}
public void scanFailed(Object ctx, Exception exception) {
enqueueDeleteOfRemainingStubs(exception);
}
public void scanFinished(Object ctx, ReasonForFinish reason) {
// If the scan finished because no more messages are present, its ok
// to leave the stubs in place because they will get filled in as
// new publishes happen. However, if the scan finished due to some
// other reason, e.g., read ahead size limit was reached, we want to
// delete the stubs, so that when the time comes, we can schedule
// another readahead request.
if (reason != ReasonForFinish.NO_MORE_MESSAGES) {
enqueueDeleteOfRemainingStubs(readAheadExceptionInstance);
}
}
private void enqueueDeleteOfRemainingStubs(Exception reason) {
CacheKey installedStub;
while ((installedStub = installedStubs.poll()) != null) {
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHE_STUBS).dec();
enqueueWithoutFailureByTopic(installedStub.getTopic(),
new ExceptionOnCacheKey(installedStub, reason));
}
}
}
protected static class HashSetCacheKeyFactory implements Factory<Set<CacheKey>> {
protected final static HashSetCacheKeyFactory instance = new HashSetCacheKeyFactory();
public Set<CacheKey> newInstance() {
return new HashSet<CacheKey>();
}
}
protected static class TreeSetLongFactory implements Factory<SortedSet<Long>> {
protected final static TreeSetLongFactory instance = new TreeSetLongFactory();
public SortedSet<Long> newInstance() {
return new TreeSet<Long>();
}
}
/**
* For adding the message to the cache, we do some bookeeping such as the
* total size of cache, order in which entries were added etc. If the size
* of the cache has exceeded our budget, old entries are collected.
*
* @param cacheKey
* @param message
*/
protected void addMessageToCache(final CacheKey cacheKey,
final Message message, final long currTime) {
logger.debug("Adding msg {} to readahead cache", cacheKey);
CacheValue cacheValue;
if ((cacheValue = cache.get(cacheKey)) == null) {
cacheValue = new CacheValue();
CacheValue oldValue = cache.putIfAbsent(cacheKey, cacheValue);
if (null != oldValue) {
logger.warn("Weird! Should not have two threads adding message to cache key {} at the same time.",
cacheKey);
cacheValue = oldValue;
}
+ } else {
+ if (cacheValue.isStub()) {
+ // We are replacing a stub.
+ ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
+ .NUM_CACHE_STUBS).dec();
+ }
}
CacheSegment segment = cacheSegment.get();
int size = message.getBody().size();
// update the cache size
segment.presentSegmentSize.addAndGet(size);
presentCacheSize.addAndGet(size);
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHED_ENTRIES).inc();
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.CACHE_ENTRY_SIZE).add(size);
synchronized (cacheValue) {
// finally add the message to the cache
cacheValue.setMessageAndInvokeCallbacks(message, currTime);
}
// maintain the index of seq-id
// no lock since threads are partitioned by topics
MapMethods.addToMultiMap(orderedIndexOnSeqId, cacheKey.getTopic(),
cacheKey.getSeqId(), TreeSetLongFactory.instance);
// maintain the time index of addition
MapMethods.addToMultiMap(segment.timeIndexOfAddition, currTime,
cacheKey, HashSetCacheKeyFactory.instance);
collectOldOrExpiredCacheEntries(segment);
}
protected void removeMessageFromCache(final CacheKey cacheKey, Exception exception,
final boolean maintainTimeIndex,
final boolean maintainSeqIdIndex) {
CacheValue cacheValue = cache.remove(cacheKey);
if (cacheValue == null) {
return;
}
CacheSegment segment = cacheSegment.get();
long timeOfAddition = 0;
synchronized (cacheValue) {
if (cacheValue.isStub()) {
cacheValue.setErrorAndInvokeCallbacks(exception);
// Stubs are not present in the indexes, so don't need to maintain
// indexes here
return;
}
int size = 0 - cacheValue.getMessage().getBody().size();
presentCacheSize.addAndGet(size);
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHED_ENTRIES).dec();
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.CACHE_ENTRY_SIZE).add(size);
segment.presentSegmentSize.addAndGet(size);
timeOfAddition = cacheValue.getTimeOfAddition();
}
if (maintainSeqIdIndex) {
MapMethods.removeFromMultiMap(orderedIndexOnSeqId, cacheKey.getTopic(),
cacheKey.getSeqId());
}
if (maintainTimeIndex) {
MapMethods.removeFromMultiMap(segment.timeIndexOfAddition,
timeOfAddition, cacheKey);
}
}
/**
* Collection of old entries is simple. Just collect in insert-time order,
* oldest to newest.
*/
protected void collectOldOrExpiredCacheEntries(CacheSegment segment) {
if (cacheEntryTTL > 0) {
// clear expired entries
while (!segment.timeIndexOfAddition.isEmpty()) {
Long earliestTime = segment.timeIndexOfAddition.firstKey();
if (MathUtils.now() - earliestTime < cacheEntryTTL) {
break;
}
collectCacheEntriesAtTimestamp(segment, earliestTime);
}
}
while (segment.presentSegmentSize.get() > maxSegmentSize &&
!segment.timeIndexOfAddition.isEmpty()) {
Long earliestTime = segment.timeIndexOfAddition.firstKey();
collectCacheEntriesAtTimestamp(segment, earliestTime);
}
}
private void collectCacheEntriesAtTimestamp(CacheSegment segment, long timestamp) {
Set<CacheKey> oldCacheEntries = segment.timeIndexOfAddition.get(timestamp);
// Note: only concrete cache entries, and not stubs are in the time
// index. Hence there can be no callbacks pending on these cache
// entries. Hence safe to remove them directly.
for (Iterator<CacheKey> iter = oldCacheEntries.iterator(); iter.hasNext();) {
final CacheKey cacheKey = iter.next();
logger.debug("Removing {} from cache because it's the oldest.", cacheKey);
removeMessageFromCache(cacheKey, readAheadExceptionInstance, //
// maintainTimeIndex=
false,
// maintainSeqIdIndex=
true);
}
segment.timeIndexOfAddition.remove(timestamp);
}
/**
* ========================================================================
* The rest is just simple wrapper classes.
*
*/
protected class ExceptionOnCacheKey implements CacheRequest {
CacheKey cacheKey;
Exception exception;
public ExceptionOnCacheKey(CacheKey cacheKey, Exception exception) {
this.cacheKey = cacheKey;
this.exception = exception;
}
/**
* If for some reason, an outstanding read on a cache stub fails,
* exception for that key is enqueued by the
* {@link ReadAheadScanCallback}. To handle this, we simply send error
* on the callbacks registered for that stub, and delete the entry from
* the cache
*/
public void performRequest() {
removeMessageFromCache(cacheKey, exception,
// maintainTimeIndex=
true,
// maintainSeqIdIndex=
true);
}
}
@SuppressWarnings("serial")
protected static class NoSuchSeqIdException extends Exception {
public NoSuchSeqIdException() {
super("No such seq-id");
}
}
@SuppressWarnings("serial")
protected static class ReadAheadException extends Exception {
public ReadAheadException() {
super("Readahead failed");
}
}
public class CancelScanRequestOp implements CacheRequest {
final CancelScanRequest request;
public CancelScanRequestOp(CancelScanRequest request) {
this.request = request;
}
public void performRequest() {
// cancel scan request
cancelScanRequest(request.getScanRequest());
}
void cancelScanRequest(ScanRequest request) {
if (null == request) {
// nothing to cancel
return;
}
CacheKey cacheKey = new CacheKey(request.getTopic(), request.getStartSeqId());
CacheValue cacheValue = cache.get(cacheKey);
if (null == cacheValue) {
// cache value is evicted
// so it's callback would be called, we don't need to worry about
// cancel it. since it was treated as executed.
return;
}
cacheValue.removeCallback(request.getCallback(), request.getCtx());
}
}
public void cancelScanRequest(ByteString topic, CancelScanRequest request) {
enqueueWithoutFailureByTopic(topic, new CancelScanRequestOp(request));
}
protected class ScanResponse implements CacheRequest {
CacheKey cacheKey;
Message message;
public ScanResponse(CacheKey cacheKey, Message message) {
this.cacheKey = cacheKey;
this.message = message;
}
public void performRequest() {
addMessageToCache(cacheKey, message, MathUtils.now());
}
}
protected class DeliveredUntil implements CacheRequest {
ByteString topic;
Long seqId;
public DeliveredUntil(ByteString topic, Long seqId) {
this.topic = topic;
this.seqId = seqId;
}
public void performRequest() {
SortedSet<Long> orderedSeqIds = orderedIndexOnSeqId.get(topic);
if (orderedSeqIds == null) {
return;
}
// focus on the set of messages with seq-ids <= the one that
// has been delivered until
SortedSet<Long> headSet = orderedSeqIds.headSet(seqId + 1);
for (Iterator<Long> iter = headSet.iterator(); iter.hasNext();) {
Long seqId = iter.next();
CacheKey cacheKey = new CacheKey(topic, seqId);
logger.debug("Removing {} from cache because every subscriber has moved past",
cacheKey);
removeMessageFromCache(cacheKey, readAheadExceptionInstance, //
// maintainTimeIndex=
true,
// maintainSeqIdIndex=
false);
iter.remove();
}
if (orderedSeqIds.isEmpty()) {
orderedIndexOnSeqId.remove(topic);
}
// Let the real persistence manager know of this, too.
realPersistenceManager.deliveredUntil(topic, seqId);
}
}
protected class ScanRequestWrapper implements CacheRequest {
ScanRequest request;
public ScanRequestWrapper(ScanRequest request) {
this.request = request;
}
/**
* To handle a scan request, we first try to do readahead (which might
* cause a range read to be issued to the underlying persistence
* manager). The readahead will put a stub in the cache, if the message
* is not already present in the cache. The scan callback that is part
* of the scan request is added to this stub, and will be called later
* when the message arrives as a result of the range scan issued to the
* underlying persistence manager.
*/
public void performRequest() {
RangeScanRequest readAheadRequest = doReadAhead(request);
// Read ahead must have installed at least a stub for us, so this
// can't be null
CacheKey cacheKey = new CacheKey(request.getTopic(), request.getStartSeqId());
CacheValue cacheValue = cache.get(cacheKey);
if (null == cacheValue) {
logger.error("Cache key {} is removed after installing stub when scanning.", cacheKey);
// reissue the request
scanSingleMessage(request);
return;
}
synchronized (cacheValue) {
// Add our callback to the stub. If the cache value was already a
// concrete message, the callback will be called right away
cacheValue.addCallback(request.getCallback(), request.getCtx());
}
if (readAheadRequest != null) {
realPersistenceManager.scanMessages(readAheadRequest);
}
}
}
@Override
public void registerJMX(HedwigMBeanInfo parent) {
try {
jmxCacheBean = new ReadAheadCacheBean(this);
HedwigMBeanRegistry.getInstance().register(jmxCacheBean, parent);
} catch (Exception e) {
logger.warn("Failed to register readahead cache with JMX", e);
jmxCacheBean = null;
}
}
@Override
public void unregisterJMX() {
try {
if (jmxCacheBean != null) {
HedwigMBeanRegistry.getInstance().unregister(jmxCacheBean);
}
} catch (Exception e) {
logger.warn("Failed to unregister readahead cache with JMX", e);
}
}
}
| true | true | protected void addMessageToCache(final CacheKey cacheKey,
final Message message, final long currTime) {
logger.debug("Adding msg {} to readahead cache", cacheKey);
CacheValue cacheValue;
if ((cacheValue = cache.get(cacheKey)) == null) {
cacheValue = new CacheValue();
CacheValue oldValue = cache.putIfAbsent(cacheKey, cacheValue);
if (null != oldValue) {
logger.warn("Weird! Should not have two threads adding message to cache key {} at the same time.",
cacheKey);
cacheValue = oldValue;
}
}
CacheSegment segment = cacheSegment.get();
int size = message.getBody().size();
// update the cache size
segment.presentSegmentSize.addAndGet(size);
presentCacheSize.addAndGet(size);
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHED_ENTRIES).inc();
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.CACHE_ENTRY_SIZE).add(size);
synchronized (cacheValue) {
// finally add the message to the cache
cacheValue.setMessageAndInvokeCallbacks(message, currTime);
}
// maintain the index of seq-id
// no lock since threads are partitioned by topics
MapMethods.addToMultiMap(orderedIndexOnSeqId, cacheKey.getTopic(),
cacheKey.getSeqId(), TreeSetLongFactory.instance);
// maintain the time index of addition
MapMethods.addToMultiMap(segment.timeIndexOfAddition, currTime,
cacheKey, HashSetCacheKeyFactory.instance);
collectOldOrExpiredCacheEntries(segment);
}
| protected void addMessageToCache(final CacheKey cacheKey,
final Message message, final long currTime) {
logger.debug("Adding msg {} to readahead cache", cacheKey);
CacheValue cacheValue;
if ((cacheValue = cache.get(cacheKey)) == null) {
cacheValue = new CacheValue();
CacheValue oldValue = cache.putIfAbsent(cacheKey, cacheValue);
if (null != oldValue) {
logger.warn("Weird! Should not have two threads adding message to cache key {} at the same time.",
cacheKey);
cacheValue = oldValue;
}
} else {
if (cacheValue.isStub()) {
// We are replacing a stub.
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHE_STUBS).dec();
}
}
CacheSegment segment = cacheSegment.get();
int size = message.getBody().size();
// update the cache size
segment.presentSegmentSize.addAndGet(size);
presentCacheSize.addAndGet(size);
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.NUM_CACHED_ENTRIES).inc();
ServerStatsProvider.getStatsLoggerInstance().getSimpleStatLogger(HedwigServerStatsLogger.HedwigServerSimpleStatType
.CACHE_ENTRY_SIZE).add(size);
synchronized (cacheValue) {
// finally add the message to the cache
cacheValue.setMessageAndInvokeCallbacks(message, currTime);
}
// maintain the index of seq-id
// no lock since threads are partitioned by topics
MapMethods.addToMultiMap(orderedIndexOnSeqId, cacheKey.getTopic(),
cacheKey.getSeqId(), TreeSetLongFactory.instance);
// maintain the time index of addition
MapMethods.addToMultiMap(segment.timeIndexOfAddition, currTime,
cacheKey, HashSetCacheKeyFactory.instance);
collectOldOrExpiredCacheEntries(segment);
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
index b9887ae..43a83fd 100644
--- a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
@@ -1,1320 +1,1326 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import org.mozilla.javascript.*;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaScriptCompressor {
static final ArrayList ones;
static final ArrayList twos;
static final ArrayList threes;
static final Set builtin = new HashSet();
static final Map literals = new Hashtable();
static final Set reserved = new HashSet();
static {
// This list contains all the 3 characters or less built-in global
// symbols available in a browser. Please add to this list if you
// see anything missing.
builtin.add("NaN");
builtin.add("top");
ones = new ArrayList();
for (char c = 'a'; c <= 'z'; c++)
ones.add(Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
ones.add(Character.toString(c));
twos = new ArrayList();
for (int i = 0; i < ones.size(); i++) {
String one = (String) ones.get(i);
for (char c = 'a'; c <= 'z'; c++)
twos.add(one + Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
twos.add(one + Character.toString(c));
for (char c = '0'; c <= '9'; c++)
twos.add(one + Character.toString(c));
}
// Remove two-letter JavaScript reserved words and built-in globals...
twos.remove("as");
twos.remove("is");
twos.remove("do");
twos.remove("if");
twos.remove("in");
twos.removeAll(builtin);
threes = new ArrayList();
for (int i = 0; i < twos.size(); i++) {
String two = (String) twos.get(i);
for (char c = 'a'; c <= 'z'; c++)
threes.add(two + Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
threes.add(two + Character.toString(c));
for (char c = '0'; c <= '9'; c++)
threes.add(two + Character.toString(c));
}
// Remove three-letter JavaScript reserved words and built-in globals...
threes.remove("for");
threes.remove("int");
threes.remove("new");
threes.remove("try");
threes.remove("use");
threes.remove("var");
threes.removeAll(builtin);
// That's up to ((26+26)*(1+(26+26+10)))*(1+(26+26+10))-8
// (206,380 symbols per scope)
// The following list comes from org/mozilla/javascript/Decompiler.java...
literals.put(new Integer(Token.GET), "get ");
literals.put(new Integer(Token.SET), "set ");
literals.put(new Integer(Token.TRUE), "true");
literals.put(new Integer(Token.FALSE), "false");
literals.put(new Integer(Token.NULL), "null");
literals.put(new Integer(Token.THIS), "this");
literals.put(new Integer(Token.FUNCTION), "function");
literals.put(new Integer(Token.COMMA), ",");
literals.put(new Integer(Token.LC), "{");
literals.put(new Integer(Token.RC), "}");
literals.put(new Integer(Token.LP), "(");
literals.put(new Integer(Token.RP), ")");
literals.put(new Integer(Token.LB), "[");
literals.put(new Integer(Token.RB), "]");
literals.put(new Integer(Token.DOT), ".");
literals.put(new Integer(Token.NEW), "new ");
literals.put(new Integer(Token.DELPROP), "delete ");
literals.put(new Integer(Token.IF), "if");
literals.put(new Integer(Token.ELSE), "else");
literals.put(new Integer(Token.FOR), "for");
literals.put(new Integer(Token.IN), " in ");
literals.put(new Integer(Token.WITH), "with");
literals.put(new Integer(Token.WHILE), "while");
literals.put(new Integer(Token.DO), "do");
literals.put(new Integer(Token.TRY), "try");
literals.put(new Integer(Token.CATCH), "catch");
literals.put(new Integer(Token.FINALLY), "finally");
literals.put(new Integer(Token.THROW), "throw");
literals.put(new Integer(Token.SWITCH), "switch");
literals.put(new Integer(Token.BREAK), "break");
literals.put(new Integer(Token.CONTINUE), "continue");
literals.put(new Integer(Token.CASE), "case");
literals.put(new Integer(Token.DEFAULT), "default");
literals.put(new Integer(Token.RETURN), "return");
literals.put(new Integer(Token.VAR), "var ");
literals.put(new Integer(Token.SEMI), ";");
literals.put(new Integer(Token.ASSIGN), "=");
literals.put(new Integer(Token.ASSIGN_ADD), "+=");
literals.put(new Integer(Token.ASSIGN_SUB), "-=");
literals.put(new Integer(Token.ASSIGN_MUL), "*=");
literals.put(new Integer(Token.ASSIGN_DIV), "/=");
literals.put(new Integer(Token.ASSIGN_MOD), "%=");
literals.put(new Integer(Token.ASSIGN_BITOR), "|=");
literals.put(new Integer(Token.ASSIGN_BITXOR), "^=");
literals.put(new Integer(Token.ASSIGN_BITAND), "&=");
literals.put(new Integer(Token.ASSIGN_LSH), "<<=");
literals.put(new Integer(Token.ASSIGN_RSH), ">>=");
literals.put(new Integer(Token.ASSIGN_URSH), ">>>=");
literals.put(new Integer(Token.HOOK), "?");
literals.put(new Integer(Token.OBJECTLIT), ":");
literals.put(new Integer(Token.COLON), ":");
literals.put(new Integer(Token.OR), "||");
literals.put(new Integer(Token.AND), "&&");
literals.put(new Integer(Token.BITOR), "|");
literals.put(new Integer(Token.BITXOR), "^");
literals.put(new Integer(Token.BITAND), "&");
literals.put(new Integer(Token.SHEQ), "===");
literals.put(new Integer(Token.SHNE), "!==");
literals.put(new Integer(Token.EQ), "==");
literals.put(new Integer(Token.NE), "!=");
literals.put(new Integer(Token.LE), "<=");
literals.put(new Integer(Token.LT), "<");
literals.put(new Integer(Token.GE), ">=");
literals.put(new Integer(Token.GT), ">");
literals.put(new Integer(Token.INSTANCEOF), " instanceof ");
literals.put(new Integer(Token.LSH), "<<");
literals.put(new Integer(Token.RSH), ">>");
literals.put(new Integer(Token.URSH), ">>>");
literals.put(new Integer(Token.TYPEOF), "typeof");
literals.put(new Integer(Token.VOID), "void ");
literals.put(new Integer(Token.CONST), "const ");
literals.put(new Integer(Token.NOT), "!");
literals.put(new Integer(Token.BITNOT), "~");
literals.put(new Integer(Token.POS), "+");
literals.put(new Integer(Token.NEG), "-");
literals.put(new Integer(Token.INC), "++");
literals.put(new Integer(Token.DEC), "--");
literals.put(new Integer(Token.ADD), "+");
literals.put(new Integer(Token.SUB), "-");
literals.put(new Integer(Token.MUL), "*");
literals.put(new Integer(Token.DIV), "/");
literals.put(new Integer(Token.MOD), "%");
literals.put(new Integer(Token.COLONCOLON), "::");
literals.put(new Integer(Token.DOTDOT), "..");
literals.put(new Integer(Token.DOTQUERY), ".(");
literals.put(new Integer(Token.XMLATTR), "@");
literals.put(new Integer(Token.LET), "let ");
literals.put(new Integer(Token.YIELD), "yield ");
// See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Reserved_Words
// JavaScript 1.5 reserved words
reserved.add("break");
reserved.add("case");
reserved.add("catch");
reserved.add("continue");
reserved.add("default");
reserved.add("delete");
reserved.add("do");
reserved.add("else");
reserved.add("finally");
reserved.add("for");
reserved.add("function");
reserved.add("if");
reserved.add("in");
reserved.add("instanceof");
reserved.add("new");
reserved.add("return");
reserved.add("switch");
reserved.add("this");
reserved.add("throw");
reserved.add("try");
reserved.add("typeof");
reserved.add("var");
reserved.add("void");
reserved.add("while");
reserved.add("with");
// Words reserved for future use
reserved.add("abstract");
reserved.add("boolean");
reserved.add("byte");
reserved.add("char");
reserved.add("class");
reserved.add("const");
reserved.add("debugger");
reserved.add("double");
reserved.add("enum");
reserved.add("export");
reserved.add("extends");
reserved.add("final");
reserved.add("float");
reserved.add("goto");
reserved.add("implements");
reserved.add("import");
reserved.add("int");
reserved.add("interface");
reserved.add("long");
reserved.add("native");
reserved.add("package");
reserved.add("private");
reserved.add("protected");
reserved.add("public");
reserved.add("short");
reserved.add("static");
reserved.add("super");
reserved.add("synchronized");
reserved.add("throws");
reserved.add("transient");
reserved.add("volatile");
// These are not reserved, but should be taken into account
// in isValidIdentifier (See jslint source code)
reserved.add("arguments");
reserved.add("eval");
reserved.add("true");
reserved.add("false");
reserved.add("Infinity");
reserved.add("NaN");
reserved.add("null");
reserved.add("undefined");
}
private static int countChar(String haystack, char needle) {
int idx = 0;
int count = 0;
int length = haystack.length();
while (idx < length) {
char c = haystack.charAt(idx++);
if (c == needle) {
count++;
}
}
return count;
}
private static int printSourceString(String source, int offset, StringBuffer sb) {
int length = source.charAt(offset);
++offset;
if ((0x8000 & length) != 0) {
length = ((0x7FFF & length) << 16) | source.charAt(offset);
++offset;
}
if (sb != null) {
String str = source.substring(offset, offset + length);
sb.append(str);
}
return offset + length;
}
private static int printSourceNumber(String source,
int offset, StringBuffer sb) {
double number = 0.0;
char type = source.charAt(offset);
++offset;
if (type == 'S') {
if (sb != null) {
number = source.charAt(offset);
}
++offset;
} else if (type == 'J' || type == 'D') {
if (sb != null) {
long lbits;
lbits = (long) source.charAt(offset) << 48;
lbits |= (long) source.charAt(offset + 1) << 32;
lbits |= (long) source.charAt(offset + 2) << 16;
lbits |= (long) source.charAt(offset + 3);
if (type == 'J') {
number = lbits;
} else {
number = Double.longBitsToDouble(lbits);
}
}
offset += 4;
} else {
// Bad source
throw new RuntimeException();
}
if (sb != null) {
sb.append(ScriptRuntime.numberToString(number, 10));
}
return offset;
}
private static ArrayList parse(Reader in, ErrorReporter reporter)
throws IOException, EvaluatorException {
CompilerEnvirons env = new CompilerEnvirons();
env.setLanguageVersion(Context.VERSION_1_7);
Parser parser = new Parser(env, reporter);
parser.parse(in, null, 1);
String source = parser.getEncodedSource();
int offset = 0;
int length = source.length();
ArrayList tokens = new ArrayList();
StringBuffer sb = new StringBuffer();
while (offset < length) {
int tt = source.charAt(offset++);
switch (tt) {
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
case Token.NAME:
case Token.REGEXP:
case Token.STRING:
sb.setLength(0);
offset = printSourceString(source, offset, sb);
tokens.add(new JavaScriptToken(tt, sb.toString()));
break;
case Token.NUMBER:
sb.setLength(0);
offset = printSourceNumber(source, offset, sb);
tokens.add(new JavaScriptToken(tt, sb.toString()));
break;
default:
String literal = (String) literals.get(new Integer(tt));
if (literal != null) {
tokens.add(new JavaScriptToken(tt, literal));
}
break;
}
}
return tokens;
}
private static void processStringLiterals(ArrayList tokens, boolean merge) {
String tv;
int i, length = tokens.size();
JavaScriptToken token, prevToken, nextToken;
if (merge) {
// Concatenate string literals that are being appended wherever
// it is safe to do so. Note that we take care of the case:
// "a" + "b".toUpperCase()
for (i = 0; i < length; i++) {
token = (JavaScriptToken) tokens.get(i);
switch (token.getType()) {
case Token.ADD:
if (i > 0 && i < length) {
prevToken = (JavaScriptToken) tokens.get(i - 1);
nextToken = (JavaScriptToken) tokens.get(i + 1);
if (prevToken.getType() == Token.STRING && nextToken.getType() == Token.STRING &&
(i == length - 1 || ((JavaScriptToken) tokens.get(i + 2)).getType() != Token.DOT)) {
tokens.set(i - 1, new JavaScriptToken(Token.STRING,
prevToken.getValue() + nextToken.getValue()));
tokens.remove(i + 1);
tokens.remove(i);
i = i - 1;
length = length - 2;
break;
}
}
}
}
}
// Second pass...
for (i = 0; i < length; i++) {
token = (JavaScriptToken) tokens.get(i);
if (token.getType() == Token.STRING) {
tv = token.getValue();
// Finally, add the quoting characters and escape the string. We use
// the quoting character that minimizes the amount of escaping to save
// a few additional bytes.
char quotechar;
int singleQuoteCount = countChar(tv, '\'');
int doubleQuoteCount = countChar(tv, '"');
if (doubleQuoteCount <= singleQuoteCount) {
quotechar = '"';
} else {
quotechar = '\'';
}
tv = quotechar + escapeString(tv, quotechar) + quotechar;
// String concatenation transforms the old script scheme:
// '<scr'+'ipt ...><'+'/script>'
// into the following:
// '<script ...></script>'
// which breaks if this code is embedded inside an HTML document.
// Since this is not the right way to do this, let's fix the code by
// transforming all "</script" into "<\/script"
if (tv.indexOf("</script") >= 0) {
tv = tv.replaceAll("<\\/script", "<\\\\/script");
}
tokens.set(i, new JavaScriptToken(Token.STRING, tv));
}
}
}
// Add necessary escaping that was removed in Rhino's tokenizer.
private static String escapeString(String s, char quotechar) {
assert quotechar == '"' || quotechar == '\'';
if (s == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0, L = s.length(); i < L; i++) {
int c = s.charAt(i);
if (c == quotechar) {
sb.append("\\");
}
sb.append((char) c);
}
return sb.toString();
}
/*
* Simple check to see whether a string is a valid identifier name.
* If a string matches this pattern, it means it IS a valid
* identifier name. If a string doesn't match it, it does not
* necessarily mean it is not a valid identifier name.
*/
private static final Pattern SIMPLE_IDENTIFIER_NAME_PATTERN = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$");
private static boolean isValidIdentifier(String s) {
Matcher m = SIMPLE_IDENTIFIER_NAME_PATTERN.matcher(s);
return (m.matches() && !reserved.contains(s));
}
/*
* Transforms obj["foo"] into obj.foo whenever possible, saving 3 bytes.
*/
private static void optimizeObjectMemberAccess(ArrayList tokens) {
String tv;
int i, length;
JavaScriptToken token;
for (i = 0, length = tokens.size(); i < length; i++) {
if (((JavaScriptToken) tokens.get(i)).getType() == Token.LB &&
i > 0 && i < length - 2 &&
((JavaScriptToken) tokens.get(i - 1)).getType() == Token.NAME &&
((JavaScriptToken) tokens.get(i + 1)).getType() == Token.STRING &&
((JavaScriptToken) tokens.get(i + 2)).getType() == Token.RB) {
token = (JavaScriptToken) tokens.get(i + 1);
tv = token.getValue();
tv = tv.substring(1, tv.length() - 1);
if (isValidIdentifier(tv)) {
tokens.set(i, new JavaScriptToken(Token.DOT, "."));
tokens.set(i + 1, new JavaScriptToken(Token.NAME, tv));
tokens.remove(i + 2);
i = i + 2;
length = length - 1;
}
}
}
}
/*
* Transforms 'foo': ... into foo: ... whenever possible, saving 2 bytes.
*/
private static void optimizeObjLitMemberDecl(ArrayList tokens) {
String tv;
int i, length;
JavaScriptToken token;
for (i = 0, length = tokens.size(); i < length; i++) {
if (((JavaScriptToken) tokens.get(i)).getType() == Token.OBJECTLIT &&
i > 0 && ((JavaScriptToken) tokens.get(i - 1)).getType() == Token.STRING) {
token = (JavaScriptToken) tokens.get(i - 1);
tv = token.getValue();
tv = tv.substring(1, tv.length() - 1);
if (isValidIdentifier(tv)) {
tokens.set(i - 1, new JavaScriptToken(Token.NAME, tv));
}
}
}
}
private ErrorReporter logger;
private boolean munge;
private boolean verbose;
private static final int BUILDING_SYMBOL_TREE = 1;
private static final int CHECKING_SYMBOL_TREE = 2;
private int mode;
private int offset;
private int braceNesting;
private ArrayList tokens;
private Stack scopes = new Stack();
private ScriptOrFnScope globalScope = new ScriptOrFnScope(-1, null);
private Hashtable indexedScopes = new Hashtable();
public JavaScriptCompressor(Reader in, ErrorReporter reporter)
throws IOException, EvaluatorException {
this.logger = reporter;
this.tokens = parse(in, reporter);
}
public void compress(Writer out, int linebreak, boolean munge, boolean verbose,
boolean preserveAllSemiColons, boolean disableOptimizations)
throws IOException {
this.munge = munge;
this.verbose = verbose;
processStringLiterals(this.tokens, !disableOptimizations);
if (!disableOptimizations) {
optimizeObjectMemberAccess(this.tokens);
optimizeObjLitMemberDecl(this.tokens);
}
buildSymbolTree();
// DO NOT TOUCH this.tokens BETWEEN THESE TWO PHASES (BECAUSE OF this.indexedScopes)
mungeSymboltree();
StringBuffer sb = printSymbolTree(linebreak, preserveAllSemiColons);
out.write(sb.toString());
}
private ScriptOrFnScope getCurrentScope() {
return (ScriptOrFnScope) scopes.peek();
}
private void enterScope(ScriptOrFnScope scope) {
scopes.push(scope);
}
private void leaveCurrentScope() {
scopes.pop();
}
private JavaScriptToken consumeToken() {
return (JavaScriptToken) tokens.get(offset++);
}
private JavaScriptToken getToken(int delta) {
return (JavaScriptToken) tokens.get(offset + delta);
}
/*
* Returns the identifier for the specified symbol defined in
* the specified scope or in any scope above it. Returns null
* if this symbol does not have a corresponding identifier.
*/
private JavaScriptIdentifier getIdentifier(String symbol, ScriptOrFnScope scope) {
JavaScriptIdentifier identifier;
while (scope != null) {
identifier = scope.getIdentifier(symbol);
if (identifier != null) {
return identifier;
}
scope = scope.getParentScope();
}
return null;
}
/*
* If either 'eval' or 'with' is used in a local scope, we must make
* sure that all containing local scopes don't get munged. Otherwise,
* the obfuscation would potentially introduce bugs.
*/
private void protectScopeFromObfuscation(ScriptOrFnScope scope) {
assert scope != null;
if (scope == globalScope) {
// The global scope does not get obfuscated,
// so we don't need to worry about it...
return;
}
// Find the highest local scope containing the specified scope.
while (scope.getParentScope() != globalScope) {
scope = scope.getParentScope();
}
assert scope.getParentScope() == globalScope;
scope.preventMunging();
}
private String getDebugString(int max) {
assert max > 0;
StringBuffer result = new StringBuffer();
int start = Math.max(offset - max, 0);
int end = Math.min(offset + max, tokens.size());
for (int i = start; i < end; i++) {
JavaScriptToken token = (JavaScriptToken) tokens.get(i);
if (i == offset - 1) {
result.append(" ---> ");
}
result.append(token.getValue());
if (i == offset - 1) {
result.append(" <--- ");
}
}
return result.toString();
}
private void warn(String message, boolean showDebugString) {
if (verbose) {
if (showDebugString) {
message = message + "\n" + getDebugString(10);
}
logger.warning(message, null, -1, null, -1);
}
}
private void parseFunctionDeclaration() {
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope, fnScope;
JavaScriptIdentifier identifier;
currentScope = getCurrentScope();
token = consumeToken();
if (token.getType() == Token.NAME) {
if (mode == BUILDING_SYMBOL_TREE) {
// Get the name of the function and declare it in the current scope.
symbol = token.getValue();
if (currentScope.getIdentifier(symbol) != null) {
warn("The function " + symbol + " has already been declared in the same scope...", true);
}
currentScope.declareIdentifier(symbol);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
if (mode == BUILDING_SYMBOL_TREE) {
fnScope = new ScriptOrFnScope(braceNesting, currentScope);
indexedScopes.put(new Integer(offset), fnScope);
} else {
fnScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
}
// Parse function arguments.
int argpos = 0;
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME ||
token.getType() == Token.COMMA;
if (token.getType() == Token.NAME && mode == BUILDING_SYMBOL_TREE) {
symbol = token.getValue();
identifier = fnScope.declareIdentifier(symbol);
if (symbol.equals("$super") && argpos == 0) {
// Exception for Prototype 1.6...
identifier.preventMunging();
}
argpos++;
}
}
token = consumeToken();
assert token.getType() == Token.LC;
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Hints are empty statements that look like
// "localvar1:nomunge, localvar2:nomunge"; They allow developers
// to prevent specific symbols from getting obfuscated (some heretic
// implementations, such as Prototype 1.6, require specific variable
// names, such as $super for example, in order to work appropriately.
// Note: right now, only "nomunge" is supported in the right hand side
// of a hint. However, in the future, the right hand side may contain
// other values.
consumeToken();
String hints = token.getValue();
// Remove the leading and trailing quotes...
hints = hints.substring(1, hints.length() - 1).trim();
StringTokenizer st1 = new StringTokenizer(hints, ",");
while (st1.hasMoreTokens()) {
String hint = st1.nextToken();
int idx = hint.indexOf(':');
if (idx <= 0 || idx >= hint.length() - 1) {
if (mode == BUILDING_SYMBOL_TREE) {
// No need to report the error twice, hence the test...
warn("Invalid hint syntax: " + hint, true);
}
break;
}
String variableName = hint.substring(0, idx).trim();
String variableType = hint.substring(idx + 1).trim();
if (mode == BUILDING_SYMBOL_TREE) {
fnScope.addHint(variableName, variableType);
} else if (mode == CHECKING_SYMBOL_TREE) {
identifier = fnScope.getIdentifier(variableName);
if (identifier != null) {
if (variableType.equals("nomunge")) {
identifier.preventMunging();
} else {
warn("Unsupported hint value: " + hint, true);
}
} else {
warn("Hint refers to an unknown identifier: " + hint, true);
}
}
}
}
parseScope(fnScope);
}
private void parseCatch() {
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
token = getToken(-1);
assert token.getType() == Token.CATCH;
token = consumeToken();
assert token.getType() == Token.LP;
token = consumeToken();
assert token.getType() == Token.NAME;
symbol = token.getValue();
currentScope = getCurrentScope();
if (mode == BUILDING_SYMBOL_TREE) {
// We must declare the exception identifier in the containing function
// scope to avoid errors related to the obfuscation process. No need to
// display a warning if the symbol was already declared here...
currentScope.declareIdentifier(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
identifier.incrementRefcount();
}
token = consumeToken();
assert token.getType() == Token.RP;
}
private void parseExpression() {
// Parse the expression until we encounter a comma or a semi-colon
// in the same brace nesting, bracket nesting and paren nesting.
// Parse functions if any...
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int expressionBraceNesting = braceNesting;
int bracketNesting = 0;
int parensNesting = 0;
int length = tokens.size();
while (offset < length) {
token = consumeToken();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.SEMI:
case Token.COMMA:
if (braceNesting == expressionBraceNesting &&
bracketNesting == 0 &&
parensNesting == 0) {
return;
}
break;
case Token.FUNCTION:
parseFunctionDeclaration();
break;
case Token.LC:
braceNesting++;
break;
case Token.RC:
braceNesting--;
assert braceNesting >= expressionBraceNesting;
break;
case Token.LB:
bracketNesting++;
break;
case Token.RB:
bracketNesting--;
break;
case Token.LP:
parensNesting++;
break;
case Token.RP:
parensNesting--;
break;
case Token.CONDCOMMENT:
if (mode == BUILDING_SYMBOL_TREE) {
protectScopeFromObfuscation(currentScope);
warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
}
break;
case Token.NAME:
symbol = token.getValue();
if (mode == BUILDING_SYMBOL_TREE) {
if (symbol.equals("eval")) {
protectScopeFromObfuscation(currentScope);
warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
}
} else if (mode == CHECKING_SYMBOL_TREE) {
if ((offset < 2 ||
(getToken(-2).getType() != Token.DOT &&
getToken(-2).getType() != Token.GET &&
getToken(-2).getType() != Token.SET)) &&
getToken(0).getType() != Token.OBJECTLIT) {
identifier = getIdentifier(symbol, currentScope);
if (identifier == null) {
if (symbol.length() <= 3 && !builtin.contains(symbol)) {
// Here, we found an undeclared and un-namespaced symbol that is
// 3 characters or less in length. Declare it in the global scope.
// We don't need to declare longer symbols since they won't cause
// any conflict with other munged symbols.
globalScope.declareIdentifier(symbol);
// I removed the warning since was only being done when
// for identifiers 3 chars or less, and was just causing
// noise for people who happen to rely on an externally
// declared variable that happen to be that short. We either
// should always warn or never warn -- the fact that we
// declare the short symbols in the global space doesn't
// change anything.
// warn("Found an undeclared symbol: " + symbol, true);
}
} else {
identifier.incrementRefcount();
}
}
}
break;
}
}
}
private void parseScope(ScriptOrFnScope scope) {
String symbol;
JavaScriptToken token;
JavaScriptIdentifier identifier;
int length = tokens.size();
enterScope(scope);
while (offset < length) {
token = consumeToken();
switch (token.getType()) {
case Token.VAR:
if (mode == BUILDING_SYMBOL_TREE && scope.incrementVarCount() > 1) {
warn("Try to use a single 'var' statement per scope.", true);
}
/* FALLSTHROUGH */
case Token.CONST:
// The var keyword is followed by at least one symbol name.
// If several symbols follow, they are comma separated.
for (; ;) {
token = consumeToken();
assert token.getType() == Token.NAME;
if (mode == BUILDING_SYMBOL_TREE) {
symbol = token.getValue();
if (scope.getIdentifier(symbol) == null) {
scope.declareIdentifier(symbol);
} else {
warn("The variable " + symbol + " has already been declared in the same scope...", true);
}
}
token = getToken(0);
assert token.getType() == Token.SEMI ||
token.getType() == Token.ASSIGN ||
token.getType() == Token.COMMA ||
token.getType() == Token.IN;
if (token.getType() == Token.IN) {
break;
} else {
parseExpression();
token = getToken(-1);
if (token.getType() == Token.SEMI) {
break;
}
}
}
break;
case Token.FUNCTION:
parseFunctionDeclaration();
break;
case Token.LC:
braceNesting++;
break;
case Token.RC:
braceNesting--;
assert braceNesting >= scope.getBraceNesting();
if (braceNesting == scope.getBraceNesting()) {
leaveCurrentScope();
return;
}
break;
case Token.WITH:
if (mode == BUILDING_SYMBOL_TREE) {
// Inside a 'with' block, it is impossible to figure out
// statically whether a symbol is a local variable or an
// object member. As a consequence, the only thing we can
// do is turn the obfuscation off for the highest scope
// containing the 'with' block.
protectScopeFromObfuscation(scope);
warn("Using 'with' is not recommended." + (munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
}
break;
case Token.CATCH:
parseCatch();
break;
case Token.CONDCOMMENT:
if (mode == BUILDING_SYMBOL_TREE) {
protectScopeFromObfuscation(scope);
warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
}
break;
case Token.NAME:
symbol = token.getValue();
if (mode == BUILDING_SYMBOL_TREE) {
if (symbol.equals("eval")) {
protectScopeFromObfuscation(scope);
warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
}
} else if (mode == CHECKING_SYMBOL_TREE) {
if ((offset < 2 || getToken(-2).getType() != Token.DOT) &&
getToken(0).getType() != Token.OBJECTLIT) {
identifier = getIdentifier(symbol, scope);
if (identifier == null) {
if (symbol.length() <= 3 && !builtin.contains(symbol)) {
// Here, we found an undeclared and un-namespaced symbol that is
// 3 characters or less in length. Declare it in the global scope.
// We don't need to declare longer symbols since they won't cause
// any conflict with other munged symbols.
globalScope.declareIdentifier(symbol);
// warn("Found an undeclared symbol: " + symbol, true);
}
} else {
identifier.incrementRefcount();
}
}
}
break;
}
}
}
private void buildSymbolTree() {
offset = 0;
braceNesting = 0;
scopes.clear();
indexedScopes.clear();
indexedScopes.put(new Integer(0), globalScope);
mode = BUILDING_SYMBOL_TREE;
parseScope(globalScope);
}
private void mungeSymboltree() {
if (!munge) {
return;
}
// One problem with obfuscation resides in the use of undeclared
// and un-namespaced global symbols that are 3 characters or less
// in length. Here is an example:
//
// var declaredGlobalVar;
//
// function declaredGlobalFn() {
// var localvar;
// localvar = abc; // abc is an undeclared global symbol
// }
//
// In the example above, there is a slim chance that localvar may be
// munged to 'abc', conflicting with the undeclared global symbol
// abc, creating a potential bug. The following code detects such
// global symbols. This must be done AFTER the entire file has been
// parsed, and BEFORE munging the symbol tree. Note that declaring
// extra symbols in the global scope won't hurt.
//
// Note: Since we go through all the tokens to do this, we also use
// the opportunity to count how many times each identifier is used.
offset = 0;
braceNesting = 0;
scopes.clear();
mode = CHECKING_SYMBOL_TREE;
parseScope(globalScope);
globalScope.munge();
}
private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
+ JavaScriptToken lastToken = getToken(0);
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
+ case Token.GET:
+ case Token.SET:
+ lastToken = token;
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
- result.append("function");
+ if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
+ result.append("function");
+ }
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
}
| false | true | private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
result.append("function");
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
| private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
JavaScriptToken lastToken = getToken(0);
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.GET:
case Token.SET:
lastToken = token;
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
result.append("function");
}
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
|
diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java
index 4c7c0dfea..4543e0be7 100644
--- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java
+++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java
@@ -1,70 +1,71 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.tags;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.SimpleWebApplicationContext;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.theme.FixedThemeResolver;
/**
* Abstract base class for testing tags; provides {@link #createPageContext()}.
*
* @author Alef Arendsen
* @author Juergen Hoeller
* @author Sam Brannen
*/
public abstract class AbstractTagTests extends TestCase {
protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();
+ sc.addInitParameter("springJspExpressionSupport", "true");
SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
wac.setServletContext(sc);
wac.setNamespace("test");
wac.refresh();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
MockHttpServletResponse response = new MockHttpServletResponse();
if (inDispatcherServlet()) {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
LocaleResolver lr = new AcceptHeaderLocaleResolver();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
ThemeResolver tr = new FixedThemeResolver();
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
}
else {
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
}
return new MockPageContext(sc, request, response);
}
protected boolean inDispatcherServlet() {
return true;
}
}
| true | true | protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();
SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
wac.setServletContext(sc);
wac.setNamespace("test");
wac.refresh();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
MockHttpServletResponse response = new MockHttpServletResponse();
if (inDispatcherServlet()) {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
LocaleResolver lr = new AcceptHeaderLocaleResolver();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
ThemeResolver tr = new FixedThemeResolver();
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
}
else {
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
}
return new MockPageContext(sc, request, response);
}
| protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();
sc.addInitParameter("springJspExpressionSupport", "true");
SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
wac.setServletContext(sc);
wac.setNamespace("test");
wac.refresh();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
MockHttpServletResponse response = new MockHttpServletResponse();
if (inDispatcherServlet()) {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
LocaleResolver lr = new AcceptHeaderLocaleResolver();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
ThemeResolver tr = new FixedThemeResolver();
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
}
else {
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
}
return new MockPageContext(sc, request, response);
}
|
diff --git a/src/java/se/idega/idegaweb/commune/childcare/event/ChildCareEventListener.java b/src/java/se/idega/idegaweb/commune/childcare/event/ChildCareEventListener.java
index 247710e7..ebb381bb 100644
--- a/src/java/se/idega/idegaweb/commune/childcare/event/ChildCareEventListener.java
+++ b/src/java/se/idega/idegaweb/commune/childcare/event/ChildCareEventListener.java
@@ -1,76 +1,76 @@
package se.idega.idegaweb.commune.childcare.event;
import java.rmi.RemoteException;
import se.idega.idegaweb.commune.childcare.business.ChildCareSession;
import se.idega.idegaweb.commune.childcare.presentation.ChildCareAdmin;
import se.idega.idegaweb.commune.childcare.presentation.ChildCareBlock;
import com.idega.business.IBOLookup;
import com.idega.event.IWPageEventListener;
import com.idega.presentation.IWContext;
/**
* @author laddi
*/
public class ChildCareEventListener implements IWPageEventListener {
/**
* @see com.idega.business.IWEventListener#actionPerformed(com.idega.presentation.IWContext)
*/
public boolean actionPerformed(IWContext iwc) {
try {
ChildCareSession session = getChildCareSession(iwc);
if (iwc.isParameterSet(session.getParameterChildCareID()))
session.setChildCareID(Integer.parseInt(iwc.getParameter(session.getParameterChildCareID())));
if (iwc.isParameterSet(session.getParameterUserID()))
session.setChildID(Integer.parseInt(iwc.getParameter(session.getParameterUserID())));
if (iwc.isParameterSet(session.getParameterApplicationID()))
session.setApplicationID(Integer.parseInt(iwc.getParameter(session.getParameterApplicationID())));
if (iwc.isParameterSet(session.getParameterFrom()))
session.setFromTimestamp(iwc.getParameter(session.getParameterFrom()));
if (iwc.isParameterSet(session.getParameterTo()))
session.setToTimestamp(iwc.getParameter(session.getParameterTo()));
if (iwc.isParameterSet(session.getParameterSortBy()))
session.setSortBy(Integer.parseInt(iwc.getParameter(session.getParameterSortBy())));
if (iwc.isParameterSet(session.getParameterGroupID()))
session.setGroupID(Integer.parseInt(iwc.getParameter(session.getParameterGroupID())));
if (iwc.isParameterSet(session.getParameterCheckID()))
session.setCheckID(Integer.parseInt(iwc.getParameter(session.getParameterCheckID())));
if (iwc.isParameterSet(session.getParameterSeasonID()))
session.setSeasonID(Integer.parseInt(iwc.getParameter(session.getParameterSeasonID())));
if (iwc.isParameterSet(session.getParameterStatus())) {
session.setStatus(iwc.getParameter(session.getParameterStatus()));
}
if (session.getSortBy() == ChildCareAdmin.SORT_ALL) {
session.setSortBy(-1);
session.setFromTimestamp(null);
session.setToTimestamp(null);
}
- if (session.getStatus().equals(ChildCareBlock.STATUS_ALL)) {
+ if (session.getStatus() != null && session.getStatus().equals(ChildCareBlock.STATUS_ALL)) {
session.setStatus(null);
}
return true;
}
catch (RemoteException re) {
return false;
}
}
private ChildCareSession getChildCareSession(IWContext iwc) throws RemoteException {
return (ChildCareSession) IBOLookup.getSessionInstance(iwc, ChildCareSession.class);
}
}
| true | true | public boolean actionPerformed(IWContext iwc) {
try {
ChildCareSession session = getChildCareSession(iwc);
if (iwc.isParameterSet(session.getParameterChildCareID()))
session.setChildCareID(Integer.parseInt(iwc.getParameter(session.getParameterChildCareID())));
if (iwc.isParameterSet(session.getParameterUserID()))
session.setChildID(Integer.parseInt(iwc.getParameter(session.getParameterUserID())));
if (iwc.isParameterSet(session.getParameterApplicationID()))
session.setApplicationID(Integer.parseInt(iwc.getParameter(session.getParameterApplicationID())));
if (iwc.isParameterSet(session.getParameterFrom()))
session.setFromTimestamp(iwc.getParameter(session.getParameterFrom()));
if (iwc.isParameterSet(session.getParameterTo()))
session.setToTimestamp(iwc.getParameter(session.getParameterTo()));
if (iwc.isParameterSet(session.getParameterSortBy()))
session.setSortBy(Integer.parseInt(iwc.getParameter(session.getParameterSortBy())));
if (iwc.isParameterSet(session.getParameterGroupID()))
session.setGroupID(Integer.parseInt(iwc.getParameter(session.getParameterGroupID())));
if (iwc.isParameterSet(session.getParameterCheckID()))
session.setCheckID(Integer.parseInt(iwc.getParameter(session.getParameterCheckID())));
if (iwc.isParameterSet(session.getParameterSeasonID()))
session.setSeasonID(Integer.parseInt(iwc.getParameter(session.getParameterSeasonID())));
if (iwc.isParameterSet(session.getParameterStatus())) {
session.setStatus(iwc.getParameter(session.getParameterStatus()));
}
if (session.getSortBy() == ChildCareAdmin.SORT_ALL) {
session.setSortBy(-1);
session.setFromTimestamp(null);
session.setToTimestamp(null);
}
if (session.getStatus().equals(ChildCareBlock.STATUS_ALL)) {
session.setStatus(null);
}
return true;
}
catch (RemoteException re) {
return false;
}
}
| public boolean actionPerformed(IWContext iwc) {
try {
ChildCareSession session = getChildCareSession(iwc);
if (iwc.isParameterSet(session.getParameterChildCareID()))
session.setChildCareID(Integer.parseInt(iwc.getParameter(session.getParameterChildCareID())));
if (iwc.isParameterSet(session.getParameterUserID()))
session.setChildID(Integer.parseInt(iwc.getParameter(session.getParameterUserID())));
if (iwc.isParameterSet(session.getParameterApplicationID()))
session.setApplicationID(Integer.parseInt(iwc.getParameter(session.getParameterApplicationID())));
if (iwc.isParameterSet(session.getParameterFrom()))
session.setFromTimestamp(iwc.getParameter(session.getParameterFrom()));
if (iwc.isParameterSet(session.getParameterTo()))
session.setToTimestamp(iwc.getParameter(session.getParameterTo()));
if (iwc.isParameterSet(session.getParameterSortBy()))
session.setSortBy(Integer.parseInt(iwc.getParameter(session.getParameterSortBy())));
if (iwc.isParameterSet(session.getParameterGroupID()))
session.setGroupID(Integer.parseInt(iwc.getParameter(session.getParameterGroupID())));
if (iwc.isParameterSet(session.getParameterCheckID()))
session.setCheckID(Integer.parseInt(iwc.getParameter(session.getParameterCheckID())));
if (iwc.isParameterSet(session.getParameterSeasonID()))
session.setSeasonID(Integer.parseInt(iwc.getParameter(session.getParameterSeasonID())));
if (iwc.isParameterSet(session.getParameterStatus())) {
session.setStatus(iwc.getParameter(session.getParameterStatus()));
}
if (session.getSortBy() == ChildCareAdmin.SORT_ALL) {
session.setSortBy(-1);
session.setFromTimestamp(null);
session.setToTimestamp(null);
}
if (session.getStatus() != null && session.getStatus().equals(ChildCareBlock.STATUS_ALL)) {
session.setStatus(null);
}
return true;
}
catch (RemoteException re) {
return false;
}
}
|
diff --git a/juddi-core/src/main/java/org/apache/juddi/rmi/JNDIRegistration.java b/juddi-core/src/main/java/org/apache/juddi/rmi/JNDIRegistration.java
index 5bf0be522..e37939c03 100644
--- a/juddi-core/src/main/java/org/apache/juddi/rmi/JNDIRegistration.java
+++ b/juddi-core/src/main/java/org/apache/juddi/rmi/JNDIRegistration.java
@@ -1,141 +1,141 @@
/*
* Copyright 2001-2009 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.juddi.rmi;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
/**
* @author Kurt Stam ([email protected])
*/
public class JNDIRegistration
{
public static String JUDDI = "/juddi";
public static String UDDI_SECURITY_SERVICE = JUDDI + "/UDDISecurityService";
public static String UDDI_PUBLICATION_SERVICE = JUDDI + "/UDDIPublicationService";
public static String UDDI_INQUIRY_SERVICE = JUDDI + "/UDDIInquiryService";
public static String UDDI_SUBSCRIPTION_SERVICE = JUDDI + "/UDDISubscriptionService";
public static String UDDI_SUBSCRIPTION_LISTENER_SERVICE = JUDDI + "/UDDISubscriptionListenerService";
public static String UDDI_CUSTODY_TRANSFER_SERVICE = JUDDI + "/UDDICustodyTransferService";
private UDDISecurityService securityService = null;
private UDDIPublicationService publicationService = null;
private UDDIInquiryService inquiryService = null;
private UDDISubscriptionService subscriptionService = null;
private UDDISubscriptionListenerService subscriptionListenerService = null;
private UDDICustodyTransferService custodyTransferService = null;
private Logger log = Logger.getLogger(this.getClass());
InitialContext context = null;
private static JNDIRegistration registration = null;
public static JNDIRegistration getInstance() throws NamingException {
if (registration==null) {
registration = new JNDIRegistration();
}
return registration;
}
private JNDIRegistration() throws NamingException{
super();
context = new InitialContext();
}
/**
* Registers the Publish and Inquiry Services to JNDI and instantiates a
* instance of each so we can remotely attach to it later.
*/
public void register() {
try {
Context juddiContext = context.createSubcontext(JUDDI);
securityService = new UDDISecurityService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SECURITY_SERVICE + ", " + securityService.getClass());
juddiContext.rebind(UDDI_SECURITY_SERVICE, securityService);
publicationService = new UDDIPublicationService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_PUBLICATION_SERVICE + ", " + publicationService.getClass());
juddiContext.rebind(UDDI_PUBLICATION_SERVICE, publicationService);
inquiryService = new UDDIInquiryService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_INQUIRY_SERVICE + ", " + inquiryService.getClass());
juddiContext.rebind(UDDI_INQUIRY_SERVICE, inquiryService);
subscriptionService = new UDDISubscriptionService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SUBSCRIPTION_SERVICE + ", " + inquiryService.getClass());
juddiContext.rebind(UDDI_SUBSCRIPTION_SERVICE, subscriptionService);
subscriptionListenerService = new UDDISubscriptionListenerService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_SUBSCRIPTION_LISTENER_SERVICE + ", " + inquiryService.getClass());
juddiContext.rebind(UDDI_SUBSCRIPTION_LISTENER_SERVICE, subscriptionListenerService);
custodyTransferService = new UDDICustodyTransferService();
if (log.isDebugEnabled()) log.debug("Setting " + UDDI_CUSTODY_TRANSFER_SERVICE + ", " + inquiryService.getClass());
juddiContext.rebind(UDDI_CUSTODY_TRANSFER_SERVICE, custodyTransferService);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
public void unregister() {
try {
context.unbind(UDDI_SECURITY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
securityService = null;
try {
context.unbind(UDDI_PUBLICATION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
publicationService = null;
try {
context.unbind(UDDI_INQUIRY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
inquiryService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_LISTENER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionListenerService = null;
try {
context.unbind(UDDI_CUSTODY_TRANSFER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
custodyTransferService = null;
try {
- context.destroySubcontext(JUDDI);
+ context.unbind(JUDDI);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
}
}
| true | true | public void unregister() {
try {
context.unbind(UDDI_SECURITY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
securityService = null;
try {
context.unbind(UDDI_PUBLICATION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
publicationService = null;
try {
context.unbind(UDDI_INQUIRY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
inquiryService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_LISTENER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionListenerService = null;
try {
context.unbind(UDDI_CUSTODY_TRANSFER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
custodyTransferService = null;
try {
context.destroySubcontext(JUDDI);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
}
| public void unregister() {
try {
context.unbind(UDDI_SECURITY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
securityService = null;
try {
context.unbind(UDDI_PUBLICATION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
publicationService = null;
try {
context.unbind(UDDI_INQUIRY_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
inquiryService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionService = null;
try {
context.unbind(UDDI_SUBSCRIPTION_LISTENER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
subscriptionListenerService = null;
try {
context.unbind(UDDI_CUSTODY_TRANSFER_SERVICE);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
custodyTransferService = null;
try {
context.unbind(JUDDI);
} catch (NamingException e) {
log.error(e.getMessage(),e);
}
}
|
diff --git a/Client/Client.java b/Client/Client.java
index 9d18be0..bbaae49 100755
--- a/Client/Client.java
+++ b/Client/Client.java
@@ -1,64 +1,64 @@
/**
* @Author Chris Card
* 9/16/13
* This Contains code for the clients
*/
package Client;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import Compute.BulletinBoard;
import Compute.Article;
import java.io.*;
public class Client
{
/**
* @param String list of arguments that must be in following order:
* 1 = hostname
* 2 = socket
* 3 = send | receive
* 4 = message file if send
*/
public static void main(String args[])
{
String host="",sendReceive="",message="";
int port = 5555;
if(args.length >= 3)
{
host = args[0];
try{
port = Integer.parseInt(args[1]);
} catch(Exception e){
System.err.println("Invalide port");
e.printStackTrace();
}
sendReceive = args[2];
- message = (args.length == 4 ? makeMessageText(args[3]) : "");
+ //message = (args.length == 4 ? makeMessageText(args[3]) : "");
}
else{
for(int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
System.err.println("Invalide args");
}
try {
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(host,port);
- Compute comp = (Compute) registry.lookup(name);
+ BulletinBoard comp = (BulletinBoard) registry.lookup(name);
- Messages task = new Messages(message,sendReceive);
- Message ret = comp.sendReceive(task);
+ //Messages task = new Messages(message,sendReceive);
+ //Message ret = comp.sendReceive(task);
}catch(Exception e){
System.err.println("Client exception:");
e.printStackTrace();
}
}
}
| false | true | public static void main(String args[])
{
String host="",sendReceive="",message="";
int port = 5555;
if(args.length >= 3)
{
host = args[0];
try{
port = Integer.parseInt(args[1]);
} catch(Exception e){
System.err.println("Invalide port");
e.printStackTrace();
}
sendReceive = args[2];
message = (args.length == 4 ? makeMessageText(args[3]) : "");
}
else{
for(int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
System.err.println("Invalide args");
}
try {
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(host,port);
Compute comp = (Compute) registry.lookup(name);
Messages task = new Messages(message,sendReceive);
Message ret = comp.sendReceive(task);
}catch(Exception e){
System.err.println("Client exception:");
e.printStackTrace();
}
}
| public static void main(String args[])
{
String host="",sendReceive="",message="";
int port = 5555;
if(args.length >= 3)
{
host = args[0];
try{
port = Integer.parseInt(args[1]);
} catch(Exception e){
System.err.println("Invalide port");
e.printStackTrace();
}
sendReceive = args[2];
//message = (args.length == 4 ? makeMessageText(args[3]) : "");
}
else{
for(int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
System.err.println("Invalide args");
}
try {
String name = "Compute";
Registry registry = LocateRegistry.getRegistry(host,port);
BulletinBoard comp = (BulletinBoard) registry.lookup(name);
//Messages task = new Messages(message,sendReceive);
//Message ret = comp.sendReceive(task);
}catch(Exception e){
System.err.println("Client exception:");
e.printStackTrace();
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java
index df1ecdaa..59f880b1 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java
@@ -1,161 +1,169 @@
package com.earth2me.essentials.commands;
import java.io.File;
import org.bukkit.Server;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
public class Commandplugin extends EssentialsCommand
{
private Server server;
public Commandplugin()
{
super("plugin");
}
@Override
public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
this.server = server;
PluginCommands sub = null;
try
{
sub = PluginCommands.valueOf(args[0].toUpperCase());
}
catch (Exception ex)
{
sender.sendMessage("§cUsage: /plugin [load|reload|enable|disable|list] [PluginName]");
return;
}
switch (sub)
{
- case LOAD:
- if (args.length < 2) return;
+ case LOAD: // All disable functions are broken until
+ // http://leaky.bukkit.org/issues/641 is fixed.
+ sender.sendMessage("This function is broken. Performing /reload now.");
+ server.reload();
+ /*if (args.length < 2) return;
User.charge(sender, this);
- loadPlugin(args[1], sender);
+ loadPlugin(args[1], sender);*/
return;
case RELOAD:
- if (args.length < 2) return;
+ sender.sendMessage("This function is broken. Performing /reload now.");
+ server.reload();
+ /*if (args.length < 2) return;
User.charge(sender, this);
- reloadPlugin(args[1], sender);
+ reloadPlugin(args[1], sender);*/
return;
case ENABLE:
- if (args.length < 2) return;
+ sender.sendMessage("This function is broken. Performing /reload now.");
+ server.reload();
+ /*if (args.length < 2) return;
User.charge(sender, this);
- enablePlugin(args[1], sender);
+ enablePlugin(args[1], sender);*/
return;
case DISABLE:
- if (args.length < 2) return;
+ sender.sendMessage("This function is broken.");
+ /*if (args.length < 2) return;
User.charge(sender, this);
- disablePlugin(args[1], sender);
+ disablePlugin(args[1], sender);*/
return;
case LIST:
User.charge(sender, this);
listPlugins(sender);
return;
}
}
private void listPlugins(CommandSender player)
{
StringBuilder plugins = new StringBuilder();
for (Plugin p : server.getPluginManager().getPlugins())
{
plugins.append(p.isEnabled() ? " §a" : " §c");
plugins.append(p.getDescription().getName());
}
plugins.insert(0, "§7Plugins:§f");
player.sendMessage(plugins.toString());
}
private boolean reloadPlugin(String name, CommandSender player)
{
return disablePlugin(name, player) && enablePlugin(name, player);
}
private boolean loadPlugin(String name, CommandSender sender)
{
try
{
PluginManager pm = server.getPluginManager();
pm.loadPlugin(new File("plugins", name + ".jar"));
sender.sendMessage("§7Plugin loaded.");
return enablePlugin(name, sender);
}
catch (Throwable ex)
{
sender.sendMessage("§cCould not load plugin. Is the file named properly?");
return false;
}
}
private boolean enablePlugin(String name, CommandSender sender)
{
try
{
final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name);
if (!plugin.isEnabled()) new Thread(new Runnable()
{
public void run()
{
synchronized (pm)
{
pm.enablePlugin(plugin);
}
}
}).start();
sender.sendMessage("§7Plugin enabled.");
return true;
}
catch (Throwable ex)
{
listPlugins(sender);
return false;
}
}
private boolean disablePlugin(String name, CommandSender sender)
{
try
{
final PluginManager pm = server.getPluginManager();
final Plugin plugin = pm.getPlugin(name);
if (plugin.isEnabled()) new Thread(new Runnable()
{
public void run()
{
synchronized (pm)
{
pm.disablePlugin(plugin);
}
}
}).start();
sender.sendMessage("§7Plugin disabled.");
return true;
}
catch (Throwable ex)
{
listPlugins(sender);
return false;
}
}
private enum PluginCommands
{
LOAD, RELOAD, LIST, ENABLE, DISABLE
}
}
| false | true | public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
this.server = server;
PluginCommands sub = null;
try
{
sub = PluginCommands.valueOf(args[0].toUpperCase());
}
catch (Exception ex)
{
sender.sendMessage("§cUsage: /plugin [load|reload|enable|disable|list] [PluginName]");
return;
}
switch (sub)
{
case LOAD:
if (args.length < 2) return;
User.charge(sender, this);
loadPlugin(args[1], sender);
return;
case RELOAD:
if (args.length < 2) return;
User.charge(sender, this);
reloadPlugin(args[1], sender);
return;
case ENABLE:
if (args.length < 2) return;
User.charge(sender, this);
enablePlugin(args[1], sender);
return;
case DISABLE:
if (args.length < 2) return;
User.charge(sender, this);
disablePlugin(args[1], sender);
return;
case LIST:
User.charge(sender, this);
listPlugins(sender);
return;
}
}
| public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception
{
this.server = server;
PluginCommands sub = null;
try
{
sub = PluginCommands.valueOf(args[0].toUpperCase());
}
catch (Exception ex)
{
sender.sendMessage("§cUsage: /plugin [load|reload|enable|disable|list] [PluginName]");
return;
}
switch (sub)
{
case LOAD: // All disable functions are broken until
// http://leaky.bukkit.org/issues/641 is fixed.
sender.sendMessage("This function is broken. Performing /reload now.");
server.reload();
/*if (args.length < 2) return;
User.charge(sender, this);
loadPlugin(args[1], sender);*/
return;
case RELOAD:
sender.sendMessage("This function is broken. Performing /reload now.");
server.reload();
/*if (args.length < 2) return;
User.charge(sender, this);
reloadPlugin(args[1], sender);*/
return;
case ENABLE:
sender.sendMessage("This function is broken. Performing /reload now.");
server.reload();
/*if (args.length < 2) return;
User.charge(sender, this);
enablePlugin(args[1], sender);*/
return;
case DISABLE:
sender.sendMessage("This function is broken.");
/*if (args.length < 2) return;
User.charge(sender, this);
disablePlugin(args[1], sender);*/
return;
case LIST:
User.charge(sender, this);
listPlugins(sender);
return;
}
}
|
diff --git a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
index 0d671eaab..df97beda7 100644
--- a/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
+++ b/jetty-osgi/jetty-osgi-boot/src/main/java/org/eclipse/jetty/osgi/boot/OSGiAppProvider.java
@@ -1,725 +1,725 @@
// ========================================================================
// Copyright (c) 2009-2010 Mortbay, Inc.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// Contributors:
// Greg Wilkins - initial API and implementation
// ========================================================================
package org.eclipse.jetty.osgi.boot;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.jetty.deploy.App;
import org.eclipse.jetty.deploy.AppProvider;
import org.eclipse.jetty.deploy.DeploymentManager;
import org.eclipse.jetty.deploy.providers.ContextProvider;
import org.eclipse.jetty.deploy.providers.ScanningAppProvider;
import org.eclipse.jetty.osgi.boot.utils.internal.PackageAdminServiceTracker;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.webapp.WebAppContext;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
/**
* AppProvider for OSGi. Supports the configuration of ContextHandlers and
* WebApps. Extends the AbstractAppProvider to support the scanning of context
* files located outside of the bundles.
* <p>
* This provider must not be called outside of jetty.boot: it should always be
* called via the OSGi service listener.
* </p>
* <p>
* This provider supports the same set of parameters than the WebAppProvider as
* it supports the deployment of WebAppContexts. Except for the scanning of the
* webapps directory.
* </p>
* <p>
* When the parameter autoInstallOSGiBundles is set to true, OSGi bundles that
* are located in the monitored directory are installed and started after the
* framework as finished auto-starting all the other bundles.
* Warning: only use this for development.
* </p>
*/
public class OSGiAppProvider extends ScanningAppProvider implements AppProvider
{
private boolean _extractWars = true;
private boolean _parentLoaderPriority = false;
private String _defaultsDescriptor;
private String _tldBundles;
private String[] _configurationClasses;
private boolean _autoInstallOSGiBundles = true;
//Keep track of the bundles that were installed and that are waiting for the
//framework to complete its initialization.
Set<Bundle> _pendingBundlesToStart = null;
/**
* When a context file corresponds to a deployed bundle and is changed we
* reload the corresponding bundle.
*/
private static class Filter implements FilenameFilter
{
OSGiAppProvider _enclosedInstance;
public boolean accept(File dir, String name)
{
File file = new File(dir,name);
if (fileMightBeAnOSGiBundle(file))
{
return true;
}
if (!file.isDirectory())
{
String contextName = getDeployedAppName(name);
if (contextName != null)
{
App app = _enclosedInstance.getDeployedApps().get(contextName);
return app != null;
}
}
return false;
}
}
/**
* @param contextFileName
* for example myContext.xml
* @return The context, for example: myContext; null if this was not a
* suitable contextFileName.
*/
private static String getDeployedAppName(String contextFileName)
{
String lowername = contextFileName.toLowerCase();
if (lowername.endsWith(".xml"))
{
String contextName = contextFileName.substring(0,lowername.length() - ".xml".length());
return contextName;
}
return null;
}
/**
* Reading the display name of a webapp is really not sufficient for indexing the various
* deployed ContextHandlers.
*
* @param context
* @return
*/
private String getContextHandlerAppName(ContextHandler context) {
String appName = context.getDisplayName();
if (appName == null || appName.length() == 0 || getDeployedApps().containsKey(appName)) {
if (context instanceof WebAppContext)
{
appName = ((WebAppContext)context).getContextPath();
if (getDeployedApps().containsKey(appName)) {
appName = "noDisplayName"+context.getClass().getSimpleName()+context.hashCode();
}
} else {
appName = "noDisplayName"+context.getClass().getSimpleName()+context.hashCode();
}
}
return appName;
}
/**
* Default OSGiAppProvider consutructed when none are defined in the
* jetty.xml configuration.
*/
public OSGiAppProvider()
{
super(new Filter());
((Filter)super._filenameFilter)._enclosedInstance = this;
}
/**
* Default OSGiAppProvider consutructed when none are defined in the
* jetty.xml configuration.
*
* @param contextsDir
*/
public OSGiAppProvider(File contextsDir) throws IOException
{
this();
setMonitoredDirResource(Resource.newResource(contextsDir.toURI()));
}
/**
* Returns the ContextHandler that was created by WebappRegistractionHelper
*
* @see AppProvider
*/
public ContextHandler createContextHandler(App app) throws Exception
{
// return pre-created Context
ContextHandler wah = app.getContextHandler();
if (wah == null)
{
// for some reason it was not defined when the App was constructed.
// we don't support this situation at this point.
// once the WebAppRegistrationHelper is refactored, the code
// that creates the ContextHandler will actually be here.
throw new IllegalStateException("The App must be passed the " + "instance of the ContextHandler when it is construsted");
}
if (_configurationClasses != null && wah instanceof WebAppContext)
{
((WebAppContext)wah).setConfigurationClasses(_configurationClasses);
}
return app.getContextHandler();
}
/**
* @see AppProvider
*/
public void setDeploymentManager(DeploymentManager deploymentManager)
{
// _manager=deploymentManager;
super.setDeploymentManager(deploymentManager);
}
private static String getOriginId(Bundle contributor, String pathInBundle)
{
return contributor.getSymbolicName() + "-" + contributor.getVersion().toString() +
(pathInBundle.startsWith("/") ? pathInBundle : "/" + pathInBundle);
}
/**
* @param context
* @throws Exception
*/
public void addContext(Bundle contributor, String pathInBundle, ContextHandler context) throws Exception
{
addContext(getOriginId(contributor, pathInBundle), context);
}
/**
* @param context
* @throws Exception
*/
public void addContext(String originId, ContextHandler context) throws Exception
{
// TODO apply configuration specific to this provider
if (context instanceof WebAppContext)
{
((WebAppContext)context).setExtractWAR(isExtract());
}
// wrap context as an App
App app = new App(getDeploymentManager(),this,originId,context);
String appName = getContextHandlerAppName(context);
getDeployedApps().put(appName,app);
getDeploymentManager().addApp(app);
}
/**
* Called by the scanner of the context files directory. If we find the
* corresponding deployed App we reload it by returning the App. Otherwise
* we return null and nothing happens: presumably the corresponding OSGi
* webapp is not ready yet.
*
* @return the corresponding already deployed App so that it will be
* reloaded. Otherwise returns null.
*/
@Override
protected App createApp(String filename)
{
// find the corresponding bundle and ContextHandler or WebAppContext
// and reload the corresponding App.
// see the 2 pass of the refactoring of the WebAppRegistrationHelper.
String name = getDeployedAppName(filename);
if (name != null)
{
return getDeployedApps().get(name);
}
return null;
}
public void removeContext(ContextHandler context) throws Exception
{
String appName = getContextHandlerAppName(context);
App app = getDeployedApps().remove(context.getDisplayName());
if (app == null) {
//try harder to undeploy this context handler.
//see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=330098
appName = null;
for (Entry<String,App> deployedApp : getDeployedApps().entrySet()) {
if (deployedApp.getValue().getContextHandler() == context) {
app = deployedApp.getValue();
appName = deployedApp.getKey();
break;
}
}
if (appName != null) {
getDeployedApps().remove(appName);
}
}
if (app != null)
{
getDeploymentManager().removeApp(app);
}
}
// //copied from WebAppProvider as the parameters are identical.
// //only removed the parameer related to extractWars.
/* ------------------------------------------------------------ */
/**
* Get the parentLoaderPriority.
*
* @return the parentLoaderPriority
*/
public boolean isParentLoaderPriority()
{
return _parentLoaderPriority;
}
/* ------------------------------------------------------------ */
/**
* Set the parentLoaderPriority.
*
* @param parentLoaderPriority
* the parentLoaderPriority to set
*/
public void setParentLoaderPriority(boolean parentLoaderPriority)
{
_parentLoaderPriority = parentLoaderPriority;
}
/* ------------------------------------------------------------ */
/**
* Get the defaultsDescriptor.
*
* @return the defaultsDescriptor
*/
public String getDefaultsDescriptor()
{
return _defaultsDescriptor;
}
/* ------------------------------------------------------------ */
/**
* Set the defaultsDescriptor.
*
* @param defaultsDescriptor
* the defaultsDescriptor to set
*/
public void setDefaultsDescriptor(String defaultsDescriptor)
{
_defaultsDescriptor = defaultsDescriptor;
}
/**
* The context xml directory. In fact it is the directory watched by the
* scanner.
*/
public File getContextXmlDirAsFile()
{
try
{
Resource monitoredDir = getMonitoredDirResource();
if (monitoredDir == null)
return null;
return monitoredDir.getFile();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
/* ------------------------------------------------------------ */
/**
* The context xml directory. In fact it is the directory watched by the
* scanner.
*/
public String getContextXmlDir()
{
try
{
Resource monitoredDir = getMonitoredDirResource();
if (monitoredDir == null)
return null;
return monitoredDir.getFile().toURI().toString();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
public boolean isExtract()
{
return _extractWars;
}
public void setExtract(boolean extract)
{
_extractWars=extract;
}
/**
* @return true when this app provider locates osgi bundles and features in
* its monitored directory and installs them. By default true if there is a folder to monitor.
*/
public boolean isAutoInstallOSGiBundles()
{
return _autoInstallOSGiBundles;
}
/**
* <autoInstallOSGiBundles>true</autoInstallOSGiBundles>
* @param installingOSGiBundles
*/
public void setAutoInstallOSGiBundles(boolean installingOSGiBundles)
{
_autoInstallOSGiBundles=installingOSGiBundles;
}
/* ------------------------------------------------------------ */
/**
* Set the directory in which to look for context XML files.
* <p>
* If a webapp call "foo/" or "foo.war" is discovered in the monitored
* directory, then the ContextXmlDir is examined to see if a foo.xml file
* exists. If it does, then this deployer will not deploy the webapp and the
* ContextProvider should be used to act on the foo.xml file.
* </p>
* <p>
* Also if this directory contains some osgi bundles, it will install them.
* </p>
*
* @see ContextProvider
* @param contextsDir
*/
public void setContextXmlDir(String contextsDir)
{
setMonitoredDirName(contextsDir);
}
/**
* @param tldBundles Comma separated list of bundles that contain tld jars
* that should be setup on the jetty instances created here.
*/
public void setTldBundles(String tldBundles)
{
_tldBundles = tldBundles;
}
/**
* @return The list of bundles that contain tld jars that should be setup
* on the jetty instances created here.
*/
public String getTldBundles()
{
return _tldBundles;
}
/**
* @param configurations The configuration class names.
*/
public void setConfigurationClasses(String[] configurations)
{
_configurationClasses = configurations==null?null:(String[])configurations.clone();
}
/* ------------------------------------------------------------ */
/**
*
*/
public String[] getConfigurationClasses()
{
return _configurationClasses;
}
/**
* Overridden to install the OSGi bundles found in the monitored folder.
*/
protected void doStart() throws Exception
{
if (isAutoInstallOSGiBundles())
{
if (getMonitoredDirResource() == null)
{
setAutoInstallOSGiBundles(false);
Log.info("Disable autoInstallOSGiBundles as there is not contexts folder to monitor.");
}
else
{
File scandir = null;
try
{
scandir = getMonitoredDirResource().getFile();
if (!scandir.exists() || !scandir.isDirectory())
{
setAutoInstallOSGiBundles(false);
- Log.info("Disable autoInstallOSGiBundles as the contexts folder '" + scandir.getAbsolutePath() + " does not exist.");
+ Log.warn("Disable autoInstallOSGiBundles as the contexts folder '" + scandir.getAbsolutePath() + " does not exist.");
scandir = null;
}
}
catch (IOException ioe)
{
setAutoInstallOSGiBundles(false);
- Log.info("Disable autoInstallOSGiBundles as the contexts folder '" + getMonitoredDirResource().getURI() + " does not exist.");
+ Log.warn("Disable autoInstallOSGiBundles as the contexts folder '" + getMonitoredDirResource().getURI() + " does not exist.");
scandir = null;
}
if (scandir != null)
{
for (File file : scandir.listFiles())
{
if (fileMightBeAnOSGiBundle(file))
{
installBundle(file, false);
}
}
}
}
}
super.doStart();
if (isAutoInstallOSGiBundles())
{
Scanner.ScanCycleListener scanCycleListner = new AutoStartWhenFrameworkHasCompleted(this);
super.addScannerListener(scanCycleListner);
}
}
/**
* When the file is a jar or a folder, we look if it looks like an OSGi bundle.
* In that case we install it and start it.
* <p>
* Really a simple trick to get going quickly with development.
* </p>
*/
@Override
protected void fileAdded(String filename) throws Exception
{
File file = new File(filename);
if (isAutoInstallOSGiBundles() && file.exists() && fileMightBeAnOSGiBundle(file))
{
installBundle(file, true);
}
else
{
super.fileAdded(filename);
}
}
/**
* @param file
* @return
*/
private static boolean fileMightBeAnOSGiBundle(File file)
{
if (file.isDirectory())
{
if (new File(file,"META-INF/MANIFEST.MF").exists())
{
return true;
}
}
else if (file.getName().endsWith(".jar"))
{
return true;
}
return false;
}
@Override
protected void fileChanged(String filename) throws Exception
{
File file = new File(filename);
if (isAutoInstallOSGiBundles() && fileMightBeAnOSGiBundle(file))
{
updateBundle(file);
}
else
{
super.fileChanged(filename);
}
}
@Override
protected void fileRemoved(String filename) throws Exception
{
File file = new File(filename);
if (isAutoInstallOSGiBundles() && fileMightBeAnOSGiBundle(file))
{
uninstallBundle(file);
}
else
{
super.fileRemoved(filename);
}
}
/**
* Returns a bundle according to its location.
* In the version 1.6 of org.osgi.framework, BundleContext.getBundle(String) is what we want.
* However to support older versions of OSGi. We use our own local refrence mechanism.
* @param location
* @return
*/
protected Bundle getBundle(BundleContext bc, String location)
{
//not available in older versions of OSGi:
//return bc.getBundle(location);
for (Bundle b : bc.getBundles())
{
if (b.getLocation().equals(location))
{
return b;
}
}
return null;
}
protected synchronized Bundle installBundle(File file, boolean start)
{
try
{
BundleContext bc = JettyBootstrapActivator.getBundleContext();
String location = file.toURI().toString();
Bundle b = getBundle(bc, location);
if (b == null)
{
b = bc.installBundle(location);
}
if (b == null)
{
//not sure we will ever be here,
//most likely a BundleException was thrown
Log.warn("The file " + location + " is not an OSGi bundle.");
return null;
}
if (start && b.getHeaders().get(Constants.FRAGMENT_HOST) == null)
{//not a fragment, try to start it. if the framework has finished auto-starting.
if (!PackageAdminServiceTracker.INSTANCE.frameworkHasCompletedAutostarts())
{
if (_pendingBundlesToStart == null)
{
_pendingBundlesToStart = new HashSet<Bundle>();
}
_pendingBundlesToStart.add(b);
return null;
}
else
{
b.start();
}
}
return b;
}
catch (BundleException e)
{
Log.warn("Unable to " + (start? "start":"install") + " the bundle " + file.getAbsolutePath(), e);
}
return null;
}
protected void uninstallBundle(File file)
{
try
{
Bundle b = getBundle(JettyBootstrapActivator.getBundleContext(), file.toURI().toString());
b.stop();
b.uninstall();
}
catch (BundleException e)
{
Log.warn("Unable to uninstall the bundle " + file.getAbsolutePath(), e);
}
}
protected void updateBundle(File file)
{
try
{
Bundle b = getBundle(JettyBootstrapActivator.getBundleContext(), file.toURI().toString());
if (b == null)
{
installBundle(file, true);
}
else if (b.getState() == Bundle.ACTIVE)
{
b.update();
}
else
{
b.start();
}
}
catch (BundleException e)
{
Log.warn("Unable to update the bundle " + file.getAbsolutePath(), e);
}
}
}
/**
* At the end of each scan, if there are some bundles to be started,
* look if the framework has completed its autostart. In that case start those bundles.
*/
class AutoStartWhenFrameworkHasCompleted implements Scanner.ScanCycleListener
{
private final OSGiAppProvider _appProvider;
AutoStartWhenFrameworkHasCompleted(OSGiAppProvider appProvider)
{
_appProvider = appProvider;
}
public void scanStarted(int cycle) throws Exception
{
}
public void scanEnded(int cycle) throws Exception
{
if (_appProvider._pendingBundlesToStart != null && PackageAdminServiceTracker.INSTANCE.frameworkHasCompletedAutostarts())
{
Iterator<Bundle> it = _appProvider._pendingBundlesToStart.iterator();
while (it.hasNext())
{
Bundle b = it.next();
if (b.getHeaders().get(Constants.FRAGMENT_HOST) != null)
{
continue;
}
try
{
b.start();
}
catch (BundleException e)
{
Log.warn("Unable to start the bundle " + b.getLocation(), e);
}
}
_appProvider._pendingBundlesToStart = null;
}
}
}
| false | true | protected void doStart() throws Exception
{
if (isAutoInstallOSGiBundles())
{
if (getMonitoredDirResource() == null)
{
setAutoInstallOSGiBundles(false);
Log.info("Disable autoInstallOSGiBundles as there is not contexts folder to monitor.");
}
else
{
File scandir = null;
try
{
scandir = getMonitoredDirResource().getFile();
if (!scandir.exists() || !scandir.isDirectory())
{
setAutoInstallOSGiBundles(false);
Log.info("Disable autoInstallOSGiBundles as the contexts folder '" + scandir.getAbsolutePath() + " does not exist.");
scandir = null;
}
}
catch (IOException ioe)
{
setAutoInstallOSGiBundles(false);
Log.info("Disable autoInstallOSGiBundles as the contexts folder '" + getMonitoredDirResource().getURI() + " does not exist.");
scandir = null;
}
if (scandir != null)
{
for (File file : scandir.listFiles())
{
if (fileMightBeAnOSGiBundle(file))
{
installBundle(file, false);
}
}
}
}
}
super.doStart();
if (isAutoInstallOSGiBundles())
{
Scanner.ScanCycleListener scanCycleListner = new AutoStartWhenFrameworkHasCompleted(this);
super.addScannerListener(scanCycleListner);
}
}
| protected void doStart() throws Exception
{
if (isAutoInstallOSGiBundles())
{
if (getMonitoredDirResource() == null)
{
setAutoInstallOSGiBundles(false);
Log.info("Disable autoInstallOSGiBundles as there is not contexts folder to monitor.");
}
else
{
File scandir = null;
try
{
scandir = getMonitoredDirResource().getFile();
if (!scandir.exists() || !scandir.isDirectory())
{
setAutoInstallOSGiBundles(false);
Log.warn("Disable autoInstallOSGiBundles as the contexts folder '" + scandir.getAbsolutePath() + " does not exist.");
scandir = null;
}
}
catch (IOException ioe)
{
setAutoInstallOSGiBundles(false);
Log.warn("Disable autoInstallOSGiBundles as the contexts folder '" + getMonitoredDirResource().getURI() + " does not exist.");
scandir = null;
}
if (scandir != null)
{
for (File file : scandir.listFiles())
{
if (fileMightBeAnOSGiBundle(file))
{
installBundle(file, false);
}
}
}
}
}
super.doStart();
if (isAutoInstallOSGiBundles())
{
Scanner.ScanCycleListener scanCycleListner = new AutoStartWhenFrameworkHasCompleted(this);
super.addScannerListener(scanCycleListner);
}
}
|
diff --git a/org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/internal/ui/IntegerFilterDialog.java b/org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/internal/ui/IntegerFilterDialog.java
index b39ca2e3e..f60357e27 100644
--- a/org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/internal/ui/IntegerFilterDialog.java
+++ b/org.caleydo.vis.lineup/src/main/java/org/caleydo/vis/lineup/internal/ui/IntegerFilterDialog.java
@@ -1,98 +1,99 @@
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.vis.lineup.internal.ui;
import org.caleydo.core.event.EventPublisher;
import org.caleydo.vis.lineup.internal.event.IntegerFilterEvent;
import org.caleydo.vis.lineup.model.mixin.IFilterColumnMixin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* @author Samuel Gratzl
*
*/
public class IntegerFilterDialog extends AFilterDialog {
private final int min;
private final int max;
private Text minUI;
private Text maxUI;
public IntegerFilterDialog(Shell parentShell, String title, Object receiver, int min, int max,
IFilterColumnMixin model, boolean hasSnapshots, Point loc) {
super(parentShell, "Filter " + title, receiver, model, hasSnapshots, loc);
this.min = min;
this.max = max;
}
@Override
public void create() {
super.create();
getShell().setText("Edit Filter of size");
}
@Override
protected void createSpecificFilterUI(Composite composite) {
VerifyListener isNumber = new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
String text = e.text;
text = text.replaceAll("\\D|-", "");
e.text = text;
}
};
Composite p = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout(3, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
p.setLayout(layout);
+ p.setLayoutData(twoColumns(new GridData(SWT.FILL, SWT.CENTER, true, true)));
- GridData d = new GridData(SWT.LEFT, SWT.CENTER, true, true);
+ GridData d = new GridData(SWT.FILL, SWT.CENTER, true, true);
d.widthHint = getCharWith(composite, 4);
minUI = new Text(p, SWT.BORDER);
minUI.setLayoutData(d);
if (min > 0)
minUI.setText(min + "");
minUI.addVerifyListener(isNumber);
Label l = new Label(p, SWT.NONE);
l.setText("<= VALUE <=");
l.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true));
maxUI = new Text(p, SWT.BORDER);
maxUI.setLayoutData(d);
if (max < Integer.MAX_VALUE)
maxUI.setText(max + "");
maxUI.addVerifyListener(isNumber);
addButtonAndOption(composite);
}
@Override
protected void triggerEvent(boolean cancel) {
if (cancel) {
EventPublisher.trigger(new IntegerFilterEvent(min, max).to(receiver));
return;
}
String t = minUI.getText().trim();
Integer minV = t.length() > 0 ? new Integer(t) : null;
t = maxUI.getText().trim();
Integer maxV = t.length() > 0 ? new Integer(t) : null;
EventPublisher.trigger(new IntegerFilterEvent(minV, maxV).to(receiver));
}
}
| false | true | protected void createSpecificFilterUI(Composite composite) {
VerifyListener isNumber = new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
String text = e.text;
text = text.replaceAll("\\D|-", "");
e.text = text;
}
};
Composite p = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout(3, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
p.setLayout(layout);
GridData d = new GridData(SWT.LEFT, SWT.CENTER, true, true);
d.widthHint = getCharWith(composite, 4);
minUI = new Text(p, SWT.BORDER);
minUI.setLayoutData(d);
if (min > 0)
minUI.setText(min + "");
minUI.addVerifyListener(isNumber);
Label l = new Label(p, SWT.NONE);
l.setText("<= VALUE <=");
l.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true));
maxUI = new Text(p, SWT.BORDER);
maxUI.setLayoutData(d);
if (max < Integer.MAX_VALUE)
maxUI.setText(max + "");
maxUI.addVerifyListener(isNumber);
addButtonAndOption(composite);
}
| protected void createSpecificFilterUI(Composite composite) {
VerifyListener isNumber = new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
String text = e.text;
text = text.replaceAll("\\D|-", "");
e.text = text;
}
};
Composite p = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout(3, false);
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 0;
p.setLayout(layout);
p.setLayoutData(twoColumns(new GridData(SWT.FILL, SWT.CENTER, true, true)));
GridData d = new GridData(SWT.FILL, SWT.CENTER, true, true);
d.widthHint = getCharWith(composite, 4);
minUI = new Text(p, SWT.BORDER);
minUI.setLayoutData(d);
if (min > 0)
minUI.setText(min + "");
minUI.addVerifyListener(isNumber);
Label l = new Label(p, SWT.NONE);
l.setText("<= VALUE <=");
l.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, true));
maxUI = new Text(p, SWT.BORDER);
maxUI.setLayoutData(d);
if (max < Integer.MAX_VALUE)
maxUI.setText(max + "");
maxUI.addVerifyListener(isNumber);
addButtonAndOption(composite);
}
|
diff --git a/src/main/org/openscience/jchempaint/action/ChangeAtomSymbolAction.java b/src/main/org/openscience/jchempaint/action/ChangeAtomSymbolAction.java
index dcc9246..9b297ce 100755
--- a/src/main/org/openscience/jchempaint/action/ChangeAtomSymbolAction.java
+++ b/src/main/org/openscience/jchempaint/action/ChangeAtomSymbolAction.java
@@ -1,161 +1,161 @@
/*
* $RCSfile$
* $Author: egonw $
* $Date: 2007-01-04 17:26:00 +0000 (Thu, 04 Jan 2007) $
* $Revision: 7634 $
*
* Copyright (C) 1997-2008 Egon Willighagen, Stefan Kuhn
*
* Contact: [email protected]
*
* This program 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.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.openscience.jchempaint.action;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.openscience.cdk.config.IsotopeFactory;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IBond;
import org.openscience.cdk.interfaces.IChemObject;
import org.openscience.cdk.interfaces.IIsotope;
import org.openscience.jchempaint.controller.AddAtomModule;
import org.openscience.jchempaint.controller.AddBondDragModule;
import org.openscience.jchempaint.controller.IControllerModule;
import org.openscience.jchempaint.dialog.EnterElementOrGroupDialog;
import org.openscience.jchempaint.dialog.EnterElementSwingModule;
import org.openscience.jchempaint.dialog.PeriodicTableDialog;
/**
* changes the atom symbol
*/
public class ChangeAtomSymbolAction extends JCPAction
{
private static final long serialVersionUID = -8502905723573311893L;
private IControllerModule newActiveModule;
public void actionPerformed(ActionEvent event)
{
logger.debug("About to change atom type of relevant atom!");
IChemObject object = getSource(event);
logger.debug("Source of call: ", object);
Iterator<IAtom> atomsInRange = null;
if (object == null){
//this means the main menu was used
if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null &&
jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled())
atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().atoms().iterator();
}else if (object instanceof IAtom)
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add((IAtom) object);
atomsInRange = atoms.iterator();
} else
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom());
atomsInRange = atoms.iterator();
}
String s = event.getActionCommand();
String symbol = s.substring(s.indexOf("@") + 1);
if(symbol.equals("periodictable")){
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
// open PeriodicTable panel
PeriodicTableDialog dialog = new PeriodicTableDialog();
dialog.setName("periodictabledialog");
symbol=dialog.getChoosenSymbol();
if(symbol.equals(""))
return;
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false);
}else if(symbol.equals("enterelement")){
newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub());
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
if(atomsInRange!=null){
String[] funcGroupsKeys=new String[0];
symbol=EnterElementOrGroupDialog.showDialog(null,null, "Enter an element symbol:", "Enter element", funcGroupsKeys, "","");
if(symbol!=null && symbol.length()>0){
if(Character.isLowerCase(symbol.toCharArray()[0]))
symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1);
IsotopeFactory ifa;
try {
ifa = IsotopeFactory.getInstance(jcpPanel.getChemModel().getBuilder());
IIsotope iso=ifa.getMajorIsotope(symbol);
if(iso==null){
JOptionPane.showMessageDialog(jcpPanel, "No valid element symbol entered", "Invalid symbol", JOptionPane.WARNING_MESSAGE);
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}else{
//it must be a symbol
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
- jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
+ jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
}
if(atomsInRange!=null){
while(atomsInRange.hasNext()){
IAtom atom = atomsInRange.next();
jcpPanel.get2DHub().setSymbol(atom,symbol);
//TODO still needed? should this go in hub?
// configure the atom, so that the atomic number matches the symbol
try
{
IsotopeFactory.getInstance(atom.getBuilder()).configure(atom);
} catch (Exception exception)
{
logger.error("Error while configuring atom");
logger.debug(exception);
}
}
}
jcpPanel.get2DHub().updateView();
}
}
| false | true | public void actionPerformed(ActionEvent event)
{
logger.debug("About to change atom type of relevant atom!");
IChemObject object = getSource(event);
logger.debug("Source of call: ", object);
Iterator<IAtom> atomsInRange = null;
if (object == null){
//this means the main menu was used
if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null &&
jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled())
atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().atoms().iterator();
}else if (object instanceof IAtom)
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add((IAtom) object);
atomsInRange = atoms.iterator();
} else
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom());
atomsInRange = atoms.iterator();
}
String s = event.getActionCommand();
String symbol = s.substring(s.indexOf("@") + 1);
if(symbol.equals("periodictable")){
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
// open PeriodicTable panel
PeriodicTableDialog dialog = new PeriodicTableDialog();
dialog.setName("periodictabledialog");
symbol=dialog.getChoosenSymbol();
if(symbol.equals(""))
return;
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false);
}else if(symbol.equals("enterelement")){
newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub());
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
if(atomsInRange!=null){
String[] funcGroupsKeys=new String[0];
symbol=EnterElementOrGroupDialog.showDialog(null,null, "Enter an element symbol:", "Enter element", funcGroupsKeys, "","");
if(symbol!=null && symbol.length()>0){
if(Character.isLowerCase(symbol.toCharArray()[0]))
symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1);
IsotopeFactory ifa;
try {
ifa = IsotopeFactory.getInstance(jcpPanel.getChemModel().getBuilder());
IIsotope iso=ifa.getMajorIsotope(symbol);
if(iso==null){
JOptionPane.showMessageDialog(jcpPanel, "No valid element symbol entered", "Invalid symbol", JOptionPane.WARNING_MESSAGE);
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}else{
//it must be a symbol
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
}
if(atomsInRange!=null){
while(atomsInRange.hasNext()){
IAtom atom = atomsInRange.next();
jcpPanel.get2DHub().setSymbol(atom,symbol);
//TODO still needed? should this go in hub?
// configure the atom, so that the atomic number matches the symbol
try
{
IsotopeFactory.getInstance(atom.getBuilder()).configure(atom);
} catch (Exception exception)
{
logger.error("Error while configuring atom");
logger.debug(exception);
}
}
}
jcpPanel.get2DHub().updateView();
}
| public void actionPerformed(ActionEvent event)
{
logger.debug("About to change atom type of relevant atom!");
IChemObject object = getSource(event);
logger.debug("Source of call: ", object);
Iterator<IAtom> atomsInRange = null;
if (object == null){
//this means the main menu was used
if(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection()!=null &&
jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().isFilled())
atomsInRange=jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getSelection().getConnectedAtomContainer().atoms().iterator();
}else if (object instanceof IAtom)
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add((IAtom) object);
atomsInRange = atoms.iterator();
} else
{
List<IAtom> atoms = new ArrayList<IAtom>();
atoms.add(jcpPanel.getRenderPanel().getRenderer().getRenderer2DModel().getHighlightedAtom());
atomsInRange = atoms.iterator();
}
String s = event.getActionCommand();
String symbol = s.substring(s.indexOf("@") + 1);
if(symbol.equals("periodictable")){
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
// open PeriodicTable panel
PeriodicTableDialog dialog = new PeriodicTableDialog();
dialog.setName("periodictabledialog");
symbol=dialog.getChoosenSymbol();
if(symbol.equals(""))
return;
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
jcpPanel.get2DHub().getController2DModel().setDrawPseudoAtom(false);
}else if(symbol.equals("enterelement")){
newActiveModule=new EnterElementSwingModule(jcpPanel.get2DHub());
newActiveModule.setID(symbol);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
if(atomsInRange!=null){
String[] funcGroupsKeys=new String[0];
symbol=EnterElementOrGroupDialog.showDialog(null,null, "Enter an element symbol:", "Enter element", funcGroupsKeys, "","");
if(symbol!=null && symbol.length()>0){
if(Character.isLowerCase(symbol.toCharArray()[0]))
symbol=Character.toUpperCase(symbol.charAt(0))+symbol.substring(1);
IsotopeFactory ifa;
try {
ifa = IsotopeFactory.getInstance(jcpPanel.getChemModel().getBuilder());
IIsotope iso=ifa.getMajorIsotope(symbol);
if(iso==null){
JOptionPane.showMessageDialog(jcpPanel, "No valid element symbol entered", "Invalid symbol", JOptionPane.WARNING_MESSAGE);
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}else{
//it must be a symbol
if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddBondDragModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddBondDragModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else if(jcpPanel.get2DHub().getActiveDrawModule() instanceof AddAtomModule)
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), ((AddAtomModule)jcpPanel.get2DHub().getActiveDrawModule()).getStereoForNewBond());
else
newActiveModule=new AddAtomModule(jcpPanel.get2DHub(), IBond.Stereo.NONE);
newActiveModule.setID(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawElement(symbol);
jcpPanel.get2DHub().getController2DModel().setDrawIsotopeNumber(0);
jcpPanel.get2DHub().setActiveDrawModule(newActiveModule);
}
if(atomsInRange!=null){
while(atomsInRange.hasNext()){
IAtom atom = atomsInRange.next();
jcpPanel.get2DHub().setSymbol(atom,symbol);
//TODO still needed? should this go in hub?
// configure the atom, so that the atomic number matches the symbol
try
{
IsotopeFactory.getInstance(atom.getBuilder()).configure(atom);
} catch (Exception exception)
{
logger.error("Error while configuring atom");
logger.debug(exception);
}
}
}
jcpPanel.get2DHub().updateView();
}
|
diff --git a/examples/sky/ViewRSSI.java b/examples/sky/ViewRSSI.java
index 6451eb56..2886662e 100644
--- a/examples/sky/ViewRSSI.java
+++ b/examples/sky/ViewRSSI.java
@@ -1,86 +1,86 @@
/**
* RSSI Viewer - view RSSI values of 802.15.4 channels
* ---------------------------------------------------
* Note: run the rssi-scanner on a Sky or sentilla node connected to USB
* then start with
* make login | java ViewRSSI
*
* Created: Fri Apr 24 00:40:01 2009, Joakim Eriksson
*
* @author Joakim Eriksson, SICS
* @version 1.0
*/
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class ViewRSSI extends JPanel {
private int[] rssi = new int[80];
private int[] rssiMax = new int[80];
/* this is the max value of the RSSI from the cc2420 */
private static final int RSSI_MAX_VALUE = 200;
public ViewRSSI() {
}
public void paint(Graphics g) {
int h = getHeight();
int w = getWidth();
- g.clearRect(0, 0, 300, h);
+ g.clearRect(0, 0, w, h);
double factor = (h - 20.0) / RSSI_MAX_VALUE;
double sSpacing = (w - 15 ) / 80.0;
int sWidth = (int) (sSpacing - 1);
if (sWidth == 0) sWidth = 1;
g.setColor(Color.gray);
double xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssi = (int) (rssiMax[i] * factor);
g.fillRect((int) xpos, h - 20 - rssi,
sWidth, rssi + 1);
xpos += sSpacing;
}
g.setColor(Color.black);
xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssiVal = (int) (rssi[i] * factor);
g.fillRect((int) xpos, h - 20 - rssiVal,
sWidth, rssiVal + 1);
xpos += sSpacing;
}
}
private void handleInput() throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
while(true) {
String line = reader.readLine();
if (line.startsWith("RSSI:")) {
try {
String[] parts = line.split(" ");
for (int i = 1, n = parts.length; i < n; i++) {
rssi[i] = 3 * Integer.parseInt(parts[i]);
if (rssi[i] > rssiMax[i]) rssiMax[i] = rssi[i];
else if (rssiMax[i] > 0) rssiMax[i]--;
}
} catch (Exception e) {
/* report but do not fail... */
e.printStackTrace();
}
repaint();
}
}
}
public static void main(String[] args) throws IOException {
JFrame win = new JFrame("RSSI Viewer");
ViewRSSI panel;
win.setBounds(10, 10, 300, 300);
win.getContentPane().add(panel = new ViewRSSI());
win.setVisible(true);
panel.handleInput();
}
}
| true | true | public void paint(Graphics g) {
int h = getHeight();
int w = getWidth();
g.clearRect(0, 0, 300, h);
double factor = (h - 20.0) / RSSI_MAX_VALUE;
double sSpacing = (w - 15 ) / 80.0;
int sWidth = (int) (sSpacing - 1);
if (sWidth == 0) sWidth = 1;
g.setColor(Color.gray);
double xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssi = (int) (rssiMax[i] * factor);
g.fillRect((int) xpos, h - 20 - rssi,
sWidth, rssi + 1);
xpos += sSpacing;
}
g.setColor(Color.black);
xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssiVal = (int) (rssi[i] * factor);
g.fillRect((int) xpos, h - 20 - rssiVal,
sWidth, rssiVal + 1);
xpos += sSpacing;
}
}
| public void paint(Graphics g) {
int h = getHeight();
int w = getWidth();
g.clearRect(0, 0, w, h);
double factor = (h - 20.0) / RSSI_MAX_VALUE;
double sSpacing = (w - 15 ) / 80.0;
int sWidth = (int) (sSpacing - 1);
if (sWidth == 0) sWidth = 1;
g.setColor(Color.gray);
double xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssi = (int) (rssiMax[i] * factor);
g.fillRect((int) xpos, h - 20 - rssi,
sWidth, rssi + 1);
xpos += sSpacing;
}
g.setColor(Color.black);
xpos = 10;
for (int i = 0, n = rssi.length; i < n; i++) {
int rssiVal = (int) (rssi[i] * factor);
g.fillRect((int) xpos, h - 20 - rssiVal,
sWidth, rssiVal + 1);
xpos += sSpacing;
}
}
|
diff --git a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
index 97ea809..d5b718e 100644
--- a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
+++ b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/Cleaner.java
@@ -1,198 +1,198 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.buildTriggers.vcs.git;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.SimpleCommandLineProcessRunner;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.serverSide.*;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.FileUtil;
import jetbrains.buildServer.vcs.SVcsRoot;
import jetbrains.buildServer.vcs.VcsException;
import jetbrains.buildServer.vcs.VcsRoot;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Cleans unused git repositories
* @author dmitry.neverov
*/
public class Cleaner extends BuildServerAdapter {
private static Logger LOG = Loggers.CLEANUP;
private final SBuildServer myServer;
private final ServerPaths myPaths;
private final GitVcsSupport myGitVcsSupport;
public Cleaner(@NotNull final SBuildServer server,
@NotNull final EventDispatcher<BuildServerListener> dispatcher,
@NotNull final ServerPaths paths,
@NotNull final GitVcsSupport gitSupport) {
myServer = server;
myPaths = paths;
myGitVcsSupport = gitSupport;
dispatcher.addListener(this);
}
@Override
public void cleanupStarted() {
super.cleanupFinished();
myServer.getExecutor().submit(new Runnable() {
public void run() {
clean();
}
});
}
private void clean() {
LOG.debug("Clean started");
removeUnusedRepositories();
if (isRunNativeGC()) {
runNativeGC();
}
LOG.debug("Clean finished");
}
private void removeUnusedRepositories() {
Collection<? extends SVcsRoot> gitRoots = getAllGitRoots();
List<File> unusedDirs = getUnusedDirs(gitRoots);
LOG.debug("Remove unused repositories started");
for (File dir : unusedDirs) {
LOG.info("Remove unused dir " + dir.getAbsolutePath());
synchronized (myGitVcsSupport.getRepositoryLock(dir)) {
FileUtil.delete(dir);
}
LOG.debug("Remove unused dir " + dir.getAbsolutePath() + " finished");
}
LOG.debug("Remove unused repositories finished");
}
private Collection<? extends SVcsRoot> getAllGitRoots() {
return myServer.getVcsManager().findRootsByVcsName(Constants.VCS_NAME);
}
private List<File> getUnusedDirs(Collection<? extends SVcsRoot> roots) {
List<File> repositoryDirs = getAllRepositoryDirs();
File cacheDir = new File(myPaths.getCachesDir());
for (VcsRoot root : roots) {
try {
File usedRootDir = Settings.getRepositoryPath(cacheDir, root);
repositoryDirs.remove(usedRootDir);
} catch (Exception e) {
LOG.warn("Get repository path error", e);
}
}
return repositoryDirs;
}
private List<File> getAllRepositoryDirs() {
String teamcityCachesPath = myPaths.getCachesDir();
File gitCacheDir = new File(teamcityCachesPath, "git");
return new ArrayList<File>(FileUtil.getSubDirectories(gitCacheDir));
}
private boolean isRunNativeGC() {
return TeamCityProperties.getBoolean("teamcity.server.git.gc.enabled");
}
private String getPathToGit() {
return TeamCityProperties.getProperty("teamcity.server.git.executable.path", "git");
}
private long getNativeGCQuotaMilliseconds() {
int quotaInMinutes = TeamCityProperties.getInteger("teamcity.server.git.gc.quota.minutes", 60);
return minutes2Milliseconds(quotaInMinutes);
}
private long minutes2Milliseconds(int quotaInMinutes) {
return quotaInMinutes * 60 * 1000L;
}
private void runNativeGC() {
final long start = System.currentTimeMillis();
final long gcTimeQuota = getNativeGCQuotaMilliseconds();
LOG.info("Garbage collection started");
List<File> allDirs = getAllRepositoryDirs();
int runGCCounter = 0;
for (File gitDir : allDirs) {
synchronized (myGitVcsSupport.getRepositoryLock(gitDir)) {
runNativeGC(gitDir);
}
runGCCounter++;
final long repositoryFinish = System.currentTimeMillis();
if ((repositoryFinish - start) > gcTimeQuota) {
final int restRepositories = allDirs.size() - runGCCounter;
if (restRepositories > 0) {
LOG.info("Garbage collection quota exceeded, skip " + restRepositories + " repositories");
break;
}
}
}
final long finish = System.currentTimeMillis();
LOG.info("Garbage collection finished, it took " + (finish - start) + "ms");
}
private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
- LOG.warn("Error output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
- LOG.warn(result.getStderr());
+ LOG.debug("Output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
+ LOG.debug(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
}
| true | true | private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
LOG.warn("Error output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
LOG.warn(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
| private void runNativeGC(final File bareGitDir) {
String pathToGit = getPathToGit();
try {
final long start = System.currentTimeMillis();
GeneralCommandLine cl = new GeneralCommandLine();
cl.setWorkingDirectory(bareGitDir.getParentFile());
cl.setExePath(pathToGit);
cl.addParameter("--git-dir="+bareGitDir.getCanonicalPath());
cl.addParameter("gc");
cl.addParameter("--auto");
cl.addParameter("--quiet");
ExecResult result = SimpleCommandLineProcessRunner.runCommand(cl, null, new SimpleCommandLineProcessRunner.RunCommandEvents() {
public void onProcessStarted(Process ps) {
if (LOG.isDebugEnabled()) {
LOG.info("Start 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
}
}
public void onProcessFinished(Process ps) {
if (LOG.isDebugEnabled()) {
final long finish = System.currentTimeMillis();
LOG.info("Finish 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc', it took " + (finish - start) + "ms");
}
}
public Integer getOutputIdleSecondsTimeout() {
return 3 * 60 * 60;//3 hours
}
});
VcsException commandError = CommandLineUtil.getCommandLineError("'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", result);
if (commandError != null) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", commandError);
}
if (result.getStderr().length() > 0) {
LOG.debug("Output produced by 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'");
LOG.debug(result.getStderr());
}
} catch (Exception e) {
LOG.error("Error while running 'git --git-dir=" + bareGitDir.getAbsolutePath() + " gc'", e);
}
}
|
diff --git a/codemodel/src/main/java/com/sun/codemodel/JExpr.java b/codemodel/src/main/java/com/sun/codemodel/JExpr.java
index e1c79bc..ac3d33e 100644
--- a/codemodel/src/main/java/com/sun/codemodel/JExpr.java
+++ b/codemodel/src/main/java/com/sun/codemodel/JExpr.java
@@ -1,251 +1,255 @@
/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* https://jwsdp.dev.java.net/CDDLv1.0.html
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* https://jwsdp.dev.java.net/CDDLv1.0.html If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
package com.sun.codemodel;
/**
* Factory methods that generate various {@link JExpression}s.
*/
public abstract class JExpr {
/**
* This class is not instanciable.
*/
private JExpr() { }
public static JExpression assign(JAssignmentTarget lhs, JExpression rhs) {
return new JAssignment(lhs, rhs);
}
public static JExpression assignPlus(JAssignmentTarget lhs, JExpression rhs) {
return new JAssignment(lhs, rhs, "+");
}
public static JInvocation _new(JClass c) {
return new JInvocation(c);
}
public static JInvocation _new(JType t) {
return new JInvocation(t);
}
public static JInvocation invoke(String method) {
return new JInvocation((JExpression)null, method);
}
public static JInvocation invoke(JMethod method) {
return new JInvocation((JExpression)null,method);
}
public static JInvocation invoke(JExpression lhs, JMethod method) {
return new JInvocation(lhs, method);
}
public static JInvocation invoke(JExpression lhs, String method) {
return new JInvocation(lhs, method);
}
public static JFieldRef ref(String field) {
return new JFieldRef((JExpression)null, field);
}
public static JFieldRef ref(JExpression lhs, JVar field) {
return new JFieldRef(lhs,field);
}
public static JFieldRef ref(JExpression lhs, String field) {
return new JFieldRef(lhs, field);
}
public static JFieldRef refthis(String field) {
return new JFieldRef(null, field, true);
}
public static JExpression dotclass(final JClass cl) {
return new JExpressionImpl() {
public void generate(JFormatter f) {
JClass c;
if(cl instanceof JNarrowedClass)
c = ((JNarrowedClass)cl).basis;
else
c = cl;
f.g(c).p(".class");
}
};
}
public static JArrayCompRef component(JExpression lhs, JExpression index) {
return new JArrayCompRef(lhs, index);
}
public static JCast cast(JType type, JExpression expr) {
return new JCast(type, expr);
}
public static JArray newArray(JType type) {
return newArray(type,null);
}
/**
* Generates {@code new T[size]}.
*
* @param type
* The type of the array component. 'T' or {@code new T[size]}.
*/
public static JArray newArray(JType type, JExpression size) {
// you cannot create an array whose component type is a generic
return new JArray(type.erasure(), size);
}
/**
* Generates {@code new T[size]}.
*
* @param type
* The type of the array component. 'T' or {@code new T[size]}.
*/
public static JArray newArray(JType type, int size) {
return newArray(type,lit(size));
}
private static final JExpression __this = new JAtom("this");
/**
* Returns a reference to "this", an implicit reference
* to the current object.
*/
public static JExpression _this() { return __this; }
private static final JExpression __super = new JAtom("super");
/**
* Returns a reference to "super", an implicit reference
* to the super class.
*/
public static JExpression _super() { return __super; }
/* -- Literals -- */
private static final JExpression __null = new JAtom("null");
public static JExpression _null() {
return __null;
}
/**
* Boolean constant that represents <code>true</code>
*/
public static final JExpression TRUE = new JAtom("true");
/**
* Boolean constant that represents <code>false</code>
*/
public static final JExpression FALSE = new JAtom("false");
public static JExpression lit(boolean b) {
return b?TRUE:FALSE;
}
public static JExpression lit(int n) {
return new JAtom(Integer.toString(n));
}
public static JExpression lit(long n) {
return new JAtom(Long.toString(n) + "L");
}
public static JExpression lit(float f) {
return new JAtom(Float.toString(f) + "F");
}
public static JExpression lit(double d) {
return new JAtom(Double.toString(d) + "D");
}
static final String charEscape = "\b\t\n\f\r\"\'\\";
static final String charMacro = "btnfr\"'\\";
/**
* Escapes the given string, then surrounds it by the specified
* quotation mark.
*/
public static String quotify(char quote, String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(n + 2);
sb.append(quote);
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int j = charEscape.indexOf(c);
if(j>=0) {
- sb.append('\\');
- sb.append(charMacro.charAt(j));
+ if((quote=='"' && c=='\'') || (quote=='\'' && c=='"')) {
+ sb.append(c);
+ } else {
+ sb.append('\\');
+ sb.append(charMacro.charAt(j));
+ }
} else {
// technically Unicode escape shouldn't be done here,
// for it's a lexical level handling.
//
// However, various tools are so broken around this area,
// so just to be on the safe side, it's better to do
// the escaping here (regardless of the actual file encoding)
//
// see bug
if( c<0x20 || 0x7E<c ) {
// not printable. use Unicode escape
sb.append("\\u");
String hex = Integer.toHexString(((int)c)&0xFFFF);
for( int k=hex.length(); k<4; k++ )
sb.append('0');
sb.append(hex);
} else {
sb.append(c);
}
}
}
sb.append(quote);
return sb.toString();
}
public static JExpression lit(char c) {
return new JAtom(quotify('\'', "" + c));
}
public static JExpression lit(String s) {
return new JStringLiteral(s);
}
/**
* Creates an expression directly from a source code fragment.
*
* <p>
* This method can be used as a short-cut to create a JExpression.
* For example, instead of <code>_a.gt(_b)</code>, you can write
* it as: <code>JExpr.direct("a>b")</code>.
*
* <p>
* Be warned that there is a danger in using this method,
* as it obfuscates the object model.
*/
public static JExpression direct( final String source ) {
return new JExpressionImpl(){
public void generate( JFormatter f ) {
f.p('(').p(source).p(')');
}
};
}
}
| true | true | public static String quotify(char quote, String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(n + 2);
sb.append(quote);
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int j = charEscape.indexOf(c);
if(j>=0) {
sb.append('\\');
sb.append(charMacro.charAt(j));
} else {
// technically Unicode escape shouldn't be done here,
// for it's a lexical level handling.
//
// However, various tools are so broken around this area,
// so just to be on the safe side, it's better to do
// the escaping here (regardless of the actual file encoding)
//
// see bug
if( c<0x20 || 0x7E<c ) {
// not printable. use Unicode escape
sb.append("\\u");
String hex = Integer.toHexString(((int)c)&0xFFFF);
for( int k=hex.length(); k<4; k++ )
sb.append('0');
sb.append(hex);
} else {
sb.append(c);
}
}
}
sb.append(quote);
return sb.toString();
}
| public static String quotify(char quote, String s) {
int n = s.length();
StringBuilder sb = new StringBuilder(n + 2);
sb.append(quote);
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int j = charEscape.indexOf(c);
if(j>=0) {
if((quote=='"' && c=='\'') || (quote=='\'' && c=='"')) {
sb.append(c);
} else {
sb.append('\\');
sb.append(charMacro.charAt(j));
}
} else {
// technically Unicode escape shouldn't be done here,
// for it's a lexical level handling.
//
// However, various tools are so broken around this area,
// so just to be on the safe side, it's better to do
// the escaping here (regardless of the actual file encoding)
//
// see bug
if( c<0x20 || 0x7E<c ) {
// not printable. use Unicode escape
sb.append("\\u");
String hex = Integer.toHexString(((int)c)&0xFFFF);
for( int k=hex.length(); k<4; k++ )
sb.append('0');
sb.append(hex);
} else {
sb.append(c);
}
}
}
sb.append(quote);
return sb.toString();
}
|
diff --git a/src/tconstruct/plugins/misc/PeaceOfMind.java b/src/tconstruct/plugins/misc/PeaceOfMind.java
index ac55756d6..fdec2f2d6 100644
--- a/src/tconstruct/plugins/misc/PeaceOfMind.java
+++ b/src/tconstruct/plugins/misc/PeaceOfMind.java
@@ -1,42 +1,43 @@
package tconstruct.plugins.misc;
import java.lang.reflect.Field;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.FMLModContainer;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.ModContainer;
@Mod(modid = "TConstruct|PeaceOfMind", name = "TConstruct|PeaceOfMind", version = "1.0")
public class PeaceOfMind
{
public static boolean completeShutdown = false;
public PeaceOfMind()
{
/** Explicit permission: http://forum.industrial-craft.net/index.php?page=Thread&postID=121457#post121457
* Fixes Ore Dictionary debug spam
*/
try
{
Class ores = Class.forName("gregtechmod.common.GT_OreDictHandler");
try
{
Field ice = ores.getDeclaredField("instance");
- MinecraftForge.EVENT_BUS.unregister(ice);
+ Object o = ice.get(this);
+ MinecraftForge.EVENT_BUS.unregister(o);
}
catch (Exception e)
{
System.err.println("Cannot unregister GregTech Ore handler");
e.printStackTrace();
}
}
catch (Exception e)
{
//GT not here
}
}
}
| true | true | public PeaceOfMind()
{
/** Explicit permission: http://forum.industrial-craft.net/index.php?page=Thread&postID=121457#post121457
* Fixes Ore Dictionary debug spam
*/
try
{
Class ores = Class.forName("gregtechmod.common.GT_OreDictHandler");
try
{
Field ice = ores.getDeclaredField("instance");
MinecraftForge.EVENT_BUS.unregister(ice);
}
catch (Exception e)
{
System.err.println("Cannot unregister GregTech Ore handler");
e.printStackTrace();
}
}
catch (Exception e)
{
//GT not here
}
}
| public PeaceOfMind()
{
/** Explicit permission: http://forum.industrial-craft.net/index.php?page=Thread&postID=121457#post121457
* Fixes Ore Dictionary debug spam
*/
try
{
Class ores = Class.forName("gregtechmod.common.GT_OreDictHandler");
try
{
Field ice = ores.getDeclaredField("instance");
Object o = ice.get(this);
MinecraftForge.EVENT_BUS.unregister(o);
}
catch (Exception e)
{
System.err.println("Cannot unregister GregTech Ore handler");
e.printStackTrace();
}
}
catch (Exception e)
{
//GT not here
}
}
|
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java
index 187eeab..9553671 100755
--- a/src/com/android/nfc/NfcService.java
+++ b/src/com/android/nfc/NfcService.java
@@ -1,2634 +1,2632 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nfc;
import com.android.internal.nfc.LlcpServiceSocket;
import com.android.internal.nfc.LlcpSocket;
import com.android.nfc.mytag.MyTagClient;
import com.android.nfc.mytag.MyTagServer;
import android.app.Application;
import android.app.StatusBarManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.ErrorCodes;
import android.nfc.FormatException;
import android.nfc.ILlcpConnectionlessSocket;
import android.nfc.ILlcpServiceSocket;
import android.nfc.ILlcpSocket;
import android.nfc.INfcAdapter;
import android.nfc.INfcTag;
import android.nfc.IP2pInitiator;
import android.nfc.IP2pTarget;
import android.nfc.LlcpPacket;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.INfcSecureElement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;
public class NfcService extends Application {
static final boolean DBG = false;
private static final String MY_TAG_FILE_NAME = "mytag";
static {
System.loadLibrary("nfc_jni");
}
public static final String SERVICE_NAME = "nfc";
private static final String TAG = "NfcService";
private static final String NFC_PERM = android.Manifest.permission.NFC;
private static final String NFC_PERM_ERROR = "NFC permission required";
private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS;
private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required";
private static final String PREF = "NfcServicePrefs";
private static final String PREF_NFC_ON = "nfc_on";
private static final boolean NFC_ON_DEFAULT = true;
private static final String PREF_SECURE_ELEMENT_ON = "secure_element_on";
private static final boolean SECURE_ELEMENT_ON_DEFAULT = false;
private static final String PREF_SECURE_ELEMENT_ID = "secure_element_id";
private static final int SECURE_ELEMENT_ID_DEFAULT = 0;
private static final String PREF_LLCP_LTO = "llcp_lto";
private static final int LLCP_LTO_DEFAULT = 150;
private static final int LLCP_LTO_MAX = 255;
/** Maximum Information Unit */
private static final String PREF_LLCP_MIU = "llcp_miu";
private static final int LLCP_MIU_DEFAULT = 128;
private static final int LLCP_MIU_MAX = 2176;
/** Well Known Service List */
private static final String PREF_LLCP_WKS = "llcp_wks";
private static final int LLCP_WKS_DEFAULT = 1;
private static final int LLCP_WKS_MAX = 15;
private static final String PREF_LLCP_OPT = "llcp_opt";
private static final int LLCP_OPT_DEFAULT = 0;
private static final int LLCP_OPT_MAX = 3;
private static final String PREF_DISCOVERY_A = "discovery_a";
private static final boolean DISCOVERY_A_DEFAULT = true;
private static final String PREF_DISCOVERY_B = "discovery_b";
private static final boolean DISCOVERY_B_DEFAULT = true;
private static final String PREF_DISCOVERY_F = "discovery_f";
private static final boolean DISCOVERY_F_DEFAULT = true;
private static final String PREF_DISCOVERY_15693 = "discovery_15693";
private static final boolean DISCOVERY_15693_DEFAULT = true;
private static final String PREF_DISCOVERY_NFCIP = "discovery_nfcip";
private static final boolean DISCOVERY_NFCIP_DEFAULT = true;
/** NFC Reader Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_READER = 0;
/** Card Emulation Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_CARD_EMULATION = 2;
private static final int LLCP_SERVICE_SOCKET_TYPE = 0;
private static final int LLCP_SOCKET_TYPE = 1;
private static final int LLCP_CONNECTIONLESS_SOCKET_TYPE = 2;
private static final int LLCP_SOCKET_NB_MAX = 5; // Maximum number of socket managed
private static final int LLCP_RW_MAX_VALUE = 15; // Receive Window
private static final int PROPERTY_LLCP_LTO = 0;
private static final String PROPERTY_LLCP_LTO_VALUE = "llcp.lto";
private static final int PROPERTY_LLCP_MIU = 1;
private static final String PROPERTY_LLCP_MIU_VALUE = "llcp.miu";
private static final int PROPERTY_LLCP_WKS = 2;
private static final String PROPERTY_LLCP_WKS_VALUE = "llcp.wks";
private static final int PROPERTY_LLCP_OPT = 3;
private static final String PROPERTY_LLCP_OPT_VALUE = "llcp.opt";
private static final int PROPERTY_NFC_DISCOVERY_A = 4;
private static final String PROPERTY_NFC_DISCOVERY_A_VALUE = "discovery.iso14443A";
private static final int PROPERTY_NFC_DISCOVERY_B = 5;
private static final String PROPERTY_NFC_DISCOVERY_B_VALUE = "discovery.iso14443B";
private static final int PROPERTY_NFC_DISCOVERY_F = 6;
private static final String PROPERTY_NFC_DISCOVERY_F_VALUE = "discovery.felica";
private static final int PROPERTY_NFC_DISCOVERY_15693 = 7;
private static final String PROPERTY_NFC_DISCOVERY_15693_VALUE = "discovery.iso15693";
private static final int PROPERTY_NFC_DISCOVERY_NFCIP = 8;
private static final String PROPERTY_NFC_DISCOVERY_NFCIP_VALUE = "discovery.nfcip";
static final int MSG_NDEF_TAG = 0;
static final int MSG_CARD_EMULATION = 1;
static final int MSG_LLCP_LINK_ACTIVATION = 2;
static final int MSG_LLCP_LINK_DEACTIVATED = 3;
static final int MSG_TARGET_DESELECTED = 4;
static final int MSG_SHOW_MY_TAG_ICON = 5;
static final int MSG_HIDE_MY_TAG_ICON = 6;
static final int MSG_MOCK_NDEF = 7;
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
private final LinkedList<RegisteredSocket> mRegisteredSocketList = new LinkedList<RegisteredSocket>();
private int mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
private int mGeneratedSocketHandle = 0;
private int mNbSocketCreated = 0;
private volatile boolean mIsNfcEnabled = false;
private int mSelectedSeId = 0;
private boolean mNfcSecureElementState;
// Secure element
private Timer mTimerOpenSmx;
private boolean isClosed = false;
private boolean isOpened = false;
private boolean mOpenSmxPending = false;
private NativeNfcSecureElement mSecureElement;
private int mSecureElementHandle;
// fields below are used in multiple threads and protected by synchronized(this)
private final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
private final HashMap<Integer, Object> mSocketMap = new HashMap<Integer, Object>();
private boolean mScreenOn;
// fields below are final after onCreate()
private Context mContext;
private NativeNfcManager mManager;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
private PowerManager.WakeLock mWakeLock;
private MyTagServer mMyTagServer;
private MyTagClient mMyTagClient;
private static NfcService sService;
public static NfcService getInstance() {
return sService;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting NFC service");
sService = this;
mContext = this;
mManager = new NativeNfcManager(mContext, this);
mManager.initializeNativeStructure();
mMyTagServer = new MyTagServer();
mMyTagClient = new MyTagClient(this);
mSecureElement = new NativeNfcSecureElement();
mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
mIsNfcEnabled = false; // real preference read later
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mScreenOn = pm.isScreenOn();
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NfcService");
ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
mContext.registerReceiver(mReceiver, filter);
Thread t = new Thread() {
@Override
public void run() {
boolean nfc_on = mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT);
if (nfc_on) {
_enable(false);
}
}
};
t.start();
}
@Override
public void onTerminate() {
super.onTerminate();
// NFC application is persistent, it should not be destroyed by framework
Log.wtf(TAG, "NFC service is under attack!");
}
private final INfcAdapter.Stub mNfcAdapter = new INfcAdapter.Stub() {
/** Protected by "this" */
NdefMessage mLocalMessage = null;
@Override
public boolean enable() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean isSuccess = false;
boolean previouslyEnabled = isEnabled();
if (!previouslyEnabled) {
reset();
isSuccess = _enable(previouslyEnabled);
}
return isSuccess;
}
@Override
public boolean disable() throws RemoteException {
boolean isSuccess = false;
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean previouslyEnabled = isEnabled();
if (DBG) Log.d(TAG, "Disabling NFC. previous=" + previouslyEnabled);
if (previouslyEnabled) {
/* tear down the my tag server */
mMyTagServer.stop();
isSuccess = mManager.deinitialize();
if (DBG) Log.d(TAG, "NFC success of deinitialize = " + isSuccess);
if (isSuccess) {
mIsNfcEnabled = false;
}
}
updateNfcOnSetting(previouslyEnabled);
return isSuccess;
}
@Override
public int createLlcpConnectionlessSocket(int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* Check SAP is not already used */
/* Check nb socket created */
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* Store the socket handle */
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpConnectionlessSocket socket;
socket = mManager.doCreateLlcpConnectionlessSocket(sap);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
return sockeHandle;
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
NativeLlcpConnectionlessSocket socket = new NativeLlcpConnectionlessSocket(sap);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(
LLCP_CONNECTIONLESS_SOCKET_TYPE, sockeHandle, sap);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpServiceSocket socket;
socket = mManager.doCreateLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/* socket creation error - update the socket handle counter */
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Service Name */
if (!CheckSocketServiceName(sn)) {
return ErrorCodes.ERROR_SERVICE_NAME_USED;
}
/* Check socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpServiceSocket socket = new NativeLlcpServiceSocket(sap, sn, miu, rw,
linearBufferLength);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SERVICE_SOCKET_TYPE,
sockeHandle, sap, sn, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle += 1;
if (DBG) Log.d(TAG, "Llcp Service Socket Handle =" + sockeHandle);
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
if (DBG) Log.d(TAG, "creating llcp socket while activated");
NativeLlcpSocket socket;
socket = mManager.doCreateLlcpSocket(sap, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
Log.d(TAG, "failed to create llcp socket: " + ErrorCodes.asString(errorStatus));
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
if (DBG) Log.d(TAG, "registering llcp socket while not activated");
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Check Socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpSocket socket = new NativeLlcpSocket(sap, miu, rw);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SOCKET_TYPE,
sockeHandle, sap, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int deselectSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == 0) {
return ErrorCodes.ERROR_NO_SE_CONNECTED;
}
mManager.doDeselectSecureElement(mSelectedSeId);
mNfcSecureElementState = false;
mSelectedSeId = 0;
/* store preference */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, false);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, 0);
mPrefsEditor.apply();
return ErrorCodes.SUCCESS;
}
@Override
public ILlcpConnectionlessSocket getLlcpConnectionlessInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpConnectionlessSocketService;
}
@Override
public ILlcpSocket getLlcpInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpSocket;
}
@Override
public ILlcpServiceSocket getLlcpServiceInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpServerSocketService;
}
@Override
public INfcTag getNfcTagInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mNfcTagService;
}
@Override
public IP2pInitiator getP2pInitiatorInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pInitiatorService;
}
@Override
public IP2pTarget getP2pTargetInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pTargetService;
}
public INfcSecureElement getNfcSecureElementInterface() {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mSecureElementService;
}
@Override
public String getProperties(String param) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
if (param == null) {
return null;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT));
} else {
return "Unknown property";
}
}
@Override
public int[] getSecureElementList() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
int[] list = null;
if (mIsNfcEnabled == true) {
list = mManager.doGetSecureElementList();
}
return list;
}
@Override
public int getSelectedSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
return mSelectedSeId;
}
@Override
public boolean isEnabled() throws RemoteException {
return mIsNfcEnabled;
}
@Override
public void openTagConnection(Tag tag) throws RemoteException {
// TODO: Remove obsolete code
}
@Override
public int selectSecureElement(int seId) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == seId) {
return ErrorCodes.ERROR_SE_ALREADY_SELECTED;
}
if (mSelectedSeId != 0) {
return ErrorCodes.ERROR_SE_CONNECTED;
}
mSelectedSeId = seId;
mManager.doSelectSecureElement(mSelectedSeId);
/* store */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, mSelectedSeId);
mPrefsEditor.apply();
mNfcSecureElementState = true;
return ErrorCodes.SUCCESS;
}
@Override
public int setProperties(String param, String value) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
if (isEnabled()) {
return ErrorCodes.ERROR_NFC_ON;
}
int val;
/* Check params validity */
if (param == null || value == null) {
return ErrorCodes.ERROR_INVALID_PARAM;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_LTO_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_LTO, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_LTO, val);
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if ((val < LLCP_MIU_DEFAULT) || (val > LLCP_MIU_MAX))
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_MIU, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_MIU, val);
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_WKS_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_WKS, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_WKS, val);
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_OPT_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_OPT, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_OPT, val);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_A, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_B, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_F, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_15693, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_NFCIP, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, b ? 1 : 0);
} else {
return ErrorCodes.ERROR_INVALID_PARAM;
}
return ErrorCodes.SUCCESS;
}
@Override
public NdefMessage localGet() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
synchronized (this) {
return mLocalMessage;
}
}
@Override
public void localSet(NdefMessage message) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
synchronized (this) {
mLocalMessage = message;
Context context = NfcService.this.getApplicationContext();
// Send a message to the UI thread to show or hide the icon so the requests are
// serialized and the icon can't get out of sync with reality.
if (message != null) {
FileOutputStream out = null;
try {
out = context.openFileOutput(MY_TAG_FILE_NAME, Context.MODE_PRIVATE);
byte[] bytes = message.toByteArray();
if (bytes.length == 0) {
Log.w(TAG, "Setting a empty mytag");
}
out.write(bytes);
} catch (IOException e) {
Log.e(TAG, "Could not write mytag file", e);
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
// Ignore
}
}
// Only show the icon if NFC is enabled.
if (mIsNfcEnabled) {
sendMessage(MSG_SHOW_MY_TAG_ICON, null);
}
} else {
context.deleteFile(MY_TAG_FILE_NAME);
sendMessage(MSG_HIDE_MY_TAG_ICON, null);
}
}
}
};
private final ILlcpSocket mLlcpSocket = new ILlcpSocket.Stub() {
private final int CONNECT_FLAG = 0x01;
private final int CLOSE_FLAG = 0x02;
private final int RECV_FLAG = 0x04;
private final int SEND_FLAG = 0x08;
private int concurrencyFlags;
private Object sync;
@Override
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int connect(int nativeHandle, int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnect(sap);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int connectByName(int nativeHandle, String sn) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnectBy(sn);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int getLocalSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
@Override
public int getLocalSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getMiu();
} else {
return 0;
}
}
@Override
public int getLocalSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getRw();
} else {
return 0;
}
}
@Override
public int getRemoteSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketMiu() != 0) {
return socket.doGetRemoteSocketMiu();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
@Override
public int getRemoteSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketRw() != 0) {
return socket.doGetRemoteSocketRw();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
@Override
public int receive(int nativeHandle, byte[] receiveBuffer) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
int receiveLength = 0;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
receiveLength = socket.doReceive(receiveBuffer);
if (receiveLength != 0) {
return receiveLength;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSend(data);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
};
private final ILlcpServiceSocket mLlcpServerSocketService = new ILlcpServiceSocket.Stub() {
@Override
public int accept(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
NativeLlcpSocket clientSocket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
clientSocket = socket.doAccept(socket.getMiu(),
socket.getRw(), socket.getLinearBufferLength());
if (clientSocket != null) {
/* Add the socket into the socket map */
synchronized(this) {
mSocketMap.put(clientSocket.getHandle(), clientSocket);
mNbSocketCreated++;
}
return clientSocket.getHandle();
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
boolean closed = false;
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
closed = true;
}
} else {
closed = true;
}
}
// If the socket is closed remove it from the socket lists
if (closed) {
synchronized (this) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
}
}
}
};
private final ILlcpConnectionlessSocket mLlcpConnectionlessSocketService = new ILlcpConnectionlessSocket.Stub() {
@Override
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
}
}
@Override
public int getSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
@Override
public LlcpPacket receiveFrom(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
LlcpPacket packet;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
packet = socket.doReceiveFrom(socket.getLinkMiu());
if (packet != null) {
return packet;
}
return null;
} else {
return null;
}
}
@Override
public int sendTo(int nativeHandle, LlcpPacket packet) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSendTo(packet.getRemoteSap(), packet.getDataBuffer());
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
};
private final INfcTag mNfcTagService = new INfcTag.Stub() {
@Override
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
/* Remove the device from the hmap */
unregisterObject(nativeHandle);
tag.disconnect();
return ErrorCodes.SUCCESS;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
return ErrorCodes.ERROR_DISCONNECT;
}
@Override
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_DISCONNECT;
}
// TODO: register the tag as being locked rather than really connect
return ErrorCodes.SUCCESS;
}
@Override
public int[] getTechList(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
NativeNfcTag tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
return tag.getTechList();
}
return null;
}
@Override
public byte[] getUid(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
byte[] uid;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
uid = tag.getUid();
return uid;
}
return null;
}
@Override
public boolean isPresent(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return false;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return false;
}
return tag.presenceCheck();
}
@Override
public boolean isNdef(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
isSuccess = tag.checkNdef();
}
return isSuccess;
}
@Override
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
byte[] response;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
response = tag.transceive(data);
return response;
}
return null;
}
@Override
public NdefMessage read(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
byte[] buf = tag.read();
if (buf == null)
return null;
/* Create an NdefMessage */
try {
return new NdefMessage(buf);
} catch (FormatException e) {
return null;
}
}
return null;
}
@Override
public int write(int nativeHandle, NdefMessage msg) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (tag.write(msg.toByteArray())) {
return ErrorCodes.SUCCESS;
}
else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int getLastError(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getModeHint(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int makeReadOnly(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
};
private final IP2pInitiator mP2pInitiatorService = new IP2pInitiator.Stub() {
@Override
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
@Override
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
@Override
public byte[] receive(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doReceive();
if (buff == null)
return null;
return buff;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
return null;
}
@Override
public boolean send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
isSuccess = device.doSend(data);
}
return isSuccess;
}
};
private final IP2pTarget mP2pTargetService = new IP2pTarget.Stub() {
@Override
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (device.doConnect()) {
return ErrorCodes.SUCCESS;
}
}
return ErrorCodes.ERROR_CONNECT;
}
@Override
public boolean disconnect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (isSuccess = device.doDisconnect()) {
/* remove the device from the hmap */
unregisterObject(nativeHandle);
/* Restart polling loop for notification */
maybeEnableDiscovery();
}
}
return isSuccess;
}
@Override
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
@Override
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
@Override
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doTransceive(data);
if (buff == null)
return null;
return buff;
}
return null;
}
};
private INfcSecureElement mSecureElementService = new INfcSecureElement.Stub() {
public int openSecureElementConnection() throws RemoteException {
Log.d(TAG, "openSecureElementConnection");
int handle;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return 0;
}
// Check in an open is already pending
if (mOpenSmxPending) {
return 0;
}
handle = mSecureElement.doOpenSecureElementConnection();
if (handle == 0) {
mOpenSmxPending = false;
} else {
mSecureElementHandle = handle;
/* Start timer */
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
/* Update state */
isOpened = true;
isClosed = false;
mOpenSmxPending = true;
}
return handle;
}
public int closeSecureElementConnection(int nativeHandle)
throws RemoteException {
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
// Check if the SE connection is closed
if (isClosed) {
return -1;
}
// Check if the SE connection is opened
if (!isOpened) {
return -1;
}
if (mSecureElement.doDisconnect(nativeHandle)) {
/* Stop timer */
mTimerOpenSmx.cancel();
/* Restart polling loop for notification */
mManager.enableDiscovery(DISCOVERY_MODE_READER);
/* Update state */
isOpened = false;
isClosed = true;
mOpenSmxPending = false;
return ErrorCodes.SUCCESS;
} else {
/* Stop timer */
mTimerOpenSmx.cancel();
/* Restart polling loop for notification */
mManager.enableDiscovery(DISCOVERY_MODE_READER);
/* Update state */
isOpened = false;
isClosed = true;
mOpenSmxPending = false;
return ErrorCodes.ERROR_DISCONNECT;
}
}
public int[] getSecureElementTechList(int nativeHandle)
throws RemoteException {
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
int[] techList = mSecureElement.doGetTechList(nativeHandle);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return techList;
}
public byte[] getSecureElementUid(int nativeHandle)
throws RemoteException {
byte[] uid;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
uid = mSecureElement.doGetUid(nativeHandle);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return uid;
}
public byte[] exchangeAPDU(int nativeHandle, byte[] data)
throws RemoteException {
byte[] response;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
response = mSecureElement.doTransceive(nativeHandle, data);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return response;
}
};
class TimerOpenSecureElement extends TimerTask {
@Override
public void run() {
if (mSecureElementHandle != 0) {
Log.d(TAG, "Open SMX timer expired");
try {
mSecureElementService
.closeSecureElementConnection(mSecureElementHandle);
} catch (RemoteException e) {
}
}
}
}
private boolean _enable(boolean oldEnabledState) {
boolean isSuccess = mManager.initialize();
if (isSuccess) {
applyProperties();
/* Check Secure Element setting */
mNfcSecureElementState = mPrefs.getBoolean(PREF_SECURE_ELEMENT_ON,
SECURE_ELEMENT_ON_DEFAULT);
if (mNfcSecureElementState) {
int secureElementId = mPrefs.getInt(PREF_SECURE_ELEMENT_ID,
SECURE_ELEMENT_ID_DEFAULT);
int[] Se_list = mManager.doGetSecureElementList();
if (Se_list != null) {
for (int i = 0; i < Se_list.length; i++) {
if (Se_list[i] == secureElementId) {
mManager.doSelectSecureElement(Se_list[i]);
mSelectedSeId = Se_list[i];
break;
}
}
}
}
mIsNfcEnabled = true;
/* Start polling loop */
maybeEnableDiscovery();
/* bring up the my tag server */
mMyTagServer.start();
} else {
mIsNfcEnabled = false;
}
updateNfcOnSetting(oldEnabledState);
return isSuccess;
}
/** Enable active tag discovery if screen is on and NFC is enabled */
private synchronized void maybeEnableDiscovery() {
if (mScreenOn && mIsNfcEnabled) {
mManager.enableDiscovery(DISCOVERY_MODE_READER);
}
}
/** Disable active tag discovery if necessary */
private synchronized void maybeDisableDiscovery() {
if (mIsNfcEnabled) {
mManager.disableDiscovery();
}
}
private void applyProperties() {
mManager.doSetProperties(PROPERTY_LLCP_LTO, mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_MIU, mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_WKS, mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_OPT, mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A,
mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B,
mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F,
mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693,
mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP,
mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT) ? 1 : 0);
}
private void updateNfcOnSetting(boolean oldEnabledState) {
int state;
mPrefsEditor.putBoolean(PREF_NFC_ON, mIsNfcEnabled);
mPrefsEditor.apply();
synchronized(this) {
if (oldEnabledState != mIsNfcEnabled) {
Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE);
intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled);
mContext.sendBroadcast(intent);
}
if (mIsNfcEnabled) {
Context context = getApplicationContext();
// Set this to null by default. If there isn't a tag on disk
// or if there was an error reading the tag then this will cause
// the status bar icon to be removed.
NdefMessage myTag = null;
FileInputStream input = null;
try {
input = context.openFileInput(MY_TAG_FILE_NAME);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = 0;
while ((read = input.read(buffer)) > 0) {
bytes.write(buffer, 0, read);
}
myTag = new NdefMessage(bytes.toByteArray());
} catch (FileNotFoundException e) {
// Ignore.
} catch (IOException e) {
Log.e(TAG, "Could not read mytag file: ", e);
context.deleteFile(MY_TAG_FILE_NAME);
} catch (FormatException e) {
Log.e(TAG, "Invalid NdefMessage for mytag", e);
context.deleteFile(MY_TAG_FILE_NAME);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
// Ignore
}
}
try {
mNfcAdapter.localSet(myTag);
} catch (RemoteException e) {
// Ignore
}
} else {
sendMessage(MSG_HIDE_MY_TAG_ICON, null);
}
}
}
// Reset all internals
private synchronized void reset() {
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
// Clear tables
mObjectMap.clear();
mSocketMap.clear();
mRegisteredSocketList.clear();
// Reset variables
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
mNbSocketCreated = 0;
mIsNfcEnabled = false;
mSelectedSeId = 0;
}
private synchronized Object findObject(int key) {
Object device = null;
device = mObjectMap.get(key);
if (device == null) {
Log.w(TAG, "Handle not found !");
}
return device;
}
synchronized void registerTagObject(NativeNfcTag nativeTag) {
mObjectMap.put(nativeTag.getHandle(), nativeTag);
}
synchronized void unregisterObject(int handle) {
mObjectMap.remove(handle);
}
private synchronized Object findSocket(int key) {
Object socket = null;
socket = mSocketMap.get(key);
return socket;
}
private void RemoveSocket(int key) {
mSocketMap.remove(key);
}
private boolean CheckSocketSap(int sap) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sap == registeredSocket.mSap) {
/* SAP already used */
return false;
}
}
return true;
}
private boolean CheckSocketOptions(int miu, int rw, int linearBufferlength) {
if (rw > LLCP_RW_MAX_VALUE || miu < LLCP_MIU_DEFAULT || linearBufferlength < miu) {
return false;
}
return true;
}
private boolean CheckSocketServiceName(String sn) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sn.equals(registeredSocket.mServiceName)) {
/* Service Name already used */
return false;
}
}
return true;
}
private void RemoveRegisteredSocket(int nativeHandle) {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (registeredSocket.mHandle == nativeHandle) {
/* remove the registered socket from the list */
it.remove();
if (DBG) Log.d(TAG, "socket removed");
}
}
}
/*
* RegisteredSocket class to store the creation request of socket until the
* LLCP link in not activated
*/
private class RegisteredSocket {
private final int mType;
private final int mHandle;
private final int mSap;
private int mMiu;
private int mRw;
private String mServiceName;
private int mlinearBufferLength;
RegisteredSocket(int type, int handle, int sap, String sn, int miu, int rw,
int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mServiceName = sn;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap, int miu, int rw, int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap) {
mType = type;
mHandle = handle;
mSap = sap;
}
}
/** For use by code in this process */
public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpSocket(sap, miu, rw, linearBufferLength);
if (ErrorCodes.isError(handle)) {
Log.e(TAG, "unable to create socket: " + ErrorCodes.asString(handle));
return null;
}
return new LlcpSocket(mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
/** For use by code in this process */
public LlcpServiceSocket createLlcpServiceSocket(int sap, String sn, int miu, int rw,
int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
if (ErrorCodes.isError(handle)) {
Log.e(TAG, "unable to create socket: " + ErrorCodes.asString(handle));
return null;
}
return new LlcpServiceSocket(mLlcpServerSocketService, mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
private void activateLlcpLink() {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
if (DBG) Log.d(TAG, "Nb socket resgistered = " + mRegisteredSocketList.size());
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_ACTIVATED;
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
switch (registeredSocket.mType) {
case LLCP_SERVICE_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Service Socket");
if (DBG) Log.d(TAG, "SAP: " + registeredSocket.mSap + ", SN: " + registeredSocket.mServiceName);
NativeLlcpServiceSocket serviceSocket;
serviceSocket = mManager.doCreateLlcpServiceSocket(
registeredSocket.mSap, registeredSocket.mServiceName,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (serviceSocket != null) {
if (DBG) Log.d(TAG, "service socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, serviceSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// NOTE: don't remove this socket from the registered sockets list.
// If it's removed it won't be created the next time an LLCP
// connection is activated and the server won't be found.
break;
case LLCP_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Socket");
NativeLlcpSocket clientSocket;
clientSocket = mManager.doCreateLlcpSocket(registeredSocket.mSap,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (clientSocket != null) {
if (DBG) Log.d(TAG, "socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, clientSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// This socket has been created, remove it from the registered sockets list.
it.remove();
break;
case LLCP_CONNECTIONLESS_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Connectionless Socket");
NativeLlcpConnectionlessSocket connectionlessSocket;
connectionlessSocket = mManager.doCreateLlcpConnectionlessSocket(
registeredSocket.mSap);
if (connectionlessSocket != null) {
if (DBG) Log.d(TAG, "connectionless socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, connectionlessSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// This socket has been created, remove it from the registered sockets list.
it.remove();
break;
}
}
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP activation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
}
public void sendMockNdefTag(NdefMessage msg) {
sendMessage(MSG_MOCK_NDEF, msg);
}
void sendMessage(int what, Object obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
final class NfcServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
- nativeTag.connect(); // reset the tag
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
- nativeTag.connect(); // reset the tag
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
device.doDisconnect();
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
private Intent buildTagIntent(Tag tag, NdefMessage[] msgs) {
Intent intent = new Intent(NfcAdapter.ACTION_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.putExtra(NfcAdapter.EXTRA_ID, tag.getId());
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, msgs);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
private NfcServiceHandler mHandler = new NfcServiceHandler();
private class EnableDisableDiscoveryTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean... enable) {
if (enable != null && enable.length > 0 && enable[0]) {
synchronized (NfcService.this) {
mScreenOn = true;
maybeEnableDiscovery();
}
} else {
mWakeLock.acquire();
synchronized (NfcService.this) {
mScreenOn = false;
maybeDisableDiscovery();
}
mWakeLock.release();
}
return null;
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
if (DBG) Log.d(TAG, "INERNAL_TARGET_DESELECTED_ACTION");
/* Restart polling loop for notification */
maybeEnableDiscovery();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Perform discovery enable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(true));
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Perform discovery disable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(false));
}
}
};
}
| false | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
nativeTag.connect(); // reset the tag
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
nativeTag.connect(); // reset the tag
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
device.doDisconnect();
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
device.doDisconnect();
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
|
diff --git a/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java b/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java
index 253f22c..c3b9d99 100644
--- a/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java
+++ b/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java
@@ -1,98 +1,98 @@
/**
*
*/
package com.asksven.mytrack.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.asksven.andoid.common.contrib.Util;
import com.asksven.android.common.utils.DataStorage;
import com.asksven.android.common.utils.DateUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* @author sven
*
*/
public class LocationWriter
{
private static final String TAG = "LocationWriter";
private static final String FILENAME = "MyTrack";
public static void LogLocationToFile(Context context, Location myLoc)
{
Uri fileUri = null;
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage can not be written");
Toast.makeText(context, "External Storage can not be written",
Toast.LENGTH_SHORT).show();
}
try
{
// open file for writing
File root;
try
{
root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
}
catch (Exception e)
{
root = Environment.getExternalStorageDirectory();
}
String path = root.getAbsolutePath();
// check if file can be written
if (root.canWrite())
{
String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS");
File textFile = new File(root, FILENAME + ".txt");
- FileWriter fw = new FileWriter(textFile);
+ FileWriter fw = new FileWriter(textFile, true);
BufferedWriter out = new BufferedWriter(fw);
- out.append(timestamp + ": "
+ out.write(timestamp + ": "
+ "LAT=" + myLoc.getLatitude()
+ "LONG=" + myLoc.getLongitude() + "\n");
out.close();
File jsonFile = new File(root, FILENAME + ".json");
- fw = new FileWriter(jsonFile);
+ fw = new FileWriter(jsonFile, true);
out = new BufferedWriter(fw);
- out.append("TrackEntry\n");
+ out.write("TrackEntry\n");
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
- out.append(gson.toJson(new TrackEntry(myLoc)));
- out.append("\n");
+ out.write(gson.toJson(new TrackEntry(myLoc)));
+ out.write("\n");
out.close();
}
else
{
Log.i(TAG,
"Write error. "
+ Environment.getExternalStorageDirectory()
+ " couldn't be written");
}
} catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
| false | true | public static void LogLocationToFile(Context context, Location myLoc)
{
Uri fileUri = null;
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage can not be written");
Toast.makeText(context, "External Storage can not be written",
Toast.LENGTH_SHORT).show();
}
try
{
// open file for writing
File root;
try
{
root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
}
catch (Exception e)
{
root = Environment.getExternalStorageDirectory();
}
String path = root.getAbsolutePath();
// check if file can be written
if (root.canWrite())
{
String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS");
File textFile = new File(root, FILENAME + ".txt");
FileWriter fw = new FileWriter(textFile);
BufferedWriter out = new BufferedWriter(fw);
out.append(timestamp + ": "
+ "LAT=" + myLoc.getLatitude()
+ "LONG=" + myLoc.getLongitude() + "\n");
out.close();
File jsonFile = new File(root, FILENAME + ".json");
fw = new FileWriter(jsonFile);
out = new BufferedWriter(fw);
out.append("TrackEntry\n");
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
out.append(gson.toJson(new TrackEntry(myLoc)));
out.append("\n");
out.close();
}
else
{
Log.i(TAG,
"Write error. "
+ Environment.getExternalStorageDirectory()
+ " couldn't be written");
}
} catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
}
}
| public static void LogLocationToFile(Context context, Location myLoc)
{
Uri fileUri = null;
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context);
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage can not be written");
Toast.makeText(context, "External Storage can not be written",
Toast.LENGTH_SHORT).show();
}
try
{
// open file for writing
File root;
try
{
root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
}
catch (Exception e)
{
root = Environment.getExternalStorageDirectory();
}
String path = root.getAbsolutePath();
// check if file can be written
if (root.canWrite())
{
String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS");
File textFile = new File(root, FILENAME + ".txt");
FileWriter fw = new FileWriter(textFile, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(timestamp + ": "
+ "LAT=" + myLoc.getLatitude()
+ "LONG=" + myLoc.getLongitude() + "\n");
out.close();
File jsonFile = new File(root, FILENAME + ".json");
fw = new FileWriter(jsonFile, true);
out = new BufferedWriter(fw);
out.write("TrackEntry\n");
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
out.write(gson.toJson(new TrackEntry(myLoc)));
out.write("\n");
out.close();
}
else
{
Log.i(TAG,
"Write error. "
+ Environment.getExternalStorageDirectory()
+ " couldn't be written");
}
} catch (Exception e)
{
Log.e(TAG, "Exception: " + e.getMessage());
}
}
|
diff --git a/bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java b/bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java
index c949d78..e8906f0 100755
--- a/bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java
+++ b/bonecp/src/main/java/com/jolbox/bonecp/DefaultConnectionStrategy.java
@@ -1,121 +1,121 @@
/**
* Copyright 2010 Wallace Wadge
*
* 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.jolbox.bonecp;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;
/** The normal getConnection() strategy class in use. Attempts to get a connection from
* one or more configured partitions.
* @author wallacew
*
*/
public class DefaultConnectionStrategy extends AbstractConnectionStrategy {
public DefaultConnectionStrategy(BoneCP pool){
this.pool = pool;
}
@Override
public ConnectionHandle pollConnection(){
ConnectionHandle result = null;
int partition = (int) (Thread.currentThread().getId() % this.pool.partitionCount);
ConnectionPartition connectionPartition = this.pool.partitions[partition];
result = connectionPartition.getFreeConnections().poll();
if (result == null) {
// we ran out of space on this partition, pick another free one
for (int i=0; i < this.pool.partitionCount; i++){
if (i == partition) {
continue; // we already determined it's not here
}
result = this.pool.partitions[i].getFreeConnections().poll(); // try our luck with this partition
connectionPartition = this.pool.partitions[i];
if (result != null) {
break; // we found a connection
}
}
}
if (!connectionPartition.isUnableToCreateMoreTransactions()){ // unless we can't create any more connections...
this.pool.maybeSignalForMoreConnections(connectionPartition); // see if we need to create more
}
return result;
}
@Override
protected Connection getConnectionInternal() throws SQLException {
ConnectionHandle result = pollConnection();
int partition = (int) (Thread.currentThread().getId() % this.pool.partitionCount);
ConnectionPartition connectionPartition = this.pool.partitions[partition];
// we still didn't find an empty one, wait forever (or as per config) until our partition is free
if (result == null) {
try {
result = connectionPartition.getFreeConnections().poll(this.pool.connectionTimeoutInMs, TimeUnit.MILLISECONDS);
if (result == null){
if (this.pool.nullOnConnectionTimeout){
return null;
}
// 08001 = The application requester is unable to establish the connection.
throw new SQLException("Timed out waiting for a free available connection.", "08001");
}
}
catch (InterruptedException e) {
if (this.pool.nullOnConnectionTimeout){
return null;
}
- throw new SQLException(e.getMessage());
+ throw new SQLException(e);
}
}
if (result.isPoison()){
if (this.pool.getDbIsDown().get() && connectionPartition.getFreeConnections().hasWaitingConsumer()){
// poison other waiting threads.
connectionPartition.getFreeConnections().offer(result);
}
throw new SQLException("Pool connections have been terminated. Aborting getConnection() request.", "08001");
}
return result;
}
/** Closes off all connections in all partitions. */
public void terminateAllConnections(){
this.terminationLock.lock();
try{
ConnectionHandle conn;
// close off all connections.
for (int i=0; i < this.pool.partitionCount; i++) {
this.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization
while ((conn = this.pool.partitions[i].getFreeConnections().poll()) != null){
this.pool.destroyConnection(conn);
}
}
} finally {
this.terminationLock.unlock();
}
}
}
| true | true | protected Connection getConnectionInternal() throws SQLException {
ConnectionHandle result = pollConnection();
int partition = (int) (Thread.currentThread().getId() % this.pool.partitionCount);
ConnectionPartition connectionPartition = this.pool.partitions[partition];
// we still didn't find an empty one, wait forever (or as per config) until our partition is free
if (result == null) {
try {
result = connectionPartition.getFreeConnections().poll(this.pool.connectionTimeoutInMs, TimeUnit.MILLISECONDS);
if (result == null){
if (this.pool.nullOnConnectionTimeout){
return null;
}
// 08001 = The application requester is unable to establish the connection.
throw new SQLException("Timed out waiting for a free available connection.", "08001");
}
}
catch (InterruptedException e) {
if (this.pool.nullOnConnectionTimeout){
return null;
}
throw new SQLException(e.getMessage());
}
}
if (result.isPoison()){
if (this.pool.getDbIsDown().get() && connectionPartition.getFreeConnections().hasWaitingConsumer()){
// poison other waiting threads.
connectionPartition.getFreeConnections().offer(result);
}
throw new SQLException("Pool connections have been terminated. Aborting getConnection() request.", "08001");
}
return result;
}
| protected Connection getConnectionInternal() throws SQLException {
ConnectionHandle result = pollConnection();
int partition = (int) (Thread.currentThread().getId() % this.pool.partitionCount);
ConnectionPartition connectionPartition = this.pool.partitions[partition];
// we still didn't find an empty one, wait forever (or as per config) until our partition is free
if (result == null) {
try {
result = connectionPartition.getFreeConnections().poll(this.pool.connectionTimeoutInMs, TimeUnit.MILLISECONDS);
if (result == null){
if (this.pool.nullOnConnectionTimeout){
return null;
}
// 08001 = The application requester is unable to establish the connection.
throw new SQLException("Timed out waiting for a free available connection.", "08001");
}
}
catch (InterruptedException e) {
if (this.pool.nullOnConnectionTimeout){
return null;
}
throw new SQLException(e);
}
}
if (result.isPoison()){
if (this.pool.getDbIsDown().get() && connectionPartition.getFreeConnections().hasWaitingConsumer()){
// poison other waiting threads.
connectionPartition.getFreeConnections().offer(result);
}
throw new SQLException("Pool connections have been terminated. Aborting getConnection() request.", "08001");
}
return result;
}
|
diff --git a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
index ffbdf9e8c..a81d294ee 100644
--- a/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
+++ b/luni/src/test/java/org/apache/harmony/regex/tests/java/util/regex/PatternTest.java
@@ -1,1777 +1,1784 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.regex.tests.java.util.regex;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import junit.framework.TestCase;
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
public class PatternTest extends TestCase {
String[] testPatterns = {
"(a|b)*abb",
"(1*2*3*4*)*567",
"(a|b|c|d)*aab",
"(1|2|3|4|5|6|7|8|9|0)(1|2|3|4|5|6|7|8|9|0)*",
"(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)*",
"(a|b)*(a|b)*A(a|b)*lice.*",
"(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)(a|b|c|d|e|f|g|h|"
+ "i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)*(1|2|3|4|5|6|7|8|9|0)*|while|for|struct|if|do",
// BEGIN android-changed
// We don't have canonical equivalence.
// "x(?c)y", "x(?cc)y"
// "x(?:c)y"
// END android-changed
};
String[] testPatternsAlt = {
/*
* According to JavaDoc 2 and 3 oct digit sequences like \\o70\\o347
* should be OK, but test is failed for them
*/
"[ab]\\b\\\\o5\\xF9\\u1E7B\\t\\n\\f\\r\\a\\e[yz]",
"^\\p{Lower}*\\p{Upper}*\\p{ASCII}?\\p{Alpha}?\\p{Digit}*\\p{Alnum}\\p{Punct}\\p{Graph}\\p{Print}\\p{Blank}\\p{Cntrl}\\p{XDigit}\\p{Space}",
"$\\p{javaLowerCase}\\p{javaUpperCase}\\p{javaWhitespace}\\p{javaMirrored}",
"\\p{InGreek}\\p{Lu}\\p{Sc}\\P{InGreek}[\\p{L}&&[^\\p{Lu}]]" };
String[] wrongTestPatterns = { "\\o9A", "\\p{Lawer}", "\\xG0" };
final static int[] flagsSet = { Pattern.CASE_INSENSITIVE,
Pattern.MULTILINE, Pattern.DOTALL, Pattern.UNICODE_CASE
/* , Pattern.CANON_EQ */ };
/*
* Based on RI implenetation documents. Need to check this set regarding
* actual implementation.
*/
final static int[] wrongFlagsSet = { 256, 512, 1024 };
final static int DEFAULT_FLAGS = 0;
public void testMatcher() {
// some very simple test
Pattern p = Pattern.compile("a");
assertNotNull(p.matcher("bcde"));
assertNotSame(p.matcher("a"), p.matcher("a"));
}
public void testSplitCharSequenceint() {
// splitting CharSequence which ends with pattern
// bug6193
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
// bug6193
// bug5391
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
// bug5391
String s[];
Pattern pat = Pattern.compile("x");
s = pat.split("zxx:zzz:zxx", 10);
assertEquals(s.length, 5);
s = pat.split("zxx:zzz:zxx", 3);
assertEquals(s.length, 3);
s = pat.split("zxx:zzz:zxx", -1);
assertEquals(s.length, 5);
s = pat.split("zxx:zzz:zxx", 0);
assertEquals(s.length, 3);
// other splitting
// negative limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", -1);
assertEquals(s.length, 5);
s = pat.split("", -1);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", -1);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", -1);
assertEquals(s.length, 11);
// zero limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 0);
assertEquals(s.length, 3);
s = pat.split("", 0);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 0);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 0);
assertEquals(s.length, 10);
// positive limit
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 12);
assertEquals(s.length, 5);
s = pat.split("", 6);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 11);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 15);
assertEquals(s.length, 11);
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 5);
assertEquals(s.length, 5);
s = pat.split("", 1);
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("", 1);
assertEquals(s.length, 1);
s = pat.split("abccbadfe", 11);
assertEquals(s.length, 11);
pat = Pattern.compile("b");
s = pat.split("abccbadfebb", 3);
assertEquals(s.length, 3);
pat = Pattern.compile("");
s = pat.split("abccbadfe", 5);
assertEquals(s.length, 5);
}
public void testSplitCharSequence() {
String s[];
Pattern pat = Pattern.compile("b");
s = pat.split("abccbadfebb");
assertEquals(s.length, 3);
s = pat.split("");
assertEquals(s.length, 1);
pat = Pattern.compile("");
s = pat.split("");
assertEquals(s.length, 1);
s = pat.split("abccbadfe");
assertEquals(s.length, 10);
// bug6544
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
// bug6544
}
public void testPattern() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertTrue(p.pattern().equals(aPattern));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testCompile() {
/* Positive assertion test. */
for (String aPattern : testPatterns) {
try {
Pattern p = Pattern.compile(aPattern);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
/* Positive assertion test with alternative templates. */
for (String aPattern : testPatternsAlt) {
try {
Pattern p = Pattern.compile(aPattern);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
/* Negative assertion test. */
for (String aPattern : wrongTestPatterns) {
try {
Pattern p = Pattern.compile(aPattern);
fail("PatternSyntaxException is expected");
} catch (PatternSyntaxException pse) {
/* OKAY */
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testFlags() {
String baseString;
String testString;
Pattern pat;
Matcher mat;
baseString = "((?i)|b)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|b";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "c|(?i)a|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?s)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?-i)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|(?-i)c|b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)a|(?-i)c|(?i)b";
testString = "B";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)a|(?-i)b";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "((?i))a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "|(?i)|a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?s)a.)";
testString = "A\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?-i)a)";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
baseString = "(?i)(?s:a.)";
testString = "A\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)fgh(?s:aa)";
testString = "fghAA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?i)((?-i))a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?i)d";
testString = "ABCD";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "abcD";
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "a(?i)a(?-i)a(?i)a(?-i)a";
testString = "aAaAa";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "aAAAa";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
// BEGIN android-removed
// The flags() method should only return those flags that were explicitly
// passed during the compilation. The JDK also accepts the ones implicitly
// contained in the pattern, but ICU doesn't do this.
//
// public void testFlagsMethod() {
// String baseString;
// Pattern pat;
//
// /*
// * These tests are for compatibility with RI only. Logically we have to
// * return only flags specified during the compilation. For example
// * pat.flags() == 0 when we compile Pattern pat =
// * Pattern.compile("(?i)abc(?-i)"); but the whole expression is compiled
// * in a case insensitive manner. So there is little sense to do calls to
// * flags() now.
// */
// baseString = "(?-i)";
// pat = Pattern.compile(baseString);
//
// baseString = "(?idmsux)abc(?-i)vg(?-dmu)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.COMMENTS);
//
// baseString = "(?idmsux)abc|(?-i)vg|(?-dmu)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.COMMENTS);
//
// baseString = "(?is)a((?x)b.)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
//
// baseString = "(?i)a((?-i))";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), Pattern.CASE_INSENSITIVE);
//
// baseString = "((?i)a)";
// pat = Pattern.compile(baseString);
// assertEquals(pat.flags(), 0);
//
// pat = Pattern.compile("(?is)abc");
// assertEquals(pat.flags(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
// }
//END android-removed
/*
* Check default flags when they are not specified in pattern. Based on RI
* since could not find that info
*/
public void testFlagsCompileDefault() {
for (String pat : testPatternsAlt) {
try {
Pattern p = Pattern.compile(pat);
assertEquals(p.flags(), DEFAULT_FLAGS);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
/*
* Check that flags specified during compile are set properly This is a
* simple implementation that does not use flags combinations. Need to
* improve.
*/
public void testFlagsCompileValid() {
for (String pat : testPatternsAlt) {
for (int flags : flagsSet) {
try {
Pattern p = Pattern.compile(pat, flags);
assertEquals(p.flags(), flags);
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
}
public void testCompileStringint() {
/*
* these tests are needed to verify that appropriate exceptions are
* thrown
*/
String pattern = "b)a";
try {
Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "bcde)a";
try {
Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "bbg())a";
try {
Pattern pat = Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
pattern = "cdb(?i))a";
try {
Pattern pat = Pattern.compile(pattern);
fail("Expected a PatternSyntaxException when compiling pattern: "
+ pattern);
} catch (PatternSyntaxException e) {
// pass
}
/*
* This pattern should compile - HARMONY-2127
*/
// pattern = "x(?c)y";
// Pattern.compile(pattern);
/*
* this pattern doesn't match any string, but should be compiled anyway
*/
pattern = "(b\\1)a";
Pattern.compile(pattern);
}
/*
* Class under test for Pattern compile(String)
*/
public void testQuantCompileNeg() {
String[] patterns = { "5{,2}", "{5asd", "{hgdhg", "{5,hjkh", "{,5hdsh",
"{5,3shdfkjh}" };
for (String element : patterns) {
try {
Pattern.compile(element);
fail("PatternSyntaxException was expected, but compilation succeeds");
} catch (PatternSyntaxException pse) {
continue;
}
}
// Regression for HARMONY-1365
// BEGIN android-changed
// Original regex contained some illegal stuff. Changed it slightly,
// while maintaining the wicked character of this "mother of all
// regexes".
// String pattern = "(?![^\\<C\\f\\0146\\0270\\}&&[|\\02-\\x3E\\}|X-\\|]]{7,}+)[|\\\\\\x98\\<\\?\\u4FCFr\\,\\0025\\}\\004|\\0025-\\052\061]|(?<![|\\01-\\u829E])|(?<!\\p{Alpha})|^|(?-s:[^\\x15\\\\\\x24F\\a\\,\\a\\u97D8[\\x38\\a[\\0224-\\0306[^\\0020-\\u6A57]]]]??)(?uxix:[^|\\{\\[\\0367\\t\\e\\x8C\\{\\[\\074c\\]V[|b\\fu\\r\\0175\\<\\07f\\066s[^D-\\x5D]]])(?xx:^{5,}+)(?uuu)(?=^\\D)|(?!\\G)(?>\\G*?)(?![^|\\]\\070\\ne\\{\\t\\[\\053\\?\\\\\\x51\\a\\075\\0023-\\[&&[|\\022-\\xEA\\00-\\u41C2&&[^|a-\\xCC&&[^\\037\\uECB3\\u3D9A\\x31\\|\\<b\\0206\\uF2EC\\01m\\,\\ak\\a\\03&&\\p{Punct}]]]])(?-dxs:[|\\06-\\07|\\e-\\x63&&[|Tp\\u18A3\\00\\|\\xE4\\05\\061\\015\\0116C|\\r\\{\\}\\006\\xEA\\0367\\xC4\\01\\0042\\0267\\xBB\\01T\\}\\0100\\?[|\\[-\\u459B|\\x23\\x91\\rF\\0376[|\\?-\\x94\\0113-\\\\\\s]]]]{6}?)(?<=[^\\t-\\x42H\\04\\f\\03\\0172\\?i\\u97B6\\e\\f\\uDAC2])(?=\\B*+)(?>[^\\016\\r\\{\\,\\uA29D\\034\\02[\\02-\\[|\\t\\056\\uF599\\x62\\e\\<\\032\\uF0AC\\0026\\0205Q\\|\\\\\\06\\0164[|\\057-\\u7A98&&[\\061-g|\\|\\0276\\n\\042\\011\\e\\xE8\\x64B\\04\\u6D0EDW^\\p{Lower}]]]]?)(?<=[^\\n\\\\\\t\\u8E13\\,\\0114\\u656E\\xA5\\]&&[\\03-\\026|\\uF39D\\01\\{i\\u3BC2\\u14FE]])(?<=[^|\\uAE62\\054H\\|\\}&&^\\p{Space}])(?sxx)(?<=[\\f\\006\\a\\r\\xB4]*+)|(?x-xd:^{5}+)()";
String pattern = "(?![^\\<C\\f\\0146\\0270\\}&&[|\\02-\\x3E\\}|X-\\|]]{7,}+)[|\\\\\\x98\\<\\?\\u4FCFr\\,\\0025\\}\\004|\\0025-\\052\061]|(?<![|\\01-\\u829E])|(?<!\\p{Alpha})|^|(?-s:[^\\x15\\\\\\x24F\\a\\,\\a\\u97D8[\\x38\\a[\\0224-\\0306[^\\0020-\\u6A57]]]]??)(?uxix:[^|\\{\\[\\0367\\t\\e\\x8C\\{\\[\\074c\\]V[|b\\fu\\r\\0175\\<\\07f\\066s[^D-\\x5D]]])(?xx:^{5,}+)(?uuu)(?=^\\D)|(?!\\G)(?>\\.*?)(?![^|\\]\\070\\ne\\{\\t\\[\\053\\?\\\\\\x51\\a\\075\\0023-\\[&&[|\\022-\\xEA\\00-\\u41C2&&[^|a-\\xCC&&[^\\037\\uECB3\\u3D9A\\x31\\|\\<b\\0206\\uF2EC\\01m\\,\\ak\\a\\03&&\\p{Punct}]]]])(?-dxs:[|\\06-\\07|\\e-\\x63&&[|Tp\\u18A3\\00\\|\\xE4\\05\\061\\015\\0116C|\\r\\{\\}\\006\\xEA\\0367\\xC4\\01\\0042\\0267\\xBB\\01T\\}\\0100\\?[|\\[-\\u459B|\\x23\\x91\\rF\\0376[|\\?-\\x94\\0113-\\\\\\s]]]]{6}?)(?<=[^\\t-\\x42H\\04\\f\\03\\0172\\?i\\u97B6\\e\\f\\uDAC2])(?=\\.*+)(?>[^\\016\\r\\{\\,\\uA29D\\034\\02[\\02-\\[|\\t\\056\\uF599\\x62\\e\\<\\032\\uF0AC\\0026\\0205Q\\|\\\\\\06\\0164[|\\057-\\u7A98&&[\\061-g|\\|\\0276\\n\\042\\011\\e\\xE8\\x64B\\04\\u6D0EDW^\\p{Lower}]]]]?)(?<=[^\\n\\\\\\t\\u8E13\\,\\0114\\u656E\\xA5\\]&&[\\03-\\026|\\uF39D\\01\\{i\\u3BC2\\u14FE]])(?<=[^|\\uAE62\\054H\\|\\}&&^\\p{Space}])(?sxx)(?<=[\\f\\006\\a\\r\\xB4]{1,5})|(?x-xd:^{5}+)()";
// END android-changed
assertNotNull(Pattern.compile(pattern));
}
public void testQuantCompilePos() {
String[] patterns = {/* "(abc){1,3}", */"abc{2,}", "abc{5}" };
for (String element : patterns) {
Pattern.compile(element);
}
}
public void testQuantComposition() {
String pattern = "(a{1,3})aab";
java.util.regex.Pattern pat = java.util.regex.Pattern.compile(pattern);
java.util.regex.Matcher mat = pat.matcher("aaab");
mat.matches();
mat.start(1);
mat.group(1);
}
public void testMatches() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.matches(testPatterns[i],
posSeq[i][j]));
}
}
}
public void testMatchesException() {
/* Negative assertion test. */
for (String aPattern : wrongTestPatterns) {
try {
Pattern.matches(aPattern, "Foo");
fail("PatternSyntaxException is expected");
} catch (PatternSyntaxException pse) {
/* OKAY */
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void testTimeZoneIssue() {
Pattern p = Pattern.compile("GMT(\\+|\\-)(\\d+)(:(\\d+))?");
Matcher m = p.matcher("GMT-9:45");
assertTrue(m.matches());
assertEquals("-", m.group(1));
assertEquals("9", m.group(2));
assertEquals(":45", m.group(3));
assertEquals("45", m.group(4));
}
// BEGIN android-changed
// Removed one pattern that is buggy on the JDK. We don't want to duplicate that.
public void testCompileRanges() {
String[] correctTestPatterns = { "[^]*abb]*", /* "[^a-d[^m-p]]*abb", */
"[a-d\\d]*abb", "[abc]*abb", "[a-e&&[de]]*abb", "[^abc]*abb",
"[a-e&&[^de]]*abb", "[a-z&&[^m-p]]*abb", "[a-d[m-p]]*abb",
"[a-zA-Z]*abb", "[+*?]*abb", "[^+*?]*abb" };
String[] inputSecuence = { "kkkk", /* "admpabb", */ "abcabcd124654abb",
"abcabccbacababb", "dededededededeedabb", "gfdhfghgdfghabb",
"accabacbcbaabb", "acbvfgtyabb", "adbcacdbmopabcoabb",
"jhfkjhaSDFGHJkdfhHNJMjkhfabb", "+*??+*abb", "sdfghjkabb" };
Pattern pat;
for (int i = 0; i < correctTestPatterns.length; i++) {
assertTrue("pattern: " + correctTestPatterns[i] + " input: "
+ inputSecuence[i], Pattern.matches(correctTestPatterns[i],
inputSecuence[i]));
}
String[] wrongInputSecuence = { "]", /* "admpkk", */ "abcabcd124k654abb",
"abwcabccbacababb", "abababdeababdeabb", "abcabcacbacbabb",
"acdcbecbaabb", "acbotyabb", "adbcaecdbmopabcoabb",
"jhfkjhaSDFGHJk;dfhHNJMjkhfabb", "+*?a?+*abb", "sdf+ghjkabb" };
for (int i = 0; i < correctTestPatterns.length; i++) {
assertFalse("pattern: " + correctTestPatterns[i] + " input: "
+ wrongInputSecuence[i], Pattern.matches(
correctTestPatterns[i], wrongInputSecuence[i]));
}
}
public void testRangesSpecialCases() {
String neg_patterns[] = { "[a-&&[b-c]]", "[a-\\w]", "[b-a]", "[]" };
for (String element : neg_patterns) {
try {
Pattern.compile(element);
fail("PatternSyntaxException was expected: " + element);
} catch (PatternSyntaxException pse) {
}
}
String pos_patterns[] = { "[-]+", "----", "[a-]+", "a-a-a-a-aa--",
"[\\w-a]+", "123-2312--aaa-213", "[a-]]+", "-]]]]]]]]]]]]]]]" };
for (int i = 0; i < pos_patterns.length; i++) {
String pat = pos_patterns[i++];
String inp = pos_patterns[i];
assertTrue("pattern: " + pat + " input: " + inp, Pattern.matches(
pat, inp));
}
}
// END android-changed
public void testZeroSymbols() {
assertTrue(Pattern.matches("[\0]*abb", "\0\0\0\0\0\0abb"));
}
public void testEscapes() {
Pattern pat = Pattern.compile("\\Q{]()*?");
Matcher mat = pat.matcher("{]()*?");
assertTrue(mat.matches());
}
public void testBug181() {
Pattern.compile("[\\t-\\r]");
}
public void testOrphanQuantifiers() {
try {
Pattern.compile("+++++");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testOrphanQuantifiers2() {
try {
Pattern pat = Pattern.compile("\\d+*");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
+ // http://code.google.com/p/android/issues/detail?id=19308
+ public void test_hitEnd() {
+ Pattern p = Pattern.compile("^2(2[4-9]|3\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
+ Matcher m = p.matcher("224..");
+ boolean isPartialMatch = !m.matches() && m.hitEnd();
+ assertFalse(isPartialMatch);
+ }
}
| true | true | public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
}
| public void testBug197() {
Object[] vals = { ":", new Integer(2),
new String[] { "boo", "and:foo" }, ":", new Integer(5),
new String[] { "boo", "and", "foo" }, ":", new Integer(-2),
new String[] { "boo", "and", "foo" }, ":", new Integer(3),
new String[] { "boo", "and", "foo" }, ":", new Integer(1),
new String[] { "boo:and:foo" }, "o", new Integer(5),
new String[] { "b", "", ":and:f", "", "" }, "o",
new Integer(4), new String[] { "b", "", ":and:f", "o" }, "o",
new Integer(-2), new String[] { "b", "", ":and:f", "", "" },
"o", new Integer(0), new String[] { "b", "", ":and:f" } };
for (int i = 0; i < vals.length / 3;) {
String[] res = Pattern.compile(vals[i++].toString()).split(
"boo:and:foo", ((Integer) vals[i++]).intValue());
String[] expectedRes = (String[]) vals[i++];
assertEquals(expectedRes.length, res.length);
for (int j = 0; j < expectedRes.length; j++) {
assertEquals(expectedRes[j], res[j]);
}
}
}
public void testURIPatterns() {
String URI_REGEXP_STR = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String SCHEME_REGEXP_STR = "^[a-zA-Z]{1}[\\w+-.]+$";
String REL_URI_REGEXP_STR = "^(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
String IPV6_REGEXP_STR = "^[0-9a-fA-F\\:\\.]+(\\%\\w+)?$";
String IPV6_REGEXP_STR2 = "^\\[[0-9a-fA-F\\:\\.]+(\\%\\w+)?\\]$";
String IPV4_REGEXP_STR = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
String HOSTNAME_REGEXP_STR = "\\w+[\\w\\-\\.]*";
Pattern URI_REGEXP = Pattern.compile(URI_REGEXP_STR);
Pattern REL_URI_REGEXP = Pattern.compile(REL_URI_REGEXP_STR);
Pattern SCHEME_REGEXP = Pattern.compile(SCHEME_REGEXP_STR);
Pattern IPV4_REGEXP = Pattern.compile(IPV4_REGEXP_STR);
Pattern IPV6_REGEXP = Pattern.compile(IPV6_REGEXP_STR);
Pattern IPV6_REGEXP2 = Pattern.compile(IPV6_REGEXP_STR2);
Pattern HOSTNAME_REGEXP = Pattern.compile(HOSTNAME_REGEXP_STR);
}
public void testFindBoundaryCases1() {
Pattern pat = Pattern.compile(".*\n");
Matcher mat = pat.matcher("a\n");
mat.find();
assertEquals("a\n", mat.group());
}
public void testFindBoundaryCases2() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("aAa");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases3() {
Pattern pat = Pattern.compile(".*A");
Matcher mat = pat.matcher("a\naA\n");
mat.find();
assertEquals("aA", mat.group());
}
public void testFindBoundaryCases4() {
Pattern pat = Pattern.compile("A.*");
Matcher mat = pat.matcher("A\n");
mat.find();
assertEquals("A", mat.group());
}
public void testFindBoundaryCases5() {
Pattern pat = Pattern.compile(".*A.*");
Matcher mat = pat.matcher("\nA\naaa\nA\naaAaa\naaaA\n");
// Matcher mat = pat.matcher("\nA\n");
String[] res = { "A", "A", "aaAaa", "aaaA" };
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testFindBoundaryCases6() {
String[] res = { "", "a", "", "" };
Pattern pat = Pattern.compile(".*");
Matcher mat = pat.matcher("\na\n");
int k = 0;
for (; mat.find(); k++) {
assertEquals(res[k], mat.group());
}
}
public void testBackReferences() {
Pattern pat = Pattern.compile("(\\((\\w*):(.*):(\\2)\\))");
Matcher mat = pat
.matcher("(start1: word :start1)(start2: word :start2)");
int k = 1;
for (; mat.find(); k++) {
assertEquals("start" + k, mat.group(2));
assertEquals(" word ", mat.group(3));
assertEquals("start" + k, mat.group(4));
}
assertEquals(3, k);
pat = Pattern.compile(".*(.)\\1");
mat = pat.matcher("saa");
assertTrue(mat.matches());
}
public void testNewLine() {
Pattern pat = Pattern.compile("(^$)*\n", Pattern.MULTILINE);
Matcher mat = pat.matcher("\r\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(2, counter);
}
public void testFindGreedy() {
Pattern pat = Pattern.compile(".*aaa", Pattern.DOTALL);
Matcher mat = pat.matcher("aaaa\naaa\naaaaaa");
mat.matches();
assertEquals(15, mat.end());
}
public void testSerialization() throws Exception {
Pattern pat = Pattern.compile("a*bc");
SerializableAssert comparator = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
assertEquals(((Pattern) initial).toString(),
((Pattern) deserialized).toString());
}
};
SerializationTest.verifyGolden(this, pat, comparator);
SerializationTest.verifySelf(pat, comparator);
}
public void testSOLQuant() {
Pattern pat = Pattern.compile("$*", Pattern.MULTILINE);
Matcher mat = pat.matcher("\n\n");
int counter = 0;
while (mat.find()) {
counter++;
}
assertEquals(3, counter);
}
public void testIllegalEscape() {
try {
Pattern.compile("\\y");
fail("PatternSyntaxException expected");
} catch (PatternSyntaxException pse) {
}
}
public void testEmptyFamily() {
Pattern.compile("\\p{Lower}");
String a = "*";
}
public void testNonCaptConstr() {
// Flags
Pattern pat = Pattern.compile("(?i)b*(?-i)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
// Non-capturing groups
pat = Pattern.compile("(?i:b*)a*");
assertTrue(pat.matcher("bBbBaaaa").matches());
assertFalse(pat.matcher("bBbBAaAa").matches());
pat = Pattern
// 1 2 3 4 5 6 7 8 9 10 11
.compile("(?:-|(-?\\d+\\d\\d\\d))?(?:-|-(\\d\\d))?(?:-|-(\\d\\d))?(T)?(?:(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?)?(?:(?:((?:\\+|\\-)\\d\\d):(\\d\\d))|(Z))?");
Matcher mat = pat.matcher("-1234-21-31T41:51:61.789+71:81");
assertTrue(mat.matches());
assertEquals("-1234", mat.group(1));
assertEquals("21", mat.group(2));
assertEquals("31", mat.group(3));
assertEquals("T", mat.group(4));
assertEquals("41", mat.group(5));
assertEquals("51", mat.group(6));
assertEquals("61", mat.group(7));
assertEquals(".789", mat.group(8));
assertEquals("+71", mat.group(9));
assertEquals("81", mat.group(10));
// positive lookahead
pat = Pattern.compile(".*\\.(?=log$).*$");
assertTrue(pat.matcher("a.b.c.log").matches());
assertFalse(pat.matcher("a.b.c.log.").matches());
// negative lookahead
pat = Pattern.compile(".*\\.(?!log$).*$");
assertFalse(pat.matcher("abc.log").matches());
assertTrue(pat.matcher("abc.logg").matches());
// positive lookbehind
pat = Pattern.compile(".*(?<=abc)\\.log$");
assertFalse(pat.matcher("cde.log").matches());
assertTrue(pat.matcher("abc.log").matches());
// negative lookbehind
pat = Pattern.compile(".*(?<!abc)\\.log$");
assertTrue(pat.matcher("cde.log").matches());
assertFalse(pat.matcher("abc.log").matches());
// atomic group
pat = Pattern.compile("(?>a*)abb");
assertFalse(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a*)bb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>a|aa)aabb");
assertTrue(pat.matcher("aaabb").matches());
pat = Pattern.compile("(?>aa|a)aabb");
assertFalse(pat.matcher("aaabb").matches());
// BEGIN android-removed
// Questionable constructs that ICU doesn't support.
// // quantifiers over look ahead
// pat = Pattern.compile(".*(?<=abc)*\\.log$");
// assertTrue(pat.matcher("cde.log").matches());
// pat = Pattern.compile(".*(?<=abc)+\\.log$");
// assertFalse(pat.matcher("cde.log").matches());
// END android-removed
}
public void testCorrectReplacementBackreferencedJointSet() {
Pattern pat = Pattern.compile("ab(a)*\\1");
pat = Pattern.compile("abc(cd)fg");
pat = Pattern.compile("aba*cd");
pat = Pattern.compile("ab(a)*+cd");
pat = Pattern.compile("ab(a)*?cd");
pat = Pattern.compile("ab(a)+cd");
pat = Pattern.compile(".*(.)\\1");
pat = Pattern.compile("ab((a)|c|d)e");
pat = Pattern.compile("abc((a(b))cd)");
pat = Pattern.compile("ab(a)++cd");
pat = Pattern.compile("ab(a)?(c)d");
pat = Pattern.compile("ab(a)?+cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a)??cd");
pat = Pattern.compile("ab(a){1,3}?(c)d");
}
public void testCompilePatternWithTerminatorMark() {
Pattern pat = Pattern.compile("a\u0000\u0000cd");
Matcher mat = pat.matcher("a\u0000\u0000cd");
assertTrue(mat.matches());
}
public void testAlternations() {
String baseString = "|a|bc";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|bc|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a|b|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(|b|cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b||cd)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|cd|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(b|c|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a(|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "|";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "a(?:|)e";
pat = Pattern.compile(baseString);
mat = pat.matcher("ae");
assertTrue(mat.matches());
baseString = "a||||bc";
pat = Pattern.compile(baseString);
mat = pat.matcher("");
assertTrue(mat.matches());
baseString = "(?i-is)|a";
pat = Pattern.compile(baseString);
mat = pat.matcher("a");
assertTrue(mat.matches());
}
public void testMatchWithGroups() {
String baseString = "jwkerhjwehrkwjehrkwjhrwkjehrjwkehrjkwhrkwehrkwhrkwrhwkhrwkjehr";
String pattern = ".*(..).*\\1.*";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
baseString = "saa";
pattern = ".*(.)\\1";
assertTrue(Pattern.compile(pattern).matcher(baseString).matches());
assertTrue(Pattern.compile(pattern).matcher(baseString).find());
}
public void testSplitEmptyCharSequence() {
String s1 = "";
String[] arr = s1.split(":");
assertEquals(arr.length, 1);
}
public void testSplitEndsWithPattern() {
assertEquals(",,".split(",", 3).length, 3);
assertEquals(",,".split(",", 4).length, 3);
assertEquals(Pattern.compile("o").split("boo:and:foo", 5).length, 5);
assertEquals(Pattern.compile("b").split("ab", -1).length, 2);
}
public void testCaseInsensitiveFlag() {
assertTrue(Pattern.matches("(?i-:AbC)", "ABC"));
}
public void testEmptyGroups() {
Pattern pat = Pattern.compile("ab(?>)cda");
Matcher mat = pat.matcher("abcda");
assertTrue(mat.matches());
pat = Pattern.compile("ab()");
mat = pat.matcher("ab");
assertTrue(mat.matches());
pat = Pattern.compile("abc(?:)(..)");
mat = pat.matcher("abcgf");
assertTrue(mat.matches());
}
public void testCompileNonCaptGroup() {
boolean isCompiled = false;
try {
// BEGIN android-change
// We don't have canonical equivalence.
Pattern pat = Pattern.compile("(?:)");
pat = Pattern.compile("(?:)", Pattern.DOTALL);
pat = Pattern.compile("(?:)", Pattern.CASE_INSENSITIVE);
pat = Pattern.compile("(?:)", Pattern.COMMENTS | Pattern.UNIX_LINES);
// END android-change
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testEmbeddedFlags() {
String baseString = "(?i)((?s)a)";
String testString = "A";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a";
testString = "A";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "(?x)(?i)(?s)(?d)a.";
testString = "a\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc(?x:(?i)(?s)(?d)a.)";
testString = "abcA\n";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
baseString = "abc((?x)d)(?i)(?s)a";
testString = "abcdA";
pat = Pattern.compile(baseString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAltWithFlags() {
boolean isCompiled = false;
try {
Pattern pat = Pattern.compile("|(?i-xi)|()");
isCompiled = true;
} catch (PatternSyntaxException e) {
System.out.println(e);
}
assertTrue(isCompiled);
}
public void testRestoreFlagsAfterGroup() {
String baseString = "abc((?x)d) a";
String testString = "abcd a";
Pattern pat = Pattern.compile(baseString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
}
/*
* Verify if the Pattern support the following character classes:
* \p{javaLowerCase} \p{javaUpperCase} \p{javaWhitespace} \p{javaMirrored}
*/
public void testCompileCharacterClass() {
// Regression for HARMONY-606, 696
Pattern pattern = Pattern.compile("\\p{javaLowerCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUpperCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaWhitespace}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaMirrored}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDefined}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaIdentifierIgnorable}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaISOControl}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaJavaIdentifierStart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetter}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaLetterOrDigit}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaSpaceChar}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaTitleCase}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierPart}");
assertNotNull(pattern);
pattern = Pattern.compile("\\p{javaUnicodeIdentifierStart}");
assertNotNull(pattern);
}
/**
* s original test was fixed to pass on RI
*/
// BEGIN android-removed
// We don't have canonical equivalence.
// public void testCanonEqFlag() {
//
// /*
// * for decompositions see
// * http://www.unicode.org/Public/4.0-Update/UnicodeData-4.0.0.txt
// * http://www.unicode.org/reports/tr15/#Decomposition
// */
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "ab(a*)\\1";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a(abcdf)d";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "aabcdfd";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// // \u01E0 -> \u0226\u0304 ->\u0041\u0307\u0304
// // \u00CC -> \u0049\u0300
//
// /*
// * baseString = "\u01E0\u00CCcdb(ac)"; testString =
// * "\u0226\u0304\u0049\u0300cdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\u01E0cdb(a\u00CCc)";
// testString = "\u0041\u0307\u0304cdba\u0049\u0300c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\u00CC";
// testString = "a\u0049\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u0226\u0304cdb(ac\u0049\u0300)"; testString =
// * "\u01E0cdbac\u00CC"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u0041\u0307\u0304\u00CC)"; testString =
// * "cdb\u0226\u0304\u0049\u0300"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0[a-c]\u0049\u0300cdb(ac)"; testString =
// * "\u01E0b\u00CCcdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u01E0|\u00CCcdb(ac)"; testString =
// * "\u0041\u0307\u0304"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\u00CC?cdb(ac)*(\u01E0)*[a-c]"; testString =
// * "cdb\u0041\u0307\u0304b"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "a\u0300";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u00E0a");
// assertTrue(mat.find());
//
// /*
// * baseString = "\u7B20\uF9F8abc"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher("\uF9F8\uF9F8abc");
// * assertTrue(mat.matches());
// *
// * //\u01F9 -> \u006E\u0300 //\u00C3 -> \u0041\u0303
// *
// * baseString = "cdb(?:\u00C3\u006E\u0300)"; testString =
// * "cdb\u0041\u0303\u01F9"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * //\u014C -> \u004F\u0304 //\u0163 -> \u0074\u0327
// *
// * baseString = "cdb(?:\u0163\u004F\u0304)"; testString =
// * "cdb\u0074\u0327\u014C"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// // \u00E1->a\u0301
// // canonical ordering takes place \u0301\u0327 -> \u0327\u0301
// baseString = "c\u0327\u0301";
// testString = "c\u0301\u0327";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * Hangul decompositions
// */
// // \uD4DB->\u1111\u1171\u11B6
// // \uD21E->\u1110\u116D\u11B5
// // \uD264->\u1110\u1170
// // not Hangul:\u0453->\u0433\u0301
// baseString = "a\uD4DB\u1111\u1171\u11B6\uD264";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "\u0453c\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// baseString = "a\u1110\u116D\u11B5b\uD21Ebc";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
//
// /*
// * baseString = "\uD4DB\uD21E\u1110\u1170cdb(ac)"; testString =
// * "\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// baseString = "\uD4DB\uD264cdb(a\uD21Ec)";
// testString = "\u1111\u1171\u11B6\u1110\u1170cdba\u1110\u116D\u11B5c";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD4DB";
// testString = "a\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "a\uD21E";
// testString = "a\u1110\u116D\u11B5";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// /*
// * baseString = "\u1111\u1171\u11B6cdb(ac\u1110\u116D\u11B5)";
// * testString = "\uD4DBcdbac\uD21E"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "cdb(?:\u1111\u1171\u11B6\uD21E)"; testString =
// * "cdb\uD4DB\u1110\u116D\u11B5"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * baseString = "\uD4DB[a-c]\u1110\u116D\u11B5cdb(ac)"; testString =
// * "\uD4DBb\uD21Ecdbac"; pat = Pattern.compile(baseString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171\u11B6";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB|\u00CCcdb(ac)";
// testString = "\u1111\u1171";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertFalse(mat.matches());
//
// baseString = "\u00CC?cdb(ac)*(\uD4DB)*[a-c]";
// testString = "cdb\u1111\u1171\u11B6b";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("a\u1111\u1171\u11B6a");
// assertTrue(mat.find());
//
// baseString = "\u1111";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\uD4DBr");
// assertFalse(mat.find());
// }
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testIndexesCanonicalEq() {
// String baseString;
// String testString;
// Pattern pat;
// Matcher mat;
//
// baseString = "\uD4DB";
// pat = Pattern.compile(baseString, Pattern.CANON_EQ);
// mat = pat.matcher("bcda\u1111\u1171\u11B6awr");
// assertTrue(mat.find());
// assertEquals(mat.start(), 4);
// assertEquals(mat.end(), 7);
//
// /*
// * baseString = "\uD4DB\u1111\u1171\u11B6"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher("bcda\u1111\u1171\u11B6\uD4DBawr");
// * assertTrue(mat.find()); assertEquals(mat.start(), 4);
// * assertEquals(mat.end(), 8);
// *
// * baseString = "\uD4DB\uD21E\u1110\u1170"; testString =
// * "abcabc\u1111\u1171\u11B6\u1110\u116D\u11B5\uD264cdbac"; pat =
// * Pattern.compile(baseString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.find());
// * assertEquals(mat.start(), 6); assertEquals(mat.end(), 13);
// */}
//
// /**
// * s original test was fixed to pass on RI
// */
//
// public void testCanonEqFlagWithSupplementaryCharacters() {
//
// /*
// * \u1D1BF->\u1D1BB\u1D16F->\u1D1B9\u1D165\u1D16F in UTF32
// * \uD834\uDDBF->\uD834\uDDBB\uD834\uDD6F
// * ->\uD834\uDDB9\uD834\uDD65\uD834\uDD6F in UTF16
// */
// String patString = "abc\uD834\uDDBFef";
// String testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// Pattern pat = Pattern.compile(patString, Pattern.CANON_EQ);
// Matcher mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// *
// * patString = "abc\uD834\uDDBB\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// */
// testString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef";
// mat = pat.matcher(testString);
// assertTrue(mat.matches());
// /*
// * patString = "abc\uD834\uDDB9\uD834\uDD65\uD834\uDD6Fef"; testString =
// * "abc\uD834\uDDBFef"; pat = Pattern.compile(patString,
// * Pattern.CANON_EQ); mat = pat.matcher(testString);
// * assertTrue(mat.matches());
// *
// * testString = "abc\uD834\uDDBB\uD834\uDD6Fef"; mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */
// /*
// * testSupplementary characters with no decomposition
// */
// /*
// * patString = "a\uD9A0\uDE8Ebc\uD834\uDDBB\uD834\uDD6Fe\uDE8Ef";
// * testString = "a\uD9A0\uDE8Ebc\uD834\uDDBFe\uDE8Ef"; pat =
// * Pattern.compile(patString, Pattern.CANON_EQ); mat =
// * pat.matcher(testString); assertTrue(mat.matches());
// */}
// END android-removed
public void testRangesWithSurrogatesSupplementary() {
String patString = "[abc\uD8D2]";
String testString = "\uD8D2";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D2\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D2gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3&&[c\uD8D3]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "a";
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uD8D3\uDBEE\uDF0C&&[c\uD8D3\uDBEE\uDF0C]]";
testString = "c";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDBEE\uDF0C";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "ef\uD8D3\uDD71gh";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "ef\uD8D3gh";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[abc\uDBFC]\uDDC2cd";
testString = "\uDBFC\uDDC2cd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "a\uDDC2cd";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testSequencesWithSurrogatesSupplementary() {
String patString = "abcd\uD8D3";
String testString = "abcd\uD8D3\uDFFC";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
// BEGIN android-changed
// This one really doesn't make sense, as the above is a corrupt surrogate.
// Even if it's matched by the JDK, it's more of a bug than of a behavior one
// might want to duplicate.
// assertFalse(mat.find());
// END android-changed
testString = "abcd\uD8D3abc";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "ab\uDBEFcd";
testString = "ab\uDBEFcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = "\uDFFCabcd";
testString = "\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "abc\uDFFCabcdecd";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "\uD8D3\uDFFCabcd";
testString = "abc\uD8D3\uD8D3\uDFFCabcd";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
}
public void testPredefinedClassesWithSurrogatesSupplementary() {
String patString = "[123\\D]";
String testString = "a";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[123[^\\p{javaDigit}]]";
testString = "a";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "5";
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "3";
mat = pat.matcher(testString);
assertTrue(mat.find());
// low surrogate
testString = "\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// high surrogate
testString = "\uDADA";
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uDADA\uDFC4";
mat = pat.matcher(testString);
assertTrue(mat.find());
// surrogate characters
patString = "\\p{Cs}";
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
/*
* see http://www.unicode.org/reports/tr18/#Supplementary_Characters we
* have to treat text as code points not code units. \\p{Cs} matches any
* surrogate character but here testString is a one code point
* consisting of two code units (two surrogate characters) so we find
* nothing
*/
// assertFalse(mat.find());
// swap low and high surrogates
testString = "\uDE27\uD916";
mat = pat.matcher(testString);
assertTrue(mat.find());
patString = "[\uD916\uDE271\uD91623&&[^\\p{Cs}]]";
testString = "1";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
testString = "\uD916";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.find());
testString = "\uD916\uDE27";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.find());
// \uD9A0\uDE8E=\u7828E
// \u78281=\uD9A0\uDE81
patString = "[a-\uD9A0\uDE8E]";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testDotConstructionWithSurrogatesSupplementary() {
String patString = ".";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\n";
mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = ".*\uDE81";
testString = "\uD9A0\uDE81\uD9A0\uDE81\uD9A0\uDE81";
pat = Pattern.compile(patString);
mat = pat.matcher(testString);
assertFalse(mat.matches());
testString = "\uD9A0\uDE81\uD9A0\uDE81\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
patString = ".*";
testString = "\uD9A0\uDE81\n\uD9A0\uDE81\uD9A0\n\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void test_quoteLjava_lang_String() {
for (String aPattern : testPatterns) {
Pattern p = Pattern.compile(aPattern);
try {
assertEquals("quote was wrong for plain text", "\\Qtest\\E", p
.quote("test"));
assertEquals("quote was wrong for text with quote sign",
"\\Q\\Qtest\\E", p.quote("\\Qtest"));
assertEquals("quote was wrong for quotted text",
"\\Q\\Qtest\\E\\\\E\\Q\\E", p.quote("\\Qtest\\E"));
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
}
public void test_matcherLjava_lang_StringLjava_lang_CharSequence() {
String[][] posSeq = {
{ "abb", "ababb", "abababbababb", "abababbababbabababbbbbabb" },
{ "213567", "12324567", "1234567", "213213567",
"21312312312567", "444444567" },
{ "abcdaab", "aab", "abaab", "cdaab", "acbdadcbaab" },
{ "213234567", "3458", "0987654", "7689546432", "0398576",
"98432", "5" },
{
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ "ababbaAabababblice", "ababbaAliceababab", "ababbAabliceaaa",
"abbbAbbbliceaaa", "Alice" },
{ "a123", "bnxnvgds156", "for", "while", "if", "struct" },
{ "xy" }, { "xy" }, { "xcy" }
};
for (int i = 0; i < testPatterns.length; i++) {
for (int j = 0; j < posSeq[i].length; j++) {
assertTrue("Incorrect match: " + testPatterns[i] + " vs "
+ posSeq[i][j], Pattern.compile(testPatterns[i])
.matcher(posSeq[i][j]).matches());
}
}
}
public void testQuantifiersWithSurrogatesSupplementary() {
String patString = "\uD9A0\uDE81*abc";
String testString = "\uD9A0\uDE81\uD9A0\uDE81abc";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "abc";
mat = pat.matcher(testString);
assertTrue(mat.matches());
}
public void testAlternationsWithSurrogatesSupplementary() {
String patString = "\uDE81|\uD9A0\uDE81|\uD9A0";
String testString = "\uD9A0";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uD9A0\uDE81";
mat = pat.matcher(testString);
assertTrue(mat.matches());
testString = "\uDE81\uD9A0";
mat = pat.matcher(testString);
assertFalse(mat.matches());
}
public void testGroupsWithSurrogatesSupplementary() {
//this pattern matches nothing
String patString = "(\uD9A0)\uDE81";
String testString = "\uD9A0\uDE81";
Pattern pat = Pattern.compile(patString);
Matcher mat = pat.matcher(testString);
assertFalse(mat.matches());
patString = "(\uD9A0)";
testString = "\uD9A0\uDE81";
pat = Pattern.compile(patString, Pattern.DOTALL);
mat = pat.matcher(testString);
assertFalse(mat.find());
}
/*
* Regression test for HARMONY-688
*/
public void testUnicodeCategoryWithSurrogatesSupplementary() {
Pattern p = Pattern.compile("\\p{javaLowerCase}");
Matcher matcher = p.matcher("\uD801\uDC28");
assertTrue(matcher.find());
}
public void testSplitEmpty() {
Pattern pat = Pattern.compile("");
String[] s = pat.split("", -1);
assertEquals(1, s.length);
assertEquals("", s[0]);
}
public void testToString() {
for (int i = 0; i < testPatterns.length; i++) {
Pattern p = Pattern.compile(testPatterns[i]);
assertEquals(testPatterns[i], p.toString());
}
}
// http://code.google.com/p/android/issues/detail?id=19308
public void test_hitEnd() {
Pattern p = Pattern.compile("^2(2[4-9]|3\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
Matcher m = p.matcher("224..");
boolean isPartialMatch = !m.matches() && m.hitEnd();
assertFalse(isPartialMatch);
}
}
|
diff --git a/GeekDroid/src/cs585_hw3/team33/lib/DatabaseHelper.java b/GeekDroid/src/cs585_hw3/team33/lib/DatabaseHelper.java
index 32dc3a0..400082b 100644
--- a/GeekDroid/src/cs585_hw3/team33/lib/DatabaseHelper.java
+++ b/GeekDroid/src/cs585_hw3/team33/lib/DatabaseHelper.java
@@ -1,141 +1,141 @@
package cs585_hw3.team33.lib;
import java.util.ArrayList;
import java.util.StringTokenizer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import cs585_hw3.team33.browse.list.Result;
public class DatabaseHelper {
private static final String DATABASE_NAME = "team33.db";
private static final int DATABASE_VERSION = 4;
private static final String TABLE_NAME = "blog_posts";
private Context context;
private SQLiteDatabase db = null;
public DatabaseHelper(Context context) {
this.context = context;
}
public boolean isOpen() {
return db != null;
}
public void createDB() {
//OpenHelper openHelper = new OpenHelper(this.context);
SQLiteOpenHelper openHelper = new SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("CREATE TABLE " + TABLE_NAME + "("
+ "id INTEGER PRIMARY KEY, "
+ "X_Coord INTEGER, "
+ "Y_Coord INTEGER, "
+ "Post_Text TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
};
db = openHelper.getWritableDatabase();
}
public void populateDB() {
insert(500,600,"Nasrullah Husami is a good boy"); // Posted from the Atlantic Ocean off the coast of Africa
insert(19240000,-99120000,"Anirudh Rekhi is a bad boy"); // Posted from Mexico City
insert(35410000,139460000,"Skyler Clark is a geek"); // Posted from Japan
}
public void dropDB() {
deleteAll();
}
public void insert(int x, int y, String postTxt) {
ContentValues values = new ContentValues();
values.put("X_Coord",x);
values.put("Y_Coord",y);
values.put("Post_Text", postTxt);
@SuppressWarnings("unused")
long newid = db.insertOrThrow(TABLE_NAME, null, values);
}
public void query(int x, int y, String keywords, int k, ArrayList<Result> res ) {
String sql = "SELECT * FROM "+TABLE_NAME;
boolean b1st = true;
StringTokenizer st = new StringTokenizer(keywords," ,\r\n");
while (st.hasMoreElements()) {
sql += (b1st?" WHERE ":" OR ") + "Post_Text LIKE '%" + st.nextToken() + "%'";
b1st = false;
}
- sql += " ORDER BY (X_Coord-"+x+")*(X_Coord-"+x+") + (Y_Coord-"+y+")*(Y_Coord-"+y+")";
+ sql += " ORDER BY (X_Coord-'"+x+"')*(X_Coord- '"+x+"') + (Y_Coord-'"+y+"')*(Y_Coord-'"+y+"')";
if (k < Integer.MAX_VALUE)
sql +=" LIMIT " + k;
try {
Cursor cursor = db.rawQuery(sql, null);
res.clear();
if (cursor.moveToFirst()) {
do {
res.add( new Result(
cursor.getInt(0),
cursor.getInt(1),
cursor.getInt(2),
cursor.getString(3)
));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
} catch (SQLiteException e) {
Log.d("QUERY_ERROR",e.toString());
}
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public void selectAll(ArrayList<Result> res) {
try {
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","X_Coord","Y_Coord","Post_Text" },null,null, null, null,null);
res.clear();
if (cursor.moveToFirst()) {
do {
res.add( new Result(
cursor.getInt(0),
cursor.getInt(1),
cursor.getInt(2),
cursor.getString(3)
));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
} catch (SQLiteException e) {
Log.d("QUERY_ERROR",e.toString());
}
}
}
| true | true | public void query(int x, int y, String keywords, int k, ArrayList<Result> res ) {
String sql = "SELECT * FROM "+TABLE_NAME;
boolean b1st = true;
StringTokenizer st = new StringTokenizer(keywords," ,\r\n");
while (st.hasMoreElements()) {
sql += (b1st?" WHERE ":" OR ") + "Post_Text LIKE '%" + st.nextToken() + "%'";
b1st = false;
}
sql += " ORDER BY (X_Coord-"+x+")*(X_Coord-"+x+") + (Y_Coord-"+y+")*(Y_Coord-"+y+")";
if (k < Integer.MAX_VALUE)
sql +=" LIMIT " + k;
try {
Cursor cursor = db.rawQuery(sql, null);
res.clear();
if (cursor.moveToFirst()) {
do {
res.add( new Result(
cursor.getInt(0),
cursor.getInt(1),
cursor.getInt(2),
cursor.getString(3)
));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
} catch (SQLiteException e) {
Log.d("QUERY_ERROR",e.toString());
}
}
| public void query(int x, int y, String keywords, int k, ArrayList<Result> res ) {
String sql = "SELECT * FROM "+TABLE_NAME;
boolean b1st = true;
StringTokenizer st = new StringTokenizer(keywords," ,\r\n");
while (st.hasMoreElements()) {
sql += (b1st?" WHERE ":" OR ") + "Post_Text LIKE '%" + st.nextToken() + "%'";
b1st = false;
}
sql += " ORDER BY (X_Coord-'"+x+"')*(X_Coord- '"+x+"') + (Y_Coord-'"+y+"')*(Y_Coord-'"+y+"')";
if (k < Integer.MAX_VALUE)
sql +=" LIMIT " + k;
try {
Cursor cursor = db.rawQuery(sql, null);
res.clear();
if (cursor.moveToFirst()) {
do {
res.add( new Result(
cursor.getInt(0),
cursor.getInt(1),
cursor.getInt(2),
cursor.getString(3)
));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
} catch (SQLiteException e) {
Log.d("QUERY_ERROR",e.toString());
}
}
|
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
index f98af922..4b90b9bc 100644
--- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
+++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
@@ -1,821 +1,824 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* 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.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ethan Hugg
* Terry Lucas
* Milen Nankov
* David P. Caldwell <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.xmlimpl;
import org.mozilla.javascript.*;
import org.mozilla.javascript.xml.*;
import java.util.ArrayList;
class XMLList extends XMLObjectImpl implements Function {
static final long serialVersionUID = -4543618751670781135L;
private XmlNode.InternalList _annos;
private XMLObjectImpl targetObject = null;
private XmlNode.QName targetProperty = null;
XMLList(XMLLibImpl lib, Scriptable scope, XMLObject prototype) {
super(lib, scope, prototype);
_annos = new XmlNode.InternalList();
}
/* TODO Will probably end up unnecessary as we move things around */
XmlNode.InternalList getNodeList() {
return _annos;
}
// TODO Should be XMLObjectImpl, XMLName?
void setTargets(XMLObjectImpl object, XmlNode.QName property) {
targetObject = object;
targetProperty = property;
}
/* TODO: original author marked this as deprecated */
private XML getXmlFromAnnotation(int index) {
return getXML(_annos, index);
}
@Override
XML getXML() {
if (length() == 1) return getXmlFromAnnotation(0);
return null;
}
private void internalRemoveFromList(int index) {
_annos.remove(index);
}
void replace(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index+1, length());
_annos = newAnnoList;
}
}
private void insert(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index, length());
_annos = newAnnoList;
}
}
//
//
// methods overriding ScriptableObject
//
//
@Override
public String getClassName() {
return "XMLList";
}
//
//
// methods overriding IdScriptableObject
//
//
@Override
public Object get(int index, Scriptable start) {
//Log("get index: " + index);
if (index >= 0 && index < length()) {
return getXmlFromAnnotation(index);
} else {
return Scriptable.NOT_FOUND;
}
}
@Override
boolean hasXMLProperty(XMLName xmlName) {
boolean result = false;
// Has now should return true if the property would have results > 0 or
// if it's a method name
String name = xmlName.localName();
if ((getPropertyList(xmlName).length() > 0) ||
(getMethod(name) != NOT_FOUND)) {
result = true;
}
return result;
}
@Override
public boolean has(int index, Scriptable start) {
return 0 <= index && index < length();
}
@Override
void putXMLProperty(XMLName xmlName, Object value) {
//Log("put property: " + name);
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (length() > 1) {
throw ScriptRuntime.typeError(
"Assignment to lists with more than one item is not supported");
} else if (length() == 0) {
// Secret sauce for super-expandos.
// We set an element here, and then add ourselves to our target.
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null &&
targetProperty.getLocalName().length() > 0)
{
// Add an empty element with our targetProperty name and
// then set it.
XML xmlValue = newTextElementXML(null, targetProperty, null);
addToList(xmlValue);
if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
}
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
} else {
throw ScriptRuntime.typeError(
"Assignment to empty XMLList without targets not supported");
}
} else if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null)
{
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
}
}
}
@Override
Object getXMLProperty(XMLName name) {
return getPropertyList(name);
}
private void replaceNode(XML xml, XML with) {
xml.replaceWith(with);
}
@Override
public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
+ if (xmlValue == null) {
+ xmlValue = item(0).copy();
+ }
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
private XML getXML(XmlNode.InternalList _annos, int index) {
if (index >= 0 && index < length()) {
return xmlFromNode(_annos.item(index));
} else {
return null;
}
}
@Override
void deleteXMLProperty(XMLName name) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml.isElement()) {
xml.deleteXMLProperty(name);
}
}
}
@Override
public void delete(int index) {
if (index >= 0 && index < length()) {
XML xml = getXmlFromAnnotation(index);
xml.remove();
internalRemoveFromList(index);
}
}
@Override
public Object[] getIds() {
Object enumObjs[];
if (isPrototype()) {
enumObjs = new Object[0];
} else {
enumObjs = new Object[length()];
for (int i = 0; i < enumObjs.length; i++) {
enumObjs[i] = Integer.valueOf(i);
}
}
return enumObjs;
}
public Object[] getIdsForDebug() {
return getIds();
}
// XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator.
void remove() {
int nLen = length();
for (int i = nLen - 1; i >= 0; i--) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
xml.remove();
internalRemoveFromList(i);
}
}
}
XML item(int index) {
return _annos != null
? getXmlFromAnnotation(index) : createEmptyXML();
}
private void setAttribute(XMLName xmlName, Object value) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
xml.setAttribute(xmlName, value);
}
}
void addToList(Object toAdd) {
_annos.addToList(toAdd);
}
//
//
// Methods from section 12.4.4 in the spec
//
//
@Override
XMLList child(int index) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(index));
}
return result;
}
@Override
XMLList child(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(xmlName));
}
return result;
}
@Override
void addMatches(XMLList rv, XMLName name) {
for (int i=0; i<length(); i++) {
getXmlFromAnnotation(i).addMatches(rv, name);
}
}
@Override
XMLList children() {
ArrayList<XML> list = new ArrayList<XML>();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
XMLList childList = xml.children();
int cChildren = childList.length();
for (int j = 0; j < cChildren; j++) {
list.add(childList.item(j));
}
}
}
XMLList allChildren = newXMLList();
int sz = list.size();
for (int i = 0; i < sz; i++) {
allChildren.addToList(list.get(i));
}
return allChildren;
}
@Override
XMLList comments() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.comments());
}
return result;
}
@Override
XMLList elements(XMLName name) {
XMLList rv = newXMLList();
for (int i=0; i<length(); i++) {
XML xml = getXmlFromAnnotation(i);
rv.addToList(xml.elements(name));
}
return rv;
}
@Override
boolean contains(Object xml) {
boolean result = false;
for (int i = 0; i < length(); i++) {
XML member = getXmlFromAnnotation(i);
if (member.equivalentXml(xml)) {
result = true;
break;
}
}
return result;
}
@Override
XMLObjectImpl copy() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.copy());
}
return result;
}
@Override
boolean hasOwnProperty(XMLName xmlName) {
if (isPrototype()) {
String property = xmlName.localName();
return (findPrototypeId(property) != 0);
} else {
return (getPropertyList(xmlName).length() > 0);
}
}
@Override
boolean hasComplexContent() {
boolean complexContent;
int length = length();
if (length == 0) {
complexContent = false;
} else if (length == 1) {
complexContent = getXmlFromAnnotation(0).hasComplexContent();
} else {
complexContent = false;
for (int i = 0; i < length; i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
complexContent = true;
break;
}
}
}
return complexContent;
}
@Override
boolean hasSimpleContent() {
if (length() == 0) {
return true;
} else if (length() == 1) {
return getXmlFromAnnotation(0).hasSimpleContent();
} else {
for (int i=0; i<length(); i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
return false;
}
}
return true;
}
}
@Override
int length() {
int result = 0;
if (_annos != null) {
result = _annos.length();
}
return result;
}
@Override
void normalize() {
for (int i = 0; i < length(); i++) {
getXmlFromAnnotation(i).normalize();
}
}
/**
* If list is empty, return undefined, if elements have different parents return undefined,
* If they all have the same parent, return that parent
*/
@Override
Object parent() {
if (length() == 0) return Undefined.instance;
XML candidateParent = null;
for (int i = 0; i < length(); i++) {
Object currParent = getXmlFromAnnotation(i).parent();
if (!(currParent instanceof XML)) return Undefined.instance;
XML xml = (XML)currParent;
if (i == 0) {
// Set the first for the rest to compare to.
candidateParent = xml;
} else {
if (candidateParent.is(xml)) {
// keep looking
} else {
return Undefined.instance;
}
}
}
return candidateParent;
}
@Override
XMLList processingInstructions(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.processingInstructions(xmlName));
}
return result;
}
@Override
boolean propertyIsEnumerable(Object name) {
long index;
if (name instanceof Integer) {
index = ((Integer)name).intValue();
} else if (name instanceof Number) {
double x = ((Number)name).doubleValue();
index = (long)x;
if (index != x) {
return false;
}
if (index == 0 && 1.0 / x < 0) {
// Negative 0
return false;
}
} else {
String s = ScriptRuntime.toString(name);
index = ScriptRuntime.testUint32String(s);
}
return (0 <= index && index < length());
}
@Override
XMLList text() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).text());
}
return result;
}
@Override
public String toString() {
// ECMA357 10.1.2
if (hasSimpleContent()) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length(); i++) {
XML next = getXmlFromAnnotation(i);
if (next.isComment() || next.isProcessingInstruction()) {
// do nothing
} else {
sb.append(next.toString());
}
}
return sb.toString();
} else {
return toXMLString();
}
}
@Override
String toSource(int indent) {
return toXMLString();
}
@Override
String toXMLString() {
// See ECMA 10.2.1
StringBuffer sb = new StringBuffer();
for (int i=0; i<length(); i++) {
if (getProcessor().isPrettyPrinting() && i != 0) {
sb.append('\n');
}
sb.append(getXmlFromAnnotation(i).toXMLString());
}
return sb.toString();
}
@Override
Object valueOf() {
return this;
}
//
// Other public Functions from XMLObject
//
@Override
boolean equivalentXml(Object target) {
boolean result = false;
// Zero length list should equate to undefined
if (target instanceof Undefined && length() == 0) {
result = true;
} else if (length() == 1) {
result = getXmlFromAnnotation(0).equivalentXml(target);
} else if (target instanceof XMLList) {
XMLList otherList = (XMLList) target;
if (otherList.length() == length()) {
result = true;
for (int i = 0; i < length(); i++) {
if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) {
result = false;
break;
}
}
}
}
return result;
}
private XMLList getPropertyList(XMLName name) {
XMLList propertyList = newXMLList();
XmlNode.QName qname = null;
if (!name.isDescendants() && !name.isAttributeName()) {
// Only set the targetProperty if this is a regular child get
// and not a descendant or attribute get
qname = name.toQname();
}
propertyList.setTargets(this, qname);
for (int i = 0; i < length(); i++) {
propertyList.addToList(
getXmlFromAnnotation(i).getPropertyList(name));
}
return propertyList;
}
private Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args) {
String methodName = isApply ? "apply" : "call";
if(!(thisObj instanceof XMLList) ||
((XMLList)thisObj).targetProperty == null)
throw ScriptRuntime.typeError1("msg.isnt.function",
methodName);
return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args);
}
@Override
protected Object jsConstructor(Context cx, boolean inNewExpr,
Object[] args)
{
if (args.length == 0) {
return newXMLList();
} else {
Object arg0 = args[0];
if (!inNewExpr && arg0 instanceof XMLList) {
// XMLList(XMLList) returns the same object.
return arg0;
}
return newXMLListFrom(arg0);
}
}
/**
* See ECMA 357, 11_2_2_1, Semantics, 3_e.
*/
@Override
public Scriptable getExtraMethodSource(Context cx) {
if (length() == 1) {
return getXmlFromAnnotation(0);
}
return null;
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) {
// This XMLList is being called as a Function.
// Let's find the real Function object.
if(targetProperty == null)
throw ScriptRuntime.notFunctionError(this);
String methodName = targetProperty.getLocalName();
boolean isApply = methodName.equals("apply");
if(isApply || methodName.equals("call"))
return applyOrCall(isApply, cx, scope, thisObj, args);
Callable method = ScriptRuntime.getElemFunctionAndThis(
this, methodName, cx);
// Call lastStoredScriptable to clear stored thisObj
// but ignore the result as the method should use the supplied
// thisObj, not one from redirected call
ScriptRuntime.lastStoredScriptable(cx);
return method.call(cx, scope, thisObj, args);
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList");
}
}
| true | true | public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
| public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
xmlValue = item(0).copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
|
diff --git a/common/net/minecraftforge/common/ForgeInternalHandler.java b/common/net/minecraftforge/common/ForgeInternalHandler.java
index 7e87bcec1..f95da0f98 100644
--- a/common/net/minecraftforge/common/ForgeInternalHandler.java
+++ b/common/net/minecraftforge/common/ForgeInternalHandler.java
@@ -1,82 +1,82 @@
package net.minecraftforge.common;
import java.util.UUID;
import cpw.mods.fml.common.FMLLog;
import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;
public class ForgeInternalHandler
{
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack stack = ((EntityItem)entity).item;
if (stack == null)
{
entity.setDead();
event.setCanceled(true);
return;
}
Item item = stack.getItem();
if (item == null)
{
FMLLog.warning("Attempted to add a EntityItem to the world with a invalid item: ID %d at " +
- "(%d, %d, %d), this is most likely a config issue between you and the server. Please double check your configs",
+ "(%2.2f, %2.2f, %2.2f), this is most likely a config issue between you and the server. Please double check your configs",
stack.itemID, entity.posX, entity.posY, entity.posZ);
entity.setDead();
event.setCanceled(true);
return;
}
if (item.hasCustomEntity(stack))
{
Entity newEntity = item.createEntity(event.world, entity, stack);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionLoad(WorldEvent.Load event)
{
ForgeChunkManager.loadWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionSave(WorldEvent.Save event)
{
ForgeChunkManager.saveWorld(event.world);
}
@ForgeSubscribe(priority = EventPriority.HIGHEST)
public void onDimensionUnload(WorldEvent.Unload event)
{
ForgeChunkManager.unloadWorld(event.world);
}
}
| true | true | public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack stack = ((EntityItem)entity).item;
if (stack == null)
{
entity.setDead();
event.setCanceled(true);
return;
}
Item item = stack.getItem();
if (item == null)
{
FMLLog.warning("Attempted to add a EntityItem to the world with a invalid item: ID %d at " +
"(%d, %d, %d), this is most likely a config issue between you and the server. Please double check your configs",
stack.itemID, entity.posX, entity.posY, entity.posZ);
entity.setDead();
event.setCanceled(true);
return;
}
if (item.hasCustomEntity(stack))
{
Entity newEntity = item.createEntity(event.world, entity, stack);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
| public void onEntityJoinWorld(EntityJoinWorldEvent event)
{
if (!event.world.isRemote)
{
if (event.entity.getPersistentID() == null)
{
event.entity.generatePersistentID();
}
else
{
ForgeChunkManager.loadEntity(event.entity);
}
}
Entity entity = event.entity;
if (entity.getClass().equals(EntityItem.class))
{
ItemStack stack = ((EntityItem)entity).item;
if (stack == null)
{
entity.setDead();
event.setCanceled(true);
return;
}
Item item = stack.getItem();
if (item == null)
{
FMLLog.warning("Attempted to add a EntityItem to the world with a invalid item: ID %d at " +
"(%2.2f, %2.2f, %2.2f), this is most likely a config issue between you and the server. Please double check your configs",
stack.itemID, entity.posX, entity.posY, entity.posZ);
entity.setDead();
event.setCanceled(true);
return;
}
if (item.hasCustomEntity(stack))
{
Entity newEntity = item.createEntity(event.world, entity, stack);
if (newEntity != null)
{
entity.setDead();
event.setCanceled(true);
event.world.spawnEntityInWorld(newEntity);
}
}
}
}
|
diff --git a/src/test/cli/cloudify/cloud/services/ec2/Ec2WinCloudService.java b/src/test/cli/cloudify/cloud/services/ec2/Ec2WinCloudService.java
index bdcdaf64..bacb6220 100644
--- a/src/test/cli/cloudify/cloud/services/ec2/Ec2WinCloudService.java
+++ b/src/test/cli/cloudify/cloud/services/ec2/Ec2WinCloudService.java
@@ -1,32 +1,32 @@
package test.cli.cloudify.cloud.services.ec2;
import java.io.IOException;
public class Ec2WinCloudService extends Ec2CloudService {
private static final String cloudName = "ec2-win";
private static final String DEFAULT_MEDIUM_WIN_AMI = "us-east-1/ami-6cb90605";
public Ec2WinCloudService(String uniqueName) {
super(uniqueName, cloudName);
}
@Override
public String getCloudName() {
return cloudName;
}
@Override
public void injectServiceAuthenticationDetails() throws IOException {
super.injectServiceAuthenticationDetails();
- getAdditionalPropsToReplace().put("cloudifyagent_", this.machinePrefix + "cloudify-agent");
+ getAdditionalPropsToReplace().put("cloudifyagent", this.machinePrefix + "cloudify-agent");
getAdditionalPropsToReplace().put("cloudifymanager", this.machinePrefix + "cloudify-manager");
if (getRegion().contains("eu")) {
getAdditionalPropsToReplace().put('"' + DEFAULT_MEDIUM_WIN_AMI + '"', '"' + "eu-west-1/ami-911616e5" + '"');
}
}
}
| true | true | public void injectServiceAuthenticationDetails() throws IOException {
super.injectServiceAuthenticationDetails();
getAdditionalPropsToReplace().put("cloudifyagent_", this.machinePrefix + "cloudify-agent");
getAdditionalPropsToReplace().put("cloudifymanager", this.machinePrefix + "cloudify-manager");
if (getRegion().contains("eu")) {
getAdditionalPropsToReplace().put('"' + DEFAULT_MEDIUM_WIN_AMI + '"', '"' + "eu-west-1/ami-911616e5" + '"');
}
}
| public void injectServiceAuthenticationDetails() throws IOException {
super.injectServiceAuthenticationDetails();
getAdditionalPropsToReplace().put("cloudifyagent", this.machinePrefix + "cloudify-agent");
getAdditionalPropsToReplace().put("cloudifymanager", this.machinePrefix + "cloudify-manager");
if (getRegion().contains("eu")) {
getAdditionalPropsToReplace().put('"' + DEFAULT_MEDIUM_WIN_AMI + '"', '"' + "eu-west-1/ami-911616e5" + '"');
}
}
|
diff --git a/src/com/android/contacts/list/ContactBrowseListFragment.java b/src/com/android/contacts/list/ContactBrowseListFragment.java
index 3e8e4a39f..09b6d4279 100644
--- a/src/com/android/contacts/list/ContactBrowseListFragment.java
+++ b/src/com/android/contacts/list/ContactBrowseListFragment.java
@@ -1,703 +1,710 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.list;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Directory;
import android.text.TextUtils;
import android.util.Log;
import com.android.common.widget.CompositeCursorAdapter.Partition;
import com.android.contacts.R;
import com.android.contacts.util.ContactLoaderUtils;
import com.android.contacts.widget.AutoScrollListView;
import java.util.List;
/**
* Fragment containing a contact list used for browsing (as compared to
* picking a contact with one of the PICK intents).
*/
public abstract class ContactBrowseListFragment extends
ContactEntryListFragment<ContactListAdapter> {
private static final String TAG = "ContactList";
private static final String KEY_SELECTED_URI = "selectedUri";
private static final String KEY_SELECTION_VERIFIED = "selectionVerified";
private static final String KEY_FILTER = "filter";
private static final String KEY_LAST_SELECTED_POSITION = "lastSelected";
private static final String PERSISTENT_SELECTION_PREFIX = "defaultContactBrowserSelection";
/**
* The id for a delayed message that triggers automatic selection of the first
* found contact in search mode.
*/
private static final int MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT = 1;
/**
* The delay that is used for automatically selecting the first found contact.
*/
private static final int DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS = 500;
/**
* The minimum number of characters in the search query that is required
* before we automatically select the first found contact.
*/
private static final int AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH = 2;
private SharedPreferences mPrefs;
private Handler mHandler;
private boolean mStartedLoading;
private boolean mSelectionRequired;
private boolean mSelectionToScreenRequested;
private boolean mSmoothScrollRequested;
private boolean mSelectionPersistenceRequested;
private Uri mSelectedContactUri;
private long mSelectedContactDirectoryId;
private String mSelectedContactLookupKey;
private long mSelectedContactId;
private boolean mSelectionVerified;
private int mLastSelectedPosition = -1;
private boolean mRefreshingContactUri;
private ContactListFilter mFilter;
private String mPersistentSelectionPrefix = PERSISTENT_SELECTION_PREFIX;
protected OnContactBrowserActionListener mListener;
private ContactLookupTask mContactLookupTask;
private final class ContactLookupTask extends AsyncTask<Void, Void, Uri> {
private final Uri mUri;
private boolean mIsCancelled;
public ContactLookupTask(Uri uri) {
mUri = uri;
}
@Override
protected Uri doInBackground(Void... args) {
Cursor cursor = null;
try {
final ContentResolver resolver = getContext().getContentResolver();
final Uri uriCurrentFormat = ContactLoaderUtils.ensureIsContactUri(resolver, mUri);
cursor = resolver.query(uriCurrentFormat,
new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final long contactId = cursor.getLong(0);
final String lookupKey = cursor.getString(1);
if (contactId != 0 && !TextUtils.isEmpty(lookupKey)) {
return Contacts.getLookupUri(contactId, lookupKey);
}
}
Log.e(TAG, "Error: No contact ID or lookup key for contact " + mUri);
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void cancel() {
super.cancel(true);
// Use a flag to keep track of whether the {@link AsyncTask} was cancelled or not in
// order to ensure onPostExecute() is not executed after the cancel request. The flag is
// necessary because {@link AsyncTask} still calls onPostExecute() if the cancel request
// came after the worker thread was finished.
mIsCancelled = true;
}
@Override
protected void onPostExecute(Uri uri) {
// Make sure the {@link Fragment} is at least still attached to the {@link Activity}
// before continuing. Null URIs should still be allowed so that the list can be
// refreshed and a default contact can be selected (i.e. the case of deleted
// contacts).
if (mIsCancelled || !isAdded()) {
return;
}
onContactUriQueryFinished(uri);
}
}
private boolean mDelaySelection;
private Handler getHandler() {
if (mHandler == null) {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT:
selectDefaultContact();
break;
}
}
};
}
return mHandler;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mPrefs = PreferenceManager.getDefaultSharedPreferences(activity);
restoreFilter();
restoreSelectedUri(false);
}
@Override
protected void setSearchMode(boolean flag) {
if (isSearchMode() != flag) {
if (!flag) {
restoreSelectedUri(true);
}
super.setSearchMode(flag);
}
}
public void setFilter(ContactListFilter filter) {
setFilter(filter, true);
}
public void setFilter(ContactListFilter filter, boolean restoreSelectedUri) {
if (mFilter == null && filter == null) {
return;
}
if (mFilter != null && mFilter.equals(filter)) {
return;
}
Log.v(TAG, "New filter: " + filter);
mFilter = filter;
mLastSelectedPosition = -1;
saveFilter();
if (restoreSelectedUri) {
mSelectedContactUri = null;
restoreSelectedUri(true);
}
reloadData();
}
public ContactListFilter getFilter() {
return mFilter;
}
@Override
public void restoreSavedState(Bundle savedState) {
super.restoreSavedState(savedState);
if (savedState == null) {
return;
}
mFilter = savedState.getParcelable(KEY_FILTER);
mSelectedContactUri = savedState.getParcelable(KEY_SELECTED_URI);
mSelectionVerified = savedState.getBoolean(KEY_SELECTION_VERIFIED);
mLastSelectedPosition = savedState.getInt(KEY_LAST_SELECTED_POSITION);
parseSelectedContactUri();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(KEY_FILTER, mFilter);
outState.putParcelable(KEY_SELECTED_URI, mSelectedContactUri);
outState.putBoolean(KEY_SELECTION_VERIFIED, mSelectionVerified);
outState.putInt(KEY_LAST_SELECTED_POSITION, mLastSelectedPosition);
}
protected void refreshSelectedContactUri() {
if (mContactLookupTask != null) {
mContactLookupTask.cancel();
}
if (!isSelectionVisible()) {
return;
}
mRefreshingContactUri = true;
if (mSelectedContactUri == null) {
onContactUriQueryFinished(null);
return;
}
if (mSelectedContactDirectoryId != Directory.DEFAULT
&& mSelectedContactDirectoryId != Directory.LOCAL_INVISIBLE) {
onContactUriQueryFinished(mSelectedContactUri);
} else {
mContactLookupTask = new ContactLookupTask(mSelectedContactUri);
mContactLookupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
}
}
protected void onContactUriQueryFinished(Uri uri) {
mRefreshingContactUri = false;
mSelectedContactUri = uri;
parseSelectedContactUri();
checkSelection();
}
@Override
protected void prepareEmptyView() {
if (isSearchMode()) {
return;
} else if (isSyncActive()) {
if (hasIccCard()) {
setEmptyText(R.string.noContactsHelpTextWithSync);
} else {
setEmptyText(R.string.noContactsNoSimHelpTextWithSync);
}
} else {
if (hasIccCard()) {
setEmptyText(R.string.noContactsHelpText);
} else {
setEmptyText(R.string.noContactsNoSimHelpText);
}
}
}
public Uri getSelectedContactUri() {
return mSelectedContactUri;
}
/**
* Sets the new selection for the list.
*/
public void setSelectedContactUri(Uri uri) {
setSelectedContactUri(uri, true, false /* no smooth scroll */, true, false);
}
@Override
public void setQueryString(String queryString, boolean delaySelection) {
mDelaySelection = delaySelection;
super.setQueryString(queryString, delaySelection);
}
/**
* Sets whether or not a contact selection must be made.
* @param required if true, we need to check if the selection is present in
* the list and if not notify the listener so that it can load a
* different list.
* TODO: Figure out how to reconcile this with {@link #setSelectedContactUri},
* without causing unnecessary loading of the list if the selected contact URI is
* the same as before.
*/
public void setSelectionRequired(boolean required) {
mSelectionRequired = required;
}
/**
* Sets the new contact selection.
*
* @param uri the new selection
* @param required if true, we need to check if the selection is present in
* the list and if not notify the listener so that it can load a
* different list
* @param smoothScroll if true, the UI will roll smoothly to the new
* selection
* @param persistent if true, the selection will be stored in shared
* preferences.
* @param willReloadData if true, the selection will be remembered but not
* actually shown, because we are expecting that the data will be
* reloaded momentarily
*/
private void setSelectedContactUri(Uri uri, boolean required, boolean smoothScroll,
boolean persistent, boolean willReloadData) {
mSmoothScrollRequested = smoothScroll;
mSelectionToScreenRequested = true;
if ((mSelectedContactUri == null && uri != null)
|| (mSelectedContactUri != null && !mSelectedContactUri.equals(uri))) {
mSelectionVerified = false;
mSelectionRequired = required;
mSelectionPersistenceRequested = persistent;
mSelectedContactUri = uri;
parseSelectedContactUri();
if (!willReloadData) {
// Configure the adapter to show the selection based on the
// lookup key extracted from the URI
ContactListAdapter adapter = getAdapter();
if (adapter != null) {
adapter.setSelectedContact(mSelectedContactDirectoryId,
mSelectedContactLookupKey, mSelectedContactId);
getListView().invalidateViews();
}
}
// Also, launch a loader to pick up a new lookup URI in case it has changed
refreshSelectedContactUri();
}
}
private void parseSelectedContactUri() {
if (mSelectedContactUri != null) {
String directoryParam =
mSelectedContactUri.getQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY);
mSelectedContactDirectoryId = TextUtils.isEmpty(directoryParam) ? Directory.DEFAULT
: Long.parseLong(directoryParam);
if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_LOOKUP_URI.toString())) {
List<String> pathSegments = mSelectedContactUri.getPathSegments();
mSelectedContactLookupKey = Uri.encode(pathSegments.get(2));
if (pathSegments.size() == 4) {
mSelectedContactId = ContentUris.parseId(mSelectedContactUri);
}
} else if (mSelectedContactUri.toString().startsWith(Contacts.CONTENT_URI.toString()) &&
mSelectedContactUri.getPathSegments().size() >= 2) {
mSelectedContactLookupKey = null;
mSelectedContactId = ContentUris.parseId(mSelectedContactUri);
} else {
Log.e(TAG, "Unsupported contact URI: " + mSelectedContactUri);
mSelectedContactLookupKey = null;
mSelectedContactId = 0;
}
} else {
mSelectedContactDirectoryId = Directory.DEFAULT;
mSelectedContactLookupKey = null;
mSelectedContactId = 0;
}
}
@Override
protected void configureAdapter() {
super.configureAdapter();
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean searchMode = isSearchMode();
if (!searchMode && mFilter != null) {
adapter.setFilter(mFilter);
if (mSelectionRequired
|| mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
}
}
// Display the user's profile if not in search mode
adapter.setIncludeProfile(!searchMode);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
super.onLoadFinished(loader, data);
mSelectionVerified = false;
// Refresh the currently selected lookup in case it changed while we were sleeping
refreshSelectedContactUri();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private void checkSelection() {
if (mSelectionVerified) {
return;
}
if (mRefreshingContactUri) {
return;
}
if (isLoadingDirectoryList()) {
return;
}
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean directoryLoading = true;
int count = adapter.getPartitionCount();
for (int i = 0; i < count; i++) {
Partition partition = adapter.getPartition(i);
if (partition instanceof DirectoryPartition) {
DirectoryPartition directory = (DirectoryPartition) partition;
if (directory.getDirectoryId() == mSelectedContactDirectoryId) {
directoryLoading = directory.isLoading();
break;
}
}
}
if (directoryLoading) {
return;
}
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
final int selectedPosition = adapter.getSelectedContactPosition();
if (selectedPosition != -1) {
mLastSelectedPosition = selectedPosition;
} else {
if (isSearchMode()) {
if (mDelaySelection) {
selectFirstFoundContactAfterDelay();
if (mListener != null) {
mListener.onSelectionChange();
}
return;
}
} else if (mSelectionRequired) {
// A specific contact was requested, but it's not in the loaded list.
// Try reconfiguring and reloading the list that will hopefully contain
// the requested contact. Only take one attempt to avoid an infinite loop
// in case the contact cannot be found at all.
mSelectionRequired = false;
// If we were looking at a different specific contact, just reload
+ // FILTER_TYPE_ALL_ACCOUNTS is needed for the case where a new contact is added
+ // on a tablet and the loader is returning a stale list. In this case, the contact
+ // will not be found until the next load. b/7621855 This will only fix the most
+ // common case where all accounts are shown. It will not fix the one account case.
+ // TODO: we may want to add more FILTER_TYPEs or relax this check to fix all other
+ // FILTER_TYPE cases.
if (mFilter != null
- && mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
+ && (mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT
+ || mFilter.filterType == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS)) {
reloadData();
} else {
// Otherwise, call the listener, which will adjust the filter.
notifyInvalidSelection();
}
return;
} else if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
// If we were trying to load a specific contact, but that contact no longer
// exists, call the listener, which will adjust the filter.
notifyInvalidSelection();
return;
}
saveSelectedUri(null);
selectDefaultContact();
}
mSelectionRequired = false;
mSelectionVerified = true;
if (mSelectionPersistenceRequested) {
saveSelectedUri(mSelectedContactUri);
mSelectionPersistenceRequested = false;
}
if (mSelectionToScreenRequested) {
requestSelectionToScreen(selectedPosition);
}
getListView().invalidateViews();
if (mListener != null) {
mListener.onSelectionChange();
}
}
/**
* Automatically selects the first found contact in search mode. The selection
* is updated after a delay to allow the user to type without to much UI churn
* and to save bandwidth on directory queries.
*/
public void selectFirstFoundContactAfterDelay() {
Handler handler = getHandler();
handler.removeMessages(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT);
String queryString = getQueryString();
if (queryString != null
&& queryString.length() >= AUTOSELECT_FIRST_FOUND_CONTACT_MIN_QUERY_LENGTH) {
handler.sendEmptyMessageDelayed(MESSAGE_AUTOSELECT_FIRST_FOUND_CONTACT,
DELAY_AUTOSELECT_FIRST_FOUND_CONTACT_MILLIS);
} else {
setSelectedContactUri(null, false, false, false, false);
}
}
protected void selectDefaultContact() {
Uri contactUri = null;
ContactListAdapter adapter = getAdapter();
if (mLastSelectedPosition != -1) {
int count = adapter.getCount();
int pos = mLastSelectedPosition;
if (pos >= count && count > 0) {
pos = count - 1;
}
contactUri = adapter.getContactUri(pos);
}
if (contactUri == null) {
contactUri = adapter.getFirstContactUri();
}
setSelectedContactUri(contactUri, false, mSmoothScrollRequested, false, false);
}
protected void requestSelectionToScreen(int selectedPosition) {
if (selectedPosition != -1) {
AutoScrollListView listView = (AutoScrollListView)getListView();
listView.requestPositionToScreen(
selectedPosition + listView.getHeaderViewsCount(), mSmoothScrollRequested);
mSelectionToScreenRequested = false;
}
}
@Override
public boolean isLoading() {
return mRefreshingContactUri || super.isLoading();
}
@Override
protected void startLoading() {
mStartedLoading = true;
mSelectionVerified = false;
super.startLoading();
}
public void reloadDataAndSetSelectedUri(Uri uri) {
setSelectedContactUri(uri, true, true, true, true);
reloadData();
}
@Override
public void reloadData() {
if (mStartedLoading) {
mSelectionVerified = false;
mLastSelectedPosition = -1;
super.reloadData();
}
}
public void setOnContactListActionListener(OnContactBrowserActionListener listener) {
mListener = listener;
}
public void createNewContact() {
if (mListener != null) mListener.onCreateNewContactAction();
}
public void viewContact(Uri contactUri) {
setSelectedContactUri(contactUri, false, false, true, false);
if (mListener != null) mListener.onViewContactAction(contactUri);
}
public void editContact(Uri contactUri) {
if (mListener != null) mListener.onEditContactAction(contactUri);
}
public void deleteContact(Uri contactUri) {
if (mListener != null) mListener.onDeleteContactAction(contactUri);
}
public void addToFavorites(Uri contactUri) {
if (mListener != null) mListener.onAddToFavoritesAction(contactUri);
}
public void removeFromFavorites(Uri contactUri) {
if (mListener != null) mListener.onRemoveFromFavoritesAction(contactUri);
}
public void callContact(Uri contactUri) {
if (mListener != null) mListener.onCallContactAction(contactUri);
}
public void smsContact(Uri contactUri) {
if (mListener != null) mListener.onSmsContactAction(contactUri);
}
private void notifyInvalidSelection() {
if (mListener != null) mListener.onInvalidSelection();
}
@Override
protected void finish() {
super.finish();
if (mListener != null) mListener.onFinishAction();
}
private void saveSelectedUri(Uri contactUri) {
if (isSearchMode()) {
return;
}
ContactListFilter.storeToPreferences(mPrefs, mFilter);
Editor editor = mPrefs.edit();
if (contactUri == null) {
editor.remove(getPersistentSelectionKey());
} else {
editor.putString(getPersistentSelectionKey(), contactUri.toString());
}
editor.apply();
}
private void restoreSelectedUri(boolean willReloadData) {
// The meaning of mSelectionRequired is that we need to show some
// selection other than the previous selection saved in shared preferences
if (mSelectionRequired) {
return;
}
String selectedUri = mPrefs.getString(getPersistentSelectionKey(), null);
if (selectedUri == null) {
setSelectedContactUri(null, false, false, false, willReloadData);
} else {
setSelectedContactUri(Uri.parse(selectedUri), false, false, false, willReloadData);
}
}
private void saveFilter() {
ContactListFilter.storeToPreferences(mPrefs, mFilter);
}
private void restoreFilter() {
mFilter = ContactListFilter.restoreDefaultPreferences(mPrefs);
}
private String getPersistentSelectionKey() {
if (mFilter == null) {
return mPersistentSelectionPrefix;
} else {
return mPersistentSelectionPrefix + "-" + mFilter.getId();
}
}
public boolean isOptionsMenuChanged() {
// This fragment does not have an option menu of its own
return false;
}
}
| false | true | private void checkSelection() {
if (mSelectionVerified) {
return;
}
if (mRefreshingContactUri) {
return;
}
if (isLoadingDirectoryList()) {
return;
}
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean directoryLoading = true;
int count = adapter.getPartitionCount();
for (int i = 0; i < count; i++) {
Partition partition = adapter.getPartition(i);
if (partition instanceof DirectoryPartition) {
DirectoryPartition directory = (DirectoryPartition) partition;
if (directory.getDirectoryId() == mSelectedContactDirectoryId) {
directoryLoading = directory.isLoading();
break;
}
}
}
if (directoryLoading) {
return;
}
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
final int selectedPosition = adapter.getSelectedContactPosition();
if (selectedPosition != -1) {
mLastSelectedPosition = selectedPosition;
} else {
if (isSearchMode()) {
if (mDelaySelection) {
selectFirstFoundContactAfterDelay();
if (mListener != null) {
mListener.onSelectionChange();
}
return;
}
} else if (mSelectionRequired) {
// A specific contact was requested, but it's not in the loaded list.
// Try reconfiguring and reloading the list that will hopefully contain
// the requested contact. Only take one attempt to avoid an infinite loop
// in case the contact cannot be found at all.
mSelectionRequired = false;
// If we were looking at a different specific contact, just reload
if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
reloadData();
} else {
// Otherwise, call the listener, which will adjust the filter.
notifyInvalidSelection();
}
return;
} else if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
// If we were trying to load a specific contact, but that contact no longer
// exists, call the listener, which will adjust the filter.
notifyInvalidSelection();
return;
}
saveSelectedUri(null);
selectDefaultContact();
}
mSelectionRequired = false;
mSelectionVerified = true;
if (mSelectionPersistenceRequested) {
saveSelectedUri(mSelectedContactUri);
mSelectionPersistenceRequested = false;
}
if (mSelectionToScreenRequested) {
requestSelectionToScreen(selectedPosition);
}
getListView().invalidateViews();
if (mListener != null) {
mListener.onSelectionChange();
}
}
| private void checkSelection() {
if (mSelectionVerified) {
return;
}
if (mRefreshingContactUri) {
return;
}
if (isLoadingDirectoryList()) {
return;
}
ContactListAdapter adapter = getAdapter();
if (adapter == null) {
return;
}
boolean directoryLoading = true;
int count = adapter.getPartitionCount();
for (int i = 0; i < count; i++) {
Partition partition = adapter.getPartition(i);
if (partition instanceof DirectoryPartition) {
DirectoryPartition directory = (DirectoryPartition) partition;
if (directory.getDirectoryId() == mSelectedContactDirectoryId) {
directoryLoading = directory.isLoading();
break;
}
}
}
if (directoryLoading) {
return;
}
adapter.setSelectedContact(
mSelectedContactDirectoryId, mSelectedContactLookupKey, mSelectedContactId);
final int selectedPosition = adapter.getSelectedContactPosition();
if (selectedPosition != -1) {
mLastSelectedPosition = selectedPosition;
} else {
if (isSearchMode()) {
if (mDelaySelection) {
selectFirstFoundContactAfterDelay();
if (mListener != null) {
mListener.onSelectionChange();
}
return;
}
} else if (mSelectionRequired) {
// A specific contact was requested, but it's not in the loaded list.
// Try reconfiguring and reloading the list that will hopefully contain
// the requested contact. Only take one attempt to avoid an infinite loop
// in case the contact cannot be found at all.
mSelectionRequired = false;
// If we were looking at a different specific contact, just reload
// FILTER_TYPE_ALL_ACCOUNTS is needed for the case where a new contact is added
// on a tablet and the loader is returning a stale list. In this case, the contact
// will not be found until the next load. b/7621855 This will only fix the most
// common case where all accounts are shown. It will not fix the one account case.
// TODO: we may want to add more FILTER_TYPEs or relax this check to fix all other
// FILTER_TYPE cases.
if (mFilter != null
&& (mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT
|| mFilter.filterType == ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS)) {
reloadData();
} else {
// Otherwise, call the listener, which will adjust the filter.
notifyInvalidSelection();
}
return;
} else if (mFilter != null
&& mFilter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
// If we were trying to load a specific contact, but that contact no longer
// exists, call the listener, which will adjust the filter.
notifyInvalidSelection();
return;
}
saveSelectedUri(null);
selectDefaultContact();
}
mSelectionRequired = false;
mSelectionVerified = true;
if (mSelectionPersistenceRequested) {
saveSelectedUri(mSelectedContactUri);
mSelectionPersistenceRequested = false;
}
if (mSelectionToScreenRequested) {
requestSelectionToScreen(selectedPosition);
}
getListView().invalidateViews();
if (mListener != null) {
mListener.onSelectionChange();
}
}
|
diff --git a/src/com/robodex/app/MyMapActivity.java b/src/com/robodex/app/MyMapActivity.java
index bdcd293..f78c10b 100644
--- a/src/com/robodex/app/MyMapActivity.java
+++ b/src/com/robodex/app/MyMapActivity.java
@@ -1,63 +1,63 @@
package com.robodex.app;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.robodex.data.DummyData;
import com.robodex.data.DummyData.DummyLocation;
import com.robodex.R;
public class MyMapActivity extends MapActivity {
private static final int DEFAULT_ZOOM = 14;
private MapView mMap;
private List<Overlay> mOverlays;
private Drawable mMarker;
private MyItemizedOverlay mItemizedOverlay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMap = (MapView) findViewById(R.id.mapview);
mMap.setBuiltInZoomControls(true);
mMap.getController().setCenter(new GeoPoint(
(int) (DummyData.LOCATIONS[0].LATITUDE * 1E6),
(int) (DummyData.LOCATIONS[0].LONGITUDE * 1E6)));
mMap.getController().setZoom(DEFAULT_ZOOM);
mOverlays = mMap.getOverlays();
- mMarker = this.getResources().getDrawable(R.drawable.androidmarker);
+ mMarker = this.getResources().getDrawable(R.drawable.marker_self);
mItemizedOverlay = new MyItemizedOverlay(mMarker, this);
addLocations();
}
private void addLocations() {
int index = 0;
for (DummyLocation dl : DummyData.LOCATIONS) {
GeoPoint point = new GeoPoint((int) (dl.LATITUDE * 1E6), (int) (dl.LONGITUDE * 1E6));
OverlayItem overlayitem = new OverlayItem(point,"Location " + index, dl.toString());
mItemizedOverlay.addOverlay(overlayitem);
++index;
}
mOverlays.add(mItemizedOverlay);
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMap = (MapView) findViewById(R.id.mapview);
mMap.setBuiltInZoomControls(true);
mMap.getController().setCenter(new GeoPoint(
(int) (DummyData.LOCATIONS[0].LATITUDE * 1E6),
(int) (DummyData.LOCATIONS[0].LONGITUDE * 1E6)));
mMap.getController().setZoom(DEFAULT_ZOOM);
mOverlays = mMap.getOverlays();
mMarker = this.getResources().getDrawable(R.drawable.androidmarker);
mItemizedOverlay = new MyItemizedOverlay(mMarker, this);
addLocations();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMap = (MapView) findViewById(R.id.mapview);
mMap.setBuiltInZoomControls(true);
mMap.getController().setCenter(new GeoPoint(
(int) (DummyData.LOCATIONS[0].LATITUDE * 1E6),
(int) (DummyData.LOCATIONS[0].LONGITUDE * 1E6)));
mMap.getController().setZoom(DEFAULT_ZOOM);
mOverlays = mMap.getOverlays();
mMarker = this.getResources().getDrawable(R.drawable.marker_self);
mItemizedOverlay = new MyItemizedOverlay(mMarker, this);
addLocations();
}
|
diff --git a/server/src/main/java/com/ece/superkids/users/entities/History.java b/server/src/main/java/com/ece/superkids/users/entities/History.java
index abf8b6f..c3df49f 100644
--- a/server/src/main/java/com/ece/superkids/users/entities/History.java
+++ b/server/src/main/java/com/ece/superkids/users/entities/History.java
@@ -1,267 +1,267 @@
package com.ece.superkids.users.entities;
import com.ece.superkids.questions.entities.Question;
import com.ece.superkids.questions.enums.QuestionLevel;
import com.ece.superkids.questions.enums.QuestionCategory;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.io.Serializable;
/**
* The <code>History</code> class represents the current state of the user.
* It maintains the history for all the questions and the scores the user answered, up to 5 attempts.
*
* @author Marc Adam
*/
public class History implements Serializable {
static final long serialVersionUID = 1L;
private Map<String, ArrayList<State>> questionToList;
private boolean gameStarted;
private Map<QuestionLevel, ArrayList<QuestionCategory>> levelToCategories;
/* whenever new categories are added these lists need to be updated, else the history won't be able to know if the user is done with the level */
private QuestionCategory level1Categories[] = {QuestionCategory.SHAPES, QuestionCategory.COLORS, QuestionCategory.ANIMALS};
private QuestionCategory level2Categories[] = {QuestionCategory.FOOD, QuestionCategory.GEOGRAPHY, QuestionCategory.PLANETS};
private QuestionCategory level3Categories[] = {QuestionCategory.STATIONARY, QuestionCategory.INSTRUMENTS, QuestionCategory.BODYPARTS};
/* whenever new levels are added this needs to be updated, else the history won't be able to know if the user is done with the game */
private QuestionLevel gameLevels[] = {QuestionLevel.LEVEL_1, QuestionLevel.LEVEL_2, QuestionLevel.LEVEL_3};
private void init() {
levelToCategories = new HashMap<QuestionLevel, ArrayList<QuestionCategory>>();
levelToCategories.put(QuestionLevel.LEVEL_1, new ArrayList<QuestionCategory>(Arrays.asList(level1Categories)));
levelToCategories.put(QuestionLevel.LEVEL_2, new ArrayList<QuestionCategory>(Arrays.asList(level2Categories)));
levelToCategories.put(QuestionLevel.LEVEL_3, new ArrayList<QuestionCategory>(Arrays.asList(level3Categories)));
}
/**
* Create a new History object.
*/
public History() {
questionToList = new HashMap();
gameStarted = false;
init();
}
/**
* Set the Game Started flag to true.
* Call this when starting a new game. This is also automatically called.
*/
public void setGameStarted() {
gameStarted = true;
}
/**
* Get the value of the Game Started flag to true.
* @return Game started
*/
public boolean getGameStarted() {
return gameStarted;
}
/**
* Get the value of Game On, whether the user should continue game or start a new game.
* Use this function to see if you wanna show 'continue game' button or not
* @return Game is on
*/
public boolean getGameOn() {
return (gameStarted && !isGameFinished());
}
/**
* Check whether the use has finished the level
* @param level Level to check
* @return Level finished
*/
public boolean isLevelFinished(QuestionLevel level) {
if(level==null){
return true;
}
ArrayList<QuestionCategory> questionCategoryList = levelToCategories.get(level);
for(int i=0; i<questionCategoryList.size(); i++) {
String key = questionCategoryList.get(i) + ":" + level;
if(!questionToList.containsKey(key)) {
return false;
}
}
return true;
}
/**
* Checks if the whole game is finished, this goes through all the levels.
* @return Game is finished.
*/
public boolean isGameFinished() {
ArrayList<QuestionLevel> gameLevelsList = new ArrayList<QuestionLevel>(Arrays.asList(gameLevels));
for(int i=0; i<gameLevelsList.size(); i++) {
if(!isLevelFinished(gameLevelsList.get(i))) {
return false;
}
}
return true;
}
/**
* Save a state to the history, to the list of attempts.
* @param state State to save to the history.
*/
public void saveToHistory(State state) {
QuestionCategory category = state.getCurrentCategory();
QuestionLevel level = state.getCurrentLevel();
String key = category.toString() + ":" + level.toString();
if(questionToList.containsKey(key)) {
ArrayList<State> states = (ArrayList<State>)questionToList.get(key);
if(states.size()==5) {
states.remove(0);
}
states.add(state);
} else {
ArrayList<State> states = new ArrayList();
states.add(state);
questionToList.put(key, states);
}
}
/**
* Get the history for a category and level
* @param category Category for the questions.
* @param level Level for the questions.
* @return Map from questions to list of up to 5 scores.
*/
public Map<Question, ArrayList<Integer>> getHistoryMap(QuestionCategory category, QuestionLevel level) {
String key = category.toString() + ":" + level.toString();
Map<Question, ArrayList<Integer>> questionToScores = new HashMap();
if(questionToList.containsKey(key)) {
ArrayList<State> states = (ArrayList<State>)questionToList.get(key);
for(int i=0; i<states.size(); i++) {
Iterator it = states.get(i).getAllScores().entrySet().iterator();
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
Question questionKey = (Question)pairs.getKey();
if(questionToScores.containsKey(questionKey)) {
ArrayList<Integer> listOfScores = (ArrayList<Integer>)questionToScores.get(questionKey);
listOfScores.add((Integer)pairs.getValue());
questionToScores.put(questionKey, listOfScores);
} else {
ArrayList<Integer> listOfScores = new ArrayList();
listOfScores.add((Integer)pairs.getValue());
questionToScores.put(questionKey, listOfScores);
}
}
}
return questionToScores;
} else {
return null;
}
}
/**
* Get the best attempt for a category and a level.
* @param category Category of the attempt.
* @param level Level of the best attempt.
* @return State map from questions to scores of the best attempt.
*/
public State getMaximumScoreState(QuestionCategory category, QuestionLevel level) {
Map maxScoresMap = new HashMap<Question, Integer>();
String key = category.toString() + ":" + level.toString();
ArrayList<State> states = (ArrayList<State>)questionToList.get(key);
int maxScore = 0;
int maxScoreIndex = 0;
for(int i=0; i<states.size(); i++) {
if(states.get(i).getTotalScore()>maxScore) {
maxScoreIndex=i;
maxScore=states.get(i).getTotalScore();
}
}
State maxScoreState = states.get(maxScoreIndex);
return maxScoreState;
}
/**
* Get the scores out of the best attempts of each of the levels and categories played by the user.
* @return Total score
*/
public int getTotalScore() {
int totalScore = 0;
for (int i= 0; i < gameLevels.length; i++) {
QuestionLevel questionLevel = gameLevels[i];
ArrayList<QuestionCategory> questionCategories = (ArrayList<QuestionCategory>)levelToCategories.get(questionLevel);
for(int j=0; j<questionCategories.size(); j++) {
QuestionCategory questionCategory = questionCategories.get(j);
if(questionToList.containsKey(questionCategory+":"+questionLevel)) {
State state = this.getMaximumScoreState(questionCategory, questionLevel);
totalScore+=state.getTotalScore();
}
}
}
return totalScore;
}
/**
* Get the history for a category and a level.
* @param category Category of the question.
* @param level Category of the level.
* @return Two dimensional array with 6 columns, first column has the questions, the 5 other columns have the scores.
*/
public Object[][] getHistory(QuestionCategory category, QuestionLevel level) {
Map<Question, ArrayList<Integer>> map = this.getHistoryMap(category, level);
if(map.size()!=0) {
Iterator it = map.entrySet().iterator();
int counter = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
counter ++;
}
Object o[][] = new Object[counter][6];
it = map.entrySet().iterator();
int index = 0;
ArrayList<Integer> scoresList;
int scoresListSize = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
scoresList = (ArrayList<Integer>)pairs.getValue();
scoresListSize = scoresList.size();
o[index][0] = ((Question)pairs.getKey()).getQuestion();
for(int i=1; i<scoresList.size()+1; i++) {
o[index][i] = scoresList.get(i-1);
}
index++;
}
index++;
for(int i=0; i<counter; i++) {
for(int j=scoresListSize+1; j<6; j++) {
- o[index][i] = 0;
+ o[i][j] = 0;
}
}
return o;
} else {
return null;
}
}
/**
* Get the history for a category and a level.
* @return Two dimensional array with fake scores.
*/
public Object[][] getHistoryTest() {
Object o[][] = new Object[10][6];
for(int i=0; i<o.length; i++) {
o[i][0] = "Question" + i;
for(int j=1; j<6; j++) {
o[i][j] = i*i;
}
}
return o;
}
}
| true | true | public Object[][] getHistory(QuestionCategory category, QuestionLevel level) {
Map<Question, ArrayList<Integer>> map = this.getHistoryMap(category, level);
if(map.size()!=0) {
Iterator it = map.entrySet().iterator();
int counter = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
counter ++;
}
Object o[][] = new Object[counter][6];
it = map.entrySet().iterator();
int index = 0;
ArrayList<Integer> scoresList;
int scoresListSize = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
scoresList = (ArrayList<Integer>)pairs.getValue();
scoresListSize = scoresList.size();
o[index][0] = ((Question)pairs.getKey()).getQuestion();
for(int i=1; i<scoresList.size()+1; i++) {
o[index][i] = scoresList.get(i-1);
}
index++;
}
index++;
for(int i=0; i<counter; i++) {
for(int j=scoresListSize+1; j<6; j++) {
o[index][i] = 0;
}
}
return o;
} else {
return null;
}
}
| public Object[][] getHistory(QuestionCategory category, QuestionLevel level) {
Map<Question, ArrayList<Integer>> map = this.getHistoryMap(category, level);
if(map.size()!=0) {
Iterator it = map.entrySet().iterator();
int counter = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
counter ++;
}
Object o[][] = new Object[counter][6];
it = map.entrySet().iterator();
int index = 0;
ArrayList<Integer> scoresList;
int scoresListSize = 0;
while(it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
scoresList = (ArrayList<Integer>)pairs.getValue();
scoresListSize = scoresList.size();
o[index][0] = ((Question)pairs.getKey()).getQuestion();
for(int i=1; i<scoresList.size()+1; i++) {
o[index][i] = scoresList.get(i-1);
}
index++;
}
index++;
for(int i=0; i<counter; i++) {
for(int j=scoresListSize+1; j<6; j++) {
o[i][j] = 0;
}
}
return o;
} else {
return null;
}
}
|
diff --git a/org.springsource.loaded/src/main/java/org/springsource/loaded/ri/MethodProvider.java b/org.springsource.loaded/src/main/java/org/springsource/loaded/ri/MethodProvider.java
index 101e83a..5bd09e6 100644
--- a/org.springsource.loaded/src/main/java/org/springsource/loaded/ri/MethodProvider.java
+++ b/org.springsource.loaded/src/main/java/org/springsource/loaded/ri/MethodProvider.java
@@ -1,147 +1,149 @@
/*
* Copyright 2010-2012 VMware and contributors
*
* 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.springsource.loaded.ri;
import java.util.Collection;
import java.util.List;
import org.objectweb.asm.Type;
import org.springsource.loaded.ReloadableType;
import org.springsource.loaded.TypeDescriptor;
import org.springsource.loaded.TypeRegistry;
import org.springsource.loaded.Utils;
/**
* To manage the complexity of the different cases created by a variety of different types of contexts where we can do 'method
* lookup' we need an abstraction to represent them all.
* <p>
* This class provides that abstraction.
*
* @author Kris De Volder
* @since 0.5.0
*/
public abstract class MethodProvider {
public static MethodProvider create(ReloadableType rtype) {
return new ReloadableTypeMethodProvider(rtype);
}
public static MethodProvider create(TypeRegistry registry, TypeDescriptor typeDescriptor) {
if (typeDescriptor.isReloadable()) {
ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), false);
if (rtype == null) {
TypeRegistry tr = registry;
while (rtype == null) {
ClassLoader pcl = tr.getClassLoader().getParent();
- if (pcl != null) {
+ if (pcl == null) {
+ break;
+ } else {
tr = TypeRegistry.getTypeRegistryFor(pcl);
if (tr == null) {
break;
}
rtype = tr.getReloadableType(typeDescriptor.getName(), false);
}
}
}
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
// ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), true);
// // TODO rtype can be null if this type hasn't been loaded yet for the first time, is that true?
// // e.g. CGLIB generated proxy for a service type in grails
// if (rtype != null) {
// return new ReloadableTypeMethodProvider(rtype);
// }
}
try {
try {
Type objectType = Type.getObjectType(typeDescriptor.getName());
// TODO doing things this way would mean we aren't 'guessing' the delegation strategy, we
// are instead allowing it to do its thing then looking for the right registry.
// Above we are guessing regular parent delegation.
Class<?> class1 = Utils.toClass(objectType, registry.getClassLoader());
if (typeDescriptor.isReloadable()) {
ClassLoader cl = class1.getClassLoader();
TypeRegistry tr = TypeRegistry.getTypeRegistryFor(cl);
ReloadableType rtype = tr.getReloadableType(typeDescriptor.getName(), true);
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
}
return create(class1);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("We have a type descriptor for '" + typeDescriptor.getName()
+ " but no corresponding Java class", e);
}
} catch (RuntimeException re) {
re.printStackTrace();
throw re;
}
}
public static MethodProvider create(Class<?> clazz) {
return new JavaClassMethodProvider(clazz);
}
public abstract List<Invoker> getDeclaredMethods();
public abstract MethodProvider getSuper();
public abstract MethodProvider[] getInterfaces();
public abstract boolean isInterface();
public abstract String getSlashedName();
/**
* @return Full qualified name with "."
*/
public String getDottedName() {
return getSlashedName().replace('/', '.');
}
public Invoker dynamicLookup(int mods, String name, String methodDescriptor) {
return new DynamicLookup(name, methodDescriptor).lookup(this);
}
public Invoker staticLookup(int mods, String name, String methodDescriptor) {
return new StaticLookup(name, methodDescriptor).lookup(this);
}
public Invoker getMethod(String name, Class<?>[] params) {
return new GetMethodLookup(name, params).lookup(this);
}
public Invoker getDeclaredMethod(String name, String paramsDescriptor) {
return new GetDeclaredMethodLookup(name, paramsDescriptor).lookup(this);
}
public Invoker getDeclaredMethod(String name, Class<?>[] params) {
return getDeclaredMethod(name, Utils.toParamDescriptor(params));
}
public Collection<Invoker> getMethods() {
return new GetMethodsLookup().lookup(this);
}
@Override
public String toString() {
return "MethodProvider(" + getDottedName() + ")";
}
}
| true | true | public static MethodProvider create(TypeRegistry registry, TypeDescriptor typeDescriptor) {
if (typeDescriptor.isReloadable()) {
ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), false);
if (rtype == null) {
TypeRegistry tr = registry;
while (rtype == null) {
ClassLoader pcl = tr.getClassLoader().getParent();
if (pcl != null) {
tr = TypeRegistry.getTypeRegistryFor(pcl);
if (tr == null) {
break;
}
rtype = tr.getReloadableType(typeDescriptor.getName(), false);
}
}
}
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
// ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), true);
// // TODO rtype can be null if this type hasn't been loaded yet for the first time, is that true?
// // e.g. CGLIB generated proxy for a service type in grails
// if (rtype != null) {
// return new ReloadableTypeMethodProvider(rtype);
// }
}
try {
try {
Type objectType = Type.getObjectType(typeDescriptor.getName());
// TODO doing things this way would mean we aren't 'guessing' the delegation strategy, we
// are instead allowing it to do its thing then looking for the right registry.
// Above we are guessing regular parent delegation.
Class<?> class1 = Utils.toClass(objectType, registry.getClassLoader());
if (typeDescriptor.isReloadable()) {
ClassLoader cl = class1.getClassLoader();
TypeRegistry tr = TypeRegistry.getTypeRegistryFor(cl);
ReloadableType rtype = tr.getReloadableType(typeDescriptor.getName(), true);
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
}
return create(class1);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("We have a type descriptor for '" + typeDescriptor.getName()
+ " but no corresponding Java class", e);
}
} catch (RuntimeException re) {
re.printStackTrace();
throw re;
}
}
| public static MethodProvider create(TypeRegistry registry, TypeDescriptor typeDescriptor) {
if (typeDescriptor.isReloadable()) {
ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), false);
if (rtype == null) {
TypeRegistry tr = registry;
while (rtype == null) {
ClassLoader pcl = tr.getClassLoader().getParent();
if (pcl == null) {
break;
} else {
tr = TypeRegistry.getTypeRegistryFor(pcl);
if (tr == null) {
break;
}
rtype = tr.getReloadableType(typeDescriptor.getName(), false);
}
}
}
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
// ReloadableType rtype = registry.getReloadableType(typeDescriptor.getName(), true);
// // TODO rtype can be null if this type hasn't been loaded yet for the first time, is that true?
// // e.g. CGLIB generated proxy for a service type in grails
// if (rtype != null) {
// return new ReloadableTypeMethodProvider(rtype);
// }
}
try {
try {
Type objectType = Type.getObjectType(typeDescriptor.getName());
// TODO doing things this way would mean we aren't 'guessing' the delegation strategy, we
// are instead allowing it to do its thing then looking for the right registry.
// Above we are guessing regular parent delegation.
Class<?> class1 = Utils.toClass(objectType, registry.getClassLoader());
if (typeDescriptor.isReloadable()) {
ClassLoader cl = class1.getClassLoader();
TypeRegistry tr = TypeRegistry.getTypeRegistryFor(cl);
ReloadableType rtype = tr.getReloadableType(typeDescriptor.getName(), true);
if (rtype != null) {
return new ReloadableTypeMethodProvider(rtype);
}
}
return create(class1);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("We have a type descriptor for '" + typeDescriptor.getName()
+ " but no corresponding Java class", e);
}
} catch (RuntimeException re) {
re.printStackTrace();
throw re;
}
}
|
diff --git a/jython/src/org/python/modules/_collections/PyDefaultDict.java b/jython/src/org/python/modules/_collections/PyDefaultDict.java
index a8013d72..7bf3b93f 100644
--- a/jython/src/org/python/modules/_collections/PyDefaultDict.java
+++ b/jython/src/org/python/modules/_collections/PyDefaultDict.java
@@ -1,142 +1,142 @@
/* Copyright (c) Jython Developers */
package org.python.modules._collections;
import java.util.Map;
import org.python.core.Py;
import org.python.core.PyDictionary;
import org.python.core.PyObject;
import org.python.core.PyTuple;
import org.python.core.PyType;
import org.python.expose.ExposedDelete;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedSet;
import org.python.expose.ExposedType;
/**
* PyDefaultDict - This is a subclass of the builtin dict(PyDictionary) class. It supports
* one additional method __missing__ and adds one writable instance variable
* defaultFactory. The remaining functionality is the same as for the dict class.
*
* collections.defaultdict([defaultFactory[, ...]]) - returns a new dictionary-like
* object. The first argument provides the initial value for the defaultFactory attribute;
* it defaults to None. All remaining arguments are treated the same as if they were
* passed to the dict constructor, including keyword arguments.
*/
@ExposedType(name = "collections.defaultdict")
public class PyDefaultDict extends PyDictionary {
public static final PyType TYPE = PyType.fromClass(PyDefaultDict.class);
/**
* This attribute is used by the __missing__ method; it is initialized from the first
* argument to the constructor, if present, or to None, if absent.
*/
private PyObject defaultFactory = Py.None;
public PyDefaultDict() {
this(TYPE);
}
public PyDefaultDict(PyType subtype) {
super(subtype);
}
public PyDefaultDict(PyType subtype, Map<PyObject, PyObject> map) {
super(subtype, map);
}
@ExposedMethod
@ExposedNew
final void defaultdict___init__(PyObject[] args, String[] kwds) {
int nargs = args.length - kwds.length;
if (nargs != 0) {
defaultFactory = args[0];
- if (defaultFactory.__findattr__("__call__") == null) {
+ if (!defaultFactory.isCallable()) {
throw Py.TypeError("first argument must be callable");
}
PyObject newargs[] = new PyObject[args.length - 1];
System.arraycopy(args, 1, newargs, 0, newargs.length);
dict___init__(newargs , kwds);
}
}
@Override
public PyObject __finditem__(PyObject key) {
return dict___getitem__(key);
}
/**
* This method is called by the __getitem__ method of the dict class when the
* requested key is not found; whatever it returns or raises is then returned or
* raised by __getitem__.
*/
@ExposedMethod
final PyObject defaultdict___missing__(PyObject key) {
if (defaultFactory == Py.None) {
throw Py.KeyError(key);
}
PyObject value = defaultFactory.__call__();
if (value == null) {
return value;
}
__setitem__(key, value);
return value;
}
@Override
public PyObject __reduce__() {
return defaultdict___reduce__();
}
@ExposedMethod
final PyObject defaultdict___reduce__() {
PyTuple args = null;
if (defaultFactory == Py.None) {
args = new PyTuple();
} else {
PyObject[] ob = {defaultFactory};
args = new PyTuple(ob);
}
return new PyTuple(getType(), args, Py.None, Py.None, items());
}
@Override
public PyDictionary copy() {
return defaultdict_copy();
}
@ExposedMethod(names = {"copy", "__copy__"})
final PyDefaultDict defaultdict_copy() {
PyDefaultDict ob = new PyDefaultDict(TYPE, table);
ob.defaultFactory = defaultFactory;
return ob;
}
@Override
public String toString() {
return defaultdict_toString();
}
@ExposedMethod(names = "__repr__")
final String defaultdict_toString() {
return String.format("defaultdict(%s, %s)", defaultFactory, super.toString());
}
@ExposedGet(name = "default_factory")
public PyObject getDefaultFactory() {
return defaultFactory;
}
@ExposedSet(name = "default_factory")
public void setDefaultFactory(PyObject value) {
defaultFactory = value;
}
@ExposedDelete(name = "default_factory")
public void delDefaultFactory() {
defaultFactory = Py.None;
}
}
| true | true | final void defaultdict___init__(PyObject[] args, String[] kwds) {
int nargs = args.length - kwds.length;
if (nargs != 0) {
defaultFactory = args[0];
if (defaultFactory.__findattr__("__call__") == null) {
throw Py.TypeError("first argument must be callable");
}
PyObject newargs[] = new PyObject[args.length - 1];
System.arraycopy(args, 1, newargs, 0, newargs.length);
dict___init__(newargs , kwds);
}
}
| final void defaultdict___init__(PyObject[] args, String[] kwds) {
int nargs = args.length - kwds.length;
if (nargs != 0) {
defaultFactory = args[0];
if (!defaultFactory.isCallable()) {
throw Py.TypeError("first argument must be callable");
}
PyObject newargs[] = new PyObject[args.length - 1];
System.arraycopy(args, 1, newargs, 0, newargs.length);
dict___init__(newargs , kwds);
}
}
|
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/function/LengthFunction.java b/src/uk/me/parabola/mkgmap/osmstyle/function/LengthFunction.java
index 5e8a3375..28d78ca3 100644
--- a/src/uk/me/parabola/mkgmap/osmstyle/function/LengthFunction.java
+++ b/src/uk/me/parabola/mkgmap/osmstyle/function/LengthFunction.java
@@ -1,90 +1,90 @@
/*
* Copyright (C) 2012.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
package uk.me.parabola.mkgmap.osmstyle.function;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.util.Map.Entry;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.reader.osm.Element;
import uk.me.parabola.mkgmap.reader.osm.Relation;
import uk.me.parabola.mkgmap.reader.osm.Way;
import uk.me.parabola.mkgmap.scan.SyntaxException;
/**
* Calculates the length of a way or a relation in meter. The length of a
* relation is defined as the sum of its member lengths.
*
* @author WanMil
*/
public class LengthFunction extends AbstractFunction {
private static final Logger log = Logger
.getLogger(LengthFunction.class);
private final DecimalFormat nf = new DecimalFormat("0.0#####################", DecimalFormatSymbols.getInstance(Locale.US));
protected String calcImpl(Element el) {
double length = calcLength(el);
return nf.format(length);
}
private double calcLength(Element el) {
if (el instanceof Way) {
Way w = (Way)el;
double length = 0;
Coord prevC = null;
for (Coord c : w.getPoints()) {
if (prevC != null) {
length += prevC.distance(c);
}
prevC = c;
}
return length;
} else if (el instanceof Relation) {
Relation rel = (Relation)el;
double length = 0;
for (Entry<String,Element> relElem : rel.getElements()) {
if (relElem.getValue() instanceof Way || relElem.getValue() instanceof Relation) {
if (rel == relElem.getValue()) {
// avoid recursive call
log.error("Relation "+rel.getId()+" contains itself as element. This is not supported.");
} else {
length += calcLength(relElem.getValue());
}
}
}
return length;
} else {
- throw new SyntaxException("mkgmap::length cannot calculate elements of type "+el.getClass().getName());
+ throw new SyntaxException("length() cannot calculate elements of type "+el.getClass().getName());
}
}
public String getName() {
return "length";
}
public boolean supportsWay() {
return true;
}
public boolean supportsRelation() {
return true;
}
}
| true | true | private double calcLength(Element el) {
if (el instanceof Way) {
Way w = (Way)el;
double length = 0;
Coord prevC = null;
for (Coord c : w.getPoints()) {
if (prevC != null) {
length += prevC.distance(c);
}
prevC = c;
}
return length;
} else if (el instanceof Relation) {
Relation rel = (Relation)el;
double length = 0;
for (Entry<String,Element> relElem : rel.getElements()) {
if (relElem.getValue() instanceof Way || relElem.getValue() instanceof Relation) {
if (rel == relElem.getValue()) {
// avoid recursive call
log.error("Relation "+rel.getId()+" contains itself as element. This is not supported.");
} else {
length += calcLength(relElem.getValue());
}
}
}
return length;
} else {
throw new SyntaxException("mkgmap::length cannot calculate elements of type "+el.getClass().getName());
}
}
| private double calcLength(Element el) {
if (el instanceof Way) {
Way w = (Way)el;
double length = 0;
Coord prevC = null;
for (Coord c : w.getPoints()) {
if (prevC != null) {
length += prevC.distance(c);
}
prevC = c;
}
return length;
} else if (el instanceof Relation) {
Relation rel = (Relation)el;
double length = 0;
for (Entry<String,Element> relElem : rel.getElements()) {
if (relElem.getValue() instanceof Way || relElem.getValue() instanceof Relation) {
if (rel == relElem.getValue()) {
// avoid recursive call
log.error("Relation "+rel.getId()+" contains itself as element. This is not supported.");
} else {
length += calcLength(relElem.getValue());
}
}
}
return length;
} else {
throw new SyntaxException("length() cannot calculate elements of type "+el.getClass().getName());
}
}
|
diff --git a/care-reporting-bundle/src/main/java/org/motechproject/care/reporting/processors/FormProcessor.java b/care-reporting-bundle/src/main/java/org/motechproject/care/reporting/processors/FormProcessor.java
index eacceea..96d2120 100644
--- a/care-reporting-bundle/src/main/java/org/motechproject/care/reporting/processors/FormProcessor.java
+++ b/care-reporting-bundle/src/main/java/org/motechproject/care/reporting/processors/FormProcessor.java
@@ -1,34 +1,34 @@
package org.motechproject.care.reporting.processors;
import org.motechproject.commcare.domain.CommcareForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class FormProcessor {
private static final Logger logger = LoggerFactory.getLogger("commcare-reporting-mapper");
private MotherFormProcessor motherFormProcessor;
private ChildFormProcessor childFormProcessor;
private static final String FORM_NAME_ATTRIBUTE = "name";
private static final String FORM_XMLNS_ATTRIBUTE = "xmlns";
@Autowired
public FormProcessor(MotherFormProcessor motherFormProcessor, ChildFormProcessor childFormProcessor) {
this.motherFormProcessor = motherFormProcessor;
this.childFormProcessor = childFormProcessor;
}
public void process(CommcareForm commcareForm) {
String formName = commcareForm.getForm().getAttributes().get(FORM_NAME_ATTRIBUTE);
String xmlns = commcareForm.getForm().getAttributes().get(FORM_XMLNS_ATTRIBUTE);
- logger.info(String.format("Received form. id: %s, type: %s; xmlns: %s; version: %s", commcareForm.getId(), formName, xmlns));
+ logger.info(String.format("Received form. id: %s, type: %s; xmlns: %s;", commcareForm.getId(), formName, xmlns));
motherFormProcessor.parseMotherForm(commcareForm);
childFormProcessor.parseChildForms(commcareForm);
}
}
| true | true | public void process(CommcareForm commcareForm) {
String formName = commcareForm.getForm().getAttributes().get(FORM_NAME_ATTRIBUTE);
String xmlns = commcareForm.getForm().getAttributes().get(FORM_XMLNS_ATTRIBUTE);
logger.info(String.format("Received form. id: %s, type: %s; xmlns: %s; version: %s", commcareForm.getId(), formName, xmlns));
motherFormProcessor.parseMotherForm(commcareForm);
childFormProcessor.parseChildForms(commcareForm);
}
| public void process(CommcareForm commcareForm) {
String formName = commcareForm.getForm().getAttributes().get(FORM_NAME_ATTRIBUTE);
String xmlns = commcareForm.getForm().getAttributes().get(FORM_XMLNS_ATTRIBUTE);
logger.info(String.format("Received form. id: %s, type: %s; xmlns: %s;", commcareForm.getId(), formName, xmlns));
motherFormProcessor.parseMotherForm(commcareForm);
childFormProcessor.parseChildForms(commcareForm);
}
|
diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java
index 65d13c5..ca29f96 100644
--- a/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java
+++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/RunnerVersionTest.java
@@ -1,34 +1,34 @@
/*
* Sonar Runner - API
* Copyright (C) 2011 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.runner.api;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class RunnerVersionTest {
@Test
public void should_load_version() {
String version = RunnerVersion.version();
- assertThat(version).isNotEmpty().contains(".").endsWith("-SNAPSHOT").doesNotContain("$");
+ assertThat(version).isNotEmpty().contains(".").doesNotContain("$");
}
}
| true | true | public void should_load_version() {
String version = RunnerVersion.version();
assertThat(version).isNotEmpty().contains(".").endsWith("-SNAPSHOT").doesNotContain("$");
}
| public void should_load_version() {
String version = RunnerVersion.version();
assertThat(version).isNotEmpty().contains(".").doesNotContain("$");
}
|
diff --git a/app/controllers/AssertionController.java b/app/controllers/AssertionController.java
index b3dba58..0d030b2 100644
--- a/app/controllers/AssertionController.java
+++ b/app/controllers/AssertionController.java
@@ -1,100 +1,102 @@
package controllers;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import models.BadgeAssertion;
import models.BadgeClass;
import models.IdentityHash;
import models.IdentityObject;
import models.IdentityType;
import models.VerificationObject;
import models.VerificationType;
import play.mvc.*;
import views.html.*;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
//@Security.Authenticated(Secured.class)
public class AssertionController extends Controller {
public static Result assertions() {
// list assertions
List<BadgeAssertion> assertionsList = BadgeAssertion.find.all();
return ok(assertions.render(assertionsList));
}
public static BadgeAssertion createBadgeAssertionAPI(String identity,
String badgeId, String evidence) {
// check badge existance
Long badgeIdLong = Long.parseLong(badgeId);
BadgeClass bc = BadgeClass.find.byId(badgeIdLong);
if (bc == null) {
// DEAD END
}
// check valid URLs
URL badgeURL = null;
try {
badgeURL = new URL(routes.BadgeController.getJson(badgeIdLong)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL exidenceURL = null;
try {
exidenceURL = new URL(evidence);
} catch (MalformedURLException e) {
e.printStackTrace();
}
IdentityHash ih = new IdentityHash(identity);
boolean hashed = true;
IdentityObject io = new IdentityObject(ih, IdentityType.email, hashed,
ih.getSalt());
io.save();
VerificationType vt = VerificationType.hosted;
URL fakeURL = null;
try {
- fakeURL = new URL("http://pacific-brushlands-7687.herokuapp.com/assertion/1.json");
+ fakeURL = new URL("http://www.example.org");
} catch (MalformedURLException e) {
e.printStackTrace();
}
VerificationObject vo = new VerificationObject(vt, fakeURL); // TRICY!!
vo.save();
BadgeAssertion ba = new BadgeAssertion(io.id, badgeURL, vo.id,
exidenceURL);
ba.save();
// get REAL vo url
URL thisURL = null;
try {
thisURL = new URL(routes.AssertionController.getAssertion(ba.uid)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
vo.url = thisURL; // replace after creation
+ vo.save();
+ ba.save();
return ba;
// return ok(Json.toJson(ba));
}
@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result getAssertion(Long id) {
BadgeAssertion ba = BadgeAssertion.find.byId(id);
return ok(Json.toJson(ba));
}
}
| false | true | public static BadgeAssertion createBadgeAssertionAPI(String identity,
String badgeId, String evidence) {
// check badge existance
Long badgeIdLong = Long.parseLong(badgeId);
BadgeClass bc = BadgeClass.find.byId(badgeIdLong);
if (bc == null) {
// DEAD END
}
// check valid URLs
URL badgeURL = null;
try {
badgeURL = new URL(routes.BadgeController.getJson(badgeIdLong)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL exidenceURL = null;
try {
exidenceURL = new URL(evidence);
} catch (MalformedURLException e) {
e.printStackTrace();
}
IdentityHash ih = new IdentityHash(identity);
boolean hashed = true;
IdentityObject io = new IdentityObject(ih, IdentityType.email, hashed,
ih.getSalt());
io.save();
VerificationType vt = VerificationType.hosted;
URL fakeURL = null;
try {
fakeURL = new URL("http://pacific-brushlands-7687.herokuapp.com/assertion/1.json");
} catch (MalformedURLException e) {
e.printStackTrace();
}
VerificationObject vo = new VerificationObject(vt, fakeURL); // TRICY!!
vo.save();
BadgeAssertion ba = new BadgeAssertion(io.id, badgeURL, vo.id,
exidenceURL);
ba.save();
// get REAL vo url
URL thisURL = null;
try {
thisURL = new URL(routes.AssertionController.getAssertion(ba.uid)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
vo.url = thisURL; // replace after creation
return ba;
// return ok(Json.toJson(ba));
}
| public static BadgeAssertion createBadgeAssertionAPI(String identity,
String badgeId, String evidence) {
// check badge existance
Long badgeIdLong = Long.parseLong(badgeId);
BadgeClass bc = BadgeClass.find.byId(badgeIdLong);
if (bc == null) {
// DEAD END
}
// check valid URLs
URL badgeURL = null;
try {
badgeURL = new URL(routes.BadgeController.getJson(badgeIdLong)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL exidenceURL = null;
try {
exidenceURL = new URL(evidence);
} catch (MalformedURLException e) {
e.printStackTrace();
}
IdentityHash ih = new IdentityHash(identity);
boolean hashed = true;
IdentityObject io = new IdentityObject(ih, IdentityType.email, hashed,
ih.getSalt());
io.save();
VerificationType vt = VerificationType.hosted;
URL fakeURL = null;
try {
fakeURL = new URL("http://www.example.org");
} catch (MalformedURLException e) {
e.printStackTrace();
}
VerificationObject vo = new VerificationObject(vt, fakeURL); // TRICY!!
vo.save();
BadgeAssertion ba = new BadgeAssertion(io.id, badgeURL, vo.id,
exidenceURL);
ba.save();
// get REAL vo url
URL thisURL = null;
try {
thisURL = new URL(routes.AssertionController.getAssertion(ba.uid)
.absoluteURL(request()));
} catch (MalformedURLException e) {
e.printStackTrace();
}
vo.url = thisURL; // replace after creation
vo.save();
ba.save();
return ba;
// return ok(Json.toJson(ba));
}
|
diff --git a/src/com/btmura/android/reddit/data/RelativeTime.java b/src/com/btmura/android/reddit/data/RelativeTime.java
index 551a4291..928936c6 100644
--- a/src/com/btmura/android/reddit/data/RelativeTime.java
+++ b/src/com/btmura/android/reddit/data/RelativeTime.java
@@ -1,50 +1,50 @@
/*
* Copyright (C) 2012 Brian Muramatsu
*
* 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.btmura.android.reddit.data;
import android.content.Context;
import com.btmura.android.reddit.R;
public class RelativeTime {
private static final int MINUTE_SECONDS = 60;
private static final int HOUR_SECONDS = MINUTE_SECONDS * 60;
private static final int DAY_SECONDS = HOUR_SECONDS * 24;
private static final int MONTH_SECONDS = DAY_SECONDS * 30;
private static final int YEAR_SECONDS = MONTH_SECONDS * 12;
- public static String format(Context context, long now, long time) {
- long diff = now - time;
+ public static String format(Context context, long nowMs, long timeSec) {
+ long diff = nowMs / 1000 - timeSec;
int resId;
double value;
if ((value = diff / YEAR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_year : R.string.time_x_years;
} else if ((value = diff / MONTH_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_month : R.string.time_x_months;
} else if ((value = diff / DAY_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_day : R.string.time_x_days;
} else if ((value = diff / HOUR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_hour : R.string.time_x_hours;
} else if ((value = diff / MINUTE_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_minute : R.string.time_x_minutes;
} else {
resId = (value = diff) == 1 ? R.string.time_one_second : R.string.time_x_seconds;
}
return context.getString(resId, Math.round(value));
}
}
| true | true | public static String format(Context context, long now, long time) {
long diff = now - time;
int resId;
double value;
if ((value = diff / YEAR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_year : R.string.time_x_years;
} else if ((value = diff / MONTH_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_month : R.string.time_x_months;
} else if ((value = diff / DAY_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_day : R.string.time_x_days;
} else if ((value = diff / HOUR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_hour : R.string.time_x_hours;
} else if ((value = diff / MINUTE_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_minute : R.string.time_x_minutes;
} else {
resId = (value = diff) == 1 ? R.string.time_one_second : R.string.time_x_seconds;
}
return context.getString(resId, Math.round(value));
}
| public static String format(Context context, long nowMs, long timeSec) {
long diff = nowMs / 1000 - timeSec;
int resId;
double value;
if ((value = diff / YEAR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_year : R.string.time_x_years;
} else if ((value = diff / MONTH_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_month : R.string.time_x_months;
} else if ((value = diff / DAY_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_day : R.string.time_x_days;
} else if ((value = diff / HOUR_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_hour : R.string.time_x_hours;
} else if ((value = diff / MINUTE_SECONDS) > 0) {
resId = value == 1 ? R.string.time_one_minute : R.string.time_x_minutes;
} else {
resId = (value = diff) == 1 ? R.string.time_one_second : R.string.time_x_seconds;
}
return context.getString(resId, Math.round(value));
}
|
diff --git a/src/ru/spbau/bioinf/tagfinder/VirtualSpectrumWrongTags.java b/src/ru/spbau/bioinf/tagfinder/VirtualSpectrumWrongTags.java
index 13ec2f4..16fe76e 100644
--- a/src/ru/spbau/bioinf/tagfinder/VirtualSpectrumWrongTags.java
+++ b/src/ru/spbau/bioinf/tagfinder/VirtualSpectrumWrongTags.java
@@ -1,89 +1,89 @@
package ru.spbau.bioinf.tagfinder;
import java.util.*;
public class VirtualSpectrumWrongTags {
private Configuration conf;
public VirtualSpectrumWrongTags(Configuration conf) {
this.conf = conf;
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
List<Protein> proteins = conf.getProteins();
Map<Integer, Integer> msAlignResults = conf.getMSAlignResults();
Map<Integer, Scan> scans = conf.getScans();
List<Integer> keys = new ArrayList<Integer>();
keys.addAll(scans.keySet());
Collections.sort(keys);
VirtualSpectrumWrongTags vswt = new VirtualSpectrumWrongTags(conf);
- Map<Integer, List<Peak>> msAlignPeaks = conf.getMSAlignPeaks();
+ Map<Integer, List<Peak>> msAlignPeaks = conf.getMSAlignPeaks(scans);
for (int key : keys) {
Scan scan = scans.get(key);
int scanId = scan.getId();
if (msAlignResults.containsKey(scanId)) {
Integer proteinId = msAlignResults.get(scanId);
String sequence = proteins.get(proteinId).getSimplifiedAcids();
List<Peak> peaks = msAlignPeaks.get(scanId);
GraphUtil.generateEdges(conf, peaks);
vswt.checkTags(peaks, sequence, scanId, proteinId);
}
}
}
private Set<String> used = new HashSet<String>();
public void checkTags(List<Peak> peaks, String sequence, int scanId, int proteinId) {
used.clear();
for (Peak peak : peaks) {
checkTags(peak, "", sequence, scanId, proteinId);
}
}
public void checkTags(Peak peak, String prefix, String sequences, int scanId, int proteinId) {
if (used.contains(prefix)) {
return;
}
if (!check(prefix.toCharArray(), 0, "", sequences)) {
System.out.println(scanId + " " + proteinId + " " + prefix + " " + peak.getValue());
}
used.add(prefix);
for (Peak next : peak.getNext()) {
for (Acid acid : Acid.values()) {
if (acid.match(conf.getEdgeLimits(peak, next))) {
checkTags(next, prefix + acid.name(), sequences, scanId, proteinId);
}
}
}
}
private char[] keys = new char[] {'K', 'K', 'Q', 'Q', 'W','W', 'W','W', 'R', 'R', 'N'};
private String[] subst = new String[] {"AG", "GA", "AG", "GA", "AD", "DA", "EG", "GE", "SV", "VS", "GV", "VG", "GG"};
private boolean check(char[] tag, int start, String prefix, String sequences) {
if (start == tag.length) {
return sequences.contains(prefix);
}
if (sequences.contains(prefix + new String(tag, start, tag.length - start)))
return true;
char old = tag[start];
for (int i = 0; i < keys.length; i++) {
char key = keys[i];
if (key == old) {
if (check(tag, start + 1, prefix + subst[i], sequences)) {
return true;
}
}
}
return false;
}
}
| true | true | public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
List<Protein> proteins = conf.getProteins();
Map<Integer, Integer> msAlignResults = conf.getMSAlignResults();
Map<Integer, Scan> scans = conf.getScans();
List<Integer> keys = new ArrayList<Integer>();
keys.addAll(scans.keySet());
Collections.sort(keys);
VirtualSpectrumWrongTags vswt = new VirtualSpectrumWrongTags(conf);
Map<Integer, List<Peak>> msAlignPeaks = conf.getMSAlignPeaks();
for (int key : keys) {
Scan scan = scans.get(key);
int scanId = scan.getId();
if (msAlignResults.containsKey(scanId)) {
Integer proteinId = msAlignResults.get(scanId);
String sequence = proteins.get(proteinId).getSimplifiedAcids();
List<Peak> peaks = msAlignPeaks.get(scanId);
GraphUtil.generateEdges(conf, peaks);
vswt.checkTags(peaks, sequence, scanId, proteinId);
}
}
}
| public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(args);
List<Protein> proteins = conf.getProteins();
Map<Integer, Integer> msAlignResults = conf.getMSAlignResults();
Map<Integer, Scan> scans = conf.getScans();
List<Integer> keys = new ArrayList<Integer>();
keys.addAll(scans.keySet());
Collections.sort(keys);
VirtualSpectrumWrongTags vswt = new VirtualSpectrumWrongTags(conf);
Map<Integer, List<Peak>> msAlignPeaks = conf.getMSAlignPeaks(scans);
for (int key : keys) {
Scan scan = scans.get(key);
int scanId = scan.getId();
if (msAlignResults.containsKey(scanId)) {
Integer proteinId = msAlignResults.get(scanId);
String sequence = proteins.get(proteinId).getSimplifiedAcids();
List<Peak> peaks = msAlignPeaks.get(scanId);
GraphUtil.generateEdges(conf, peaks);
vswt.checkTags(peaks, sequence, scanId, proteinId);
}
}
}
|
diff --git a/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/client/screen/views/ViewHandlers.java b/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/client/screen/views/ViewHandlers.java
index 4a64579a7..dc78c066e 100644
--- a/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/client/screen/views/ViewHandlers.java
+++ b/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/client/screen/views/ViewHandlers.java
@@ -1,499 +1,505 @@
/*
* Copyright 2011 cruxframework.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.cruxframework.crux.core.client.screen.views;
import org.cruxframework.crux.core.client.collection.FastList;
import org.cruxframework.crux.core.client.executor.BeginEndExecutor;
import org.cruxframework.crux.core.client.screen.DeviceAdaptive.Device;
import org.cruxframework.crux.core.client.screen.Screen;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.IFrameElement;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.ui.RootPanel;
/**
* @author Thiago da Rosa de Bustamante
*
*/
public class ViewHandlers
{
private static boolean initialized = false;
private static FastList<ViewContainer> boundContainers = null;
private static boolean hasWindowResizeHandler = false;
private static boolean hasOrientationChangeOrResizeHandler = false;
private static boolean hasWindowCloseHandler = false;
private static boolean hasWindowClosingHandler = false;
private static boolean hasHistoryHandler = false;
private static boolean historyFrameInitialized = false;
private static HandlerRegistration resizeHandler;
private static HandlerRegistration orientationChangeOrResizeHandler;
private static HandlerRegistration closeHandler;
private static HandlerRegistration closingHandler;
private static HandlerRegistration historyHandler;
protected static void initializeWindowContainers()
{
if (!initialized)
{
boundContainers = new FastList<ViewContainer>();
initialized = true;
}
}
/**
* This method must be called when the container is attached to DOM
*/
protected static void bindToDOM(ViewContainer container)
{
boundContainers.add(container);
ensureViewContainerHandlers(container);
}
/**
* This method must be called when the container is detached from DOM
*/
protected static void unbindToDOM(ViewContainer container)
{
boundContainers.remove(boundContainers.indexOf(container));
ViewHandlers.removeViewContainerHandlers();
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerHandlers(ViewContainer viewContainer)
{
ensureViewContainerResizeHandler(viewContainer);
ensureViewContainerOrientationChangeOrResizeHandler(viewContainer);
ensureViewContainerCloseHandler(viewContainer);
ensureViewContainerClosingHandler(viewContainer);
ensureViewContainerHistoryHandler(viewContainer);
}
/**
*
*/
protected static void removeViewContainerHandlers()
{
removeViewContainerResizeHandler();
removeViewContainerOrientationChangeOrResizeHandler();
removeViewContainerCloseHandler();
removeViewContainerClosingHandler();
removeViewContainerHistoryHandler();
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerResizeHandler(ViewContainer viewContainer)
{
if (!hasWindowResizeHandler && viewContainer.hasResizeHandlers())
{
hasWindowResizeHandler = true;
resizeHandler = Window.addResizeHandler(new ResizeHandler()
{
@Override
public void onResize(ResizeEvent event)
{
for (int i=0; i< boundContainers.size(); i++)
{
boundContainers.get(i).notifyViewsAboutWindowResize(event);
}
}
});
}
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerHistoryHandler(ViewContainer viewContainer)
{
if (!hasHistoryHandler && viewContainer.hasHistoryHandlers())
{
prepareHistoryFrame();
hasHistoryHandler = true;
historyHandler = History.addValueChangeHandler(new ValueChangeHandler<String>()
{
@Override
public void onValueChange(ValueChangeEvent<String> event)
{
for (int i=0; i< boundContainers.size(); i++)
{
boundContainers.get(i).notifyViewsAboutHistoryChange(event);
}
}
});
}
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerOrientationChangeOrResizeHandler(ViewContainer viewContainer)
{
if (!hasOrientationChangeOrResizeHandler && viewContainer.hasOrientationChangeOrResizeHandlers())
{
hasOrientationChangeOrResizeHandler = true;
orientationChangeOrResizeHandler = addWindowOrientationChangeOrResizeHandler(new OrientationChangeOrResizeHandler()
{
@Override
public void onOrientationChangeOrResize()
{
for (int i=0; i< boundContainers.size(); i++)
{
boundContainers.get(i).notifyViewsAboutOrientationChangeOrResize();
}
}
});
}
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerCloseHandler(ViewContainer viewContainer)
{
if (!hasWindowCloseHandler && viewContainer.hasWindowCloseHandlers())
{
hasWindowCloseHandler = true;
closeHandler = Window.addCloseHandler(new CloseHandler<Window>()
{
@Override
public void onClose(CloseEvent<Window> event)
{
for (int i=0; i< boundContainers.size(); i++)
{
boundContainers.get(i).notifyViewsAboutWindowClose(event);
}
}
});
}
}
/**
*
* @param viewContainer
*/
protected static void ensureViewContainerClosingHandler(ViewContainer viewContainer)
{
if (!hasWindowClosingHandler && viewContainer.hasWindowClosingHandlers())
{
hasWindowClosingHandler = true;
closingHandler = Window.addWindowClosingHandler(new ClosingHandler()
{
@Override
public void onWindowClosing(ClosingEvent event)
{
for (int i=0; i< boundContainers.size(); i++)
{
boundContainers.get(i).notifyViewsAboutWindowClosing(event);
}
}
});
}
}
/**
*
*/
private static void removeViewContainerOrientationChangeOrResizeHandler()
{
if (hasOrientationChangeOrResizeHandler)
{
boolean hasOrientationOrResizeHandlers = false;
for(int i=0; i< boundContainers.size(); i++)
{
if (boundContainers.get(i).hasOrientationChangeOrResizeHandlers())
{
hasOrientationOrResizeHandlers = true;
break;
}
}
if (!hasOrientationOrResizeHandlers)
{
if(orientationChangeOrResizeHandler != null)
{
orientationChangeOrResizeHandler.removeHandler();
}
orientationChangeOrResizeHandler = null;
hasOrientationChangeOrResizeHandler = false;
}
}
}
/**
*
*/
private static void removeViewContainerResizeHandler()
{
if (hasWindowResizeHandler)
{
boolean hasResizeHandlers = false;
for(int i=0; i< boundContainers.size(); i++)
{
if (boundContainers.get(i).hasResizeHandlers())
{
hasResizeHandlers = true;
break;
}
}
if (!hasResizeHandlers)
{
if(resizeHandler != null)
{
resizeHandler.removeHandler();
}
resizeHandler = null;
hasWindowResizeHandler = false;
}
}
}
/**
*
*/
private static void removeViewContainerHistoryHandler()
{
if (hasHistoryHandler)
{
boolean hasHistoryHandlers = false;
for(int i=0; i< boundContainers.size(); i++)
{
if (boundContainers.get(i).hasHistoryHandlers())
{
hasHistoryHandlers = true;
break;
}
}
if (!hasHistoryHandlers)
{
if(historyHandler != null)
{
historyHandler.removeHandler();
}
historyHandler = null;
hasHistoryHandler = false;
}
}
}
/**
*
*/
private static void removeViewContainerCloseHandler()
{
if (hasWindowCloseHandler)
{
boolean hasCloseHandlers = false;
for(int i=0; i< boundContainers.size(); i++)
{
if (boundContainers.get(i).hasWindowCloseHandlers())
{
hasCloseHandlers = true;
break;
}
}
if (!hasCloseHandlers)
{
if(closeHandler != null)
{
closeHandler.removeHandler();
}
closeHandler = null;
hasWindowCloseHandler = false;
}
}
}
/**
*
*/
private static void removeViewContainerClosingHandler()
{
if (hasWindowClosingHandler)
{
boolean hasClosingHandlers = false;
for(int i=0; i< boundContainers.size(); i++)
{
if (boundContainers.get(i).hasWindowClosingHandlers())
{
hasClosingHandlers = true;
break;
}
}
if (!hasClosingHandlers)
{
if(closingHandler != null)
{
closingHandler.removeHandler();
}
closingHandler = null;
hasWindowClosingHandler = false;
}
}
}
/**
* @param handler
* @return
*/
private static HandlerRegistration addWindowOrientationChangeOrResizeHandler(final OrientationChangeOrResizeHandler handler)
{
final BeginEndExecutor executor = new BeginEndExecutor(100)
{
private int clientHeight = Window.getClientHeight();
private int clientWidth = Window.getClientWidth();
@Override
protected void doEndAction()
{
if (!Screen.getCurrentDevice().equals(Device.largeDisplayMouse))
{
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
if (this.clientHeight != newClientHeight || clientWidth != newClientWidth)
{
handler.onOrientationChangeOrResize();
}
clientHeight = newClientHeight;
clientWidth = newClientWidth;
}
else
{
handler.onOrientationChangeOrResize();
}
}
@Override
protected void doBeginAction()
{
// nothing
}
};
ResizeHandler resizeHandler = new ResizeHandler()
{
public void onResize(ResizeEvent event)
{
- executor.execute();
+ if(Screen.isIos())
+ {
+ handler.onOrientationChangeOrResize();
+ } else
+ {
+ executor.execute();
+ }
}
};
final HandlerRegistration resizeHandlerRegistration = Window.addResizeHandler(resizeHandler);
final JavaScriptObject orientationHandler = attachOrientationChangeHandler(executor);
return new HandlerRegistration()
{
public void removeHandler()
{
if(resizeHandlerRegistration != null)
{
resizeHandlerRegistration.removeHandler();
}
if(orientationHandler != null)
{
removeOrientationChangeHandler(orientationHandler);
}
}
};
}
/**
* @param orientationHandler
*/
private static native void removeOrientationChangeHandler(JavaScriptObject orientationHandler) /*-{
var supportsOrientationChange = 'onorientationchange' in $wnd;
if (supportsOrientationChange)
{
$wnd.removeEventListener("orientationchange", orientationHandler);
}
}-*/;
/**
* @param executor
* @return
*/
private static native JavaScriptObject attachOrientationChangeHandler(BeginEndExecutor executor)/*-{
var supportsOrientationChange = 'onorientationchange' in $wnd;
if (supportsOrientationChange)
{
$wnd.previousOrientation = $wnd.orientation;
var checkOrientation = function()
{
if($wnd.orientation !== $wnd.previousOrientation)
{
$wnd.previousOrientation = $wnd.orientation;
executor.@org.cruxframework.crux.core.client.executor.BeginEndExecutor::execute()();
}
};
$wnd.addEventListener("orientationchange", checkOrientation, false);
return checkOrientation;
}
return null;
}-*/;
/**
*
*/
private static void prepareHistoryFrame()
{
if (!historyFrameInitialized)
{
Element body = RootPanel.getBodyElement();
IFrameElement historyFrame = DOM.createIFrame().cast();
historyFrame.setSrc("javascript:''");
historyFrame.setId("__gwt_historyFrame");
historyFrame.getStyle().setProperty("position", "absolute");
historyFrame.getStyle().setProperty("width", "0");
historyFrame.getStyle().setProperty("height", "0");
historyFrame.getStyle().setProperty("border", "0");
body.appendChild(historyFrame);
History.fireCurrentHistoryState();
historyFrameInitialized = true;
}
}
}
| true | true | private static HandlerRegistration addWindowOrientationChangeOrResizeHandler(final OrientationChangeOrResizeHandler handler)
{
final BeginEndExecutor executor = new BeginEndExecutor(100)
{
private int clientHeight = Window.getClientHeight();
private int clientWidth = Window.getClientWidth();
@Override
protected void doEndAction()
{
if (!Screen.getCurrentDevice().equals(Device.largeDisplayMouse))
{
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
if (this.clientHeight != newClientHeight || clientWidth != newClientWidth)
{
handler.onOrientationChangeOrResize();
}
clientHeight = newClientHeight;
clientWidth = newClientWidth;
}
else
{
handler.onOrientationChangeOrResize();
}
}
@Override
protected void doBeginAction()
{
// nothing
}
};
ResizeHandler resizeHandler = new ResizeHandler()
{
public void onResize(ResizeEvent event)
{
executor.execute();
}
};
final HandlerRegistration resizeHandlerRegistration = Window.addResizeHandler(resizeHandler);
final JavaScriptObject orientationHandler = attachOrientationChangeHandler(executor);
return new HandlerRegistration()
{
public void removeHandler()
{
if(resizeHandlerRegistration != null)
{
resizeHandlerRegistration.removeHandler();
}
if(orientationHandler != null)
{
removeOrientationChangeHandler(orientationHandler);
}
}
};
}
| private static HandlerRegistration addWindowOrientationChangeOrResizeHandler(final OrientationChangeOrResizeHandler handler)
{
final BeginEndExecutor executor = new BeginEndExecutor(100)
{
private int clientHeight = Window.getClientHeight();
private int clientWidth = Window.getClientWidth();
@Override
protected void doEndAction()
{
if (!Screen.getCurrentDevice().equals(Device.largeDisplayMouse))
{
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
if (this.clientHeight != newClientHeight || clientWidth != newClientWidth)
{
handler.onOrientationChangeOrResize();
}
clientHeight = newClientHeight;
clientWidth = newClientWidth;
}
else
{
handler.onOrientationChangeOrResize();
}
}
@Override
protected void doBeginAction()
{
// nothing
}
};
ResizeHandler resizeHandler = new ResizeHandler()
{
public void onResize(ResizeEvent event)
{
if(Screen.isIos())
{
handler.onOrientationChangeOrResize();
} else
{
executor.execute();
}
}
};
final HandlerRegistration resizeHandlerRegistration = Window.addResizeHandler(resizeHandler);
final JavaScriptObject orientationHandler = attachOrientationChangeHandler(executor);
return new HandlerRegistration()
{
public void removeHandler()
{
if(resizeHandlerRegistration != null)
{
resizeHandlerRegistration.removeHandler();
}
if(orientationHandler != null)
{
removeOrientationChangeHandler(orientationHandler);
}
}
};
}
|
diff --git a/src/com/esn/idea/liquibaseejb/model/ejb/member/AnyToOneModel.java b/src/com/esn/idea/liquibaseejb/model/ejb/member/AnyToOneModel.java
index 3c7580a..0ea9109 100644
--- a/src/com/esn/idea/liquibaseejb/model/ejb/member/AnyToOneModel.java
+++ b/src/com/esn/idea/liquibaseejb/model/ejb/member/AnyToOneModel.java
@@ -1,88 +1,88 @@
package com.esn.idea.liquibaseejb.model.ejb.member;
import com.esn.idea.liquibaseejb.model.database.DatabaseModel;
import com.esn.idea.liquibaseejb.model.ejb.context.EjbModelContext;
import com.esn.idea.liquibaseejb.model.ejb.module.ModuleModel;
import com.intellij.javaee.model.common.persistence.mapping.JoinColumnBase;
import com.intellij.javaee.model.common.persistence.mapping.OneToOne;
import com.intellij.javaee.model.common.persistence.mapping.RelationAttributeBase;
import com.intellij.persistence.model.PersistentAttribute;
import com.intellij.psi.*;
import com.intellij.util.xml.GenericValue;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.PrimaryKeyJoinColumns;
import java.util.List;
import java.util.Collections;
/**
* Author: Marcus Nilsson
* Date: 2008-nov-09
* Time: 19:01:04
*/
public class AnyToOneModel extends RelationModel<RelationAttributeBase.AnyToOneBase>
{
public AnyToOneModel(ModuleModel moduleModel, RelationAttributeBase.AnyToOneBase attribute)
{
super(moduleModel, attribute);
}
protected void executeMember(EjbModelContext context, DatabaseModel databaseModel, PsiMember psiMember, PsiType memberType)
{
if (memberType instanceof PsiClassType && !isAttributeInverse())
{
PsiClass memberClass = ((PsiClassType) memberType).resolve();
PsiModifierList modifierList = psiMember.getModifierList();
if (modifierList != null)
{
if (modifierList.findAnnotation(PrimaryKeyJoinColumn.class.getName()) != null ||
modifierList.findAnnotation(PrimaryKeyJoinColumns.class.getName()) != null)
{
// No extra fields are needed
return;
}
}
String columnPrefix = psiMember.getName() + "_";
Boolean isOptional = attribute.getOptional().getValue();
if (isOptional == null) isOptional = true;
String tableName = context.getTableName();
RelationAttributeBase.NonManyToManyBase nonManyToMany = (RelationAttributeBase.NonManyToManyBase) attribute;
List<? extends JoinColumnBase> joinColumnBases = nonManyToMany.getJoinColumns();
List<JoinColumnBase> overridingJoinColumnBases = context.getAssociationOverride(getMember().getName());
if (overridingJoinColumnBases != null && !overridingJoinColumnBases.isEmpty())
{
joinColumnBases = overridingJoinColumnBases;
}
- List<String> sourceColumns = createJoinColumns(databaseModel, tableName, memberClass, joinColumnBases, columnPrefix, isOptional, isOptional, moduleModel, "fk_" + attribute.getName());
+ List<String> sourceColumns = createJoinColumns(databaseModel, tableName, memberClass, joinColumnBases, columnPrefix, isOptional, true, moduleModel, "fk_" + attribute.getName());
if (attribute instanceof OneToOne)
{
databaseModel.addUniqueConstraint(tableName, null, sourceColumns);
}
}
}
private boolean isAttributeInverse()
{
boolean isInverse = false;
if (attribute instanceof OneToOne)
{
GenericValue<PersistentAttribute> mappedBy = ((OneToOne) attribute).getMappedBy();
String mappedByStringValue = mappedBy.getStringValue();
if (mappedByStringValue == null) mappedByStringValue = "";
isInverse = !("".equals(mappedByStringValue));
}
return isInverse;
}
}
| true | true | protected void executeMember(EjbModelContext context, DatabaseModel databaseModel, PsiMember psiMember, PsiType memberType)
{
if (memberType instanceof PsiClassType && !isAttributeInverse())
{
PsiClass memberClass = ((PsiClassType) memberType).resolve();
PsiModifierList modifierList = psiMember.getModifierList();
if (modifierList != null)
{
if (modifierList.findAnnotation(PrimaryKeyJoinColumn.class.getName()) != null ||
modifierList.findAnnotation(PrimaryKeyJoinColumns.class.getName()) != null)
{
// No extra fields are needed
return;
}
}
String columnPrefix = psiMember.getName() + "_";
Boolean isOptional = attribute.getOptional().getValue();
if (isOptional == null) isOptional = true;
String tableName = context.getTableName();
RelationAttributeBase.NonManyToManyBase nonManyToMany = (RelationAttributeBase.NonManyToManyBase) attribute;
List<? extends JoinColumnBase> joinColumnBases = nonManyToMany.getJoinColumns();
List<JoinColumnBase> overridingJoinColumnBases = context.getAssociationOverride(getMember().getName());
if (overridingJoinColumnBases != null && !overridingJoinColumnBases.isEmpty())
{
joinColumnBases = overridingJoinColumnBases;
}
List<String> sourceColumns = createJoinColumns(databaseModel, tableName, memberClass, joinColumnBases, columnPrefix, isOptional, isOptional, moduleModel, "fk_" + attribute.getName());
if (attribute instanceof OneToOne)
{
databaseModel.addUniqueConstraint(tableName, null, sourceColumns);
}
}
}
| protected void executeMember(EjbModelContext context, DatabaseModel databaseModel, PsiMember psiMember, PsiType memberType)
{
if (memberType instanceof PsiClassType && !isAttributeInverse())
{
PsiClass memberClass = ((PsiClassType) memberType).resolve();
PsiModifierList modifierList = psiMember.getModifierList();
if (modifierList != null)
{
if (modifierList.findAnnotation(PrimaryKeyJoinColumn.class.getName()) != null ||
modifierList.findAnnotation(PrimaryKeyJoinColumns.class.getName()) != null)
{
// No extra fields are needed
return;
}
}
String columnPrefix = psiMember.getName() + "_";
Boolean isOptional = attribute.getOptional().getValue();
if (isOptional == null) isOptional = true;
String tableName = context.getTableName();
RelationAttributeBase.NonManyToManyBase nonManyToMany = (RelationAttributeBase.NonManyToManyBase) attribute;
List<? extends JoinColumnBase> joinColumnBases = nonManyToMany.getJoinColumns();
List<JoinColumnBase> overridingJoinColumnBases = context.getAssociationOverride(getMember().getName());
if (overridingJoinColumnBases != null && !overridingJoinColumnBases.isEmpty())
{
joinColumnBases = overridingJoinColumnBases;
}
List<String> sourceColumns = createJoinColumns(databaseModel, tableName, memberClass, joinColumnBases, columnPrefix, isOptional, true, moduleModel, "fk_" + attribute.getName());
if (attribute instanceof OneToOne)
{
databaseModel.addUniqueConstraint(tableName, null, sourceColumns);
}
}
}
|
diff --git a/codjo-mad-server/src/test/java/net/codjo/mad/server/plugin/InstituteAmbassadorParticipantTest.java b/codjo-mad-server/src/test/java/net/codjo/mad/server/plugin/InstituteAmbassadorParticipantTest.java
index d9ceaa4..ddc790f 100644
--- a/codjo-mad-server/src/test/java/net/codjo/mad/server/plugin/InstituteAmbassadorParticipantTest.java
+++ b/codjo-mad-server/src/test/java/net/codjo/mad/server/plugin/InstituteAmbassadorParticipantTest.java
@@ -1,138 +1,139 @@
/*
* Team : AGF AM / OSI / SI / BO
*
* Copyright (c) 2001 AGF Asset Management.
*/
package net.codjo.mad.server.plugin;
import net.codjo.agent.AclMessage;
import net.codjo.agent.Aid;
import net.codjo.agent.UserId;
import net.codjo.agent.test.BehaviourTestCase;
import net.codjo.agent.test.DummyAgent;
import net.codjo.mad.common.message.InstituteAmbassadorProtocol;
import net.codjo.mad.server.handler.HandlerListener;
import net.codjo.mad.server.handler.HandlerListenerMock;
import net.codjo.sql.server.ConnectionPoolMock;
import net.codjo.test.common.LogString;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
/**
* Classe de test de {@link InstituteAmbassadorParticipant}.
*/
public class InstituteAmbassadorParticipantTest extends BehaviourTestCase {
private static final String EXPECTED_TEMPLATE =
"(( Language: " + AclMessage.OBJECT_LANGUAGE + " ) AND ( Protocol: "
+ InstituteAmbassadorProtocol.ID + " ))";
private LogString logString = new LogString();
private InstituteAmbassadorParticipant participant;
private SecretaryGeneralAgentMock secretaryGeneral;
private DummyAgent president = new DummyAgent();
private UserId userId = UserId.createId("login", "password");
private static final String PRESIDENT_NAME = "president";
private static final String AMBASSADOR_FOR_PRESIDENT = "AmbassadorFor" + PRESIDENT_NAME;
public void test_action() throws Exception {
mockConnectionPool();
acceptAgent("secretaryGeneral", secretaryGeneral);
acceptAgent(PRESIDENT_NAME, president);
assertFalse(participant.done());
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
secretaryGeneral.mockReceiveContent(createInstituteMessage(userId));
participant.action();
assertFalse(participant.done());
UserId realUserId = secretaryGeneral.getLastSentMessage().decodeUserId();
assertNotNull("login OK", realUserId);
secretaryGeneral.getLog().assertContent(
String.format("agent.receive(%s)", EXPECTED_TEMPLATE) + ", " +
String.format("getUser(%s)", userId.getLogin()) + ", " +
String.format("getPool(%s)", realUserId.encode()) + ", " +
"createHandlerMap(UserId(" + userId.getLogin() + "), {UserId, ConnectionPoolMock})" + ", " +
String.format("agent.send(president, null, %s)", AMBASSADOR_FOR_PRESIDENT));
AclMessage lastSentMessage = secretaryGeneral.getLastSentMessage();
assertEquals(InstituteAmbassadorProtocol.ID, lastSentMessage.getProtocol());
containerFixture.assertContainsAgent(AMBASSADOR_FOR_PRESIDENT);
logString.assertContent(
String.format("declare(president, %s, %s)", AMBASSADOR_FOR_PRESIDENT, realUserId.encode()));
+ Thread.sleep(100);
president.die();
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
}
public void test_ambassadorCreationError() throws Exception {
mockGetUserFailure(new RuntimeException("Impossible de r�cup�rer le user !!!"));
acceptAgent("secretaryGeneral", secretaryGeneral);
acceptAgent(PRESIDENT_NAME, president);
secretaryGeneral.mockReceiveContent(createInstituteMessage(userId));
participant.action();
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
secretaryGeneral.getLog().assertContent(
String.format("agent.receive(%s)", EXPECTED_TEMPLATE),
"agent.send(president, null, java.lang.RuntimeException: Impossible de r�cup�rer le user !!!)");
AclMessage lastSentMessage = secretaryGeneral.getLastSentMessage();
assertEquals(InstituteAmbassadorProtocol.ID, lastSentMessage.getProtocol());
}
@Override
protected void doSetUp() throws MalformedURLException {
secretaryGeneral = new SecretaryGeneralAgentMock();
AmbassadorRemovalBehaviour removalBehaviour =
new AmbassadorRemovalBehaviour() {
@Override
public void declare(Aid presidentAID, Aid ambassadorAID, UserId poolUserId) {
super.declare(presidentAID, ambassadorAID, poolUserId);
logString.call("declare",
presidentAID.getLocalName(),
ambassadorAID.getLocalName(),
poolUserId.encode());
}
};
secretaryGeneral.addBehaviour(removalBehaviour);
BackPack backPack =
BackPackBuilder.init()
.setHandlerMapBuilder(new HandlerMapBuilderMock(secretaryGeneral.getLog()))
.setCastorConfig(new URL("http://pipo"))
.setHandlerListeners(Arrays.<HandlerListener>asList(new HandlerListenerMock(logString)))
.get();
backPack.setHandlerExecutorFactory(new DefaultHandlerExecutorFactory());
participant = new InstituteAmbassadorParticipant(backPack, removalBehaviour);
participant.setAgent(secretaryGeneral);
}
private void mockConnectionPool() throws ClassNotFoundException {
secretaryGeneral.getJdbcServiceHelperMock().mockGetPool(new ConnectionPoolMock());
}
private void mockGetUserFailure(RuntimeException exception) {
secretaryGeneral.getSecurityServiceHelperMock().mockGetUserFailure(exception);
}
private AclMessage createInstituteMessage(UserId aUserId) {
AclMessage aclMessage = new AclMessage(AclMessage.Performative.REQUEST);
aclMessage.setSender(president.getAID());
aclMessage.encodeUserId(aUserId);
return aclMessage;
}
}
| true | true | public void test_action() throws Exception {
mockConnectionPool();
acceptAgent("secretaryGeneral", secretaryGeneral);
acceptAgent(PRESIDENT_NAME, president);
assertFalse(participant.done());
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
secretaryGeneral.mockReceiveContent(createInstituteMessage(userId));
participant.action();
assertFalse(participant.done());
UserId realUserId = secretaryGeneral.getLastSentMessage().decodeUserId();
assertNotNull("login OK", realUserId);
secretaryGeneral.getLog().assertContent(
String.format("agent.receive(%s)", EXPECTED_TEMPLATE) + ", " +
String.format("getUser(%s)", userId.getLogin()) + ", " +
String.format("getPool(%s)", realUserId.encode()) + ", " +
"createHandlerMap(UserId(" + userId.getLogin() + "), {UserId, ConnectionPoolMock})" + ", " +
String.format("agent.send(president, null, %s)", AMBASSADOR_FOR_PRESIDENT));
AclMessage lastSentMessage = secretaryGeneral.getLastSentMessage();
assertEquals(InstituteAmbassadorProtocol.ID, lastSentMessage.getProtocol());
containerFixture.assertContainsAgent(AMBASSADOR_FOR_PRESIDENT);
logString.assertContent(
String.format("declare(president, %s, %s)", AMBASSADOR_FOR_PRESIDENT, realUserId.encode()));
president.die();
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
}
| public void test_action() throws Exception {
mockConnectionPool();
acceptAgent("secretaryGeneral", secretaryGeneral);
acceptAgent(PRESIDENT_NAME, president);
assertFalse(participant.done());
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
secretaryGeneral.mockReceiveContent(createInstituteMessage(userId));
participant.action();
assertFalse(participant.done());
UserId realUserId = secretaryGeneral.getLastSentMessage().decodeUserId();
assertNotNull("login OK", realUserId);
secretaryGeneral.getLog().assertContent(
String.format("agent.receive(%s)", EXPECTED_TEMPLATE) + ", " +
String.format("getUser(%s)", userId.getLogin()) + ", " +
String.format("getPool(%s)", realUserId.encode()) + ", " +
"createHandlerMap(UserId(" + userId.getLogin() + "), {UserId, ConnectionPoolMock})" + ", " +
String.format("agent.send(president, null, %s)", AMBASSADOR_FOR_PRESIDENT));
AclMessage lastSentMessage = secretaryGeneral.getLastSentMessage();
assertEquals(InstituteAmbassadorProtocol.ID, lastSentMessage.getProtocol());
containerFixture.assertContainsAgent(AMBASSADOR_FOR_PRESIDENT);
logString.assertContent(
String.format("declare(president, %s, %s)", AMBASSADOR_FOR_PRESIDENT, realUserId.encode()));
Thread.sleep(100);
president.die();
containerFixture.assertNotContainsAgent(AMBASSADOR_FOR_PRESIDENT);
}
|
diff --git a/api/java/internal/src/main/java/org/societies/api/internal/useragent/model/AbstractDecisionMaker.java b/api/java/internal/src/main/java/org/societies/api/internal/useragent/model/AbstractDecisionMaker.java
index b5a0f7f9f..22c510e7e 100644
--- a/api/java/internal/src/main/java/org/societies/api/internal/useragent/model/AbstractDecisionMaker.java
+++ b/api/java/internal/src/main/java/org/societies/api/internal/useragent/model/AbstractDecisionMaker.java
@@ -1,95 +1,95 @@
/**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.api.internal.useragent.model;
import java.util.ArrayList;
import java.util.List;
import org.societies.api.internal.useragent.conflict.IConflictResolutionManager;
import org.societies.api.internal.useragent.decisionmaking.IDecisionMaker;
import org.societies.api.internal.useragent.feedback.IUserFeedback;
import org.societies.api.personalisation.model.IAction;
import org.societies.api.internal.personalisation.model.IOutcome;
public abstract class AbstractDecisionMaker implements IDecisionMaker {
IConflictResolutionManager manager;
IUserFeedback feedbackHandler;
public IConflictResolutionManager getManager() {
return manager;
}
public void setManager(IConflictResolutionManager manager) {
this.manager = manager;
}
public IUserFeedback getFeedbackHandler() {
return feedbackHandler;
}
public void setFeedbackHandler(IUserFeedback feedbackHandler) {
this.feedbackHandler = feedbackHandler;
}
@Override
public void makeDecision(List<IOutcome> intents, List<IOutcome> preferences) {
// TODO Auto-generated method stub
for (IOutcome intent : intents) {
IOutcome action=intent;
for (IOutcome preference : preferences) {
ConflictType conflict = detectConflict(intent, preference);
if (conflict == ConflictType.PREFERNCE_INTENT_NOT_MATCH) {
action = manager.resolveConflict(action,preference);
if(action ==null){
List<String> options=new ArrayList<String>();
- options.add(action.toString());
+ options.add(intent.toString());
options.add(preference.toString());
ExpProposalContent epc=new ExpProposalContent("Conflict Detected!",
options);
if(feedbackHandler.getExplicitFB(
ExpProposalType.RADIOLIST,epc)){
action=intent;
/*return true for intent false for preference*/
}else{
action=preference;
}
}
}else if (conflict==ConflictType.UNKNOWN_CONFLICT){
/*handler the unknown work*/
}
}
this.implementIAction(action);
}
}
protected abstract ConflictType detectConflict(IOutcome intent,
IOutcome prefernce);
protected abstract void implementIAction(IAction action);
}
| true | true | public void makeDecision(List<IOutcome> intents, List<IOutcome> preferences) {
// TODO Auto-generated method stub
for (IOutcome intent : intents) {
IOutcome action=intent;
for (IOutcome preference : preferences) {
ConflictType conflict = detectConflict(intent, preference);
if (conflict == ConflictType.PREFERNCE_INTENT_NOT_MATCH) {
action = manager.resolveConflict(action,preference);
if(action ==null){
List<String> options=new ArrayList<String>();
options.add(action.toString());
options.add(preference.toString());
ExpProposalContent epc=new ExpProposalContent("Conflict Detected!",
options);
if(feedbackHandler.getExplicitFB(
ExpProposalType.RADIOLIST,epc)){
action=intent;
/*return true for intent false for preference*/
}else{
action=preference;
}
}
}else if (conflict==ConflictType.UNKNOWN_CONFLICT){
/*handler the unknown work*/
}
}
this.implementIAction(action);
}
}
| public void makeDecision(List<IOutcome> intents, List<IOutcome> preferences) {
// TODO Auto-generated method stub
for (IOutcome intent : intents) {
IOutcome action=intent;
for (IOutcome preference : preferences) {
ConflictType conflict = detectConflict(intent, preference);
if (conflict == ConflictType.PREFERNCE_INTENT_NOT_MATCH) {
action = manager.resolveConflict(action,preference);
if(action ==null){
List<String> options=new ArrayList<String>();
options.add(intent.toString());
options.add(preference.toString());
ExpProposalContent epc=new ExpProposalContent("Conflict Detected!",
options);
if(feedbackHandler.getExplicitFB(
ExpProposalType.RADIOLIST,epc)){
action=intent;
/*return true for intent false for preference*/
}else{
action=preference;
}
}
}else if (conflict==ConflictType.UNKNOWN_CONFLICT){
/*handler the unknown work*/
}
}
this.implementIAction(action);
}
}
|
diff --git a/src/com/android/dialer/calllog/CallLogAdapter.java b/src/com/android/dialer/calllog/CallLogAdapter.java
index b2493cf97..86540efbb 100644
--- a/src/com/android/dialer/calllog/CallLogAdapter.java
+++ b/src/com/android/dialer/calllog/CallLogAdapter.java
@@ -1,926 +1,928 @@
/*
* Copyright (C) 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.dialer.calllog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.PhoneLookup;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.common.widget.GroupingListAdapter;
import com.android.contacts.common.ContactPhotoManager;
import com.android.contacts.common.util.UriUtils;
import com.android.dialer.PhoneCallDetails;
import com.android.dialer.PhoneCallDetailsHelper;
import com.android.dialer.R;
import com.android.dialer.util.ExpirableCache;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import java.util.LinkedList;
/**
* Adapter class to fill in data for the Call Log.
*/
public class CallLogAdapter extends GroupingListAdapter
implements ViewTreeObserver.OnPreDrawListener, CallLogGroupBuilder.GroupCreator {
/** Interface used to initiate a refresh of the content. */
public interface CallFetcher {
public void fetchCalls();
}
/**
* Stores a phone number of a call with the country code where it originally occurred.
* <p>
* Note the country does not necessarily specifies the country of the phone number itself, but
* it is the country in which the user was in when the call was placed or received.
*/
private static final class NumberWithCountryIso {
public final String number;
public final String countryIso;
public NumberWithCountryIso(String number, String countryIso) {
this.number = number;
this.countryIso = countryIso;
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (!(o instanceof NumberWithCountryIso)) return false;
NumberWithCountryIso other = (NumberWithCountryIso) o;
return TextUtils.equals(number, other.number)
&& TextUtils.equals(countryIso, other.countryIso);
}
@Override
public int hashCode() {
return (number == null ? 0 : number.hashCode())
^ (countryIso == null ? 0 : countryIso.hashCode());
}
}
/** The time in millis to delay starting the thread processing requests. */
private static final int START_PROCESSING_REQUESTS_DELAY_MILLIS = 1000;
/** The size of the cache of contact info. */
private static final int CONTACT_INFO_CACHE_SIZE = 100;
protected final Context mContext;
private final ContactInfoHelper mContactInfoHelper;
private final CallFetcher mCallFetcher;
private ViewTreeObserver mViewTreeObserver = null;
/**
* A cache of the contact details for the phone numbers in the call log.
* <p>
* The content of the cache is expired (but not purged) whenever the application comes to
* the foreground.
* <p>
* The key is number with the country in which the call was placed or received.
*/
private ExpirableCache<NumberWithCountryIso, ContactInfo> mContactInfoCache;
/**
* A request for contact details for the given number.
*/
private static final class ContactInfoRequest {
/** The number to look-up. */
public final String number;
/** The country in which a call to or from this number was placed or received. */
public final String countryIso;
/** The cached contact information stored in the call log. */
public final ContactInfo callLogInfo;
public ContactInfoRequest(String number, String countryIso, ContactInfo callLogInfo) {
this.number = number;
this.countryIso = countryIso;
this.callLogInfo = callLogInfo;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof ContactInfoRequest)) return false;
ContactInfoRequest other = (ContactInfoRequest) obj;
if (!TextUtils.equals(number, other.number)) return false;
if (!TextUtils.equals(countryIso, other.countryIso)) return false;
if (!Objects.equal(callLogInfo, other.callLogInfo)) return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((callLogInfo == null) ? 0 : callLogInfo.hashCode());
result = prime * result + ((countryIso == null) ? 0 : countryIso.hashCode());
result = prime * result + ((number == null) ? 0 : number.hashCode());
return result;
}
}
/**
* List of requests to update contact details.
* <p>
* Each request is made of a phone number to look up, and the contact info currently stored in
* the call log for this number.
* <p>
* The requests are added when displaying the contacts and are processed by a background
* thread.
*/
private final LinkedList<ContactInfoRequest> mRequests;
private boolean mLoading = true;
private static final int REDRAW = 1;
private static final int START_THREAD = 2;
private QueryThread mCallerIdThread;
/** Instance of helper class for managing views. */
private final CallLogListItemHelper mCallLogViewsHelper;
/** Helper to set up contact photos. */
private final ContactPhotoManager mContactPhotoManager;
/** Helper to parse and process phone numbers. */
private PhoneNumberHelper mPhoneNumberHelper;
/** Helper to group call log entries. */
private final CallLogGroupBuilder mCallLogGroupBuilder;
/** Can be set to true by tests to disable processing of requests. */
private volatile boolean mRequestProcessingDisabled = false;
/** True if CallLogAdapter is created from the PhoneFavoriteFragment, where the primary
* action should be set to call a number instead of opening the detail page. */
private boolean mUseCallAsPrimaryAction = false;
private boolean mIsCallLog = true;
private int mNumMissedCalls = 0;
private int mNumMissedCallsShown = 0;
private Uri mCurrentPhotoUri;
private View mBadgeContainer;
private ImageView mBadgeImageView;
private TextView mBadgeText;
/** Listener for the primary action in the list, opens the call details. */
private final View.OnClickListener mPrimaryActionListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentProvider intentProvider = (IntentProvider) view.getTag();
if (intentProvider != null) {
mContext.startActivity(intentProvider.getIntent(mContext));
}
}
};
/** Listener for the secondary action in the list, either call or play. */
private final View.OnClickListener mSecondaryActionListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
IntentProvider intentProvider = (IntentProvider) view.getTag();
if (intentProvider != null) {
mContext.startActivity(intentProvider.getIntent(mContext));
}
}
};
@Override
public boolean onPreDraw() {
// We only wanted to listen for the first draw (and this is it).
unregisterPreDrawListener();
// Only schedule a thread-creation message if the thread hasn't been
// created yet. This is purely an optimization, to queue fewer messages.
if (mCallerIdThread == null) {
mHandler.sendEmptyMessageDelayed(START_THREAD, START_PROCESSING_REQUESTS_DELAY_MILLIS);
}
return true;
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REDRAW:
notifyDataSetChanged();
break;
case START_THREAD:
startRequestProcessing();
break;
}
}
};
public CallLogAdapter(Context context, CallFetcher callFetcher,
ContactInfoHelper contactInfoHelper, boolean useCallAsPrimaryAction,
boolean isCallLog) {
super(context);
mContext = context;
mCallFetcher = callFetcher;
mContactInfoHelper = contactInfoHelper;
mUseCallAsPrimaryAction = useCallAsPrimaryAction;
mIsCallLog = isCallLog;
mContactInfoCache = ExpirableCache.create(CONTACT_INFO_CACHE_SIZE);
mRequests = new LinkedList<ContactInfoRequest>();
Resources resources = mContext.getResources();
CallTypeHelper callTypeHelper = new CallTypeHelper(resources);
mContactPhotoManager = ContactPhotoManager.getInstance(mContext);
mPhoneNumberHelper = new PhoneNumberHelper(resources);
PhoneCallDetailsHelper phoneCallDetailsHelper = new PhoneCallDetailsHelper(
resources, callTypeHelper, new PhoneNumberUtilsWrapper());
mCallLogViewsHelper =
new CallLogListItemHelper(
phoneCallDetailsHelper, mPhoneNumberHelper, resources);
mCallLogGroupBuilder = new CallLogGroupBuilder(this);
}
/**
* Requery on background thread when {@link Cursor} changes.
*/
@Override
protected void onContentChanged() {
mCallFetcher.fetchCalls();
}
public void setLoading(boolean loading) {
mLoading = loading;
}
@Override
public boolean isEmpty() {
if (mLoading) {
// We don't want the empty state to show when loading.
return false;
} else {
return super.isEmpty();
}
}
/**
* Starts a background thread to process contact-lookup requests, unless one
* has already been started.
*/
private synchronized void startRequestProcessing() {
// For unit-testing.
if (mRequestProcessingDisabled) return;
// Idempotence... if a thread is already started, don't start another.
if (mCallerIdThread != null) return;
mCallerIdThread = new QueryThread();
mCallerIdThread.setPriority(Thread.MIN_PRIORITY);
mCallerIdThread.start();
}
/**
* Stops the background thread that processes updates and cancels any
* pending requests to start it.
*/
public synchronized void stopRequestProcessing() {
// Remove any pending requests to start the processing thread.
mHandler.removeMessages(START_THREAD);
if (mCallerIdThread != null) {
// Stop the thread; we are finished with it.
mCallerIdThread.stopProcessing();
mCallerIdThread.interrupt();
mCallerIdThread = null;
}
}
/**
* Stop receiving onPreDraw() notifications.
*/
private void unregisterPreDrawListener() {
if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
mViewTreeObserver.removeOnPreDrawListener(this);
}
mViewTreeObserver = null;
}
public void invalidateCache() {
mContactInfoCache.expireAll();
// Restart the request-processing thread after the next draw.
stopRequestProcessing();
unregisterPreDrawListener();
}
/**
* Enqueues a request to look up the contact details for the given phone number.
* <p>
* It also provides the current contact info stored in the call log for this number.
* <p>
* If the {@code immediate} parameter is true, it will start immediately the thread that looks
* up the contact information (if it has not been already started). Otherwise, it will be
* started with a delay. See {@link #START_PROCESSING_REQUESTS_DELAY_MILLIS}.
*/
protected void enqueueRequest(String number, String countryIso, ContactInfo callLogInfo,
boolean immediate) {
ContactInfoRequest request = new ContactInfoRequest(number, countryIso, callLogInfo);
synchronized (mRequests) {
if (!mRequests.contains(request)) {
mRequests.add(request);
mRequests.notifyAll();
}
}
if (immediate) startRequestProcessing();
}
/**
* Queries the appropriate content provider for the contact associated with the number.
* <p>
* Upon completion it also updates the cache in the call log, if it is different from
* {@code callLogInfo}.
* <p>
* The number might be either a SIP address or a phone number.
* <p>
* It returns true if it updated the content of the cache and we should therefore tell the
* view to update its content.
*/
private boolean queryContactInfo(String number, String countryIso, ContactInfo callLogInfo) {
final ContactInfo info = mContactInfoHelper.lookupNumber(number, countryIso);
if (info == null) {
// The lookup failed, just return without requesting to update the view.
return false;
}
// Check the existing entry in the cache: only if it has changed we should update the
// view.
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ContactInfo existingInfo = mContactInfoCache.getPossiblyExpired(numberCountryIso);
boolean updated = !info.equals(existingInfo);
// Store the data in the cache so that the UI thread can use to display it. Store it
// even if it has not changed so that it is marked as not expired.
mContactInfoCache.put(numberCountryIso, info);
// Update the call log even if the cache it is up-to-date: it is possible that the cache
// contains the value from a different call log entry.
updateCallLogContactInfoCache(number, countryIso, info, callLogInfo);
return updated;
}
/*
* Handles requests for contact name and number type.
*/
private class QueryThread extends Thread {
private volatile boolean mDone = false;
public QueryThread() {
super("CallLogAdapter.QueryThread");
}
public void stopProcessing() {
mDone = true;
}
@Override
public void run() {
boolean needRedraw = false;
while (true) {
// Check if thread is finished, and if so return immediately.
if (mDone) return;
// Obtain next request, if any is available.
// Keep synchronized section small.
ContactInfoRequest req = null;
synchronized (mRequests) {
if (!mRequests.isEmpty()) {
req = mRequests.removeFirst();
}
}
if (req != null) {
// Process the request. If the lookup succeeds, schedule a
// redraw.
needRedraw |= queryContactInfo(req.number, req.countryIso, req.callLogInfo);
} else {
// Throttle redraw rate by only sending them when there are
// more requests.
if (needRedraw) {
needRedraw = false;
mHandler.sendEmptyMessage(REDRAW);
}
// Wait until another request is available, or until this
// thread is no longer needed (as indicated by being
// interrupted).
try {
synchronized (mRequests) {
mRequests.wait(1000);
}
} catch (InterruptedException ie) {
// Ignore, and attempt to continue processing requests.
}
}
}
}
}
@Override
protected void addGroups(Cursor cursor) {
mCallLogGroupBuilder.addGroups(cursor);
}
@Override
protected View newStandAloneView(Context context, ViewGroup parent) {
return newChildView(context, parent);
}
@Override
protected View newGroupView(Context context, ViewGroup parent) {
return newChildView(context, parent);
}
@Override
protected View newChildView(Context context, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.call_log_list_item, parent, false);
findAndCacheViews(view);
return view;
}
@Override
protected void bindStandAloneView(View view, Context context, Cursor cursor) {
bindView(view, cursor, 1);
}
@Override
protected void bindChildView(View view, Context context, Cursor cursor) {
bindView(view, cursor, 1);
}
@Override
protected void bindGroupView(View view, Context context, Cursor cursor, int groupSize,
boolean expanded) {
bindView(view, cursor, groupSize);
}
private void findAndCacheViews(View view) {
// Get the views to bind to.
CallLogListItemViews views = CallLogListItemViews.fromView(view);
views.primaryActionView.setOnClickListener(mPrimaryActionListener);
views.secondaryActionView.setOnClickListener(mSecondaryActionListener);
view.setTag(views);
}
/**
* Binds the views in the entry to the data in the call log.
*
* @param view the view corresponding to this entry
* @param c the cursor pointing to the entry in the call log
* @param count the number of entries in the current item, greater than 1 if it is a group
*/
private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
+ } else {
+ views.primaryActionView.setTag(null);
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
protected void bindBadge(View view, ContactInfo info, PhoneCallDetails details, int callType) {
// Do not show badge in call log.
if (!mIsCallLog) {
final int numMissed = getNumMissedCalls(callType);
final ViewStub stub = (ViewStub) view.findViewById(R.id.link_stub);
if (shouldShowBadge(numMissed, info, details)) {
// stub will be null if it was already inflated.
if (stub != null) {
final View inflated = stub.inflate();
inflated.setVisibility(View.VISIBLE);
mBadgeContainer = inflated.findViewById(R.id.badge_link_container);
mBadgeImageView = (ImageView) inflated.findViewById(R.id.badge_image);
mBadgeText = (TextView) inflated.findViewById(R.id.badge_text);
}
mBadgeContainer.setOnClickListener(getBadgeClickListener());
mBadgeImageView.setImageResource(getBadgeImageResId());
mBadgeText.setText(getBadgeText(numMissed));
mNumMissedCallsShown = numMissed;
} else {
// Hide badge if it was previously shown.
if (stub == null) {
final View container = view.findViewById(R.id.badge_container);
if (container != null) {
container.setVisibility(View.GONE);
}
}
}
}
}
public void setMissedCalls(Cursor data) {
final int missed;
if (data == null) {
missed = 0;
} else {
missed = data.getCount();
}
// Only need to update if the number of calls changed.
if (missed != mNumMissedCalls) {
mNumMissedCalls = missed;
notifyDataSetChanged();
}
}
protected View.OnClickListener getBadgeClickListener() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(mContext, CallLogActivity.class);
mContext.startActivity(intent);
}
};
}
/**
* Get the resource id for the image to be shown for the badge.
*/
protected int getBadgeImageResId() {
return R.drawable.ic_call_log_blue;
}
/**
* Get the text to be shown for the badge.
*
* @param numMissed The number of missed calls.
*/
protected String getBadgeText(int numMissed) {
return mContext.getResources().getString(R.string.num_missed_calls, numMissed);
}
/**
* Whether to show the badge.
*
* @param numMissedCalls The number of missed calls.
* @param info The contact info.
* @param details The call detail.
* @return {@literal true} if badge should be shown. {@literal false} otherwise.
*/
protected boolean shouldShowBadge(int numMissedCalls, ContactInfo info,
PhoneCallDetails details) {
// Do not process if the data has not changed (optimization since bind view is called
// multiple times due to contact lookup).
if (numMissedCalls == mNumMissedCallsShown) {
return false;
}
return numMissedCalls > 0;
}
private int getNumMissedCalls(int callType) {
if (callType == Calls.MISSED_TYPE) {
// Exclude the current missed call shown in the shortcut.
return mNumMissedCalls - 1;
}
return mNumMissedCalls;
}
/** Checks whether the contact info from the call log matches the one from the contacts db. */
private boolean callLogInfoMatches(ContactInfo callLogInfo, ContactInfo info) {
// The call log only contains a subset of the fields in the contacts db.
// Only check those.
return TextUtils.equals(callLogInfo.name, info.name)
&& callLogInfo.type == info.type
&& TextUtils.equals(callLogInfo.label, info.label);
}
/** Stores the updated contact info in the call log if it is different from the current one. */
private void updateCallLogContactInfoCache(String number, String countryIso,
ContactInfo updatedInfo, ContactInfo callLogInfo) {
final ContentValues values = new ContentValues();
boolean needsUpdate = false;
if (callLogInfo != null) {
if (!TextUtils.equals(updatedInfo.name, callLogInfo.name)) {
values.put(Calls.CACHED_NAME, updatedInfo.name);
needsUpdate = true;
}
if (updatedInfo.type != callLogInfo.type) {
values.put(Calls.CACHED_NUMBER_TYPE, updatedInfo.type);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.label, callLogInfo.label)) {
values.put(Calls.CACHED_NUMBER_LABEL, updatedInfo.label);
needsUpdate = true;
}
if (!UriUtils.areEqual(updatedInfo.lookupUri, callLogInfo.lookupUri)) {
values.put(Calls.CACHED_LOOKUP_URI, UriUtils.uriToString(updatedInfo.lookupUri));
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.normalizedNumber, callLogInfo.normalizedNumber)) {
values.put(Calls.CACHED_NORMALIZED_NUMBER, updatedInfo.normalizedNumber);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.number, callLogInfo.number)) {
values.put(Calls.CACHED_MATCHED_NUMBER, updatedInfo.number);
needsUpdate = true;
}
if (updatedInfo.photoId != callLogInfo.photoId) {
values.put(Calls.CACHED_PHOTO_ID, updatedInfo.photoId);
needsUpdate = true;
}
if (!TextUtils.equals(updatedInfo.formattedNumber, callLogInfo.formattedNumber)) {
values.put(Calls.CACHED_FORMATTED_NUMBER, updatedInfo.formattedNumber);
needsUpdate = true;
}
} else {
// No previous values, store all of them.
values.put(Calls.CACHED_NAME, updatedInfo.name);
values.put(Calls.CACHED_NUMBER_TYPE, updatedInfo.type);
values.put(Calls.CACHED_NUMBER_LABEL, updatedInfo.label);
values.put(Calls.CACHED_LOOKUP_URI, UriUtils.uriToString(updatedInfo.lookupUri));
values.put(Calls.CACHED_MATCHED_NUMBER, updatedInfo.number);
values.put(Calls.CACHED_NORMALIZED_NUMBER, updatedInfo.normalizedNumber);
values.put(Calls.CACHED_PHOTO_ID, updatedInfo.photoId);
values.put(Calls.CACHED_FORMATTED_NUMBER, updatedInfo.formattedNumber);
needsUpdate = true;
}
if (!needsUpdate) return;
if (countryIso == null) {
mContext.getContentResolver().update(Calls.CONTENT_URI_WITH_VOICEMAIL, values,
Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " IS NULL",
new String[]{ number });
} else {
mContext.getContentResolver().update(Calls.CONTENT_URI_WITH_VOICEMAIL, values,
Calls.NUMBER + " = ? AND " + Calls.COUNTRY_ISO + " = ?",
new String[]{ number, countryIso });
}
}
/** Returns the contact information as stored in the call log. */
private ContactInfo getContactInfoFromCallLog(Cursor c) {
ContactInfo info = new ContactInfo();
info.lookupUri = UriUtils.parseUriOrNull(c.getString(CallLogQuery.CACHED_LOOKUP_URI));
info.name = c.getString(CallLogQuery.CACHED_NAME);
info.type = c.getInt(CallLogQuery.CACHED_NUMBER_TYPE);
info.label = c.getString(CallLogQuery.CACHED_NUMBER_LABEL);
String matchedNumber = c.getString(CallLogQuery.CACHED_MATCHED_NUMBER);
info.number = matchedNumber == null ? c.getString(CallLogQuery.NUMBER) : matchedNumber;
info.normalizedNumber = c.getString(CallLogQuery.CACHED_NORMALIZED_NUMBER);
info.photoId = c.getLong(CallLogQuery.CACHED_PHOTO_ID);
info.photoUri = null; // We do not cache the photo URI.
info.formattedNumber = c.getString(CallLogQuery.CACHED_FORMATTED_NUMBER);
return info;
}
/**
* Returns the call types for the given number of items in the cursor.
* <p>
* It uses the next {@code count} rows in the cursor to extract the types.
* <p>
* It position in the cursor is unchanged by this function.
*/
private int[] getCallTypes(Cursor cursor, int count) {
int position = cursor.getPosition();
int[] callTypes = new int[count];
for (int index = 0; index < count; ++index) {
callTypes[index] = cursor.getInt(CallLogQuery.CALL_TYPE);
cursor.moveToNext();
}
cursor.moveToPosition(position);
return callTypes;
}
private void setPhoto(CallLogListItemViews views, long photoId, Uri contactUri) {
mCurrentPhotoUri = null;
views.quickContactView.assignContactUri(contactUri);
mContactPhotoManager.loadThumbnail(views.quickContactView, photoId, false /* darkTheme */);
}
private void setPhoto(CallLogListItemViews views, Uri photoUri, Uri contactUri) {
if (photoUri.equals(mCurrentPhotoUri)) {
// photo manager will perform a fade in transition. To avoid flicker, do not set the
// same photo multiple times.
return;
}
mCurrentPhotoUri = photoUri;
views.quickContactView.assignContactUri(contactUri);
mContactPhotoManager.loadDirectoryPhoto(views.quickContactView, photoUri,
false /* darkTheme */);
}
/**
* Sets whether processing of requests for contact details should be enabled.
* <p>
* This method should be called in tests to disable such processing of requests when not
* needed.
*/
@VisibleForTesting
void disableRequestProcessingForTest() {
mRequestProcessingDisabled = true;
}
@VisibleForTesting
void injectContactInfoForTest(String number, String countryIso, ContactInfo contactInfo) {
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
mContactInfoCache.put(numberCountryIso, contactInfo);
}
@Override
public void addGroup(int cursorPosition, int size, boolean expanded) {
super.addGroup(cursorPosition, size, expanded);
}
/*
* Get the number from the Contacts, if available, since sometimes
* the number provided by caller id may not be formatted properly
* depending on the carrier (roaming) in use at the time of the
* incoming call.
* Logic : If the caller-id number starts with a "+", use it
* Else if the number in the contacts starts with a "+", use that one
* Else if the number in the contacts is longer, use that one
*/
public String getBetterNumberFromContacts(String number, String countryIso) {
String matchingNumber = null;
// Look in the cache first. If it's not found then query the Phones db
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ContactInfo ci = mContactInfoCache.getPossiblyExpired(numberCountryIso);
if (ci != null && ci != ContactInfo.EMPTY) {
matchingNumber = ci.number;
} else {
try {
Cursor phonesCursor = mContext.getContentResolver().query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, number),
PhoneQuery._PROJECTION, null, null, null);
if (phonesCursor != null) {
if (phonesCursor.moveToFirst()) {
matchingNumber = phonesCursor.getString(PhoneQuery.MATCHED_NUMBER);
}
phonesCursor.close();
}
} catch (Exception e) {
// Use the number from the call log
}
}
if (!TextUtils.isEmpty(matchingNumber) &&
(matchingNumber.startsWith("+")
|| matchingNumber.length() > number.length())) {
number = matchingNumber;
}
return number;
}
}
| true | true | private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
| private void bindView(View view, Cursor c, int count) {
final CallLogListItemViews views = (CallLogListItemViews) view.getTag();
// Default case: an item in the call log.
views.primaryActionView.setVisibility(View.VISIBLE);
views.listHeaderTextView.setVisibility(View.GONE);
final String number = c.getString(CallLogQuery.NUMBER);
final int numberPresentation = c.getInt(CallLogQuery.NUMBER_PRESENTATION);
final long date = c.getLong(CallLogQuery.DATE);
final long duration = c.getLong(CallLogQuery.DURATION);
final int callType = c.getInt(CallLogQuery.CALL_TYPE);
final String countryIso = c.getString(CallLogQuery.COUNTRY_ISO);
final ContactInfo cachedContactInfo = getContactInfoFromCallLog(c);
if (!mUseCallAsPrimaryAction) {
// Sets the primary action to open call detail page.
views.primaryActionView.setTag(
IntentProvider.getCallDetailIntentProvider(
getCursor(), c.getPosition(), c.getLong(CallLogQuery.ID), count));
} else if (PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)) {
// Sets the primary action to call the number.
views.primaryActionView.setTag(IntentProvider.getReturnCallIntentProvider(number));
} else {
views.primaryActionView.setTag(null);
}
// Store away the voicemail information so we can play it directly.
if (callType == Calls.VOICEMAIL_TYPE) {
String voicemailUri = c.getString(CallLogQuery.VOICEMAIL_URI);
final long rowId = c.getLong(CallLogQuery.ID);
views.secondaryActionView.setTag(
IntentProvider.getPlayVoicemailIntentProvider(rowId, voicemailUri));
} else if (!TextUtils.isEmpty(number)) {
// Store away the number so we can call it directly if you click on the call icon.
views.secondaryActionView.setTag(
IntentProvider.getReturnCallIntentProvider(number));
} else {
// No action enabled.
views.secondaryActionView.setTag(null);
}
// Lookup contacts with this number
NumberWithCountryIso numberCountryIso = new NumberWithCountryIso(number, countryIso);
ExpirableCache.CachedValue<ContactInfo> cachedInfo =
mContactInfoCache.getCachedValue(numberCountryIso);
ContactInfo info = cachedInfo == null ? null : cachedInfo.getValue();
if (!PhoneNumberUtilsWrapper.canPlaceCallsTo(number, numberPresentation)
|| new PhoneNumberUtilsWrapper().isVoicemailNumber(number)) {
// If this is a number that cannot be dialed, there is no point in looking up a contact
// for it.
info = ContactInfo.EMPTY;
} else if (cachedInfo == null) {
mContactInfoCache.put(numberCountryIso, ContactInfo.EMPTY);
// Use the cached contact info from the call log.
info = cachedContactInfo;
// The db request should happen on a non-UI thread.
// Request the contact details immediately since they are currently missing.
enqueueRequest(number, countryIso, cachedContactInfo, true);
// We will format the phone number when we make the background request.
} else {
if (cachedInfo.isExpired()) {
// The contact info is no longer up to date, we should request it. However, we
// do not need to request them immediately.
enqueueRequest(number, countryIso, cachedContactInfo, false);
} else if (!callLogInfoMatches(cachedContactInfo, info)) {
// The call log information does not match the one we have, look it up again.
// We could simply update the call log directly, but that needs to be done in a
// background thread, so it is easier to simply request a new lookup, which will, as
// a side-effect, update the call log.
enqueueRequest(number, countryIso, cachedContactInfo, false);
}
if (info == ContactInfo.EMPTY) {
// Use the cached contact info from the call log.
info = cachedContactInfo;
}
}
final Uri lookupUri = info.lookupUri;
final String name = info.name;
final int ntype = info.type;
final String label = info.label;
final long photoId = info.photoId;
final Uri photoUri = info.photoUri;
CharSequence formattedNumber = info.formattedNumber;
final int[] callTypes = getCallTypes(c, count);
final String geocode = c.getString(CallLogQuery.GEOCODED_LOCATION);
final PhoneCallDetails details;
if (TextUtils.isEmpty(name)) {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration);
} else {
details = new PhoneCallDetails(number, numberPresentation,
formattedNumber, countryIso, geocode, callTypes, date,
duration, name, ntype, label, lookupUri, photoUri);
}
final boolean isNew = c.getInt(CallLogQuery.IS_READ) == 0;
// New items also use the highlighted version of the text.
final boolean isHighlighted = isNew;
mCallLogViewsHelper.setPhoneCallDetails(views, details, isHighlighted,
mUseCallAsPrimaryAction);
if (photoId == 0 && photoUri != null) {
setPhoto(views, photoUri, lookupUri);
} else {
setPhoto(views, photoId, lookupUri);
}
views.quickContactView.setContentDescription(views.phoneCallDetailsViews.nameView.
getText());
// Listen for the first draw
if (mViewTreeObserver == null) {
mViewTreeObserver = view.getViewTreeObserver();
mViewTreeObserver.addOnPreDrawListener(this);
}
bindBadge(view, info, details, callType);
}
|
diff --git a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java
index 7b2fee14..b3d420e8 100644
--- a/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java
+++ b/framework/src/play/server/ssl/SslHttpServerPipelineFactory.java
@@ -1,93 +1,93 @@
package play.server.ssl;
import javax.net.ssl.SSLEngine;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import play.Play;
import play.server.FlashPolicyHandler;
import play.server.PlayHandler;
import play.server.StreamChunkAggregator;
import play.server.HttpServerPipelineFactory;
import org.jboss.netty.channel.ChannelHandler;
import play.Logger;
import play.server.Server;
import static org.jboss.netty.channel.Channels.pipeline;
public class SslHttpServerPipelineFactory extends HttpServerPipelineFactory {
private String pipelineConfig = Play.configuration.getProperty("play.ssl.netty.pipeline", "play.server.FlashPolicyHandler,org.jboss.netty.handler.codec.http.HttpRequestDecoder,play.server.StreamChunkAggregator,org.jboss.netty.handler.codec.http.HttpResponseEncoder,org.jboss.netty.handler.stream.ChunkedWriteHandler,play.server.ssl.SslPlayHandler");
public ChannelPipeline getPipeline() throws Exception {
String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");
String enabledCiphers = Play.configuration.getProperty("play.ssl.enabledCiphers", "");
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
if (enabledCiphers != null && enabledCiphers.length() > 0) {
engine.setEnabledCipherSuites(enabledCiphers.replaceAll(" ", "").split(","));
}
if ("want".equalsIgnoreCase(mode)) {
engine.setWantClientAuth(true);
} else if ("need".equalsIgnoreCase(mode)) {
engine.setNeedClientAuth(true);
}
engine.setEnableSessionCreation(true);
pipeline.addLast("ssl", new SslHandler(engine));
// Get all the pipeline. Give the user the opportunity to add their own
String[] handlers = pipelineConfig.split(",");
if(handlers.length <= 0){
Logger.error("You must defined at least the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
// Create the play Handler (always the last one)
String handler = handlers[handlers.length - 1];
ChannelHandler instance = getInstance(handler);
SslPlayHandler sslPlayHandler = (SslPlayHandler) instance;
- if (instance == null || !(instance instanceof SslPlayHandler) || sslPlayHandler != null) {
+ if (instance == null || !(instance instanceof SslPlayHandler) || sslPlayHandler == null) {
Logger.error("The last handler must be the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
for (int i = 0; i < handlers.length - 1; i++) {
handler = handlers[i];
try {
String name = getName(handler.trim());
instance = getInstance(handler);
if (instance != null) {
pipeline.addLast(name, instance);
sslPlayHandler.pipelines.put("Ssl" + name, instance);
}
} catch(Throwable e) {
Logger.error(" error adding " + handler, e);
}
}
if (sslPlayHandler != null) {
- pipeline.addLast("handler", instance);
- sslPlayHandler.pipelines.put("SslHandler", instance);
+ pipeline.addLast("handler", sslPlayHandler);
+ sslPlayHandler.pipelines.put("SslHandler", sslPlayHandler);
}
return pipeline;
}
}
| false | true | public ChannelPipeline getPipeline() throws Exception {
String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");
String enabledCiphers = Play.configuration.getProperty("play.ssl.enabledCiphers", "");
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
if (enabledCiphers != null && enabledCiphers.length() > 0) {
engine.setEnabledCipherSuites(enabledCiphers.replaceAll(" ", "").split(","));
}
if ("want".equalsIgnoreCase(mode)) {
engine.setWantClientAuth(true);
} else if ("need".equalsIgnoreCase(mode)) {
engine.setNeedClientAuth(true);
}
engine.setEnableSessionCreation(true);
pipeline.addLast("ssl", new SslHandler(engine));
// Get all the pipeline. Give the user the opportunity to add their own
String[] handlers = pipelineConfig.split(",");
if(handlers.length <= 0){
Logger.error("You must defined at least the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
// Create the play Handler (always the last one)
String handler = handlers[handlers.length - 1];
ChannelHandler instance = getInstance(handler);
SslPlayHandler sslPlayHandler = (SslPlayHandler) instance;
if (instance == null || !(instance instanceof SslPlayHandler) || sslPlayHandler != null) {
Logger.error("The last handler must be the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
for (int i = 0; i < handlers.length - 1; i++) {
handler = handlers[i];
try {
String name = getName(handler.trim());
instance = getInstance(handler);
if (instance != null) {
pipeline.addLast(name, instance);
sslPlayHandler.pipelines.put("Ssl" + name, instance);
}
} catch(Throwable e) {
Logger.error(" error adding " + handler, e);
}
}
if (sslPlayHandler != null) {
pipeline.addLast("handler", instance);
sslPlayHandler.pipelines.put("SslHandler", instance);
}
return pipeline;
}
| public ChannelPipeline getPipeline() throws Exception {
String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");
String enabledCiphers = Play.configuration.getProperty("play.ssl.enabledCiphers", "");
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
if (enabledCiphers != null && enabledCiphers.length() > 0) {
engine.setEnabledCipherSuites(enabledCiphers.replaceAll(" ", "").split(","));
}
if ("want".equalsIgnoreCase(mode)) {
engine.setWantClientAuth(true);
} else if ("need".equalsIgnoreCase(mode)) {
engine.setNeedClientAuth(true);
}
engine.setEnableSessionCreation(true);
pipeline.addLast("ssl", new SslHandler(engine));
// Get all the pipeline. Give the user the opportunity to add their own
String[] handlers = pipelineConfig.split(",");
if(handlers.length <= 0){
Logger.error("You must defined at least the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
// Create the play Handler (always the last one)
String handler = handlers[handlers.length - 1];
ChannelHandler instance = getInstance(handler);
SslPlayHandler sslPlayHandler = (SslPlayHandler) instance;
if (instance == null || !(instance instanceof SslPlayHandler) || sslPlayHandler == null) {
Logger.error("The last handler must be the SslPlayHandler in \"play.netty.pipeline\"");
return pipeline;
}
for (int i = 0; i < handlers.length - 1; i++) {
handler = handlers[i];
try {
String name = getName(handler.trim());
instance = getInstance(handler);
if (instance != null) {
pipeline.addLast(name, instance);
sslPlayHandler.pipelines.put("Ssl" + name, instance);
}
} catch(Throwable e) {
Logger.error(" error adding " + handler, e);
}
}
if (sslPlayHandler != null) {
pipeline.addLast("handler", sslPlayHandler);
sslPlayHandler.pipelines.put("SslHandler", sslPlayHandler);
}
return pipeline;
}
|
diff --git a/src/main/java/servlet/MyDataServlet.java b/src/main/java/servlet/MyDataServlet.java
index 18bd573..98e6647 100644
--- a/src/main/java/servlet/MyDataServlet.java
+++ b/src/main/java/servlet/MyDataServlet.java
@@ -1,191 +1,191 @@
package main.java.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@WebServlet(
name = "MyDataServlet",
urlPatterns = {"/mydata"}
)
public class MyDataServlet extends HttpServlet {
// Database Connection
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user_id = request.getParameter("user_id");
UserData userData = getData(user_id);
//Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
Gson gson = new Gson();
String json = gson.toJson(userData);
//System.out.println(json);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
private UserData getData(String user_id) {
UserData data = new UserData(user_id);
List<Hub> hubs = data.hubs;
try {
Connection connection = DbManager.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM hubs WHERE users_user_id = '" + user_id + "'");
while (rs.next()) {
Integer hub_id = rs.getInt("hub_id");
String name = rs.getString("name");
String api_key = rs.getString("api_key");
Integer pan_id = rs.getInt("pan_id");
- hubs.add(new Hub(hub_id, name, api_key, pan_id));
+ hubs.add(new Hub(hub_id, api_key, name, pan_id));
}
rs.close();
stmt.close();
List<Node> nodes = new ArrayList<Node> ();
for (Hub hub:hubs) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM nodes WHERE hubs_hub_id = '" + hub.hub_id + "'");
while (rs.next()) {
Integer node_id = rs.getInt("node_id");
String address = rs.getString("address");
String name = rs.getString("name");
String type = rs.getString("type");
Node node = new Node(node_id, address, name, type);
hub.nodes.add(node);
nodes.add(node);
}
rs.close();
stmt.close();
}
List<Pin> pins = new ArrayList<Pin> ();
for (Node node:nodes) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pins WHERE nodes_node_id = '" + node.node_id + "'");
while (rs.next()) {
Integer pin_id = rs.getInt("pin_id");
String data_type = rs.getString("data_type");
String name = rs.getString("name");
Pin pin = new Pin(pin_id, data_type, name);
node.pins.add(pin);
pins.add(pin);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM tags WHERE pins_pin_id = '" + pin.pin_id + "'");
while (rs.next()) {
String tag = rs.getString("tag");
Tag t = new Tag(tag);
pin.tags.add(t);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pin_data WHERE pins_pin_id = '" + pin.pin_id + "' ORDER BY time");
while (rs.next()) {
Timestamp time = rs.getTimestamp("time");
String pin_type = rs.getString("pin_type");
String pin_value = rs.getString("pin_value");
PinData pinData = new PinData(time, pin_type, pin_value);
pin.pin_data.add(pinData);
}
}
} catch (SQLException e) {
return null;
} catch (URISyntaxException e) {
return null;
}
return data;
}
class UserData {
public String user_id;
public List<Hub> hubs = new ArrayList<Hub>();
public UserData(String user_id) {
this.user_id = user_id;
}
}
class Hub {
public Integer hub_id;
public String api_key;
public String name;
public Integer pan_id;
public List<Node> nodes = new ArrayList<Node>();
public Hub(Integer hub_id, String api_key, String name, Integer pan_id) {
this.hub_id = hub_id;
this.api_key = api_key;
this.name = name;
this.pan_id = pan_id;
}
}
class Node {
public Integer node_id;
public String address;
public String name;
public String type;
public List<Pin> pins = new ArrayList<Pin> ();
public Node(Integer node_id, String address, String name, String type) {
this.node_id = node_id;
this.address = address;
this.name = name;
this.type = type;
}
}
class Pin {
public Integer pin_id;
public String data_type;
public String name;
public List<Tag> tags = new ArrayList<Tag> ();
public List<PinData> pin_data = new ArrayList<PinData> ();
public Pin(Integer pin_id, String data_type, String name) {
this.pin_id = pin_id;
this.data_type = data_type;
this.name = name;
}
}
class Tag {
public String tag;
public Tag(String tag) {
this.tag = tag;
}
}
class PinData {
public Timestamp time;
public String pin_value;
public String pin_type;
public PinData(Timestamp time, String pin_value, String pin_type) {
this.time = time;
this.pin_value = pin_value;
this.pin_type = pin_type;
}
}
};
| true | true | private UserData getData(String user_id) {
UserData data = new UserData(user_id);
List<Hub> hubs = data.hubs;
try {
Connection connection = DbManager.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM hubs WHERE users_user_id = '" + user_id + "'");
while (rs.next()) {
Integer hub_id = rs.getInt("hub_id");
String name = rs.getString("name");
String api_key = rs.getString("api_key");
Integer pan_id = rs.getInt("pan_id");
hubs.add(new Hub(hub_id, name, api_key, pan_id));
}
rs.close();
stmt.close();
List<Node> nodes = new ArrayList<Node> ();
for (Hub hub:hubs) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM nodes WHERE hubs_hub_id = '" + hub.hub_id + "'");
while (rs.next()) {
Integer node_id = rs.getInt("node_id");
String address = rs.getString("address");
String name = rs.getString("name");
String type = rs.getString("type");
Node node = new Node(node_id, address, name, type);
hub.nodes.add(node);
nodes.add(node);
}
rs.close();
stmt.close();
}
List<Pin> pins = new ArrayList<Pin> ();
for (Node node:nodes) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pins WHERE nodes_node_id = '" + node.node_id + "'");
while (rs.next()) {
Integer pin_id = rs.getInt("pin_id");
String data_type = rs.getString("data_type");
String name = rs.getString("name");
Pin pin = new Pin(pin_id, data_type, name);
node.pins.add(pin);
pins.add(pin);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM tags WHERE pins_pin_id = '" + pin.pin_id + "'");
while (rs.next()) {
String tag = rs.getString("tag");
Tag t = new Tag(tag);
pin.tags.add(t);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pin_data WHERE pins_pin_id = '" + pin.pin_id + "' ORDER BY time");
while (rs.next()) {
Timestamp time = rs.getTimestamp("time");
String pin_type = rs.getString("pin_type");
String pin_value = rs.getString("pin_value");
PinData pinData = new PinData(time, pin_type, pin_value);
pin.pin_data.add(pinData);
}
}
} catch (SQLException e) {
return null;
} catch (URISyntaxException e) {
return null;
}
return data;
}
| private UserData getData(String user_id) {
UserData data = new UserData(user_id);
List<Hub> hubs = data.hubs;
try {
Connection connection = DbManager.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM hubs WHERE users_user_id = '" + user_id + "'");
while (rs.next()) {
Integer hub_id = rs.getInt("hub_id");
String name = rs.getString("name");
String api_key = rs.getString("api_key");
Integer pan_id = rs.getInt("pan_id");
hubs.add(new Hub(hub_id, api_key, name, pan_id));
}
rs.close();
stmt.close();
List<Node> nodes = new ArrayList<Node> ();
for (Hub hub:hubs) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM nodes WHERE hubs_hub_id = '" + hub.hub_id + "'");
while (rs.next()) {
Integer node_id = rs.getInt("node_id");
String address = rs.getString("address");
String name = rs.getString("name");
String type = rs.getString("type");
Node node = new Node(node_id, address, name, type);
hub.nodes.add(node);
nodes.add(node);
}
rs.close();
stmt.close();
}
List<Pin> pins = new ArrayList<Pin> ();
for (Node node:nodes) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pins WHERE nodes_node_id = '" + node.node_id + "'");
while (rs.next()) {
Integer pin_id = rs.getInt("pin_id");
String data_type = rs.getString("data_type");
String name = rs.getString("name");
Pin pin = new Pin(pin_id, data_type, name);
node.pins.add(pin);
pins.add(pin);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM tags WHERE pins_pin_id = '" + pin.pin_id + "'");
while (rs.next()) {
String tag = rs.getString("tag");
Tag t = new Tag(tag);
pin.tags.add(t);
}
rs.close();
stmt.close();
}
for (Pin pin:pins) {
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT * FROM pin_data WHERE pins_pin_id = '" + pin.pin_id + "' ORDER BY time");
while (rs.next()) {
Timestamp time = rs.getTimestamp("time");
String pin_type = rs.getString("pin_type");
String pin_value = rs.getString("pin_value");
PinData pinData = new PinData(time, pin_type, pin_value);
pin.pin_data.add(pinData);
}
}
} catch (SQLException e) {
return null;
} catch (URISyntaxException e) {
return null;
}
return data;
}
|
diff --git a/src/demos/GLNewtRun.java b/src/demos/GLNewtRun.java
index a1b22e3..c981012 100755
--- a/src/demos/GLNewtRun.java
+++ b/src/demos/GLNewtRun.java
@@ -1,256 +1,256 @@
package demos;
import java.lang.reflect.*;
import javax.media.opengl.*;
import javax.media.nativewindow.*;
import com.jogamp.newt.*;
import com.jogamp.newt.event.*;
import com.jogamp.newt.opengl.*;
public class GLNewtRun implements WindowListener, KeyListener, MouseListener {
static GLWindow window;
static volatile boolean quit = false;
public void windowResized(WindowEvent e) { }
public void windowMoved(WindowEvent e) { }
public void windowGainedFocus(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowDestroyNotify(WindowEvent e) {
quit = true;
}
static int dx=0;
static int dy=0;
static int dw=0;
static int dh=0;
public void keyPressed(KeyEvent e) {
System.out.println(e);
if(e.getKeyChar()=='f') {
window.setFullscreen(!window.isFullscreen());
} else if(e.getKeyChar()=='q') {
quit = true;
} else if(e.getKeyChar()=='p') {
int x = window.getX() + dx;
int y = window.getY() + dy;
System.out.println("Reset Pos "+x+"/"+y);
window.setPosition(x, y);
} else if(e.getKeyChar()=='s') {
int w = window.getWidth() + dw;
int h = window.getHeight() + dh;
System.out.println("Reset Size "+w+"x"+h);
window.setSize(w, h);
}
}
public void keyReleased(KeyEvent e) {
System.out.println(e);
}
public void keyTyped(KeyEvent e) {
System.out.println(e);
}
public void mouseClicked(MouseEvent e) {
System.out.println(" mouseevent: "+e);
switch(e.getClickCount()) {
case 1:
if(e.getButton()>MouseEvent.BUTTON1) {
window.setFullscreen(!window.isFullscreen());
}
break;
default:
quit=true;
break;
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseWheelMoved(MouseEvent e) {
}
public boolean shouldQuit() { return quit; }
public static int str2int(String str, int def) {
try {
return Integer.parseInt(str);
} catch (Exception ex) { ex.printStackTrace(); }
return def;
}
public static boolean setField(Object instance, String fieldName, Object value) {
try {
Field f = instance.getClass().getField(fieldName);
if(f.getType().isInstance(value)) {
f.set(instance, value);
return true;
} else {
System.out.println(instance.getClass()+" '"+fieldName+"' field not assignable with "+value.getClass()+", it's a: "+f.getType());
}
} catch (NoSuchFieldException nsfe) {
System.out.println(instance.getClass()+" has no '"+fieldName+"' field");
} catch (Throwable t) {
t.printStackTrace();
}
return false;
}
public static void main(String[] args) {
boolean parented = false;
boolean useAWTTestFrame = false;
boolean useAWT = false;
boolean undecorated = false;
boolean fullscreen = false;
int x_p = 0;
int y_p = 0;
int x = 0;
int y = 0;
int width = 800;
int height = 480;
String glProfileStr = null;
if(0==args.length) {
throw new RuntimeException("Usage: "+GLNewtRun.class+" <demo class name (GLEventListener)>");
}
GLNewtRun listener = new GLNewtRun();
int i=0;
while(i<args.length-1) {
if(args[i].equals("-awt")) {
useAWT = true;
} else if(args[i].equals("-awttestframe")) {
useAWT = true;
useAWTTestFrame = true;
} else if(args[i].equals("-undecorated")) {
undecorated = true;
} else if(args[i].equals("-parented")) {
parented = true;
} else if(args[i].equals("-fs")) {
fullscreen = true;
} else if(args[i].equals("-xp")) {
i++;
x_p = str2int(args[i], x_p);
} else if(args[i].equals("-yp")) {
i++;
y_p = str2int(args[i], y_p);
} else if(args[i].equals("-x")) {
i++;
x = str2int(args[i], x);
} else if(args[i].equals("-y")) {
i++;
y = str2int(args[i], y);
} else if(args[i].equals("-width")) {
i++;
width = str2int(args[i], width);
} else if(args[i].equals("-height")) {
i++;
height = str2int(args[i], height);
} else if(args[i].startsWith("-GL")) {
glProfileStr = args[i].substring(1);
} else if(args[i].equals("-dx")) {
i++;
dx = str2int(args[i], dx);
} else if(args[i].equals("-dy")) {
i++;
dy = str2int(args[i], dy);
} else if(args[i].equals("-dw")) {
i++;
dw = str2int(args[i], dw);
} else if(args[i].equals("-dh")) {
i++;
dh = str2int(args[i], dh);
}
i++;
}
String demoClassName = args[i];
Object demoObject = null;
try {
Class demoClazz = Class.forName(demoClassName);
demoObject = demoClazz.newInstance();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException("Error while instantiating demo: "+demoClassName);
}
if( !(demoObject instanceof GLEventListener) ) {
throw new RuntimeException("Not a GLEventListener: "+demoClassName);
}
GLEventListener demo = (GLEventListener) demoObject;
GLProfile glp = GLProfile.get(glProfileStr);
try {
GLCapabilities caps = new GLCapabilities(glp);
NewtFactory.setUseEDT(true);
Window nWindow = null;
if(useAWT) {
Display nDisplay = NewtFactory.createDisplay(NativeWindowFactory.TYPE_AWT, null); // local display
Screen nScreen = NewtFactory.createScreen(NativeWindowFactory.TYPE_AWT, nDisplay, 0); // screen 0
if(useAWTTestFrame) {
java.awt.MenuBar menuTest = new java.awt.MenuBar();
menuTest.add(new java.awt.Menu("External Frame Test - Menu"));
java.awt.Frame frame = new java.awt.Frame("External Frame Test");
frame.setMenuBar(menuTest);
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, new Object[] { frame }, nScreen, caps, undecorated);
} else {
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, nScreen, caps, undecorated);
}
} else {
Display nDisplay = NewtFactory.createDisplay(null); // local display
Screen nScreen = NewtFactory.createScreen(nDisplay, 0); // screen 0
if(parented) {
Window parent = NewtFactory.createWindow(nScreen, caps, undecorated);
parent.setPosition(x_p, y_p);
parent.setSize(width+width/10, height+height/10);
parent.setVisible(true);
- nWindow = NewtFactory.createWindow(parent.getWindowHandle(), nScreen, caps, undecorated);
+ nWindow = NewtFactory.createWindow(parent, nScreen, caps);
} else {
nWindow = NewtFactory.createWindow(nScreen, caps, undecorated);
}
}
window = GLWindow.create(nWindow);
if(!setField(demo, "window", window)) {
setField(demo, "glWindow", window);
}
window.addWindowListener(listener);
window.addMouseListener(listener);
window.addKeyListener(listener);
window.addGLEventListener(demo);
window.setPosition(x, y);
window.setSize(width, height);
window.setFullscreen(fullscreen);
// Size OpenGL to Video Surface
window.setVisible(true);
window.enablePerfLog(true);
do {
window.display();
} while (!quit && window.getDuration() < 20000) ;
window.destroy();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
boolean parented = false;
boolean useAWTTestFrame = false;
boolean useAWT = false;
boolean undecorated = false;
boolean fullscreen = false;
int x_p = 0;
int y_p = 0;
int x = 0;
int y = 0;
int width = 800;
int height = 480;
String glProfileStr = null;
if(0==args.length) {
throw new RuntimeException("Usage: "+GLNewtRun.class+" <demo class name (GLEventListener)>");
}
GLNewtRun listener = new GLNewtRun();
int i=0;
while(i<args.length-1) {
if(args[i].equals("-awt")) {
useAWT = true;
} else if(args[i].equals("-awttestframe")) {
useAWT = true;
useAWTTestFrame = true;
} else if(args[i].equals("-undecorated")) {
undecorated = true;
} else if(args[i].equals("-parented")) {
parented = true;
} else if(args[i].equals("-fs")) {
fullscreen = true;
} else if(args[i].equals("-xp")) {
i++;
x_p = str2int(args[i], x_p);
} else if(args[i].equals("-yp")) {
i++;
y_p = str2int(args[i], y_p);
} else if(args[i].equals("-x")) {
i++;
x = str2int(args[i], x);
} else if(args[i].equals("-y")) {
i++;
y = str2int(args[i], y);
} else if(args[i].equals("-width")) {
i++;
width = str2int(args[i], width);
} else if(args[i].equals("-height")) {
i++;
height = str2int(args[i], height);
} else if(args[i].startsWith("-GL")) {
glProfileStr = args[i].substring(1);
} else if(args[i].equals("-dx")) {
i++;
dx = str2int(args[i], dx);
} else if(args[i].equals("-dy")) {
i++;
dy = str2int(args[i], dy);
} else if(args[i].equals("-dw")) {
i++;
dw = str2int(args[i], dw);
} else if(args[i].equals("-dh")) {
i++;
dh = str2int(args[i], dh);
}
i++;
}
String demoClassName = args[i];
Object demoObject = null;
try {
Class demoClazz = Class.forName(demoClassName);
demoObject = demoClazz.newInstance();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException("Error while instantiating demo: "+demoClassName);
}
if( !(demoObject instanceof GLEventListener) ) {
throw new RuntimeException("Not a GLEventListener: "+demoClassName);
}
GLEventListener demo = (GLEventListener) demoObject;
GLProfile glp = GLProfile.get(glProfileStr);
try {
GLCapabilities caps = new GLCapabilities(glp);
NewtFactory.setUseEDT(true);
Window nWindow = null;
if(useAWT) {
Display nDisplay = NewtFactory.createDisplay(NativeWindowFactory.TYPE_AWT, null); // local display
Screen nScreen = NewtFactory.createScreen(NativeWindowFactory.TYPE_AWT, nDisplay, 0); // screen 0
if(useAWTTestFrame) {
java.awt.MenuBar menuTest = new java.awt.MenuBar();
menuTest.add(new java.awt.Menu("External Frame Test - Menu"));
java.awt.Frame frame = new java.awt.Frame("External Frame Test");
frame.setMenuBar(menuTest);
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, new Object[] { frame }, nScreen, caps, undecorated);
} else {
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, nScreen, caps, undecorated);
}
} else {
Display nDisplay = NewtFactory.createDisplay(null); // local display
Screen nScreen = NewtFactory.createScreen(nDisplay, 0); // screen 0
if(parented) {
Window parent = NewtFactory.createWindow(nScreen, caps, undecorated);
parent.setPosition(x_p, y_p);
parent.setSize(width+width/10, height+height/10);
parent.setVisible(true);
nWindow = NewtFactory.createWindow(parent.getWindowHandle(), nScreen, caps, undecorated);
} else {
nWindow = NewtFactory.createWindow(nScreen, caps, undecorated);
}
}
window = GLWindow.create(nWindow);
if(!setField(demo, "window", window)) {
setField(demo, "glWindow", window);
}
window.addWindowListener(listener);
window.addMouseListener(listener);
window.addKeyListener(listener);
window.addGLEventListener(demo);
window.setPosition(x, y);
window.setSize(width, height);
window.setFullscreen(fullscreen);
// Size OpenGL to Video Surface
window.setVisible(true);
window.enablePerfLog(true);
do {
window.display();
} while (!quit && window.getDuration() < 20000) ;
window.destroy();
} catch (Throwable t) {
t.printStackTrace();
}
}
| public static void main(String[] args) {
boolean parented = false;
boolean useAWTTestFrame = false;
boolean useAWT = false;
boolean undecorated = false;
boolean fullscreen = false;
int x_p = 0;
int y_p = 0;
int x = 0;
int y = 0;
int width = 800;
int height = 480;
String glProfileStr = null;
if(0==args.length) {
throw new RuntimeException("Usage: "+GLNewtRun.class+" <demo class name (GLEventListener)>");
}
GLNewtRun listener = new GLNewtRun();
int i=0;
while(i<args.length-1) {
if(args[i].equals("-awt")) {
useAWT = true;
} else if(args[i].equals("-awttestframe")) {
useAWT = true;
useAWTTestFrame = true;
} else if(args[i].equals("-undecorated")) {
undecorated = true;
} else if(args[i].equals("-parented")) {
parented = true;
} else if(args[i].equals("-fs")) {
fullscreen = true;
} else if(args[i].equals("-xp")) {
i++;
x_p = str2int(args[i], x_p);
} else if(args[i].equals("-yp")) {
i++;
y_p = str2int(args[i], y_p);
} else if(args[i].equals("-x")) {
i++;
x = str2int(args[i], x);
} else if(args[i].equals("-y")) {
i++;
y = str2int(args[i], y);
} else if(args[i].equals("-width")) {
i++;
width = str2int(args[i], width);
} else if(args[i].equals("-height")) {
i++;
height = str2int(args[i], height);
} else if(args[i].startsWith("-GL")) {
glProfileStr = args[i].substring(1);
} else if(args[i].equals("-dx")) {
i++;
dx = str2int(args[i], dx);
} else if(args[i].equals("-dy")) {
i++;
dy = str2int(args[i], dy);
} else if(args[i].equals("-dw")) {
i++;
dw = str2int(args[i], dw);
} else if(args[i].equals("-dh")) {
i++;
dh = str2int(args[i], dh);
}
i++;
}
String demoClassName = args[i];
Object demoObject = null;
try {
Class demoClazz = Class.forName(demoClassName);
demoObject = demoClazz.newInstance();
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException("Error while instantiating demo: "+demoClassName);
}
if( !(demoObject instanceof GLEventListener) ) {
throw new RuntimeException("Not a GLEventListener: "+demoClassName);
}
GLEventListener demo = (GLEventListener) demoObject;
GLProfile glp = GLProfile.get(glProfileStr);
try {
GLCapabilities caps = new GLCapabilities(glp);
NewtFactory.setUseEDT(true);
Window nWindow = null;
if(useAWT) {
Display nDisplay = NewtFactory.createDisplay(NativeWindowFactory.TYPE_AWT, null); // local display
Screen nScreen = NewtFactory.createScreen(NativeWindowFactory.TYPE_AWT, nDisplay, 0); // screen 0
if(useAWTTestFrame) {
java.awt.MenuBar menuTest = new java.awt.MenuBar();
menuTest.add(new java.awt.Menu("External Frame Test - Menu"));
java.awt.Frame frame = new java.awt.Frame("External Frame Test");
frame.setMenuBar(menuTest);
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, new Object[] { frame }, nScreen, caps, undecorated);
} else {
nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, nScreen, caps, undecorated);
}
} else {
Display nDisplay = NewtFactory.createDisplay(null); // local display
Screen nScreen = NewtFactory.createScreen(nDisplay, 0); // screen 0
if(parented) {
Window parent = NewtFactory.createWindow(nScreen, caps, undecorated);
parent.setPosition(x_p, y_p);
parent.setSize(width+width/10, height+height/10);
parent.setVisible(true);
nWindow = NewtFactory.createWindow(parent, nScreen, caps);
} else {
nWindow = NewtFactory.createWindow(nScreen, caps, undecorated);
}
}
window = GLWindow.create(nWindow);
if(!setField(demo, "window", window)) {
setField(demo, "glWindow", window);
}
window.addWindowListener(listener);
window.addMouseListener(listener);
window.addKeyListener(listener);
window.addGLEventListener(demo);
window.setPosition(x, y);
window.setSize(width, height);
window.setFullscreen(fullscreen);
// Size OpenGL to Video Surface
window.setVisible(true);
window.enablePerfLog(true);
do {
window.display();
} while (!quit && window.getDuration() < 20000) ;
window.destroy();
} catch (Throwable t) {
t.printStackTrace();
}
}
|
diff --git a/displaytag/src/main/java/org/displaytag/tags/ColumnTag.java b/displaytag/src/main/java/org/displaytag/tags/ColumnTag.java
index 7203498..f0655b9 100644
--- a/displaytag/src/main/java/org/displaytag/tags/ColumnTag.java
+++ b/displaytag/src/main/java/org/displaytag/tags/ColumnTag.java
@@ -1,718 +1,718 @@
package org.displaytag.tags;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.displaytag.decorator.DecoratorFactory;
import org.displaytag.exception.MissingAttributeException;
import org.displaytag.exception.TagStructureException;
import org.displaytag.export.MediaTypeEnum;
import org.displaytag.model.Cell;
import org.displaytag.model.HeaderCell;
import org.displaytag.util.Href;
import org.displaytag.util.HtmlAttributeMap;
import org.displaytag.util.MultipleHtmlAttribute;
import org.displaytag.util.TagConstants;
/**
* <p>
* This tag works hand in hand with the TableTag to display a list of objects. This describes a column of data in the
* TableTag. There can be any number of columns that make up the list.
* </p>
* <p>
* This tag does no work itself, it is simply a container of information. The TableTag does all the work based on the
* information provided in the attributes of this tag.
* <p>
* @author mraible
* @version $Revision$ ($Author$)
*/
public class ColumnTag extends BodyTagSupport
{
/**
* logger.
*/
private static Log log = LogFactory.getLog(ColumnTag.class);
/**
* html pass-through attributes for cells.
*/
private HtmlAttributeMap attributeMap = new HtmlAttributeMap();
/**
* html pass-through attributes for cell headers.
*/
private HtmlAttributeMap headerAttributeMap = new HtmlAttributeMap();
/**
* the property method that is called to retrieve the information to be displayed in this column. This method is
* called on the current object in the iteration for the given row. The property format is in typical struts format
* for properties (required)
*/
private String property;
/**
* the title displayed for this column. if this is omitted then the property name is used for the title of the
* column (optional).
*/
private String title;
/**
* by default, null values don't appear in the list, by setting viewNulls to 'true', then null values will appear
* as "null" in the list (mostly useful for debugging) (optional).
*/
private boolean nulls;
/**
* is the column sortable?
*/
private boolean sortable;
/**
* if set to true, then any email addresses and URLs found in the content of the column are automatically converted
* into a hypertext link.
*/
private boolean autolink;
/**
* the grouping level (starting at 1 and incrementing) of this column (indicates if successive contain the same
* values, then they should not be displayed). The level indicates that if a lower level no longer matches, then
* the matching for this higher level should start over as well. If this attribute is not included, then no
* grouping is performed. (optional)
*/
private int group = -1;
/**
* if this attribute is provided, then the data that is shown for this column is wrapped inside a <a href>
* tag with the url provided through this attribute. Typically you would use this attribute along with one of the
* struts-like param attributes below to create a dynamic link so that each row creates a different URL based on
* the data that is being viewed. (optional)
*/
private Href href;
/**
* The name of the request parameter that will be dynamically added to the generated href URL. The corresponding
* value is defined by the paramProperty and (optional) paramName attributes, optionally scoped by the paramScope
* attribute. (optional)
*/
private String paramId;
/**
* The name of a JSP bean that is a String containing the value for the request parameter named by paramId (if
* paramProperty is not specified), or a JSP bean whose property getter is called to return a String (if
* paramProperty is specified). The JSP bean is constrained to the bean scope specified by the paramScope property,
* if it is specified. If paramName is omitted, then it is assumed that the current object being iterated on is the
* target bean. (optional)
*/
private String paramName;
/**
* The name of a property of the bean specified by the paramName attribute (or the current object being iterated on
* if paramName is not provided), whose return value must be a String containing the value of the request parameter
* (named by the paramId attribute) that will be dynamically added to this href URL. (optional)
* @deprecated use Expressions in paramName
*/
private String paramProperty;
/**
* The scope within which to search for the bean specified by the paramName attribute. If not specified, all scopes
* are searched. If paramName is not provided, then the current object being iterated on is assumed to be the
* target bean. (optional)
* @deprecated use Expressions in paramName
*/
private String paramScope;
/**
* If this attribute is provided, then the column's displayed is limited to this number of characters. An elipse
* (...) is appended to the end if this column is linked, and the user can mouseover the elipse to get the full
* text. (optional)
*/
private int maxLength;
/**
* If this attribute is provided, then the column's displayed is limited to this number of words. An elipse (...)
* is appended to the end if this column is linked, and the user can mouseover the elipse to get the full text.
* (optional)
*/
private int maxWords;
/**
* a class that should be used to "decorate" the underlying object being displayed. If a decorator is specified for
* the entire table, then this decorator will decorate that decorator. (optional)
*/
private String decorator;
/**
* is the column already sorted?
*/
private boolean alreadySorted;
/**
* The media supported attribute.
*/
private List supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
/**
* setter for the "property" tag attribute.
* @param value attribute value
*/
public void setProperty(String value)
{
this.property = value;
}
/**
* setter for the "title" tag attribute.
* @param value attribute value
*/
public void setTitle(String value)
{
this.title = value;
}
/**
* setter for the "nulls" tag attribute.
* @param value attribute value
*/
public void setNulls(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.nulls = true;
}
}
/**
* setter for the "sortable" tag attribute.
* @param value attribute value
*/
public void setSortable(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.sortable = true;
}
}
/**
* @deprecated use setSortable()
* @param value String
*/
public void setSort(String value)
{
setSortable(value);
}
/**
* setter for the "autolink" tag attribute.
* @param value attribute value
*/
public void setAutolink(String value)
{
if (!Boolean.FALSE.toString().equals(value))
{
this.autolink = true;
}
}
/**
* setter for the "group" tag attribute.
* @param value attribute value
*/
public void setGroup(String value)
{
try
{
this.group = Integer.parseInt(value);
}
catch (NumberFormatException e)
{
// ignore?
log.warn("Invalid \"group\" attribute: value=\"" + value + "\"");
}
}
/**
* setter for the "href" tag attribute.
* @param value attribute value
*/
public void setHref(String value)
{
this.href = new Href(value);
}
/**
* setter for the "paramId" tag attribute.
* @param value attribute value
*/
public void setParamId(String value)
{
this.paramId = value;
}
/**
* setter for the "paramName" tag attribute.
* @param value attribute value
*/
public void setParamName(String value)
{
this.paramName = value;
}
/**
* setter for the "paramProperty" tag attribute.
* @param value attribute value
*/
public void setParamProperty(String value)
{
this.paramProperty = value;
}
/**
* setter for the "paramScope" tag attribute.
* @param value attribute value
*/
public void setParamScope(String value)
{
this.paramScope = value;
}
/**
* setter for the "maxLength" tag attribute.
* @param value attribute value
*/
public void setMaxLength(int value)
{
this.maxLength = value;
}
/**
* setter for the "maxWords" tag attribute.
* @param value attribute value
*/
public void setMaxWords(int value)
{
this.maxWords = value;
}
/**
* setter for the "width" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setWidth(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_WIDTH, value);
}
/**
* setter for the "align" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setAlign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_ALIGN, value);
}
/**
* setter for the "background" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBackground(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BACKGROUND, value);
}
/**
* setter for the "bgcolor" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setBgcolor(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_BGCOLOR, value);
}
/**
* setter for the "height" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setHeight(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_HEIGHT, value);
}
/**
* setter for the "nowrap" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setNowrap(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_NOWRAP, value);
}
/**
* setter for the "valign" tag attribute.
* @param value attribute value
* @deprecated use css in "class" or "style"
*/
public void setValign(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_VALIGN, value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
* @deprecated use the "class" attribute
*/
public void setStyleClass(String value)
{
setClass(value);
}
/**
* setter for the "class" tag attribute.
* @param value attribute value
*/
public void setClass(String value)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* Adds a css class to the class attribute (html class suports multiple values).
* @param value attribute value
*/
public void addClass(String value)
{
Object classAttributes = this.attributeMap.get(TagConstants.ATTRIBUTE_CLASS);
if (classAttributes == null)
{
this.attributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
else
{
((MultipleHtmlAttribute) classAttributes).addAttributeValue(value);
}
}
/**
* setter for the "headerClass" tag attribute.
* @param value attribute value
*/
public void setHeaderClass(String value)
{
this.headerAttributeMap.put(TagConstants.ATTRIBUTE_CLASS, new MultipleHtmlAttribute(value));
}
/**
* setter for the "headerStyleClass" tag attribute.
* @param value attribute value
* @deprecated use setHeaderClass()
*/
public void setHeaderStyleClass(String value)
{
setHeaderClass(value);
}
/**
* setter for the "decorator" tag attribute.
* @param value attribute value
*/
public void setDecorator(String value)
{
this.decorator = value;
}
/**
* Is this column configured for the media type?
* @param mediaType the currentMedia type
* @return true if the column should be displayed for this request
*/
public boolean availableForMedia(MediaTypeEnum mediaType)
{
return this.supportedMedia.contains(mediaType);
}
/**
* Tag setter.
* @param media the space delimited list of supported types
*/
public void setMedia(String media)
{
if (StringUtils.isBlank(media) || media.toLowerCase().indexOf("all") > -1)
{
this.supportedMedia = Arrays.asList(MediaTypeEnum.ALL);
return;
}
this.supportedMedia = new ArrayList();
String[] values = StringUtils.split(media);
for (int i = 0; i < values.length; i++)
{
String value = values[i];
if (!StringUtils.isBlank(value))
{
MediaTypeEnum type = MediaTypeEnum.fromName(value.toLowerCase());
if (type == null)
{ // Should be in a tag validator..
String msg =
"Unknown media type \""
+ value
+ "\"; media must be one or more values, space separated."
+ " Possible values are:";
for (int j = 0; j < MediaTypeEnum.ALL.length; j++)
{
MediaTypeEnum mediaTypeEnum = MediaTypeEnum.ALL[j];
msg += " '" + mediaTypeEnum.getName() + "'";
}
throw new IllegalArgumentException(msg + ".");
}
this.supportedMedia.add(type);
}
}
}
/**
* Passes attribute information up to the parent TableTag.
* <p>
* When we hit the end of the tag, we simply let our parent (which better be a TableTag) know what the user wants
* to do with this column. We do that by simple registering this tag with the parent. This tag's only job is to
* hold the configuration information to describe this particular column. The TableTag does all the work.
* </p>
* @return int
* @throws JspException if this tag is being used outside of a <display:list...> tag.
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (currentMediaType != null && !availableForMedia(currentMediaType))
{
if (log.isDebugEnabled())
{
log.debug("skipping column body, currentMediaType=" + currentMediaType);
}
return SKIP_BODY;
}
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
// add column header only once
if (tableTag.isFirstIteration())
{
HeaderCell headerCell = new HeaderCell();
headerCell.setHeaderAttributes((HtmlAttributeMap) this.headerAttributeMap.clone());
headerCell.setHtmlAttributes((HtmlAttributeMap) this.attributeMap.clone());
headerCell.setTitle(this.title);
headerCell.setSortable(this.sortable);
headerCell.setColumnDecorator(DecoratorFactory.loadColumnDecorator(this.decorator));
headerCell.setBeanPropertyName(this.property);
headerCell.setShowNulls(this.nulls);
headerCell.setMaxLength(this.maxLength);
headerCell.setMaxWords(this.maxWords);
headerCell.setAutoLink(this.autolink);
headerCell.setGroup(this.group);
// href and parameter, create link
if (this.href != null && this.paramId != null)
{
Href colHref = new Href(this.href);
// parameter value is in a different object than the iterated one
if (this.paramName != null || this.paramScope != null)
{
// create a complete string for compatibility with previous version before expression evaluation.
// this approach is optimized for new expressions, not for previous property/scope parameters
StringBuffer expression = new StringBuffer();
// append scope
if (StringUtils.isNotBlank(this.paramScope))
{
expression.append(this.paramScope).append("Scope.");
}
// base bean name
if (this.paramId != null)
{
expression.append(this.paramName);
}
else
{
expression.append(tableTag.getName());
}
// append property
if (StringUtils.isNotBlank(this.paramProperty))
{
- expression.append('.').append(this.property);
+ expression.append('.').append(this.paramProperty);
}
// evaluate expression.
// note the value is fixed, not based on any object created during iteration
// this is here for compatibility with the old version mainly
Object paramValue = tableTag.evaluateExpression(expression.toString());
// add parameter
colHref.addParameter(this.paramId, paramValue);
}
else
{
// lookup value as a property on the list object. This should not be done here to avoid useless
// work when only a part of the list is displayed
// set id
headerCell.setParamName(this.paramId);
// set property
headerCell.setParamProperty(this.paramProperty);
}
// sets the base href
headerCell.setHref(colHref);
}
tableTag.addColumn(headerCell);
if (log.isDebugEnabled())
{
log.debug("columnTag.doEndTag() :: first iteration - adding header " + headerCell);
}
}
Cell cell;
if (this.property == null)
{
Object cellValue;
if (getBodyContent() != null)
{
String value = null;
BodyContent bodyContent = getBodyContent();
if (bodyContent != null)
{
value = bodyContent.getString();
}
if (value == null && this.nulls)
{
value = "";
}
cellValue = value;
}
// BodyContent will be null if the body was not eval'd, eg an empty list.
else if (tableTag.isEmpty())
{
cellValue = Cell.EMPTY_CELL;
}
else
{
throw new MissingAttributeException(
getClass(),
new String[] { "property attribute", "value attribute", "tag body" });
}
cell = new Cell(cellValue);
}
else
{
cell = Cell.EMPTY_CELL;
}
tableTag.addCell(cell);
this.attributeMap.clear();
this.headerAttributeMap.clear();
this.paramName = null;
this.decorator = null;
// fix for tag pooling in tomcat
setBodyContent(null);
return super.doEndTag();
}
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
public void release()
{
super.release();
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
public int doStartTag() throws JspException
{
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
if (tableTag == null)
{
throw new TagStructureException(getClass(), "column", "table");
}
// If the list is empty, do not execute the body; may result in NPE
if (tableTag.isEmpty())
{
return SKIP_BODY;
}
else
{
MediaTypeEnum currentMediaType =
(MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (!availableForMedia(currentMediaType))
{
return SKIP_BODY;
}
return super.doStartTag();
}
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SIMPLE_STYLE)
.append("bodyContent", this.bodyContent)
.append("group", this.group)
.append("maxLength", this.maxLength)
.append("decorator", this.decorator)
.append("href", this.href)
.append("title", this.title)
.append("paramScope", this.paramScope)
.append("property", this.property)
.append("paramProperty", this.paramProperty)
.append("headerAttributeMap", this.headerAttributeMap)
.append("paramName", this.paramName)
.append("autolink", this.autolink)
.append("nulls", this.nulls)
.append("maxWords", this.maxWords)
.append("attributeMap", this.attributeMap)
.append("sortable", this.sortable)
.append("paramId", this.paramId)
.append("alreadySorted", this.alreadySorted)
.toString();
}
}
| true | true | public int doEndTag() throws JspException
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (currentMediaType != null && !availableForMedia(currentMediaType))
{
if (log.isDebugEnabled())
{
log.debug("skipping column body, currentMediaType=" + currentMediaType);
}
return SKIP_BODY;
}
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
// add column header only once
if (tableTag.isFirstIteration())
{
HeaderCell headerCell = new HeaderCell();
headerCell.setHeaderAttributes((HtmlAttributeMap) this.headerAttributeMap.clone());
headerCell.setHtmlAttributes((HtmlAttributeMap) this.attributeMap.clone());
headerCell.setTitle(this.title);
headerCell.setSortable(this.sortable);
headerCell.setColumnDecorator(DecoratorFactory.loadColumnDecorator(this.decorator));
headerCell.setBeanPropertyName(this.property);
headerCell.setShowNulls(this.nulls);
headerCell.setMaxLength(this.maxLength);
headerCell.setMaxWords(this.maxWords);
headerCell.setAutoLink(this.autolink);
headerCell.setGroup(this.group);
// href and parameter, create link
if (this.href != null && this.paramId != null)
{
Href colHref = new Href(this.href);
// parameter value is in a different object than the iterated one
if (this.paramName != null || this.paramScope != null)
{
// create a complete string for compatibility with previous version before expression evaluation.
// this approach is optimized for new expressions, not for previous property/scope parameters
StringBuffer expression = new StringBuffer();
// append scope
if (StringUtils.isNotBlank(this.paramScope))
{
expression.append(this.paramScope).append("Scope.");
}
// base bean name
if (this.paramId != null)
{
expression.append(this.paramName);
}
else
{
expression.append(tableTag.getName());
}
// append property
if (StringUtils.isNotBlank(this.paramProperty))
{
expression.append('.').append(this.property);
}
// evaluate expression.
// note the value is fixed, not based on any object created during iteration
// this is here for compatibility with the old version mainly
Object paramValue = tableTag.evaluateExpression(expression.toString());
// add parameter
colHref.addParameter(this.paramId, paramValue);
}
else
{
// lookup value as a property on the list object. This should not be done here to avoid useless
// work when only a part of the list is displayed
// set id
headerCell.setParamName(this.paramId);
// set property
headerCell.setParamProperty(this.paramProperty);
}
// sets the base href
headerCell.setHref(colHref);
}
tableTag.addColumn(headerCell);
if (log.isDebugEnabled())
{
log.debug("columnTag.doEndTag() :: first iteration - adding header " + headerCell);
}
}
Cell cell;
if (this.property == null)
{
Object cellValue;
if (getBodyContent() != null)
{
String value = null;
BodyContent bodyContent = getBodyContent();
if (bodyContent != null)
{
value = bodyContent.getString();
}
if (value == null && this.nulls)
{
value = "";
}
cellValue = value;
}
// BodyContent will be null if the body was not eval'd, eg an empty list.
else if (tableTag.isEmpty())
{
cellValue = Cell.EMPTY_CELL;
}
else
{
throw new MissingAttributeException(
getClass(),
new String[] { "property attribute", "value attribute", "tag body" });
}
cell = new Cell(cellValue);
}
else
{
cell = Cell.EMPTY_CELL;
}
tableTag.addCell(cell);
this.attributeMap.clear();
this.headerAttributeMap.clear();
this.paramName = null;
this.decorator = null;
// fix for tag pooling in tomcat
setBodyContent(null);
return super.doEndTag();
}
| public int doEndTag() throws JspException
{
MediaTypeEnum currentMediaType = (MediaTypeEnum) this.pageContext.findAttribute(TableTag.PAGE_ATTRIBUTE_MEDIA);
if (currentMediaType != null && !availableForMedia(currentMediaType))
{
if (log.isDebugEnabled())
{
log.debug("skipping column body, currentMediaType=" + currentMediaType);
}
return SKIP_BODY;
}
TableTag tableTag = (TableTag) findAncestorWithClass(this, TableTag.class);
// add column header only once
if (tableTag.isFirstIteration())
{
HeaderCell headerCell = new HeaderCell();
headerCell.setHeaderAttributes((HtmlAttributeMap) this.headerAttributeMap.clone());
headerCell.setHtmlAttributes((HtmlAttributeMap) this.attributeMap.clone());
headerCell.setTitle(this.title);
headerCell.setSortable(this.sortable);
headerCell.setColumnDecorator(DecoratorFactory.loadColumnDecorator(this.decorator));
headerCell.setBeanPropertyName(this.property);
headerCell.setShowNulls(this.nulls);
headerCell.setMaxLength(this.maxLength);
headerCell.setMaxWords(this.maxWords);
headerCell.setAutoLink(this.autolink);
headerCell.setGroup(this.group);
// href and parameter, create link
if (this.href != null && this.paramId != null)
{
Href colHref = new Href(this.href);
// parameter value is in a different object than the iterated one
if (this.paramName != null || this.paramScope != null)
{
// create a complete string for compatibility with previous version before expression evaluation.
// this approach is optimized for new expressions, not for previous property/scope parameters
StringBuffer expression = new StringBuffer();
// append scope
if (StringUtils.isNotBlank(this.paramScope))
{
expression.append(this.paramScope).append("Scope.");
}
// base bean name
if (this.paramId != null)
{
expression.append(this.paramName);
}
else
{
expression.append(tableTag.getName());
}
// append property
if (StringUtils.isNotBlank(this.paramProperty))
{
expression.append('.').append(this.paramProperty);
}
// evaluate expression.
// note the value is fixed, not based on any object created during iteration
// this is here for compatibility with the old version mainly
Object paramValue = tableTag.evaluateExpression(expression.toString());
// add parameter
colHref.addParameter(this.paramId, paramValue);
}
else
{
// lookup value as a property on the list object. This should not be done here to avoid useless
// work when only a part of the list is displayed
// set id
headerCell.setParamName(this.paramId);
// set property
headerCell.setParamProperty(this.paramProperty);
}
// sets the base href
headerCell.setHref(colHref);
}
tableTag.addColumn(headerCell);
if (log.isDebugEnabled())
{
log.debug("columnTag.doEndTag() :: first iteration - adding header " + headerCell);
}
}
Cell cell;
if (this.property == null)
{
Object cellValue;
if (getBodyContent() != null)
{
String value = null;
BodyContent bodyContent = getBodyContent();
if (bodyContent != null)
{
value = bodyContent.getString();
}
if (value == null && this.nulls)
{
value = "";
}
cellValue = value;
}
// BodyContent will be null if the body was not eval'd, eg an empty list.
else if (tableTag.isEmpty())
{
cellValue = Cell.EMPTY_CELL;
}
else
{
throw new MissingAttributeException(
getClass(),
new String[] { "property attribute", "value attribute", "tag body" });
}
cell = new Cell(cellValue);
}
else
{
cell = Cell.EMPTY_CELL;
}
tableTag.addCell(cell);
this.attributeMap.clear();
this.headerAttributeMap.clear();
this.paramName = null;
this.decorator = null;
// fix for tag pooling in tomcat
setBodyContent(null);
return super.doEndTag();
}
|
diff --git a/branches/autocheckin/src/com/coffeeandpower/cache/CachedNetworkData.java b/branches/autocheckin/src/com/coffeeandpower/cache/CachedNetworkData.java
index 55dda99..4c60255 100644
--- a/branches/autocheckin/src/com/coffeeandpower/cache/CachedNetworkData.java
+++ b/branches/autocheckin/src/com/coffeeandpower/cache/CachedNetworkData.java
@@ -1,99 +1,99 @@
package com.coffeeandpower.cache;
import java.util.Observable;
import android.location.Location;
import android.util.Log;
import com.coffeeandpower.Constants;
import com.coffeeandpower.cont.DataHolder;
import com.google.android.maps.GeoPoint;
public class CachedNetworkData extends Observable{
private boolean isActive;
private boolean hasData;
private Location userLocationWhenDataCollected = new Location("userDataLocation");
private String type;
private DataHolder cachedData;
public CachedNetworkData(String myType) {
isActive = false;
hasData = false;
this.type = myType;
}
public void activate() {
this.isActive = true;
}
public void deactivate() {
this.isActive = false;
}
public boolean isActive() {
return isActive;
}
public void setNewData(DataHolder newData, double[] userLocation) {
- if (cachedData.getResponseMessage().equals("HTTP 200 OK")) {
+ if (newData.getResponseMessage().equals("HTTP 200 OK")) {
cachedData = newData;
//This gets called so often it makes a mess
//Log.d("CachedNetworkData","Setting user location to: " + userLocation[0] + ", " + userLocation[1]);
userLocationWhenDataCollected.setLatitude(userLocation[0]);
userLocationWhenDataCollected.setLongitude(userLocation[1]);
if (Constants.debugLog)
Log.d("CachedNetworkData","Sending notifyObservers with received data from API call: " + type + "...");
// Send notify for nearby venues
hasData = true;
setChanged();
notifyObservers(new CachedDataContainer(cachedData));
} else {
if (Constants.debugLog)
Log.d("CachedNetworkData","Skipping notifyObservers for API call: " + type);
}
}
/*
* returns distance in meters from a given lat/lon
*/
public double dataDistanceFrom(double[] llArray) {
Location testLoc = new Location("testLoc");
testLoc.setLatitude(llArray[0]);
testLoc.setLongitude(llArray[1]);
return userLocationWhenDataCollected.distanceTo(testLoc);
}
public void sendCachedData() {
if (hasData) {
if (Constants.debugLog)
Log.d("CachedNetworkData","Sending cached data for API: " + this.type + "...");
setChanged(); // Not sure if this is necessary
notifyObservers(new CachedDataContainer(cachedData));
}
}
public DataHolder getData() {
return cachedData;
}
public String getType() {
return type;
}
public boolean hasData() {
return this.hasData;
}
}
| true | true | public void setNewData(DataHolder newData, double[] userLocation) {
if (cachedData.getResponseMessage().equals("HTTP 200 OK")) {
cachedData = newData;
//This gets called so often it makes a mess
//Log.d("CachedNetworkData","Setting user location to: " + userLocation[0] + ", " + userLocation[1]);
userLocationWhenDataCollected.setLatitude(userLocation[0]);
userLocationWhenDataCollected.setLongitude(userLocation[1]);
if (Constants.debugLog)
Log.d("CachedNetworkData","Sending notifyObservers with received data from API call: " + type + "...");
// Send notify for nearby venues
hasData = true;
setChanged();
notifyObservers(new CachedDataContainer(cachedData));
} else {
if (Constants.debugLog)
Log.d("CachedNetworkData","Skipping notifyObservers for API call: " + type);
}
}
| public void setNewData(DataHolder newData, double[] userLocation) {
if (newData.getResponseMessage().equals("HTTP 200 OK")) {
cachedData = newData;
//This gets called so often it makes a mess
//Log.d("CachedNetworkData","Setting user location to: " + userLocation[0] + ", " + userLocation[1]);
userLocationWhenDataCollected.setLatitude(userLocation[0]);
userLocationWhenDataCollected.setLongitude(userLocation[1]);
if (Constants.debugLog)
Log.d("CachedNetworkData","Sending notifyObservers with received data from API call: " + type + "...");
// Send notify for nearby venues
hasData = true;
setChanged();
notifyObservers(new CachedDataContainer(cachedData));
} else {
if (Constants.debugLog)
Log.d("CachedNetworkData","Skipping notifyObservers for API call: " + type);
}
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletResponseImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletResponseImpl.java
index c5682b198..4d4c9a366 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletResponseImpl.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletResponseImpl.java
@@ -1,648 +1,653 @@
/*
* 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.servlet.sip.message;
import gov.nist.javax.sip.DialogExt;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.sip.Proxy;
import javax.servlet.sip.ProxyBranch;
import javax.servlet.sip.Rel100Exception;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.InvalidArgumentException;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.Transaction;
import javax.sip.TransactionState;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.Header;
import javax.sip.header.ProxyAuthenticateHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.RequireHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.SupportedHeader;
import javax.sip.header.WWWAuthenticateHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.core.RoutingState;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
/**
* Implementation of the sip servlet response interface
*
*/
public class SipServletResponseImpl extends SipServletMessageImpl implements
SipServletResponse {
private static final long serialVersionUID = 1L;
private static final String REL100_OPTION_TAG = "100rel";
private static final Logger logger = Logger.getLogger(SipServletResponseImpl.class);
Response response;
SipServletRequestImpl originalRequest;
ProxyBranch proxyBranch;
private boolean isProxiedResponse;
private boolean isResponseForwardedUpstream;
private boolean isAckGenerated;
private boolean isPrackGenerated;
/**
* Constructor
* @param response
* @param sipFactoryImpl
* @param transaction
* @param session
* @param dialog
* @param originalRequest
*/
public SipServletResponseImpl (
Response response,
SipFactoryImpl sipFactoryImpl,
Transaction transaction,
MobicentsSipSession session,
Dialog dialog) {
super(response, sipFactoryImpl, transaction, session, dialog);
this.response = response;
setProxiedResponse(false);
isResponseForwardedUpstream = false;
isAckGenerated = false;
}
/**
* @return the response
*/
public Response getResponse() {
return response;
}
@Override
public boolean isSystemHeader(String headerName) {
String hName = getFullHeaderName(headerName);
/*
* Contact is a system header field in messages other than REGISTER
* requests and responses, 3xx and 485 responses, and 200/OPTIONS
* responses.
*/
// This doesnt contain contact!!!!
boolean isSystemHeader = JainSipUtils.SYSTEM_HEADERS.contains(hName);
if (isSystemHeader) {
return isSystemHeader;
}
boolean isContactSystem = false;
Response sipResponse = (Response) this.message;
String method = ((CSeqHeader) sipResponse.getHeader(CSeqHeader.NAME))
.getMethod();
//Killer condition, see comment above for meaning
if (method.equals(Request.REGISTER)
|| (Response.MULTIPLE_CHOICES <= sipResponse.getStatusCode() && sipResponse.getStatusCode() < Response.BAD_REQUEST)
|| sipResponse.getStatusCode() == Response.AMBIGUOUS
|| (sipResponse.getStatusCode() == Response.OK && method.equals(Request.OPTIONS))) {
isContactSystem = false;
} else {
isContactSystem = true;
}
if (isContactSystem && hName.equals(ContactHeader.NAME)) {
isSystemHeader = true;
} else {
isSystemHeader = false;
}
return isSystemHeader;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#createAck()
*/
@SuppressWarnings("unchecked")
public SipServletRequest createAck() {
if(!Request.INVITE.equals(getTransaction().getRequest().getMethod()) || (response.getStatusCode() >= 100 && response.getStatusCode() < 200) || isAckGenerated) {
throw new IllegalStateException("the transaction state is such that it doesn't allow an ACK to be sent now, e.g. the original request was not an INVITE, or this response is provisional only, or an ACK has already been generated");
}
final MobicentsSipSession session = getSipSession();
Dialog dialog = session.getSessionCreatingDialog();
CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME);
SipServletRequestImpl sipServletAckRequest = null;
try {
if(logger.isDebugEnabled()) {
logger.debug("dialog to create the ack Request " + dialog);
}
Request ackRequest = dialog.createAck(cSeqHeader.getSeqNumber());
if(logger.isInfoEnabled()) {
logger.info("ackRequest just created " + ackRequest);
}
//Application Routing to avoid going through the same app that created the ack
ListIterator<RouteHeader> routeHeaders = ackRequest.getHeaders(RouteHeader.NAME);
ackRequest.removeHeader(RouteHeader.NAME);
while (routeHeaders.hasNext()) {
RouteHeader routeHeader = routeHeaders.next();
String routeAppNameHashed = ((SipURI)routeHeader .getAddress().getURI()).
getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME);
String routeAppName = null;
if(routeAppNameHashed != null) {
routeAppName = sipFactoryImpl.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed);
}
if(routeAppName == null || !routeAppName.equals(getSipSession().getKey().getApplicationName())) {
ackRequest.addHeader(routeHeader);
}
}
sipServletAckRequest = new SipServletRequestImpl(
ackRequest,
this.sipFactoryImpl,
this.getSipSession(),
this.getTransaction(),
dialog,
false);
isAckGenerated = true;
} catch (InvalidArgumentException e) {
logger.error("Impossible to create the ACK",e);
} catch (SipException e) {
logger.error("Impossible to create the ACK",e);
}
return sipServletAckRequest;
}
public SipServletRequest createPrack() throws Rel100Exception {
if((response.getStatusCode() == 100 && response.getStatusCode() >= 200) || isPrackGenerated) {
throw new IllegalStateException("the transaction state is such that it doesn't allow a PRACK to be sent now, or this response is provisional only, or a PRACK has already been generated");
}
if(!Request.INVITE.equals(getTransaction().getRequest().getMethod())) {
throw new Rel100Exception(Rel100Exception.NOT_INVITE);
}
final MobicentsSipSession session = getSipSession();
Dialog dialog = session.getSessionCreatingDialog();
SipServletRequestImpl sipServletPrackRequest = null;
try {
if(logger.isDebugEnabled()) {
logger.debug("dialog to create the prack Request " + dialog);
}
Request prackRequest = dialog.createPrack(response);
if(logger.isInfoEnabled()) {
logger.info("prackRequest just created " + prackRequest);
}
//Application Routing to avoid going through the same app that created the ack
ListIterator<RouteHeader> routeHeaders = prackRequest.getHeaders(RouteHeader.NAME);
prackRequest.removeHeader(RouteHeader.NAME);
while (routeHeaders.hasNext()) {
RouteHeader routeHeader = routeHeaders.next();
String routeAppNameHashed = ((SipURI)routeHeader .getAddress().getURI()).
getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME);
String routeAppName = null;
if(routeAppNameHashed != null) {
routeAppName = sipFactoryImpl.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed);
}
if(routeAppName == null || !routeAppName.equals(getSipSession().getKey().getApplicationName())) {
prackRequest.addHeader(routeHeader);
}
}
sipServletPrackRequest = new SipServletRequestImpl(
prackRequest,
this.sipFactoryImpl,
this.getSipSession(),
this.getTransaction(),
dialog,
false);
isPrackGenerated = true;
} catch (SipException e) {
logger.error("Impossible to create the ACK",e);
}
return sipServletPrackRequest;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getOutputStream()
*/
public ServletOutputStream getOutputStream() throws IOException {
// Always return null
return null;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getProxy()
*/
public Proxy getProxy() {
if(proxyBranch != null) {
return proxyBranch.getProxy();
} else {
return null;
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getReasonPhrase()
*/
public String getReasonPhrase() {
return response.getReasonPhrase();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getRequest()
*/
public SipServletRequest getRequest() {
return originalRequest;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getStatus()
*/
public int getStatus() {
return response.getStatusCode();
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getWriter()
*/
public PrintWriter getWriter() throws IOException {
// Always returns null.
return null;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#sendReliably()
*/
public void sendReliably() throws Rel100Exception {
final int statusCode = getStatus();
if(statusCode == 100 || statusCode >= 200) {
throw new Rel100Exception(Rel100Exception.NOT_1XX);
}
if(!Request.INVITE.equals(originalRequest.getMethod())) {
throw new Rel100Exception(Rel100Exception.NOT_INVITE);
}
if(!REL100_OPTION_TAG.equals(originalRequest.getHeader(RequireHeader.NAME)) && !REL100_OPTION_TAG.equals(originalRequest.getHeader(SupportedHeader.NAME))) {
throw new Rel100Exception(Rel100Exception.NO_REQ_SUPPORT);
}
send(true);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#setStatus(int)
*/
public void setStatus(int statusCode) {
try {
response.setStatusCode(statusCode);
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#setStatus(int, java.lang.String)
*/
public void setStatus(int statusCode, String reasonPhrase) {
try {
response.setStatusCode(statusCode);
response.setReasonPhrase(reasonPhrase);
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#flushBuffer()
*/
public void flushBuffer() throws IOException {
// Do nothing
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#getBufferSize()
*/
public int getBufferSize() {
return 0;
}
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#reset()
*/
public void reset() {
// Do nothing
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#resetBuffer()
*/
public void resetBuffer() {
// Do nothing
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#setBufferSize(int)
*/
public void setBufferSize(int arg0) {
// Do nothing
}
public void setLocale(Locale arg0) {
// TODO Auto-generated method stub
}
@Override
public void send() {
send(false);
}
public void send(boolean sendReliably) {
if(isMessageSent) {
throw new IllegalStateException("message already sent");
}
try {
final int statusCode = response.getStatusCode();
final MobicentsSipSession session = getSipSession();
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
final SipApplicationSessionKey sipAppSessionKey = sipApplicationSession.getKey();
final ProxyImpl proxy = session.getProxy();
// if this is a proxy response and the branch is record routing http://code.google.com/p/mobicents/issues/detail?id=747
// we add a record route
if(proxy != null && proxy.getFinalBranchForSubsequentRequests() == null &&
proxyBranch != null && proxyBranch.getRecordRoute() &&
statusCode > Response.TRYING &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
//Issue 112 fix by folsson: use the viaheader transport
final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
response);
sipURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
sipURI.setParameter(MessageDispatcher.APP_ID, sipAppSessionKey.getId());
sipURI.setLrParam();
javax.sip.address.Address recordRouteAddress =
SipFactories.addressFactory.createAddress(sipURI);
RecordRouteHeader recordRouteHeader =
SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress);
response.addFirst(recordRouteHeader);
if(logger.isDebugEnabled()) {
logger.debug("Record Route added to the response "+ recordRouteHeader);
}
}
final ServerTransaction transaction = (ServerTransaction) getTransaction();
// Update Session state
session.updateStateOnResponse(this, false);
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE request,
// it creates a new subscription and a new dialog.
if(Request.SUBSCRIBE.equals(getMethod()) && statusCode >= 200 && statusCode <= 300) {
session.addSubscription(this);
}
// RFC 3262 Section 3 UAS Behavior
if(sendReliably) {
Header requireHeader = SipFactories.headerFactory.createRequireHeader(REL100_OPTION_TAG);
response.addHeader(requireHeader);
Header rseqHeader = SipFactories.headerFactory.createRSeqHeader(getTransactionApplicationData().getRseqNumber().getAndIncrement());
response.addHeader(rseqHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("sending response "+ this.message);
}
//if a response is sent for an initial request, it means that the application
//acted as an endpoint so a dialog must be created but only for dialog creating method
if(!Request.CANCEL.equals(originalRequest.getMethod())
&& (RoutingState.INITIAL.equals(originalRequest.getRoutingState())
|| RoutingState.RELAYED.equals(originalRequest.getRoutingState()))
&& getTransaction().getDialog() == null
&& JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) {
final String transport = JainSipUtils.findTransport(transaction.getRequest());
final SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
Dialog dialog = null;
// Creates a dialog only for non trying responses
if(statusCode != Response.TRYING) {
dialog = sipProvider.getNewDialog(this
.getTransaction());
((DialogExt)dialog).disableSequenceNumberValidation();
}
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("created following dialog since the application is acting as an endpoint " + dialog);
}
}
- final Dialog dialog = transaction.getDialog();
+ final Dialog dialog = transaction == null ? null:transaction.getDialog();
//keeping track of application data and transaction in the dialog
if(dialog != null) {
if(dialog.getApplicationData() == null) {
dialog.setApplicationData(
originalRequest.getTransactionApplicationData());
}
((TransactionApplicationData)dialog.getApplicationData()).
setTransaction(transaction);
}
//specify that a final response has been sent for the request
//so that the application dispatcher knows it has to stop
//processing the request
// if(response.getStatusCode() > Response.TRYING &&
// response.getStatusCode() < Response.OK) {
// originalRequest.setRoutingState(RoutingState.INFORMATIONAL_RESPONSE_SENT);
// }
if(statusCode >= Response.OK &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
originalRequest.setRoutingState(RoutingState.FINAL_RESPONSE_SENT);
}
if(originalRequest != null) {
originalRequest.setResponse(this);
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
- if(sendReliably) {
+ if(transaction == null) {
+ final String transport = JainSipUtils.findTransport(((SipServletRequestImpl)this.getRequest()).getMessage());
+ final SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
+ transport, false).getSipProvider();
+ sipProvider.sendResponse((Response)this.message);
+ } else if(sendReliably) {
dialog.sendReliableProvisionalResponse((Response)this.message);
} else {
transaction.sendResponse( (Response)this.message );
}
isMessageSent = true;
if(isProxiedResponse) {
isResponseForwardedUpstream = true;
}
} catch (Exception e) {
logger.error("an exception occured when sending the response", e);
throw new IllegalStateException(e);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletResponse#getChallengeRealms()
*/
public Iterator<String> getChallengeRealms() {
List<String> realms = new ArrayList<String>();
if(response.getStatusCode() == SipServletResponse.SC_UNAUTHORIZED) {
WWWAuthenticateHeader authenticateHeader = (WWWAuthenticateHeader)
response.getHeader(WWWAuthenticateHeader.NAME);
realms.add(authenticateHeader.getRealm());
} else if (response.getStatusCode() == SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED) {
ProxyAuthenticateHeader authenticateHeader = (ProxyAuthenticateHeader)
response.getHeader(ProxyAuthenticateHeader.NAME);
realms.add(authenticateHeader.getRealm());
}
return realms.iterator();
}
/**
* {@inheritDoc}
*/
public ProxyBranch getProxyBranch() {
return proxyBranch;
}
/**
* @param proxyBranch the proxyBranch to set
*/
public void setProxyBranch(ProxyBranch proxyBranch) {
this.proxyBranch = proxyBranch;
}
/**
* {@inheritDoc}
*/
public boolean isBranchResponse() {
return this.proxyBranch != null;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletMessage#isCommitted()
*/
public boolean isCommitted() {
//the message is an incoming non-reliable provisional response received by a servlet acting as a UAC
if(getTransaction() instanceof ClientTransaction && getStatus() >= 101 && getStatus() <= 199 && getHeader("RSeq") == null) {
if(this.proxyBranch == null) { // Make sure this is not a proxy. Proxies are allowed to modify headers.
return true;
} else {
return false;
}
}
//the message is an incoming reliable provisional response for which PRACK has already been generated. (Note that this scenario applies to containers that support the 100rel extension.)
if(getTransaction() instanceof ClientTransaction && getStatus() >= 101 && getStatus() <= 199 && getHeader("RSeq") != null && TransactionState.TERMINATED.equals(getTransaction().getState())) {
if(this.proxyBranch == null) { // Make sure this is not a proxy. Proxies are allowed to modify headers.
return true;
} else {
return false;
}
}
//the message is an incoming final response received by a servlet acting as a UAC for a Non INVITE transaction
if(getTransaction() instanceof ClientTransaction && getStatus() >= 200 && getStatus() <= 999 && !Request.INVITE.equals(getTransaction().getRequest().getMethod())) {
if(this.proxyBranch == null) { // Make sure this is not a proxy. Proxies are allowed to modify headers.
return true;
} else {
return false;
}
}
//the message is a response which has been forwarded upstream
if(isResponseForwardedUpstream) {
return true;
}
//message is an incoming final response to an INVITE transaction and an ACK has been generated
if(getTransaction() instanceof ClientTransaction && getStatus() >= 200 && getStatus() <= 999 && TransactionState.TERMINATED.equals(getTransaction().getState()) && isAckGenerated) {
return true;
}
return false;
}
@Override
protected void checkMessageState() {
if(isMessageSent || getTransaction() instanceof ClientTransaction) {
throw new IllegalStateException("Message already sent or incoming message");
}
}
public void setOriginalRequest(SipServletRequestImpl originalRequest) {
this.originalRequest = originalRequest;
}
/**
* @param isProxiedResponse the isProxiedResponse to set
*/
public void setProxiedResponse(boolean isProxiedResponse) {
this.isProxiedResponse = isProxiedResponse;
}
/**
* @return the isProxiedResponse
*/
public boolean isProxiedResponse() {
return isProxiedResponse;
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletResponse#setCharacterEncoding(java.lang.String)
*/
public void setCharacterEncoding(String enc) {
try {
this.message.setContentEncoding(SipFactories.headerFactory
.createContentEncodingHeader(enc));
} catch (Exception ex) {
throw new IllegalArgumentException("Encoding " + enc + " not valid", ex);
}
}
}
| false | true | public void send(boolean sendReliably) {
if(isMessageSent) {
throw new IllegalStateException("message already sent");
}
try {
final int statusCode = response.getStatusCode();
final MobicentsSipSession session = getSipSession();
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
final SipApplicationSessionKey sipAppSessionKey = sipApplicationSession.getKey();
final ProxyImpl proxy = session.getProxy();
// if this is a proxy response and the branch is record routing http://code.google.com/p/mobicents/issues/detail?id=747
// we add a record route
if(proxy != null && proxy.getFinalBranchForSubsequentRequests() == null &&
proxyBranch != null && proxyBranch.getRecordRoute() &&
statusCode > Response.TRYING &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
//Issue 112 fix by folsson: use the viaheader transport
final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
response);
sipURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
sipURI.setParameter(MessageDispatcher.APP_ID, sipAppSessionKey.getId());
sipURI.setLrParam();
javax.sip.address.Address recordRouteAddress =
SipFactories.addressFactory.createAddress(sipURI);
RecordRouteHeader recordRouteHeader =
SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress);
response.addFirst(recordRouteHeader);
if(logger.isDebugEnabled()) {
logger.debug("Record Route added to the response "+ recordRouteHeader);
}
}
final ServerTransaction transaction = (ServerTransaction) getTransaction();
// Update Session state
session.updateStateOnResponse(this, false);
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE request,
// it creates a new subscription and a new dialog.
if(Request.SUBSCRIBE.equals(getMethod()) && statusCode >= 200 && statusCode <= 300) {
session.addSubscription(this);
}
// RFC 3262 Section 3 UAS Behavior
if(sendReliably) {
Header requireHeader = SipFactories.headerFactory.createRequireHeader(REL100_OPTION_TAG);
response.addHeader(requireHeader);
Header rseqHeader = SipFactories.headerFactory.createRSeqHeader(getTransactionApplicationData().getRseqNumber().getAndIncrement());
response.addHeader(rseqHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("sending response "+ this.message);
}
//if a response is sent for an initial request, it means that the application
//acted as an endpoint so a dialog must be created but only for dialog creating method
if(!Request.CANCEL.equals(originalRequest.getMethod())
&& (RoutingState.INITIAL.equals(originalRequest.getRoutingState())
|| RoutingState.RELAYED.equals(originalRequest.getRoutingState()))
&& getTransaction().getDialog() == null
&& JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) {
final String transport = JainSipUtils.findTransport(transaction.getRequest());
final SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
Dialog dialog = null;
// Creates a dialog only for non trying responses
if(statusCode != Response.TRYING) {
dialog = sipProvider.getNewDialog(this
.getTransaction());
((DialogExt)dialog).disableSequenceNumberValidation();
}
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("created following dialog since the application is acting as an endpoint " + dialog);
}
}
final Dialog dialog = transaction.getDialog();
//keeping track of application data and transaction in the dialog
if(dialog != null) {
if(dialog.getApplicationData() == null) {
dialog.setApplicationData(
originalRequest.getTransactionApplicationData());
}
((TransactionApplicationData)dialog.getApplicationData()).
setTransaction(transaction);
}
//specify that a final response has been sent for the request
//so that the application dispatcher knows it has to stop
//processing the request
// if(response.getStatusCode() > Response.TRYING &&
// response.getStatusCode() < Response.OK) {
// originalRequest.setRoutingState(RoutingState.INFORMATIONAL_RESPONSE_SENT);
// }
if(statusCode >= Response.OK &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
originalRequest.setRoutingState(RoutingState.FINAL_RESPONSE_SENT);
}
if(originalRequest != null) {
originalRequest.setResponse(this);
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
if(sendReliably) {
dialog.sendReliableProvisionalResponse((Response)this.message);
} else {
transaction.sendResponse( (Response)this.message );
}
isMessageSent = true;
if(isProxiedResponse) {
isResponseForwardedUpstream = true;
}
} catch (Exception e) {
logger.error("an exception occured when sending the response", e);
throw new IllegalStateException(e);
}
}
| public void send(boolean sendReliably) {
if(isMessageSent) {
throw new IllegalStateException("message already sent");
}
try {
final int statusCode = response.getStatusCode();
final MobicentsSipSession session = getSipSession();
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
final SipApplicationSessionKey sipAppSessionKey = sipApplicationSession.getKey();
final ProxyImpl proxy = session.getProxy();
// if this is a proxy response and the branch is record routing http://code.google.com/p/mobicents/issues/detail?id=747
// we add a record route
if(proxy != null && proxy.getFinalBranchForSubsequentRequests() == null &&
proxyBranch != null && proxyBranch.getRecordRoute() &&
statusCode > Response.TRYING &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
//Issue 112 fix by folsson: use the viaheader transport
final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
response);
sipURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
sipURI.setParameter(MessageDispatcher.APP_ID, sipAppSessionKey.getId());
sipURI.setLrParam();
javax.sip.address.Address recordRouteAddress =
SipFactories.addressFactory.createAddress(sipURI);
RecordRouteHeader recordRouteHeader =
SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress);
response.addFirst(recordRouteHeader);
if(logger.isDebugEnabled()) {
logger.debug("Record Route added to the response "+ recordRouteHeader);
}
}
final ServerTransaction transaction = (ServerTransaction) getTransaction();
// Update Session state
session.updateStateOnResponse(this, false);
// RFC 3265 : If a 200-class response matches such a SUBSCRIBE request,
// it creates a new subscription and a new dialog.
if(Request.SUBSCRIBE.equals(getMethod()) && statusCode >= 200 && statusCode <= 300) {
session.addSubscription(this);
}
// RFC 3262 Section 3 UAS Behavior
if(sendReliably) {
Header requireHeader = SipFactories.headerFactory.createRequireHeader(REL100_OPTION_TAG);
response.addHeader(requireHeader);
Header rseqHeader = SipFactories.headerFactory.createRSeqHeader(getTransactionApplicationData().getRseqNumber().getAndIncrement());
response.addHeader(rseqHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("sending response "+ this.message);
}
//if a response is sent for an initial request, it means that the application
//acted as an endpoint so a dialog must be created but only for dialog creating method
if(!Request.CANCEL.equals(originalRequest.getMethod())
&& (RoutingState.INITIAL.equals(originalRequest.getRoutingState())
|| RoutingState.RELAYED.equals(originalRequest.getRoutingState()))
&& getTransaction().getDialog() == null
&& JainSipUtils.DIALOG_CREATING_METHODS.contains(getMethod())) {
final String transport = JainSipUtils.findTransport(transaction.getRequest());
final SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
Dialog dialog = null;
// Creates a dialog only for non trying responses
if(statusCode != Response.TRYING) {
dialog = sipProvider.getNewDialog(this
.getTransaction());
((DialogExt)dialog).disableSequenceNumberValidation();
}
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("created following dialog since the application is acting as an endpoint " + dialog);
}
}
final Dialog dialog = transaction == null ? null:transaction.getDialog();
//keeping track of application data and transaction in the dialog
if(dialog != null) {
if(dialog.getApplicationData() == null) {
dialog.setApplicationData(
originalRequest.getTransactionApplicationData());
}
((TransactionApplicationData)dialog.getApplicationData()).
setTransaction(transaction);
}
//specify that a final response has been sent for the request
//so that the application dispatcher knows it has to stop
//processing the request
// if(response.getStatusCode() > Response.TRYING &&
// response.getStatusCode() < Response.OK) {
// originalRequest.setRoutingState(RoutingState.INFORMATIONAL_RESPONSE_SENT);
// }
if(statusCode >= Response.OK &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
originalRequest.setRoutingState(RoutingState.FINAL_RESPONSE_SENT);
}
if(originalRequest != null) {
originalRequest.setResponse(this);
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
if(transaction == null) {
final String transport = JainSipUtils.findTransport(((SipServletRequestImpl)this.getRequest()).getMessage());
final SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
sipProvider.sendResponse((Response)this.message);
} else if(sendReliably) {
dialog.sendReliableProvisionalResponse((Response)this.message);
} else {
transaction.sendResponse( (Response)this.message );
}
isMessageSent = true;
if(isProxiedResponse) {
isResponseForwardedUpstream = true;
}
} catch (Exception e) {
logger.error("an exception occured when sending the response", e);
throw new IllegalStateException(e);
}
}
|
diff --git a/src/main/java/org/mozilla/gecko/sync/setup/activities/AccountActivity.java b/src/main/java/org/mozilla/gecko/sync/setup/activities/AccountActivity.java
index 4effd15bd..dadca4a90 100644
--- a/src/main/java/org/mozilla/gecko/sync/setup/activities/AccountActivity.java
+++ b/src/main/java/org/mozilla/gecko/sync/setup/activities/AccountActivity.java
@@ -1,296 +1,298 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* 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.
*
* The Original Code is Android Sync Client.
*
* The Initial Developer of the Original Code is
* the Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chenxia Liu <[email protected]>
* Richard Newman <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either 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 MPL, 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 MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.gecko.sync.setup.activities;
import org.mozilla.gecko.R;
import org.mozilla.gecko.sync.Utils;
import org.mozilla.gecko.sync.repositories.android.Authorities;
import org.mozilla.gecko.sync.setup.Constants;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class AccountActivity extends AccountAuthenticatorActivity {
private final static String LOG_TAG = "AccountActivity";
private final static String DEFAULT_SERVER = "https://auth.services.mozilla.com/";
private AccountManager mAccountManager;
private Context mContext;
private String username;
private String password;
private String key;
private String server;
// UI elements.
private EditText serverInput;
private EditText usernameInput;
private EditText passwordInput;
private EditText synckeyInput;
private CheckBox serverCheckbox;
private Button connectButton;
@Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.SyncTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.sync_account);
mContext = getApplicationContext();
Log.d(LOG_TAG, "AccountManager.get(" + mContext + ")");
mAccountManager = AccountManager.get(mContext);
// Find UI elements.
usernameInput = (EditText) findViewById(R.id.usernameInput);
passwordInput = (EditText) findViewById(R.id.passwordInput);
synckeyInput = (EditText) findViewById(R.id.keyInput);
serverInput = (EditText) findViewById(R.id.serverInput);
TextWatcher inputValidator = makeInputValidator();
usernameInput.addTextChangedListener(inputValidator);
passwordInput.addTextChangedListener(inputValidator);
synckeyInput.addTextChangedListener(inputValidator);
serverInput.addTextChangedListener(inputValidator);
connectButton = (Button) findViewById(R.id.accountConnectButton);
serverCheckbox = (CheckBox) findViewById(R.id.checkbox_server);
serverCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(LOG_TAG, "Toggling checkbox: " + isChecked);
// Hack for pre-3.0 Android: can enter text into disabled EditText.
if (!isChecked) { // Clear server input.
serverInput.setVisibility(View.GONE);
serverInput.setText("");
} else {
serverInput.setVisibility(View.VISIBLE);
}
// Activate connectButton if necessary.
activateView(connectButton, validateInputs());
}
});
}
@Override
public void onStart() {
super.onStart();
// Start with an empty form
usernameInput.setText("");
passwordInput.setText("");
synckeyInput.setText("");
passwordInput.setText("");
}
public void cancelClickHandler(View target) {
finish();
}
/*
* Get credentials on "Connect" and write to AccountManager, where it can be
* accessed by Fennec and Sync Service.
*/
public void connectClickHandler(View target) {
Log.d(LOG_TAG, "connectClickHandler for view " + target);
username = usernameInput.getText().toString();
password = passwordInput.getText().toString();
key = synckeyInput.getText().toString();
if (serverCheckbox.isChecked()) {
server = serverInput.getText().toString();
}
enableCredEntry(false);
// TODO : Authenticate with Sync Service, once implemented, with
// onAuthSuccess as callback
authCallback();
}
/* Helper UI functions */
private void enableCredEntry(boolean toEnable) {
usernameInput.setEnabled(toEnable);
passwordInput.setEnabled(toEnable);
synckeyInput.setEnabled(toEnable);
if (!toEnable) {
serverInput.setEnabled(toEnable);
} else {
serverInput.setEnabled(serverCheckbox.isChecked());
}
}
private TextWatcher makeInputValidator() {
return new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
activateView(connectButton, validateInputs());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
}
private boolean validateInputs() {
if (usernameInput.length() == 0 || passwordInput.length() == 0
|| synckeyInput.length() == 0
|| (serverCheckbox.isChecked() && serverInput.length() == 0)) {
return false;
}
return true;
}
/*
* Callback that handles auth based on success/failure
*/
private void authCallback() {
// Create and add account to AccountManager
// TODO: only allow one account to be added?
Log.d(LOG_TAG, "Using account manager " + mAccountManager);
final Intent intent = createAccount(mContext, mAccountManager,
username,
key, password, server);
setAccountAuthenticatorResult(intent.getExtras());
// Testing out the authFailure case
// authFailure();
// TODO: Currently, we do not actually authenticate username/pass against
// Moz sync server.
// Successful authentication result
setResult(RESULT_OK, intent);
runOnUiThread(new Runnable() {
@Override
public void run() {
authSuccess();
}
});
}
// TODO: lift this out.
public static Intent createAccount(Context context,
AccountManager accountManager,
String username,
String syncKey,
- String password, String serverURL) {
+ String password,
+ String serverURL) {
final Account account = new Account(username, Constants.ACCOUNTTYPE_SYNC);
final Bundle userbundle = new Bundle();
// Add sync key and server URL.
userbundle.putString(Constants.OPTION_SYNCKEY, syncKey);
if (serverURL != null) {
Log.i(LOG_TAG, "Setting explicit server URL: " + serverURL);
userbundle.putString(Constants.OPTION_SERVER, serverURL);
} else {
userbundle.putString(Constants.OPTION_SERVER, DEFAULT_SERVER);
}
Log.d(LOG_TAG, "Adding account for " + Constants.ACCOUNTTYPE_SYNC);
boolean result = accountManager.addAccountExplicitly(account, password, userbundle);
- Log.d(LOG_TAG, "Account: " + account.toString() + " added successfully? " + result);
+ Log.d(LOG_TAG, "Account: " + account + " added successfully? " + result);
if (!result) {
Log.e(LOG_TAG, "Error adding account!");
}
// Set components to sync (default: all).
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, Authorities.BROWSER_AUTHORITY, true);
+ ContentResolver.setIsSyncable(account, Authorities.BROWSER_AUTHORITY, 1);
// TODO: add other ContentProviders as needed (e.g. passwords)
// TODO: for each, also add to res/xml to make visible in account settings
Log.d(LOG_TAG, "Finished setting syncables.");
// TODO: correctly implement Sync Options.
Log.i(LOG_TAG, "Clearing preferences for this account.");
try {
Utils.getSharedPreferences(context, username, serverURL).edit().clear().commit();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not clear prefs path!", e);
}
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, Constants.ACCOUNTTYPE_SYNC);
return intent;
}
@SuppressWarnings("unused")
private void authFailure() {
enableCredEntry(true);
Intent intent = new Intent(mContext, SetupFailureActivity.class);
intent.setFlags(Constants.FLAG_ACTIVITY_REORDER_TO_FRONT_NO_ANIMATION);
startActivity(intent);
}
private void authSuccess() {
Intent intent = new Intent(mContext, SetupSuccessActivity.class);
intent.setFlags(Constants.FLAG_ACTIVITY_REORDER_TO_FRONT_NO_ANIMATION);
startActivity(intent);
finish();
}
private void activateView(View view, boolean toActivate) {
view.setEnabled(toActivate);
view.setClickable(toActivate);
}
}
| false | true | public static Intent createAccount(Context context,
AccountManager accountManager,
String username,
String syncKey,
String password, String serverURL) {
final Account account = new Account(username, Constants.ACCOUNTTYPE_SYNC);
final Bundle userbundle = new Bundle();
// Add sync key and server URL.
userbundle.putString(Constants.OPTION_SYNCKEY, syncKey);
if (serverURL != null) {
Log.i(LOG_TAG, "Setting explicit server URL: " + serverURL);
userbundle.putString(Constants.OPTION_SERVER, serverURL);
} else {
userbundle.putString(Constants.OPTION_SERVER, DEFAULT_SERVER);
}
Log.d(LOG_TAG, "Adding account for " + Constants.ACCOUNTTYPE_SYNC);
boolean result = accountManager.addAccountExplicitly(account, password, userbundle);
Log.d(LOG_TAG, "Account: " + account.toString() + " added successfully? " + result);
if (!result) {
Log.e(LOG_TAG, "Error adding account!");
}
// Set components to sync (default: all).
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, Authorities.BROWSER_AUTHORITY, true);
// TODO: add other ContentProviders as needed (e.g. passwords)
// TODO: for each, also add to res/xml to make visible in account settings
Log.d(LOG_TAG, "Finished setting syncables.");
// TODO: correctly implement Sync Options.
Log.i(LOG_TAG, "Clearing preferences for this account.");
try {
Utils.getSharedPreferences(context, username, serverURL).edit().clear().commit();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not clear prefs path!", e);
}
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, Constants.ACCOUNTTYPE_SYNC);
return intent;
}
| public static Intent createAccount(Context context,
AccountManager accountManager,
String username,
String syncKey,
String password,
String serverURL) {
final Account account = new Account(username, Constants.ACCOUNTTYPE_SYNC);
final Bundle userbundle = new Bundle();
// Add sync key and server URL.
userbundle.putString(Constants.OPTION_SYNCKEY, syncKey);
if (serverURL != null) {
Log.i(LOG_TAG, "Setting explicit server URL: " + serverURL);
userbundle.putString(Constants.OPTION_SERVER, serverURL);
} else {
userbundle.putString(Constants.OPTION_SERVER, DEFAULT_SERVER);
}
Log.d(LOG_TAG, "Adding account for " + Constants.ACCOUNTTYPE_SYNC);
boolean result = accountManager.addAccountExplicitly(account, password, userbundle);
Log.d(LOG_TAG, "Account: " + account + " added successfully? " + result);
if (!result) {
Log.e(LOG_TAG, "Error adding account!");
}
// Set components to sync (default: all).
ContentResolver.setMasterSyncAutomatically(true);
ContentResolver.setSyncAutomatically(account, Authorities.BROWSER_AUTHORITY, true);
ContentResolver.setIsSyncable(account, Authorities.BROWSER_AUTHORITY, 1);
// TODO: add other ContentProviders as needed (e.g. passwords)
// TODO: for each, also add to res/xml to make visible in account settings
Log.d(LOG_TAG, "Finished setting syncables.");
// TODO: correctly implement Sync Options.
Log.i(LOG_TAG, "Clearing preferences for this account.");
try {
Utils.getSharedPreferences(context, username, serverURL).edit().clear().commit();
} catch (Exception e) {
Log.e(LOG_TAG, "Could not clear prefs path!", e);
}
final Intent intent = new Intent();
intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNTTYPE_SYNC);
intent.putExtra(AccountManager.KEY_AUTHTOKEN, Constants.ACCOUNTTYPE_SYNC);
return intent;
}
|
diff --git a/src/org/biojava/bio/program/das/DASSequence.java b/src/org/biojava/bio/program/das/DASSequence.java
index 38b45d6be..b124b419f 100755
--- a/src/org/biojava/bio/program/das/DASSequence.java
+++ b/src/org/biojava/bio/program/das/DASSequence.java
@@ -1,747 +1,751 @@
/*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.program.das;
import java.util.*;
import java.util.zip.*;
import java.net.*;
import java.io.*;
import org.biojava.utils.*;
import org.biojava.utils.cache.*;
import org.biojava.bio.*;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.seq.db.*;
import org.biojava.bio.seq.impl.*;
import org.biojava.bio.symbol.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;
import org.biojava.utils.stax.*;
/**
* Sequence reflecting a DAS reference sequence, possibly
* decorated with one of more annotation sets.
*
* <p>
* This is an first-pass implementation. In future, I hope
* to add query optimization for better performance on large
* sequences, and pluggable transducers to parameterize the
* creation of BioJava features.
* </p>
*
* @since 1.1
* @author Thomas Down
* @author Matthew Pocock
* @author David Huen
*/
public class DASSequence
extends
AbstractChangeable
implements
DASSequenceI,
DASOptimizableFeatureHolder
{
/**
* Change type which indicates that the set of annotation servers used
* by this DASSequence has been changed. This extends Feature.FEATURES as
* the addition and removal of annotation servers adds and removes features.
*/
public static final ChangeType ANNOTATIONS = new ChangeType(
"Annotation sets have been added or removed from the DAS sequence",
"org.biojava.bio.program.das.DASSequence",
"ANNOTATIONS",
Feature.FEATURES
);
public static final String PROPERTY_ANNOTATIONSERVER = "org.biojava.bio.program.das.annotation_server";
public static final String PROPERTY_FEATUREID = "org.biojava.bio.program.das.feature_id";
public static final String PROPERTY_FEATURELABEL = "org.biojava.bio.program.das.feature_label";
public static final String PROPERTY_LINKS = "org.biojava.bio.program.das.links";
public static final String PROPERTY_SEQUENCEVERSION = "org.biojava.bio.program.das.sequence_version";
public static final int SIZE_THRESHOLD = 500000;
private static final int SYMBOL_TILE_THRESHOLD = 100000;
private static final int SYMBOL_TILE_SIZE = 20000;
private DASSequenceDB parentdb;
private Alphabet alphabet = DNATools.getDNA();
private URL dataSourceURL;
private String seqID;
private String version = null;
private FeatureRealizer featureRealizer = FeatureImpl.DEFAULT;
private FeatureRequestManager.Ticket structureTicket;
private CacheReference refSymbols;
private int length = -1;
private Map featureSets;
private FeatureHolder structure;
private DASMergeFeatureHolder features;
{
featureSets = new HashMap();
features = new DASMergeFeatureHolder();
}
DASSequence(DASSequenceDB db, URL dataSourceURL, String seqID, Set dataSources)
throws BioException, IllegalIDException
{
this.parentdb = db;
this.dataSourceURL = dataSourceURL;
this.seqID = seqID;
//
// Check for deep structure. This also checks that the sequence
// really exists, and hopefully picks up the length along the way.
//
SeqIOListener listener = new SkeletonListener();
FeatureRequestManager frm = getParentDB().getFeatureRequestManager();
this.structureTicket = frm.requestFeatures(getDataSourceURL(), seqID, listener, null, "component");
//
// Pick up some annotations
//
for (Iterator dsi = dataSources.iterator(); dsi.hasNext(); ) {
URL annoURL = (URL) dsi.next();
FeatureHolder newFeatureSet = new DASFeatureSet(this, annoURL, seqID);
featureSets.put(annoURL, newFeatureSet);
try {
features.addFeatureHolder(newFeatureSet, new FeatureFilter.ByAnnotation(DASSequence.PROPERTY_ANNOTATIONSERVER,
dataSourceURL));
} catch (ChangeVetoException cve) {
throw new BioError(cve);
}
}
}
private class SkeletonListener extends SeqIOAdapter {
private SimpleFeatureHolder structureF;
public void startSequence() {
structureF = new SimpleFeatureHolder();
}
public void endSequence() {
structure = structureF;
if (structure.countFeatures() > 0) {
try {
features.addFeatureHolder(structure, new FeatureFilter.ByClass(ComponentFeature.class));
} catch (ChangeVetoException cve) {
throw new BioError(cve);
}
}
}
public void addSequenceProperty(Object key, Object value)
throws ParseException
{
try {
if (key.equals("sequence.start")) {
int start = Integer.parseInt(value.toString());
if (start != 1) {
throw new ParseException("Server doesn't think sequence starts at 1. Wierd.");
}
} else if (key.equals("sequence.stop")) {
length = Integer.parseInt(value.toString());
} else if (key.equals("sequence.version")) {
version = value.toString();
}
} catch (NumberFormatException ex) {
throw new ParseException(ex, "Expect numbers for segment start and stop");
}
}
public void startFeature(Feature.Template temp)
throws ParseException
{
if (temp instanceof ComponentFeature.Template) {
String id = (String) temp.annotation.getProperty("sequence.id");
try {
ComponentFeature.Template ctemp = (ComponentFeature.Template) temp;
ComponentFeature cf = new DASComponentFeature(DASSequence.this,
ctemp);
structureF.addFeature(cf);
length = Math.max(length, ctemp.location.getMax());
} catch (BioException ex) {
throw new ParseException(ex, "Error instantiating DASComponent");
} catch (ChangeVetoException ex) {
throw new BioError(ex, "Immutable FeatureHolder when trying to build structure");
}
} else {
// Server seems not to honour category=
// This hurts performance, but we can just elide the unwanted
// features on the client side.
}
}
}
URL getDataSourceURL() {
return dataSourceURL;
}
public DASSequenceDB getParentDB() {
return parentdb;
}
FeatureHolder getStructure() throws BioException {
if(!this.structureTicket.isFetched()) {
this.structureTicket.doFetch();
}
return this.structure;
}
private void _addAnnotationSource(URL dataSourceURL)
throws BioException, ChangeVetoException
{
FeatureHolder structure = getStructure();
for (Iterator i = structure.features(); i.hasNext(); ) {
DASComponentFeature dcf = (DASComponentFeature) i.next();
DASSequence seq = dcf.getSequenceLazy();
if (seq != null) {
seq.addAnnotationSource(dataSourceURL);
}
}
FeatureHolder fs = new DASFeatureSet(this, dataSourceURL, this.seqID);
featureSets.put(dataSourceURL, fs);
features.addFeatureHolder(fs);
}
public Set dataSourceURLs() {
return Collections.unmodifiableSet(featureSets.keySet());
}
public void addAnnotationSource(URL dataSourceURL)
throws BioException, ChangeVetoException
{
if(!featureSets.containsKey(dataSourceURL)) {
if (!hasListeners()) {
_addAnnotationSource(dataSourceURL);
} else {
ChangeSupport changeSupport = getChangeSupport(ANNOTATIONS);
synchronized (changeSupport) {
ChangeEvent ce = new ChangeEvent(
this,
ANNOTATIONS,
null,
null
) ;
changeSupport.firePreChangeEvent(ce);
_addAnnotationSource(dataSourceURL);
changeSupport.firePostChangeEvent(ce);
}
}
}
}
private void _removeAnnotationSource(URL dataSourceURL)
throws ChangeVetoException, BioException
{
FeatureHolder structure = getStructure();
FeatureHolder fh = (FeatureHolder) featureSets.get(dataSourceURL);
if (fh != null) {
for (Iterator i = structure.features(); i.hasNext(); ) {
DASComponentFeature dcf = (DASComponentFeature) i.next();
DASSequence seq = dcf.getSequenceLazy();
if (seq != null) {
seq.removeAnnotationSource(dataSourceURL);
}
}
features.removeFeatureHolder(fh);
featureSets.remove(dataSourceURL);
}
}
public void removeAnnotationSource(URL dataSourceURL)
throws ChangeVetoException, BioException
{
if (featureSets.containsKey(dataSourceURL)) {
if (!hasListeners()) {
_removeAnnotationSource(dataSourceURL);
} else {
ChangeSupport changeSupport = getChangeSupport(ANNOTATIONS);
synchronized (changeSupport) {
ChangeEvent ce = new ChangeEvent(
this,
ANNOTATIONS,
null,
null
) ;
changeSupport.firePreChangeEvent(ce);
_removeAnnotationSource(dataSourceURL);
changeSupport.firePostChangeEvent(ce);
}
}
}
}
private int registerLocalFeatureFetchers(Object regKey) {
// System.err.println(getName() + ": registerLocalFeatureFetchers()");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(regKey);
}
return featureSets.size();
}
private int registerLocalFeatureFetchers(Location l, Object regKey) {
// System.err.println(getName() + ": registerLocalFeatureFetchers(" + l.toString() + ")");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(l, regKey);
}
return featureSets.size();
}
int registerFeatureFetchers(Object regKey) throws BioException {
// System.err.println(getName() + ": registerFeatureFetchers()");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(regKey);
}
int num = featureSets.size();
FeatureHolder structure = getStructure();
if (length() < SIZE_THRESHOLD && structure.countFeatures() > 0) {
List sequences = new ArrayList();
for (Iterator fi = structure.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
DASSequence cseq = (DASSequence) cf.getComponentSequence();
sequences.add(cseq);
}
for (Iterator si = sequences.iterator(); si.hasNext(); ) {
DASSequence cseq = (DASSequence) si.next();
num += cseq.registerFeatureFetchers(regKey);
}
}
return num;
}
int registerFeatureFetchers(Location l, Object regKey) throws BioException {
// System.err.println(getName() + ": registerFeatureFetchers(" + l.toString() + ")");
for (Iterator i = featureSets.values().iterator(); i.hasNext(); ) {
DASFeatureSet dfs = (DASFeatureSet) i.next();
dfs.registerFeatureFetcher(l, regKey);
}
int num = featureSets.size();
FeatureHolder structure = getStructure();
if (structure.countFeatures() > 0) {
FeatureHolder componentsBelow = structure.filter(new FeatureFilter.OverlapsLocation(l), false);
Map sequencesToRegions = new HashMap();
for (Iterator fi = componentsBelow.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
DASSequence cseq = (DASSequence) cf.getComponentSequence();
if (l.contains(cf.getLocation())) {
sequencesToRegions.put(cseq, null);
} else {
Location partNeeded = l.intersection(cf.getLocation());
if (cf.getStrand() == StrandedFeature.POSITIVE) {
partNeeded = partNeeded.translate(cf.getComponentLocation().getMin() - cf.getLocation().getMin());
sequencesToRegions.put(cseq, partNeeded);
} else {
sequencesToRegions.put(cseq, null);
}
}
}
for (Iterator sri = sequencesToRegions.entrySet().iterator(); sri.hasNext(); ) {
Map.Entry srme = (Map.Entry) sri.next();
DASSequence cseq = (DASSequence) srme.getKey();
Location partNeeded = (Location) srme.getValue();
if (partNeeded != null) {
num += cseq.registerFeatureFetchers(partNeeded, regKey);
} else {
num += cseq.registerFeatureFetchers(regKey);
}
}
}
return num;
}
//
// SymbolList stuff
//
public Alphabet getAlphabet() {
return alphabet;
}
public Iterator iterator() {
try {
return getSymbols().iterator();
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't iterate over symbols");
}
}
public int length() {
try {
if (length < 0 && !structureTicket.isFetched()) {
// Hope that the length is set when we get the structure
structureTicket.doFetch();
}
if (length < 0) {
throw new BioError("Assertion Failure: structure fetch didn't get length");
}
return length;
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't calculate length");
}
}
public String seqString() {
try {
return getSymbols().seqString();
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't create seqString");
}
}
public String subStr(int start, int end) {
try {
return getSymbols().subStr(start, end);
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't create substring");
}
}
public SymbolList subList(int start, int end) {
try {
return getSymbols().subList(start, end);
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't create subList");
}
}
public Symbol symbolAt(int pos) {
try {
return getSymbols().symbolAt(pos);
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't fetch symbol");
}
}
public List toList() {
try {
return getSymbols().toList();
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't create list");
}
}
public void edit(Edit e)
throws ChangeVetoException
{
throw new ChangeVetoException("/You/ try implementing read-write DAS");
}
//
// DNA fetching stuff
//
protected SymbolList getSymbols() throws BioException {
SymbolList sl = null;
if (refSymbols != null) {
sl = (SymbolList) refSymbols.get();
}
if (sl == null) {
FeatureHolder structure = getStructure();
if (structure.countFeatures() == 0) {
if (length() > SYMBOL_TILE_THRESHOLD) {
AssembledSymbolList asl = new AssembledSymbolList();
int tileStart = 1;
- while (tileStart < length()) {
+ while (tileStart <= length()) {
int tileEnd = Math.min(tileStart + SYMBOL_TILE_SIZE - 1, length());
+ if ((length() - tileEnd) < 1000) {
+ // snap the tiny bit onto the end of the last tile
+ tileEnd = length();
+ }
Location l = new RangeLocation(tileStart, tileEnd);
SymbolList symbols = new DASRawSymbolList(this,
new Segment(getName(), tileStart, tileEnd));
asl.putComponent(l, symbols);
tileStart = tileEnd + 1;
}
sl = asl;
} else {
sl = new DASRawSymbolList(this, new Segment(getName()));
}
} else {
//
// VERY, VERY, naive approach to identifying canonical components. FIXME
//
Location coverage = Location.empty;
AssembledSymbolList asl = new AssembledSymbolList();
asl.setLength(length);
for (Iterator i = structure.features(); i.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) i.next();
Location loc = cf.getLocation();
if (LocationTools.overlaps(loc, coverage)) {
// Assume that this is non-cannonical. Maybe not a great thing to
// do, but...
} else {
asl.putComponent(cf);
coverage = LocationTools.union(coverage, loc);
}
}
sl = asl;
}
refSymbols = parentdb.getSymbolsCache().makeReference(sl);
}
return sl;
}
//
// Identification stuff
//
public String getName() {
return seqID;
}
public String getURN() {
try {
return new URL(getDataSourceURL(), "?ref=" + seqID).toString();
} catch (MalformedURLException ex) {
throw new BioRuntimeException(ex);
}
}
//
// FeatureHolder stuff
//
public Iterator features() {
try {
registerFeatureFetchers(null);
return features.features();
} catch (BioException be) {
throw new BioRuntimeException(be, "Couldn't create features iterator");
}
}
public boolean containsFeature(Feature f) {
return features.containsFeature(f);
}
public FeatureHolder filter(FeatureFilter ff, boolean recurse) {
try {
//
// We optimise for the case of just wanting `structural' features,
// which improves the scalability of the Dazzle server (and probably
// other applications, too)
//
FeatureHolder structure = getStructure();
FeatureFilter structureMembershipFilter = new FeatureFilter.ByClass(ComponentFeature.class);
if (FilterUtils.areProperSubset(ff, structureMembershipFilter)) {
if (recurse) {
for (Iterator fi = structure.features(); fi.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) fi.next();
Sequence cseq = cf.getComponentSequence();
// Just ensuring that the sequence is instantiated should be sufficient.
}
}
return structure.filter(ff, recurse);
}
//
// Otherwise they want /real/ features, I'm afraid...
//
Location ffl = extractInterestingLocation(ff);
if (recurse) {
int numComponents = 1;
if (ffl != null) {
numComponents = registerFeatureFetchers(ffl, ff);
} else {
numComponents = registerFeatureFetchers(ff);
}
getParentDB().ensureFeaturesCacheCapacity(numComponents * 3);
} else {
if (ffl != null) {
registerLocalFeatureFetchers(ffl, ff);
} else {
// new Exception("Hmmm, this is dangerous...").printStackTrace();
registerLocalFeatureFetchers(ff);
}
}
return features.filter(ff, recurse);
} catch (BioException be) {
throw new BioRuntimeException(be, "Can't filter");
}
}
static Location extractInterestingLocation(FeatureFilter ff) {
if (ff instanceof FeatureFilter.OverlapsLocation) {
return ((FeatureFilter.OverlapsLocation) ff).getLocation();
} else if (ff instanceof FeatureFilter.ContainedByLocation) {
return ((FeatureFilter.ContainedByLocation) ff).getLocation();
} else if (ff instanceof FeatureFilter.And) {
FeatureFilter.And ffa = (FeatureFilter.And) ff;
Location l1 = extractInterestingLocation(ffa.getChild1());
Location l2 = extractInterestingLocation(ffa.getChild2());
if (l1 != null) {
if (l2 != null) {
return l1.intersection(l2);
} else {
return l1;
}
} else {
if (l2 != null) {
return l2;
} else {
return null;
}
}
}
// Don't know how this filter relates to location.
return null;
}
public int countFeatures() {
return features.countFeatures();
}
public Feature createFeature(Feature.Template temp)
throws ChangeVetoException
{
throw new ChangeVetoException("Can't create features on DAS sequences.");
}
public void removeFeature(Feature f)
throws ChangeVetoException
{
throw new ChangeVetoException("Can't remove features from DAS sequences.");
}
//
// Optimizable feature-holder
//
public Set getOptimizableFilters() throws BioException {
return features.getOptimizableFilters();
}
public FeatureHolder getOptimizedSubset(FeatureFilter ff) throws BioException {
return features.getOptimizedSubset(ff);
}
//
// Feature realization stuff
//
public Feature realizeFeature(FeatureHolder dest,
Feature.Template temp)
throws BioException
{
// workaround for features with bad locations - usualy starting at 0
// e.g. enxembl830 has a cytogenetic band starting at 0
if(temp.location.getMin() < 1 || temp.location.getMax() > length()) {
temp.location = LocationTools.intersection(temp.location,
new RangeLocation(1, length()) );
}
return featureRealizer.realizeFeature(this, dest, temp);
}
//
// Annotatable stuff
//
public Annotation getAnnotation() {
try {
Annotation anno = new SmallAnnotation();
anno.setProperty(PROPERTY_SEQUENCEVERSION, version);
return anno;
} catch (ChangeVetoException ex) {
throw new BioError("Expected to be able to modify annotation");
}
}
//
// Utility method to turn of the awkward bits of Xerces-J
//
static DocumentBuilder nonvalidatingParser() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
return dbf.newDocumentBuilder();
} catch (Exception ex) {
throw new BioError(ex);
}
}
static XMLReader nonvalidatingSAXParser() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(false);
spf.setNamespaceAware(true);
return spf.newSAXParser().getXMLReader();
} catch (Exception ex) {
throw new BioError(ex);
}
}
}
| false | true | protected SymbolList getSymbols() throws BioException {
SymbolList sl = null;
if (refSymbols != null) {
sl = (SymbolList) refSymbols.get();
}
if (sl == null) {
FeatureHolder structure = getStructure();
if (structure.countFeatures() == 0) {
if (length() > SYMBOL_TILE_THRESHOLD) {
AssembledSymbolList asl = new AssembledSymbolList();
int tileStart = 1;
while (tileStart < length()) {
int tileEnd = Math.min(tileStart + SYMBOL_TILE_SIZE - 1, length());
Location l = new RangeLocation(tileStart, tileEnd);
SymbolList symbols = new DASRawSymbolList(this,
new Segment(getName(), tileStart, tileEnd));
asl.putComponent(l, symbols);
tileStart = tileEnd + 1;
}
sl = asl;
} else {
sl = new DASRawSymbolList(this, new Segment(getName()));
}
} else {
//
// VERY, VERY, naive approach to identifying canonical components. FIXME
//
Location coverage = Location.empty;
AssembledSymbolList asl = new AssembledSymbolList();
asl.setLength(length);
for (Iterator i = structure.features(); i.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) i.next();
Location loc = cf.getLocation();
if (LocationTools.overlaps(loc, coverage)) {
// Assume that this is non-cannonical. Maybe not a great thing to
// do, but...
} else {
asl.putComponent(cf);
coverage = LocationTools.union(coverage, loc);
}
}
sl = asl;
}
refSymbols = parentdb.getSymbolsCache().makeReference(sl);
}
return sl;
}
| protected SymbolList getSymbols() throws BioException {
SymbolList sl = null;
if (refSymbols != null) {
sl = (SymbolList) refSymbols.get();
}
if (sl == null) {
FeatureHolder structure = getStructure();
if (structure.countFeatures() == 0) {
if (length() > SYMBOL_TILE_THRESHOLD) {
AssembledSymbolList asl = new AssembledSymbolList();
int tileStart = 1;
while (tileStart <= length()) {
int tileEnd = Math.min(tileStart + SYMBOL_TILE_SIZE - 1, length());
if ((length() - tileEnd) < 1000) {
// snap the tiny bit onto the end of the last tile
tileEnd = length();
}
Location l = new RangeLocation(tileStart, tileEnd);
SymbolList symbols = new DASRawSymbolList(this,
new Segment(getName(), tileStart, tileEnd));
asl.putComponent(l, symbols);
tileStart = tileEnd + 1;
}
sl = asl;
} else {
sl = new DASRawSymbolList(this, new Segment(getName()));
}
} else {
//
// VERY, VERY, naive approach to identifying canonical components. FIXME
//
Location coverage = Location.empty;
AssembledSymbolList asl = new AssembledSymbolList();
asl.setLength(length);
for (Iterator i = structure.features(); i.hasNext(); ) {
ComponentFeature cf = (ComponentFeature) i.next();
Location loc = cf.getLocation();
if (LocationTools.overlaps(loc, coverage)) {
// Assume that this is non-cannonical. Maybe not a great thing to
// do, but...
} else {
asl.putComponent(cf);
coverage = LocationTools.union(coverage, loc);
}
}
sl = asl;
}
refSymbols = parentdb.getSymbolsCache().makeReference(sl);
}
return sl;
}
|
diff --git a/src/org/ohmage/domain/survey/read/ConfigurationValueMerger.java b/src/org/ohmage/domain/survey/read/ConfigurationValueMerger.java
index 2e2f5162..d61d0f5d 100644
--- a/src/org/ohmage/domain/survey/read/ConfigurationValueMerger.java
+++ b/src/org/ohmage/domain/survey/read/ConfigurationValueMerger.java
@@ -1,244 +1,244 @@
/*******************************************************************************
* Copyright 2011 The Regents of the University of California
*
* 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.ohmage.domain.survey.read;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.domain.configuration.Configuration;
import org.ohmage.util.JsonUtils;
/**
* For survey response read, merges values from a campaign configuration with
* the query results. Also performs display value formatting depending on the
* prompt type contained in the SurveyResponseReadResult.
*
* @author Joshua Selsky
*/
public class ConfigurationValueMerger {
private static Logger _logger = Logger.getLogger(ConfigurationValueMerger.class);
/**
* Private to prevent instantiation.
*/
private ConfigurationValueMerger() { }
/**
* For the given result, includes static values from the configuration that
* are used for writing output
*
* @param result The result to merge configuration values into.
* @param configuration The configuration to retrieve values from.
*/
public static void merge(SurveyResponseReadResult result, Configuration configuration) {
result.setSurveyTitle(configuration.getSurveyTitleFor(result.getSurveyId()));
result.setSurveyDescription(configuration.getSurveyDescriptionFor(result.getSurveyId()));
if(result.isRepeatableSetResult()) {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setDisplayLabel(
configuration.getDisplayLabelFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setDisplayType(configuration.getDisplayTypeFor(
result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if(PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
result.setDisplayValue((String) result.getResponse());
}
else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
} else {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayLabel(configuration.getDisplayLabelFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayType(configuration.getDisplayTypeFor(result.getSurveyId(), result.getPromptId()));
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if (PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if (PromptTypeUtils.isRemoteActivityType(result.getPromptType())) {
setDisplayValueFromRemoteActivity(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
try {
result.setDisplayValue(new JSONObject(String.valueOf(result.getResponse())));
}
catch(JSONException e) {
_logger.warn("could not convert custom choice prompt response to a JSON object");
- result.setDisplayValue("{}");
+ result.setDisplayValue(new JSONObject());
}
} else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
}
// if(_logger.isDebugEnabled()) {
// _logger.debug(result);
// }
}
/**
* Sets the display value on the result the for single_choice prompt type.
* The display value is converted to a number if it is indeed a number. If
* the result cannot be coerced into a number, the display value will be
* treated as a String. It would be quite unusual for the key not to be a
* number, but perhaps in the future non-numeric keys will be allowed.
*
* @param result The result to set the display value on.
*/
private static void setDisplayValueFromSingleChoice(SurveyResponseReadResult result) {
// The response here is the *index* (key) of the single_choice response
result.setDisplayValue(convertToNumber(result.getResponse()));
}
/**
* Sets the display value for the multi_choice prompt type. The display
* value is a JSON array. If the value cannot be converted into an
* array, a warning message is printed and an empty array is set as the
* display value.
*
* @param result The result to set the display value on.
*/
private static void setDisplayValueFromMultiChoice(SurveyResponseReadResult result) {
try {
result.setDisplayValue(new JSONArray(String.valueOf(result.getResponse())));
} catch (JSONException je) {
// Check for SKIPPED or NOT_DISPLAYED
String str = String.valueOf(result.getResponse());
if("SKIPPED".equals(str) || "NOT_DISPLAYED".equals(str)) {
result.setDisplayValue(str);
}
else {
_logger.warn("multi_choice response is not a string or a JSONArray: " + result.getResponse());
result.setDisplayValue(new JSONArray());
}
}
}
/**
* Formats and sets the display value in the result for the remote activity
* prompt type.
*
* @param result The result where the display value will be set.
*/
private static void setDisplayValueFromRemoteActivity(SurveyResponseReadResult result) {
JSONArray responseArray = JsonUtils.getJsonArrayFromString(String.valueOf(result.getResponse()));
if(responseArray != null) {
double total = 0.0f;
for(int i = 0; i < responseArray.length(); i++) {
JSONObject currRun;
try {
currRun = responseArray.getJSONObject(i);
}
catch(JSONException e) {
_logger.warn("Could not convert an individual run of a RemoteActivity response into JSONObjects.", e);
continue;
}
try {
total += Double.valueOf(currRun.get("score").toString());
}
catch(JSONException e) {
_logger.warn("Missing necessary key in RemoteActivity run.", e);
continue;
}
catch(NullPointerException e) {
_logger.warn("Missing necessary key in RemoteActivity run.", e);
continue;
}
catch(ClassCastException e) {
_logger.warn("Cannot cast the score value into a double.");
continue;
}
}
if(responseArray.length() == 0) {
result.setDisplayValue(0.0);
}
else {
result.setDisplayValue(total / responseArray.length());
}
}
else {
result.setDisplayValue(String.valueOf(result.getResponse()));
}
}
/**
* Lazy number conversion so the JSON lib serializes output properly.
* Individual prompt responses are stored in a schema-less db column
* and retrieved as Objects. Here type coercion is attempted in order to
* avoid quoting numbers that may have a String datatype given to them via
* JDBC.
*/
private static Object convertToNumber(Object value) {
try {
return Integer.parseInt(String.valueOf(value));
} catch (NumberFormatException e) {
try {
return Double.parseDouble(String.valueOf(value));
} catch (NumberFormatException e2) {
// Ignore because the value must be a string or some other
// number representation that can be treated as a JSON string
}
}
return value;
}
}
| true | true | public static void merge(SurveyResponseReadResult result, Configuration configuration) {
result.setSurveyTitle(configuration.getSurveyTitleFor(result.getSurveyId()));
result.setSurveyDescription(configuration.getSurveyDescriptionFor(result.getSurveyId()));
if(result.isRepeatableSetResult()) {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setDisplayLabel(
configuration.getDisplayLabelFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setDisplayType(configuration.getDisplayTypeFor(
result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if(PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
result.setDisplayValue((String) result.getResponse());
}
else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
} else {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayLabel(configuration.getDisplayLabelFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayType(configuration.getDisplayTypeFor(result.getSurveyId(), result.getPromptId()));
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if (PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if (PromptTypeUtils.isRemoteActivityType(result.getPromptType())) {
setDisplayValueFromRemoteActivity(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
try {
result.setDisplayValue(new JSONObject(String.valueOf(result.getResponse())));
}
catch(JSONException e) {
_logger.warn("could not convert custom choice prompt response to a JSON object");
result.setDisplayValue("{}");
}
} else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
}
// if(_logger.isDebugEnabled()) {
// _logger.debug(result);
// }
}
| public static void merge(SurveyResponseReadResult result, Configuration configuration) {
result.setSurveyTitle(configuration.getSurveyTitleFor(result.getSurveyId()));
result.setSurveyDescription(configuration.getSurveyDescriptionFor(result.getSurveyId()));
if(result.isRepeatableSetResult()) {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setDisplayLabel(
configuration.getDisplayLabelFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setDisplayType(configuration.getDisplayTypeFor(
result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId())
);
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if(PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getRepeatableSetId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
result.setDisplayValue((String) result.getResponse());
}
else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
} else {
result.setUnit(configuration.getUnitFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayLabel(configuration.getDisplayLabelFor(result.getSurveyId(), result.getPromptId()));
result.setDisplayType(configuration.getDisplayTypeFor(result.getSurveyId(), result.getPromptId()));
result.setPromptText(configuration.getPromptTextFor(result.getSurveyId(), result.getPromptId()));
if(PromptTypeUtils.isSingleChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
result.setSingleChoiceOrdinalValue(convertToNumber(configuration.getValueForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse()))));
result.setSingleChoiceLabel(configuration.getLabelForChoiceKey(result.getSurveyId(), result.getPromptId(), String.valueOf(result.getResponse())));
setDisplayValueFromSingleChoice(result);
}
else if (PromptTypeUtils.isMultiChoiceType(result.getPromptType())) {
result.setChoiceGlossary(configuration.getChoiceGlossaryFor(result.getSurveyId(), result.getPromptId()));
setDisplayValueFromMultiChoice(result);
}
else if (PromptTypeUtils.isRemoteActivityType(result.getPromptType())) {
setDisplayValueFromRemoteActivity(result);
}
else if(PromptTypeUtils.isJsonObject(result.getPromptType())) {
try {
result.setDisplayValue(new JSONObject(String.valueOf(result.getResponse())));
}
catch(JSONException e) {
_logger.warn("could not convert custom choice prompt response to a JSON object");
result.setDisplayValue(new JSONObject());
}
} else {
result.setDisplayValue(PromptTypeUtils.isNumberPromptType(result.getPromptType()) ? convertToNumber(result.getResponse()) : result.getResponse());
}
}
// if(_logger.isDebugEnabled()) {
// _logger.debug(result);
// }
}
|
diff --git a/src/main/java/com/skype/connector/linux/SkypeFramework.java b/src/main/java/com/skype/connector/linux/SkypeFramework.java
index 9d20259..28d65aa 100644
--- a/src/main/java/com/skype/connector/linux/SkypeFramework.java
+++ b/src/main/java/com/skype/connector/linux/SkypeFramework.java
@@ -1,128 +1,128 @@
/*******************************************************************************
* Copyright (c) 2006-2007 Koji Hisano <[email protected]> - UBION Inc. Developer
* Copyright (c) 2006-2007 UBION Inc. <http://www.ubion.co.jp/>
*
* Copyright (c) 2006-2007 Skype Technologies S.A. <http://www.skype.com/>
*
* Skype4Java is licensed under either the Apache License, Version 2.0 or
* the Eclipse Public License v1.0.
* You may use it freely in commercial and non-commercial products.
* You may obtain a copy of the licenses at
*
* the Apache License - http://www.apache.org/licenses/LICENSE-2.0
* the Eclipse Public License - http://www.eclipse.org/legal/epl-v10.html
*
* If it is possible to cooperate with the publicity of Skype4Java, please add
* links to the Skype4Java web site <https://developer.skype.com/wiki/Java_API>
* in your web site or documents.
*
* Contributors:
* Koji Hisano - initial API and implementation
* Gabriel Takeuchi - linux 64 bit support added
******************************************************************************/
package com.skype.connector.linux;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.lang.SystemUtils;
import com.skype.connector.ConnectorUtils;
import com.skype.connector.LoadLibraryException;
final class SkypeFramework {
private static final String SKYPE_API_LINUX_IMPL_PROPERTY = "skype.api.impl";
private static Object initializedFieldMutex = new Object();
private static boolean initialized = false;
private static CountDownLatch eventLoopFinishedLatch;
private static Thread eventLoop;
private static final List<SkypeFrameworkListener> listeners = new CopyOnWriteArrayList<SkypeFrameworkListener>();
public static boolean isDebugging;
static void setDebugging(boolean debug) {
isDebugging = true;
}
static boolean isDebugging() {
return isDebugging;
}
static void init() throws LoadLibraryException {
synchronized(initializedFieldMutex) {
if (!initialized) {
if (SystemUtils.OS_ARCH.contains("64")) {
ConnectorUtils.loadLibrary(getLibName("x64"));
}
else {
- ConnectorUtils.loadLibrary(getLibName("skype_x86"));
+ ConnectorUtils.loadLibrary(getLibName("x86"));
}
setup0();
eventLoopFinishedLatch = new CountDownLatch(1);
eventLoop = new Thread(new Runnable() {
public void run() {
runEventLoop0();
eventLoopFinishedLatch.countDown();
}
}, "Skype4Java Event Loop");
eventLoop.setDaemon(true);
eventLoop.start();
initialized = true;
}
}
}
private static String getLibName(String arch) {
String libImpl = System.getProperty(SKYPE_API_LINUX_IMPL_PROPERTY, "dbus");
return "libskype_"+libImpl+"_"+arch+".so";
}
private static native void setup0();
private static native void runEventLoop0();
static void addSkypeFrameworkListener(SkypeFrameworkListener listener) {
listeners.add(listener);
}
static void removeSkypeFrameworkListener(SkypeFrameworkListener listener) {
listeners.remove(listener);
}
static boolean isRunning() {
return isRunning0();
}
private static native boolean isRunning0();
static void sendCommand(String commandString) {
sendCommand0(commandString);
}
private static native void sendCommand0(String commandString);
static void fireNotificationReceived(String notificationString) {
for (SkypeFrameworkListener listener: listeners) {
listener.notificationReceived(notificationString);
}
}
static void dispose() {
synchronized(initializedFieldMutex) {
if (initialized) {
listeners.clear();
stopEventLoop0();
try {
eventLoopFinishedLatch.await();
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
closeDisplay0();
initialized = false;
}
}
}
private static native void stopEventLoop0();
private static native void closeDisplay0();
}
| true | true | static void init() throws LoadLibraryException {
synchronized(initializedFieldMutex) {
if (!initialized) {
if (SystemUtils.OS_ARCH.contains("64")) {
ConnectorUtils.loadLibrary(getLibName("x64"));
}
else {
ConnectorUtils.loadLibrary(getLibName("skype_x86"));
}
setup0();
eventLoopFinishedLatch = new CountDownLatch(1);
eventLoop = new Thread(new Runnable() {
public void run() {
runEventLoop0();
eventLoopFinishedLatch.countDown();
}
}, "Skype4Java Event Loop");
eventLoop.setDaemon(true);
eventLoop.start();
initialized = true;
}
}
}
| static void init() throws LoadLibraryException {
synchronized(initializedFieldMutex) {
if (!initialized) {
if (SystemUtils.OS_ARCH.contains("64")) {
ConnectorUtils.loadLibrary(getLibName("x64"));
}
else {
ConnectorUtils.loadLibrary(getLibName("x86"));
}
setup0();
eventLoopFinishedLatch = new CountDownLatch(1);
eventLoop = new Thread(new Runnable() {
public void run() {
runEventLoop0();
eventLoopFinishedLatch.countDown();
}
}, "Skype4Java Event Loop");
eventLoop.setDaemon(true);
eventLoop.start();
initialized = true;
}
}
}
|
diff --git a/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java b/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
index ffc9deb8..973b2c1a 100755
--- a/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
+++ b/core/src/main/java/org/mule/galaxy/impl/jcr/CommentManagerImpl.java
@@ -1,95 +1,95 @@
package org.mule.galaxy.impl.jcr;
import java.io.IOException;
import java.util.List;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.mule.galaxy.DuplicateItemException;
import org.mule.galaxy.Item;
import org.mule.galaxy.NotFoundException;
import org.mule.galaxy.collab.Comment;
import org.mule.galaxy.collab.CommentManager;
import org.mule.galaxy.event.EntryCommentCreatedEvent;
import org.mule.galaxy.event.EventManager;
import org.mule.galaxy.impl.jcr.onm.AbstractReflectionDao;
import org.mule.galaxy.util.SecurityUtils;
import org.springmodules.jcr.JcrCallback;
public class CommentManagerImpl extends AbstractReflectionDao<Comment> implements CommentManager {
private EventManager eventManager;
public CommentManagerImpl() throws Exception {
super(Comment.class, "comments", true);
}
public List<Comment> getComments(final String artifactId) {
return getComments(artifactId, false);
}
@SuppressWarnings("unchecked")
public List<Comment> getComments(final String artifactId, final boolean includeChildren) {
return (List<Comment>) execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
StringBuilder qstr = new StringBuilder();
qstr.append("/jcr:root/comments/*[");
if (!includeChildren) {
qstr.append("not(@parent) and");
}
qstr.append("@item='")
.append(artifactId)
.append("'] order by @date ascending");
return query(qstr.toString(), session);
}
});
}
@SuppressWarnings("unchecked")
public List<Comment> getRecentComments(final int maxResults) {
return (List<Comment>) execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
return query("/jcr:root/comments/* order by @date descending", session, maxResults);
}
});
}
public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
- parent = c.getParent();
+ parent = parent.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
public Comment getComment(String commentId) throws NotFoundException {
return get(commentId);
}
public EventManager getEventManager() {
return eventManager;
}
public void setEventManager(final EventManager eventManager) {
this.eventManager = eventManager;
}
}
| true | true | public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
parent = c.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
| public void addComment(Comment c) {
try {
save(c);
} catch (DuplicateItemException e1) {
// should never happen
throw new RuntimeException(e1);
} catch (NotFoundException e1) {
// should never happen
throw new RuntimeException(e1);
}
// fire the event
// FIXME: null pointer on test and itemNotFoundException over rpc
Item item = c.getItem();
Comment parent = c;
while (item == null) {
parent = parent.getParent();
item = parent.getItem();
}
EntryCommentCreatedEvent event = new EntryCommentCreatedEvent(item, c);
event.setUser(SecurityUtils.getCurrentUser());
eventManager.fireEvent(event);
}
|
diff --git a/com.buglabs.bug.bmi/com/buglabs/bug/bmi/BMIModuleEventHandler.java b/com.buglabs.bug.bmi/com/buglabs/bug/bmi/BMIModuleEventHandler.java
index 6127fc9..433b33f 100644
--- a/com.buglabs.bug.bmi/com/buglabs/bug/bmi/BMIModuleEventHandler.java
+++ b/com.buglabs.bug.bmi/com/buglabs/bug/bmi/BMIModuleEventHandler.java
@@ -1,167 +1,167 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Bug Labs, Inc.
* 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 Bug Labs, Inc. 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 OWNER 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 com.buglabs.bug.bmi;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.log.LogService;
import com.buglabs.bug.bmi.api.BMIModuleProperties;
import com.buglabs.bug.bmi.api.IModlet;
import com.buglabs.bug.bmi.api.IModletFactory;
import com.buglabs.util.osgi.LogServiceUtil;
/**
* Manages logic of receiving messages from BMI and making changes to runtime.
* runtime.
*
* @author ken
*
*/
public class BMIModuleEventHandler {
private static LogService logService;
private static Map<String, List<IModletFactory>> modletFactories;
private static Map<String, List<IModlet>> activeModlets;
/**
* @return Map of active IModlets
*/
public static Map<String, List<IModlet>> getActiveModlets() {
return activeModlets;
}
private final BundleContext context;
/**
* @param context BundleContext
* @param logService log service
* @param modletFactories map of modlet factories
* @param activeModlets map of active modlets
*/
protected BMIModuleEventHandler(BundleContext context, LogService logService, Map<String, List<IModletFactory>> modletFactories, Map<String, List<IModlet>> activeModlets) {
BMIModuleEventHandler.logService = logService;
BMIModuleEventHandler.modletFactories = modletFactories;
BMIModuleEventHandler.activeModlets = activeModlets;
this.context = context;
}
/**
* This method is responsible for loading and starting any bundles that
* provide Modlets for given module type.
*
* After bundle(s) are started, those bundles expose IModulet services. The
* BMI activator then listens for modlets. Upon new modlet creation, the
* setup is called.
*
* @param event event to handle
*/
public void handleEvent(BMIModuleEvent event) {
if (!modletFactories.containsKey(event.getModuleId())) {
logService.log(LogService.LOG_ERROR, "No modlet factories support module, aborting event: " + event.getModuleId());
return;
}
try {
List<IModlet> ml;
switch (event.getType()) {
case INSERT:
for (IModletFactory mf : modletFactories.get(event.getModuleId())) {
IModlet m = mf.createModlet(context, event.getSlot(), event.getBMIDevice());
try {
m.setup();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR, "Unable to setup Modlet " + mf.getName() + ": " + e.getMessage(), e);
continue;
}
m.start();
logService.log(LogService.LOG_INFO, "Started modlet from factory " + mf.getName() + "...");
// Add this model to our map of running Modlets.
if (!activeModlets.containsKey(m.getModuleId())) {
activeModlets.put(m.getModuleId(), new ArrayList<IModlet>());
}
List<IModlet> am = activeModlets.get(m.getModuleId());
if (!am.contains(m)) {
am.add(m);
}
}
break;
case REMOVE:
List<IModlet> removalList = new ArrayList<IModlet>();
ml = activeModlets.get(event.getModuleId());
for (IModlet m : ml) {
if (m.getSlotId() == event.getSlot()) {
logService.log(LogService.LOG_INFO, "Stopping modlet " + m.getModuleId() + "...");
m.stop();
removalList.add(m);
}
}
- for (IModlet m : ml)
+ for (IModlet m : removalList)
ml.remove(m);
removalList.clear();
logService.log(LogService.LOG_INFO, "Modlet removal complete.");
break;
}
} catch (BundleException e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
if (e.getNestedException() != null) {
logService.log(LogService.LOG_ERROR
, "Nested Exception: " + e.getNestedException().getClass().getName() + ", " + e.getNestedException().getMessage());
}
e.printStackTrace();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
}
}
}
| true | true | public void handleEvent(BMIModuleEvent event) {
if (!modletFactories.containsKey(event.getModuleId())) {
logService.log(LogService.LOG_ERROR, "No modlet factories support module, aborting event: " + event.getModuleId());
return;
}
try {
List<IModlet> ml;
switch (event.getType()) {
case INSERT:
for (IModletFactory mf : modletFactories.get(event.getModuleId())) {
IModlet m = mf.createModlet(context, event.getSlot(), event.getBMIDevice());
try {
m.setup();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR, "Unable to setup Modlet " + mf.getName() + ": " + e.getMessage(), e);
continue;
}
m.start();
logService.log(LogService.LOG_INFO, "Started modlet from factory " + mf.getName() + "...");
// Add this model to our map of running Modlets.
if (!activeModlets.containsKey(m.getModuleId())) {
activeModlets.put(m.getModuleId(), new ArrayList<IModlet>());
}
List<IModlet> am = activeModlets.get(m.getModuleId());
if (!am.contains(m)) {
am.add(m);
}
}
break;
case REMOVE:
List<IModlet> removalList = new ArrayList<IModlet>();
ml = activeModlets.get(event.getModuleId());
for (IModlet m : ml) {
if (m.getSlotId() == event.getSlot()) {
logService.log(LogService.LOG_INFO, "Stopping modlet " + m.getModuleId() + "...");
m.stop();
removalList.add(m);
}
}
for (IModlet m : ml)
ml.remove(m);
removalList.clear();
logService.log(LogService.LOG_INFO, "Modlet removal complete.");
break;
}
} catch (BundleException e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
if (e.getNestedException() != null) {
logService.log(LogService.LOG_ERROR
, "Nested Exception: " + e.getNestedException().getClass().getName() + ", " + e.getNestedException().getMessage());
}
e.printStackTrace();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
}
}
| public void handleEvent(BMIModuleEvent event) {
if (!modletFactories.containsKey(event.getModuleId())) {
logService.log(LogService.LOG_ERROR, "No modlet factories support module, aborting event: " + event.getModuleId());
return;
}
try {
List<IModlet> ml;
switch (event.getType()) {
case INSERT:
for (IModletFactory mf : modletFactories.get(event.getModuleId())) {
IModlet m = mf.createModlet(context, event.getSlot(), event.getBMIDevice());
try {
m.setup();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR, "Unable to setup Modlet " + mf.getName() + ": " + e.getMessage(), e);
continue;
}
m.start();
logService.log(LogService.LOG_INFO, "Started modlet from factory " + mf.getName() + "...");
// Add this model to our map of running Modlets.
if (!activeModlets.containsKey(m.getModuleId())) {
activeModlets.put(m.getModuleId(), new ArrayList<IModlet>());
}
List<IModlet> am = activeModlets.get(m.getModuleId());
if (!am.contains(m)) {
am.add(m);
}
}
break;
case REMOVE:
List<IModlet> removalList = new ArrayList<IModlet>();
ml = activeModlets.get(event.getModuleId());
for (IModlet m : ml) {
if (m.getSlotId() == event.getSlot()) {
logService.log(LogService.LOG_INFO, "Stopping modlet " + m.getModuleId() + "...");
m.stop();
removalList.add(m);
}
}
for (IModlet m : removalList)
ml.remove(m);
removalList.clear();
logService.log(LogService.LOG_INFO, "Modlet removal complete.");
break;
}
} catch (BundleException e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
if (e.getNestedException() != null) {
logService.log(LogService.LOG_ERROR
, "Nested Exception: " + e.getNestedException().getClass().getName() + ", " + e.getNestedException().getMessage());
}
e.printStackTrace();
} catch (Exception e) {
logService.log(LogService.LOG_ERROR
, "Bundle/Modlet error occurred: " + e.getClass().getName() + ", " + e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logService.log(LogService.LOG_ERROR, sw.getBuffer().toString());
}
}
|
diff --git a/lib/src/test/java/com/github/fhirschmann/clozegen/lib/generator/GapTest.java b/lib/src/test/java/com/github/fhirschmann/clozegen/lib/generator/GapTest.java
index b322b37..03d27ae 100644
--- a/lib/src/test/java/com/github/fhirschmann/clozegen/lib/generator/GapTest.java
+++ b/lib/src/test/java/com/github/fhirschmann/clozegen/lib/generator/GapTest.java
@@ -1,86 +1,86 @@
/*
* Copyright (C) 2012 Fabian Hirschmann <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.github.fhirschmann.clozegen.lib.generator;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.matchers.JUnitMatchers.*;
/**
*
* @author Fabian Hirschmann <[email protected]>
*/
public class GapTest {
private Gap gap;
private Gap gap2;
@Before
public void setUp() {
gap = new Gap();
gap.addValidAnswers("val1", "val2");
gap.addInvalidAnswers("inval1", "inval2", "inval3");
gap2 = new Gap();
- gap2 = new Gap(Sets.newHashSet("val1", "val2"),
+ gap2 = Gap.with(Sets.newHashSet("val1", "val2"),
Sets.newHashSet("inval1", "inval2", "inval3"));
gap2.addValidAnswers("val1", "val2");
}
@Test
public void testGetInvalidAnswers() {
assertEquals(Sets.newHashSet("inval1", "inval2", "inval3"),
gap.getInvalidAnswers());
}
@Test
public void testGetValidAnswers() {
assertEquals(Sets.newHashSet("val1", "val2"), gap.getValidAnswers());
}
@Test
public void testGetAllAnswers() {
assertEquals(Sets.newHashSet("inval1", "inval2", "inval3", "val1", "val2"),
gap.getAllAnswers());
}
@Test
public void testHashCode() {
assertEquals(gap2.hashCode(), gap.hashCode());
}
@Test
public void testEquals() {
assertEquals(gap2, gap);
assertFalse(gap.equals(null));
}
@Test
public void testToString() {
assertEquals("Gap{valid=[val1, val2], invalid=[inval3, inval2, inval1]}",
gap.toString());
}
@Test
public void testWith_String_StringArr() {
Gap gap = Gap.with("foo", "bar", "bar2");
assertThat(gap.getValidAnswers(), hasItem("foo"));
assertThat(gap.getInvalidAnswers(), hasItems("bar", "bar2"));
}
}
| true | true | public void setUp() {
gap = new Gap();
gap.addValidAnswers("val1", "val2");
gap.addInvalidAnswers("inval1", "inval2", "inval3");
gap2 = new Gap();
gap2 = new Gap(Sets.newHashSet("val1", "val2"),
Sets.newHashSet("inval1", "inval2", "inval3"));
gap2.addValidAnswers("val1", "val2");
}
| public void setUp() {
gap = new Gap();
gap.addValidAnswers("val1", "val2");
gap.addInvalidAnswers("inval1", "inval2", "inval3");
gap2 = new Gap();
gap2 = Gap.with(Sets.newHashSet("val1", "val2"),
Sets.newHashSet("inval1", "inval2", "inval3"));
gap2.addValidAnswers("val1", "val2");
}
|
diff --git a/src/main/java/com/github/derwisch/paperMail/PaperMailCommandExecutor.java b/src/main/java/com/github/derwisch/paperMail/PaperMailCommandExecutor.java
index a486096..e2517ee 100644
--- a/src/main/java/com/github/derwisch/paperMail/PaperMailCommandExecutor.java
+++ b/src/main/java/com/github/derwisch/paperMail/PaperMailCommandExecutor.java
@@ -1,190 +1,185 @@
package com.github.derwisch.paperMail;
import java.io.IOException;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class PaperMailCommandExecutor implements CommandExecutor {
private PaperMail plugin;
private double Cost = Settings.Price;
public PaperMailCommandExecutor(PaperMail plugin) {
this.plugin = plugin;
this.plugin.getLogger().info("ItemMailCommandExecutor initialized");
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("papermail")){
if (!(sender instanceof Player) && args.length > 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
} else {
if (args.length == 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
}
Player player = (Player) sender;
if (!args[0].toLowerCase().equals("sendtext") && !args[0].toLowerCase().equals("createbox")) {
player.sendMessage(ChatColor.DARK_RED + "invalid argument \"" + args[0] + "\"" + ChatColor.RESET);
return true;
}
if (Settings.EnableTextMail && args[0].toLowerCase().equals("sendtext") && player.hasPermission(Permissions.SEND_TEXT_PERM)) {
if (args.length < 3) {
if (args.length < 2) {
player.sendMessage(ChatColor.DARK_RED + "Missing arguments for textmail!" + ChatColor.RESET);
return true;
}
player.sendMessage(ChatColor.DARK_RED + "Missing text of textmail!" + ChatColor.RESET);
return true;
}
//if player isn't cost exempt and costs is enabled and price is set, try to send textmail
if((Settings.EnableMailCosts == true) && (Settings.Price != 0) && (!player.hasPermission(Permissions.COSTS_EXEMPT))){
//check if player has the correct amount of currency
if(PaperMailEconomy.hasMoney(Settings.Price, player) == true){
sendText(player, args);
PaperMailEconomy.takeMoney(Cost, player);
return true;
//if player doesn't have enough money don't send textmail
}else{
player.sendMessage(ChatColor.RED + "Not Enough Money to send your mail!");
return true;
}
}
- //if costs are turned off send textmail
- if(Settings.EnableMailCosts == false){
- sendText(player, args);
- return true;
- }
- //if player is cost exempt send textmail
- if(player.hasPermission(Permissions.COSTS_EXEMPT)){
+ //if player is cost exempt or price is zero or mailcosts is off send textmail
+ if((Settings.EnableMailCosts == false) || (player.hasPermission(Permissions.COSTS_EXEMPT) && (Settings.EnableMailCosts == true)) || ((Settings.EnableMailCosts == true) && (Settings.Price == 0) && (!player.hasPermission(Permissions.COSTS_EXEMPT)))){
sendText(player, args);
return true;
}
}
//create inbox chest
if (args[0].toLowerCase().equals("createbox")) {
Inbox inbox = null;
if (args.length == 1 && (player.hasPermission(Permissions.CREATE_CHEST_SELF_PERM) || player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM))) {
try {
inbox = Inbox.GetInbox(player.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (args.length == 2 && player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM)) {
try {
inbox = Inbox.GetInbox(args[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
player.sendMessage(ChatColor.DARK_RED + "Too many arguments!" + ChatColor.RESET);
return true;
}
Block block = player.getTargetBlock(null, 10);
if (block != null && block.getType() == Material.CHEST) {
Chest chest = (Chest)block.getState();
inbox.SetChest(chest);
player.sendMessage(ChatColor.DARK_GREEN + "Inbox created!" + ChatColor.RESET);
return true;
} else {
player.sendMessage(ChatColor.DARK_RED + "You must focus a chest" + ChatColor.RESET);
return true;
}
}
}
return true;
}
return false;
}
//Send the textmail
public void sendText(Player player, String[] args){
ItemStack itemStack = new ItemStack(Material.PAPER);
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setDisplayName(ChatColor.WHITE + "Letter from " + player.getName() + ChatColor.RESET);
ArrayList<String> lines = new ArrayList<String>();
int count = 0;
String currentLine = "";
for (int i = 2; i < args.length; i++) {
currentLine += args[i] + " ";
count += args[i].length() + 1;
if (++count >= 20) {
count = 0;
lines.add(ChatColor.GRAY + currentLine + ChatColor.RESET);
currentLine = "";
}
}
if (currentLine != "") {
lines.add(ChatColor.GRAY + currentLine + ChatColor.RESET);
}
itemMeta.setLore(lines);
itemStack.setItemMeta(itemMeta);
String playerName = args[1];
Player p = Bukkit.getPlayer(playerName);
if (p != null) {
playerName = p.getName();
} else {
OfflinePlayer op = Bukkit.getOfflinePlayer(playerName);
if (op != null) {
playerName = op.getName();
player.sendMessage(ChatColor.GREEN + "Player " + playerName + " is Offline. Dropping it in their mailbox!" + ChatColor.RESET);
} else {
playerName = args[1];
player.sendMessage(ChatColor.DARK_RED + "Player " + playerName + " may not exist or doesn't have an Inbox yet. Creating Inbox for player " + playerName + ChatColor.RESET);
}
}
try {
Inbox.GetInbox(playerName).AddItem(itemStack, player);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.sendMessage(ChatColor.DARK_GREEN + "Textmail sent to " + playerName + "!" + ChatColor.RESET);
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("papermail")){
if (!(sender instanceof Player) && args.length > 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
} else {
if (args.length == 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
}
Player player = (Player) sender;
if (!args[0].toLowerCase().equals("sendtext") && !args[0].toLowerCase().equals("createbox")) {
player.sendMessage(ChatColor.DARK_RED + "invalid argument \"" + args[0] + "\"" + ChatColor.RESET);
return true;
}
if (Settings.EnableTextMail && args[0].toLowerCase().equals("sendtext") && player.hasPermission(Permissions.SEND_TEXT_PERM)) {
if (args.length < 3) {
if (args.length < 2) {
player.sendMessage(ChatColor.DARK_RED + "Missing arguments for textmail!" + ChatColor.RESET);
return true;
}
player.sendMessage(ChatColor.DARK_RED + "Missing text of textmail!" + ChatColor.RESET);
return true;
}
//if player isn't cost exempt and costs is enabled and price is set, try to send textmail
if((Settings.EnableMailCosts == true) && (Settings.Price != 0) && (!player.hasPermission(Permissions.COSTS_EXEMPT))){
//check if player has the correct amount of currency
if(PaperMailEconomy.hasMoney(Settings.Price, player) == true){
sendText(player, args);
PaperMailEconomy.takeMoney(Cost, player);
return true;
//if player doesn't have enough money don't send textmail
}else{
player.sendMessage(ChatColor.RED + "Not Enough Money to send your mail!");
return true;
}
}
//if costs are turned off send textmail
if(Settings.EnableMailCosts == false){
sendText(player, args);
return true;
}
//if player is cost exempt send textmail
if(player.hasPermission(Permissions.COSTS_EXEMPT)){
sendText(player, args);
return true;
}
}
//create inbox chest
if (args[0].toLowerCase().equals("createbox")) {
Inbox inbox = null;
if (args.length == 1 && (player.hasPermission(Permissions.CREATE_CHEST_SELF_PERM) || player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM))) {
try {
inbox = Inbox.GetInbox(player.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (args.length == 2 && player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM)) {
try {
inbox = Inbox.GetInbox(args[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
player.sendMessage(ChatColor.DARK_RED + "Too many arguments!" + ChatColor.RESET);
return true;
}
Block block = player.getTargetBlock(null, 10);
if (block != null && block.getType() == Material.CHEST) {
Chest chest = (Chest)block.getState();
inbox.SetChest(chest);
player.sendMessage(ChatColor.DARK_GREEN + "Inbox created!" + ChatColor.RESET);
return true;
} else {
player.sendMessage(ChatColor.DARK_RED + "You must focus a chest" + ChatColor.RESET);
return true;
}
}
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("papermail")){
if (!(sender instanceof Player) && args.length > 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
} else {
if (args.length == 0) {
sender.sendMessage("Current Version of ItemMail is " + PaperMail.instance.getDescription().getVersion());
return true;
}
Player player = (Player) sender;
if (!args[0].toLowerCase().equals("sendtext") && !args[0].toLowerCase().equals("createbox")) {
player.sendMessage(ChatColor.DARK_RED + "invalid argument \"" + args[0] + "\"" + ChatColor.RESET);
return true;
}
if (Settings.EnableTextMail && args[0].toLowerCase().equals("sendtext") && player.hasPermission(Permissions.SEND_TEXT_PERM)) {
if (args.length < 3) {
if (args.length < 2) {
player.sendMessage(ChatColor.DARK_RED + "Missing arguments for textmail!" + ChatColor.RESET);
return true;
}
player.sendMessage(ChatColor.DARK_RED + "Missing text of textmail!" + ChatColor.RESET);
return true;
}
//if player isn't cost exempt and costs is enabled and price is set, try to send textmail
if((Settings.EnableMailCosts == true) && (Settings.Price != 0) && (!player.hasPermission(Permissions.COSTS_EXEMPT))){
//check if player has the correct amount of currency
if(PaperMailEconomy.hasMoney(Settings.Price, player) == true){
sendText(player, args);
PaperMailEconomy.takeMoney(Cost, player);
return true;
//if player doesn't have enough money don't send textmail
}else{
player.sendMessage(ChatColor.RED + "Not Enough Money to send your mail!");
return true;
}
}
//if player is cost exempt or price is zero or mailcosts is off send textmail
if((Settings.EnableMailCosts == false) || (player.hasPermission(Permissions.COSTS_EXEMPT) && (Settings.EnableMailCosts == true)) || ((Settings.EnableMailCosts == true) && (Settings.Price == 0) && (!player.hasPermission(Permissions.COSTS_EXEMPT)))){
sendText(player, args);
return true;
}
}
//create inbox chest
if (args[0].toLowerCase().equals("createbox")) {
Inbox inbox = null;
if (args.length == 1 && (player.hasPermission(Permissions.CREATE_CHEST_SELF_PERM) || player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM))) {
try {
inbox = Inbox.GetInbox(player.getName());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (args.length == 2 && player.hasPermission(Permissions.CREATE_CHEST_ALL_PERM)) {
try {
inbox = Inbox.GetInbox(args[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
player.sendMessage(ChatColor.DARK_RED + "Too many arguments!" + ChatColor.RESET);
return true;
}
Block block = player.getTargetBlock(null, 10);
if (block != null && block.getType() == Material.CHEST) {
Chest chest = (Chest)block.getState();
inbox.SetChest(chest);
player.sendMessage(ChatColor.DARK_GREEN + "Inbox created!" + ChatColor.RESET);
return true;
} else {
player.sendMessage(ChatColor.DARK_RED + "You must focus a chest" + ChatColor.RESET);
return true;
}
}
}
return true;
}
return false;
}
|
diff --git a/src/test/java/com/jeklsoft/cassandraclient/BaseReadingsTest.java b/src/test/java/com/jeklsoft/cassandraclient/BaseReadingsTest.java
index 42ff02e..b090c1a 100644
--- a/src/test/java/com/jeklsoft/cassandraclient/BaseReadingsTest.java
+++ b/src/test/java/com/jeklsoft/cassandraclient/BaseReadingsTest.java
@@ -1,90 +1,92 @@
package com.jeklsoft.cassandraclient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Interval;
public class BaseReadingsTest {
private static final Logger log = Logger.getLogger(BaseReadingsTest.class);
protected static final String configurationPath = "/tmp/cassandra";
protected static final String cassandraHostname = "localhost";
protected static final Integer cassandraPort = 9160;
protected static final String cassandraKeySpaceName = "Climate";
protected static final String cassandraClusterName = "SensorNet";
protected static final String columnFamilyName = "BoulderSensors";
protected void runAccessorTest(ReadingsPersistor persistor) {
UUID sensorId1 = new UUID(0, 100);
UUID sensorId2 = new UUID(0, 200);
DateTime baseDate = new DateTime();
int readingInterval = 15; // 15 minutes
List<Reading> readings = new ArrayList<Reading>();
for (int ii = 0; ii < 10; ii++) {
BigDecimal temperature = new BigDecimal(230 + ii).movePointLeft(1);
readings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * ii), temperature,
16, "W", BigInteger.valueOf(17L), false));
temperature = new BigDecimal(195 - ii).movePointLeft(1);
readings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii), temperature,
24, "ESE", BigInteger.valueOf(17L), false));
}
persistor.addReadings(readings);
List<Reading> expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 3; ii++) {
BigDecimal temperature = new BigDecimal(234 + ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * (ii + 4)),
temperature, 16, "W", BigInteger.valueOf(17L), false));
}
DateTime startTime = new DateTime(baseDate.plusMinutes(readingInterval * 4));
DateTime endTime = new DateTime(baseDate.plusMinutes(readingInterval * 6));
Duration duration = new Duration(startTime, endTime);
Interval interval = new Interval(startTime, duration);
List<Reading> returnedReadings = persistor.querySensorReadingsByInterval(sensorId1, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
+ log.info("Sensor1: " + expectedReading);
assertTrue(returnedReadings.contains(expectedReading));
}
expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 4; ii++) {
BigDecimal temperature = new BigDecimal(195 - ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii),
temperature, 24, "ESE", BigInteger.valueOf(17L), false));
}
startTime = new DateTime(baseDate);
endTime = new DateTime(baseDate.plusMinutes(readingInterval * 3));
duration = new Duration(startTime, endTime);
interval = new Interval(startTime, duration);
returnedReadings = persistor.querySensorReadingsByInterval(sensorId2, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
+ log.info("Sensor2: " + expectedReading);
assertTrue(returnedReadings.contains(expectedReading));
}
}
}
| false | true | protected void runAccessorTest(ReadingsPersistor persistor) {
UUID sensorId1 = new UUID(0, 100);
UUID sensorId2 = new UUID(0, 200);
DateTime baseDate = new DateTime();
int readingInterval = 15; // 15 minutes
List<Reading> readings = new ArrayList<Reading>();
for (int ii = 0; ii < 10; ii++) {
BigDecimal temperature = new BigDecimal(230 + ii).movePointLeft(1);
readings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * ii), temperature,
16, "W", BigInteger.valueOf(17L), false));
temperature = new BigDecimal(195 - ii).movePointLeft(1);
readings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii), temperature,
24, "ESE", BigInteger.valueOf(17L), false));
}
persistor.addReadings(readings);
List<Reading> expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 3; ii++) {
BigDecimal temperature = new BigDecimal(234 + ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * (ii + 4)),
temperature, 16, "W", BigInteger.valueOf(17L), false));
}
DateTime startTime = new DateTime(baseDate.plusMinutes(readingInterval * 4));
DateTime endTime = new DateTime(baseDate.plusMinutes(readingInterval * 6));
Duration duration = new Duration(startTime, endTime);
Interval interval = new Interval(startTime, duration);
List<Reading> returnedReadings = persistor.querySensorReadingsByInterval(sensorId1, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
assertTrue(returnedReadings.contains(expectedReading));
}
expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 4; ii++) {
BigDecimal temperature = new BigDecimal(195 - ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii),
temperature, 24, "ESE", BigInteger.valueOf(17L), false));
}
startTime = new DateTime(baseDate);
endTime = new DateTime(baseDate.plusMinutes(readingInterval * 3));
duration = new Duration(startTime, endTime);
interval = new Interval(startTime, duration);
returnedReadings = persistor.querySensorReadingsByInterval(sensorId2, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
assertTrue(returnedReadings.contains(expectedReading));
}
}
| protected void runAccessorTest(ReadingsPersistor persistor) {
UUID sensorId1 = new UUID(0, 100);
UUID sensorId2 = new UUID(0, 200);
DateTime baseDate = new DateTime();
int readingInterval = 15; // 15 minutes
List<Reading> readings = new ArrayList<Reading>();
for (int ii = 0; ii < 10; ii++) {
BigDecimal temperature = new BigDecimal(230 + ii).movePointLeft(1);
readings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * ii), temperature,
16, "W", BigInteger.valueOf(17L), false));
temperature = new BigDecimal(195 - ii).movePointLeft(1);
readings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii), temperature,
24, "ESE", BigInteger.valueOf(17L), false));
}
persistor.addReadings(readings);
List<Reading> expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 3; ii++) {
BigDecimal temperature = new BigDecimal(234 + ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId1, baseDate.plusMinutes(readingInterval * (ii + 4)),
temperature, 16, "W", BigInteger.valueOf(17L), false));
}
DateTime startTime = new DateTime(baseDate.plusMinutes(readingInterval * 4));
DateTime endTime = new DateTime(baseDate.plusMinutes(readingInterval * 6));
Duration duration = new Duration(startTime, endTime);
Interval interval = new Interval(startTime, duration);
List<Reading> returnedReadings = persistor.querySensorReadingsByInterval(sensorId1, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
log.info("Sensor1: " + expectedReading);
assertTrue(returnedReadings.contains(expectedReading));
}
expectedReadings = new ArrayList<Reading>();
for (int ii = 0; ii < 4; ii++) {
BigDecimal temperature = new BigDecimal(195 - ii).movePointLeft(1);
expectedReadings.add(new Reading(sensorId2, baseDate.plusMinutes(readingInterval * ii),
temperature, 24, "ESE", BigInteger.valueOf(17L), false));
}
startTime = new DateTime(baseDate);
endTime = new DateTime(baseDate.plusMinutes(readingInterval * 3));
duration = new Duration(startTime, endTime);
interval = new Interval(startTime, duration);
returnedReadings = persistor.querySensorReadingsByInterval(sensorId2, interval, 10);
assertEquals(expectedReadings.size(), returnedReadings.size());
for (Reading expectedReading : expectedReadings) {
log.info("Sensor2: " + expectedReading);
assertTrue(returnedReadings.contains(expectedReading));
}
}
|
diff --git a/src/test/java/org/jboss/ejb/client/test/client/EJBClientAPIUsageTestCase.java b/src/test/java/org/jboss/ejb/client/test/client/EJBClientAPIUsageTestCase.java
index 0d3dce7..f227e73 100644
--- a/src/test/java/org/jboss/ejb/client/test/client/EJBClientAPIUsageTestCase.java
+++ b/src/test/java/org/jboss/ejb/client/test/client/EJBClientAPIUsageTestCase.java
@@ -1,105 +1,105 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb.client.test.client;
import org.jboss.ejb.client.EJBClient;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.ejb.client.Locator;
import org.jboss.ejb.client.StatelessEJBLocator;
import org.jboss.ejb.client.test.common.AnonymousCallbackHandler;
import org.jboss.ejb.client.test.common.DummyServer;
import org.jboss.remoting3.Connection;
import org.jboss.remoting3.Endpoint;
import org.jboss.remoting3.Registration;
import org.jboss.remoting3.Remoting;
import org.jboss.remoting3.remote.RemoteConnectionProviderFactory;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.xnio.IoFuture;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
import java.net.URI;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.jboss.ejb.client.remoting.IoFutureHelper.get;
/**
* User: jpai
*/
public class EJBClientAPIUsageTestCase {
private static DummyServer server;
private static Connection connection;
@AfterClass
public static void afterClass() throws Exception {
if (server != null) {
server.stop();
}
}
@BeforeClass
public static void beforeClass() throws Exception {
server = new DummyServer("localhost", 6999);
server.start();
- server.register("my-app", "my-module", null, EchoBean.class.getSimpleName(), new EchoBean());
+ server.register("my-app", "my-module", "", EchoBean.class.getSimpleName(), new EchoBean());
final Endpoint endpoint = Remoting.createEndpoint("endpoint", Executors.newSingleThreadExecutor(), OptionMap.EMPTY);
final Xnio xnio = Xnio.getInstance();
final Registration registration = endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(xnio), OptionMap.create(Options.SSL_ENABLED, false));
// open a connection
final IoFuture<Connection> futureConnection = endpoint.connect(new URI("remote://localhost:6999"), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE), new AnonymousCallbackHandler());
connection = get(futureConnection, 5, TimeUnit.SECONDS);
}
@Test
public void testProxyGeneration() throws Exception {
final StatelessEJBLocator<EchoRemote> statelessEJBLocator = new StatelessEJBLocator<EchoRemote>(EchoRemote.class, "my-app", "my-module", EchoBean.class.getSimpleName(), "");
final EchoRemote proxy = EJBClient.createProxy(statelessEJBLocator);
Assert.assertNotNull("Received a null proxy", proxy);
}
@Test
public void testProxyInvocation() throws Exception {
final StatelessEJBLocator<EchoRemote> statelessEJBLocator = new StatelessEJBLocator<EchoRemote>(EchoRemote.class, "my-app", "my-module", EchoBean.class.getSimpleName(), "");
final EchoRemote proxy = EJBClient.createProxy(statelessEJBLocator);
Assert.assertNotNull("Received a null proxy", proxy);
final String message = "Yet another Hello World!!!";
EJBClientContext ejbClientContext = EJBClientContext.create();
try {
ejbClientContext.registerConnection(connection);
final String echo = proxy.echo(message);
Assert.assertEquals("Unexpected echo message", message, echo);
} finally {
EJBClientContext.suspendCurrent();
}
}
}
| true | true | public static void beforeClass() throws Exception {
server = new DummyServer("localhost", 6999);
server.start();
server.register("my-app", "my-module", null, EchoBean.class.getSimpleName(), new EchoBean());
final Endpoint endpoint = Remoting.createEndpoint("endpoint", Executors.newSingleThreadExecutor(), OptionMap.EMPTY);
final Xnio xnio = Xnio.getInstance();
final Registration registration = endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(xnio), OptionMap.create(Options.SSL_ENABLED, false));
// open a connection
final IoFuture<Connection> futureConnection = endpoint.connect(new URI("remote://localhost:6999"), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE), new AnonymousCallbackHandler());
connection = get(futureConnection, 5, TimeUnit.SECONDS);
}
| public static void beforeClass() throws Exception {
server = new DummyServer("localhost", 6999);
server.start();
server.register("my-app", "my-module", "", EchoBean.class.getSimpleName(), new EchoBean());
final Endpoint endpoint = Remoting.createEndpoint("endpoint", Executors.newSingleThreadExecutor(), OptionMap.EMPTY);
final Xnio xnio = Xnio.getInstance();
final Registration registration = endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(xnio), OptionMap.create(Options.SSL_ENABLED, false));
// open a connection
final IoFuture<Connection> futureConnection = endpoint.connect(new URI("remote://localhost:6999"), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE), new AnonymousCallbackHandler());
connection = get(futureConnection, 5, TimeUnit.SECONDS);
}
|
diff --git a/modules/xdr/src/main/java/org/dcache/xdr/RpcMessageParserTCP.java b/modules/xdr/src/main/java/org/dcache/xdr/RpcMessageParserTCP.java
index 45d92b55ea..c81f2c287b 100644
--- a/modules/xdr/src/main/java/org/dcache/xdr/RpcMessageParserTCP.java
+++ b/modules/xdr/src/main/java/org/dcache/xdr/RpcMessageParserTCP.java
@@ -1,153 +1,153 @@
/*
* 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 program (see the file COPYING.LIB for more details); if not,
* write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
* 02139, USA.
*/
package org.dcache.xdr;
import java.io.IOException;
import java.nio.ByteOrder;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import org.glassfish.grizzly.memory.Buffers;
import org.glassfish.grizzly.memory.BuffersBuffer;
import org.glassfish.grizzly.memory.MemoryManager;
public class RpcMessageParserTCP extends BaseFilter {
/**
* RPC fragment record marker mask
*/
private final static int RPC_LAST_FRAG = 0x80000000;
/**
* RPC fragment size mask
*/
private final static int RPC_SIZE_MASK = 0x7fffffff;
@Override
public NextAction handleRead(FilterChainContext ctx) throws IOException {
Buffer messageBuffer = ctx.getMessage();
if (messageBuffer == null) {
return ctx.getStopAction();
}
if (!isAllFragmentsArrived(messageBuffer)) {
return ctx.getStopAction(messageBuffer);
}
ctx.setMessage(assembleXdr(messageBuffer));
final Buffer reminder = messageBuffer.hasRemaining()
? messageBuffer.split(messageBuffer.position()) : null;
return ctx.getInvokeAction(reminder);
}
@Override
public NextAction handleWrite(FilterChainContext ctx) throws IOException {
Buffer b = ctx.getMessage();
int len = b.remaining() | RPC_LAST_FRAG;
byte[] bytes = new byte[4];
Buffer marker = Buffers.wrap(MemoryManager.DEFAULT_MEMORY_MANAGER, bytes);
marker.order(ByteOrder.BIG_ENDIAN);
marker.putInt(len);
marker.flip();
marker.allowBufferDispose(true);
b.allowBufferDispose(true);
Buffer composite = BuffersBuffer.create(MemoryManager.DEFAULT_MEMORY_MANAGER,
marker, b );
composite.allowBufferDispose(true);
ctx.setMessage(composite);
return ctx.getInvokeAction();
}
private boolean isAllFragmentsArrived(Buffer messageBuffer) throws IOException {
final Buffer buffer = messageBuffer.duplicate();
buffer.order(ByteOrder.BIG_ENDIAN);
while (buffer.remaining() >= 4) {
int messageMarker = buffer.getInt();
int size = getMessageSize(messageMarker);
/*
* fragmen size bigger than we have received
*/
if (size > buffer.remaining()) {
return false;
}
/*
* complete fragment received
*/
if (isLastFragment(messageMarker)) {
return true;
}
/*
* seek to the end of the current fragment
*/
buffer.position(buffer.position() + size);
}
return false;
}
private int getMessageSize(int marker) {
return marker & RPC_SIZE_MASK;
}
private boolean isLastFragment(int marker) {
return (marker & RPC_LAST_FRAG) != 0;
}
private Xdr assembleXdr(Buffer messageBuffer) {
Buffer currentFragment = null;
- BuffersBuffer multipleFarments = null;
+ BuffersBuffer multipleFragments = null;
boolean messageComplete;
do {
int messageMarker = messageBuffer.getInt();
int size = getMessageSize(messageMarker);
messageComplete = isLastFragment(messageMarker);
int pos = messageBuffer.position();
currentFragment = messageBuffer.slice(pos, pos + size);
currentFragment.limit(size);
messageBuffer.position(pos + size);
- if (!messageComplete & multipleFarments == null) {
+ if (!messageComplete & multipleFragments == null) {
/*
* we use composite buffer only if required as they not for
* free.
*/
- multipleFarments = BuffersBuffer.create();
+ multipleFragments = BuffersBuffer.create();
}
- if (multipleFarments != null) {
- multipleFarments.append(currentFragment);
+ if (multipleFragments != null) {
+ multipleFragments.append(currentFragment);
}
} while (!messageComplete);
- return new Xdr(multipleFarments == null ? currentFragment : messageBuffer);
+ return new Xdr(multipleFragments == null ? currentFragment : multipleFragments);
}
}
| false | true | private Xdr assembleXdr(Buffer messageBuffer) {
Buffer currentFragment = null;
BuffersBuffer multipleFarments = null;
boolean messageComplete;
do {
int messageMarker = messageBuffer.getInt();
int size = getMessageSize(messageMarker);
messageComplete = isLastFragment(messageMarker);
int pos = messageBuffer.position();
currentFragment = messageBuffer.slice(pos, pos + size);
currentFragment.limit(size);
messageBuffer.position(pos + size);
if (!messageComplete & multipleFarments == null) {
/*
* we use composite buffer only if required as they not for
* free.
*/
multipleFarments = BuffersBuffer.create();
}
if (multipleFarments != null) {
multipleFarments.append(currentFragment);
}
} while (!messageComplete);
return new Xdr(multipleFarments == null ? currentFragment : messageBuffer);
}
| private Xdr assembleXdr(Buffer messageBuffer) {
Buffer currentFragment = null;
BuffersBuffer multipleFragments = null;
boolean messageComplete;
do {
int messageMarker = messageBuffer.getInt();
int size = getMessageSize(messageMarker);
messageComplete = isLastFragment(messageMarker);
int pos = messageBuffer.position();
currentFragment = messageBuffer.slice(pos, pos + size);
currentFragment.limit(size);
messageBuffer.position(pos + size);
if (!messageComplete & multipleFragments == null) {
/*
* we use composite buffer only if required as they not for
* free.
*/
multipleFragments = BuffersBuffer.create();
}
if (multipleFragments != null) {
multipleFragments.append(currentFragment);
}
} while (!messageComplete);
return new Xdr(multipleFragments == null ? currentFragment : multipleFragments);
}
|
diff --git a/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java b/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java
index 3e95d64c6..5c8b65e18 100644
--- a/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java
+++ b/adm/src/main/java/de/escidoc/core/adm/business/admin/ReindexStatus.java
@@ -1,138 +1,138 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2009 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.core.adm.business.admin;
import de.escidoc.core.common.business.fedora.resources.ResourceType;
/**
* Singleton which contains all information about a running or finished
* reindexing process.
*
* @author mih
*/
public final class ReindexStatus extends AdminMethodStatus {
/**
* Singleton instance.
*/
private static final ReindexStatus instance = new ReindexStatus();
/**
* Create a new ReindexStatus object.
*/
private ReindexStatus() {
}
/**
* Decrease the number of resources of the given type which still have to be
* processed.
*
* @param type
* resource type
*/
public synchronized void dec(final ResourceType type) {
final Integer oldValue = get(type);
if (oldValue != null) {
if (oldValue == 1) {
remove(type);
}
else {
treeMap.put(type, oldValue - 1);
}
}
if (this.isFillingComplete() && (size() == 0)) {
finishMethod();
}
}
/**
* Get the singleton instance.
*
* @return ReindexStatus singleton
*/
public static ReindexStatus getInstance() {
return instance;
}
/**
* Increase the number of resources of the given type which still have to be
* processed.
*
* @param type
* resource type
*/
public synchronized void inc(final ResourceType type) {
final Integer oldValue = get(type);
if (oldValue != null) {
treeMap.put(type, oldValue + 1);
}
else {
treeMap.put(type, 1);
}
}
/**
* Set a flag to signalize that the queue was completely filled. Now an
* empty queue would mean the whole process has been finished.
*/
public void setFillingComplete() {
this.setFillingComplete(true);
if (size() == 0) {
finishMethod();
}
}
/**
* Return a string representation of the object.
*
* @return a string representation of this object
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
if (getCompletionDate() != null) {
result.append("<message>reindexing finished at ").append(getCompletionDate()).append("</message>\n");
}
else {
result.append("<message>reindexing currently running</message>\n");
for (final Entry e : entrySet()) {
result.append("<message>\n");
result.append(e.getValue());
result.append(' ');
- result.append(e.getKey());
+ result.append(e.getLabel());
result.append("(s) still to be reindexed\n");
result.append("</message>\n");
}
}
return result.toString();
}
}
| true | true | public String toString() {
final StringBuilder result = new StringBuilder();
if (getCompletionDate() != null) {
result.append("<message>reindexing finished at ").append(getCompletionDate()).append("</message>\n");
}
else {
result.append("<message>reindexing currently running</message>\n");
for (final Entry e : entrySet()) {
result.append("<message>\n");
result.append(e.getValue());
result.append(' ');
result.append(e.getKey());
result.append("(s) still to be reindexed\n");
result.append("</message>\n");
}
}
return result.toString();
}
| public String toString() {
final StringBuilder result = new StringBuilder();
if (getCompletionDate() != null) {
result.append("<message>reindexing finished at ").append(getCompletionDate()).append("</message>\n");
}
else {
result.append("<message>reindexing currently running</message>\n");
for (final Entry e : entrySet()) {
result.append("<message>\n");
result.append(e.getValue());
result.append(' ');
result.append(e.getLabel());
result.append("(s) still to be reindexed\n");
result.append("</message>\n");
}
}
return result.toString();
}
|
diff --git a/src/de/ueller/midlet/gps/Trace.java b/src/de/ueller/midlet/gps/Trace.java
index 5bce01b3..0dcb65b0 100644
--- a/src/de/ueller/midlet/gps/Trace.java
+++ b/src/de/ueller/midlet/gps/Trace.java
@@ -1,2044 +1,2044 @@
package de.ueller.midlet.gps;
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See Copying
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;
import de.ueller.gps.SECellID;
import de.ueller.gps.data.Configuration;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satelit;
import de.ueller.gps.nmea.NmeaInput;
import de.ueller.gps.sirf.SirfInput;
import de.ueller.gps.tools.HelperRoutines;
import de.ueller.gps.tools.intTree;
import de.ueller.gps.tools.Shape;
import de.ueller.gpsMid.mapData.DictReader;
//#if polish.api.osm-editing
import de.ueller.gpsMid.GUIosmWayDisplay;
import de.ueller.midlet.gps.data.EditableWay;
//#endif
import de.ueller.gpsMid.mapData.QueueDataReader;
import de.ueller.gpsMid.mapData.QueueDictReader;
import de.ueller.gpsMid.mapData.Tile;
import de.ueller.midlet.gps.data.Proj2D;
import de.ueller.midlet.gps.data.ProjFactory;
import de.ueller.midlet.gps.data.ProjMath;
import de.ueller.midlet.gps.data.Gpx;
import de.ueller.midlet.gps.data.IntPoint;
import de.ueller.midlet.gps.data.MoreMath;
import de.ueller.midlet.gps.data.Node;
import de.ueller.midlet.gps.data.PositionMark;
import de.ueller.midlet.gps.data.SECellLocLogger;
import de.ueller.midlet.gps.data.Way;
import de.ueller.midlet.gps.names.Names;
import de.ueller.midlet.gps.routing.ConnectionWithNode;
import de.ueller.midlet.gps.routing.RouteHelper;
import de.ueller.midlet.gps.routing.RouteNode;
import de.ueller.midlet.gps.routing.Routing;
import de.ueller.midlet.gps.tile.C;
import de.ueller.midlet.gps.GuiMapFeatures;
import de.ueller.midlet.gps.tile.Images;
import de.ueller.midlet.gps.tile.PaintContext;
import de.ueller.midlet.gps.tile.WayDescription;
import de.ueller.midlet.gps.GpsMidDisplayable;
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends KeyCommandCanvas implements LocationMsgReceiver,
Runnable , GpsMidDisplayable{
/** Soft button for exiting the map screen */
private static final int EXIT_CMD = 1;
private static final int CONNECT_GPS_CMD = 2;
private static final int DISCONNECT_GPS_CMD = 3;
private static final int START_RECORD_CMD = 4;
private static final int STOP_RECORD_CMD = 5;
private static final int MANAGE_TRACKS_CMD = 6;
private static final int SAVE_WAYP_CMD = 7;
private static final int ENTER_WAYP_CMD = 8;
private static final int MAN_WAYP_CMD = 9;
private static final int ROUTE_TO_CMD = 10;
private static final int CAMERA_CMD = 11;
private static final int CLEARTARGET_CMD = 12;
private static final int SETTARGET_CMD = 13;
private static final int MAPFEATURES_CMD = 14;
private static final int RECORDINGS_CMD = 16;
private static final int ROUTINGS_CMD = 17;
private static final int OK_CMD =18;
private static final int BACK_CMD = 19;
private static final int ZOOM_IN_CMD = 20;
private static final int ZOOM_OUT_CMD = 21;
private static final int MANUAL_ROTATION_MODE_CMD = 22;
private static final int TOGGLE_OVERLAY_CMD = 23;
private static final int TOGGLE_BACKLIGHT_CMD = 24;
private static final int TOGGLE_FULLSCREEN_CMD = 25;
private static final int TOGGLE_MAP_PROJ_CMD = 26;
private static final int TOGGLE_KEY_LOCK_CMD = 27;
private static final int TOGGLE_RECORDING_CMD = 28;
private static final int TOGGLE_RECORDING_SUSP_CMD = 29;
private static final int RECENTER_GPS_CMD = 30;
private static final int DATASCREEN_CMD = 31;
private static final int OVERVIEW_MAP_CMD = 32;
private static final int RETRIEVE_XML = 33;
private static final int PAN_LEFT25_CMD = 34;
private static final int PAN_RIGHT25_CMD = 35;
private static final int PAN_UP25_CMD = 36;
private static final int PAN_DOWN25_CMD = 37;
private static final int PAN_LEFT2_CMD = 38;
private static final int PAN_RIGHT2_CMD = 39;
private static final int PAN_UP2_CMD = 40;
private static final int PAN_DOWN2_CMD = 41;
private static final int REFRESH_CMD = 42;
private static final int SEARCH_CMD = 43;
private static final int TOGGLE_AUDIO_REC = 44;
//#if polish.api.wmapi
private static final int SEND_MESSAGE_CMD = 45;
//#endif
private final Command [] CMDS = new Command[46];
public static final int DATASCREEN_NONE = 0;
public static final int DATASCREEN_TACHO = 1;
public static final int DATASCREEN_TRIP = 2;
public static final int DATASCREEN_SATS = 3;
// private SirfInput si;
private LocationMsgProducer locationProducer;
public String solution = "NoFix";
/** Flag if the map is centered to the current GPS position (true)
* or if the user moved the map away from this position (false).
*/
public boolean gpsRecenter = true;
private Position pos = new Position(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1,
new Date());
/**
* this node contains actually RAD coordinates
* although the constructor for Node(lat, lon) requires parameters in DEC format
* - e. g. "new Node(49.328010f, 11.352556f)"
*/
Node center = new Node(49.328010f, 11.352556f);
// Projection projection;
private final GpsMid parent;
private String lastTitleMsg;
private String currentTitleMsg;
private volatile int currentTitleMsgOpenCount = 0;
private volatile int setTitleMsgTimeout = 0;
private Calendar lastTitleMsgTime = Calendar.getInstance();
private String currentAlertTitle;
private String currentAlertMessage;
private volatile int currentAlertsOpenCount = 0;
private volatile int setAlertTimeout = 0;
private long lastBackLightOnTime = 0;
private long collected = 0;
public PaintContext pc;
public float scale = 15000f;
int showAddons = 0;
private int fontHeight = 0;
private int compassRectHeight = 0;
/** x position display was touched last time */
private static int touchX = 0;
/** y position display was touched last time */
private static int touchY = 0;
/** center when display was touched last time */
private static Node centerPointerPressedN = new Node();
/** indicates whether this is a touch button or drag action*/
private static boolean pointerDragAction = false;
public volatile boolean routeCalc=false;
public Tile t[] = new Tile[6];
public Way actualWay;
PositionMark source;
// this is only for visual debugging of the routing engine
Vector routeNodes = new Vector();
private long oldRecalculationTime;
private List recordingsMenu = null;
private List routingsMenu = null;
private GuiTacho guiTacho = null;
private GuiTrip guiTrip = null;
private GuiSatellites guiSatellites = null;
private GuiWaypointSave guiWaypointSave = null;
private final static Logger logger = Logger.getInstance(Trace.class,Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
/**
* Current speed from GPS in km/h.
*/
public volatile int speed;
/**
* Flag if we're speeding
*/
private volatile boolean speeding = false;
private long lastTimeOfSpeedingSound = 0;
private long startTimeOfSpeedingSign = 0;
private int speedingSpeedLimit = 0;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course = 0;
public boolean atTarget = false;
public boolean movedAwayFromTarget = true;
private Names namesThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private Runtime runtime = Runtime.getRuntime();
private PositionMark target = null;
private Vector route = null;
private RouteInstructions ri = null;
private boolean running = false;
private static final int CENTERPOS = Graphics.HCENTER | Graphics.VCENTER;
public Gpx gpx;
private AudioRecorder audioRec;
private static Trace traceInstance = null;
private Routing routeEngine;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
private boolean manualRotationMode = false;
private Shape shapeZoomIn = null;
private Shape shapeZoomOut = null;
public Vector locationUpdateListeners;
public Trace() throws Exception {
//#debug
logger.info("init Trace");
this.parent = GpsMid.getInstance();
CMDS[EXIT_CMD] = new Command("Back", Command.BACK, 2);
CMDS[REFRESH_CMD] = new Command("Refresh", Command.ITEM, 4);
CMDS[SEARCH_CMD] = new Command("Search", Command.OK, 1);
CMDS[CONNECT_GPS_CMD] = new Command("Start gps",Command.ITEM, 2);
CMDS[DISCONNECT_GPS_CMD] = new Command("Stop gps",Command.ITEM, 2);
CMDS[START_RECORD_CMD] = new Command("Start record",Command.ITEM, 4);
CMDS[STOP_RECORD_CMD] = new Command("Stop record",Command.ITEM, 4);
CMDS[MANAGE_TRACKS_CMD] = new Command("Manage tracks",Command.ITEM, 5);
CMDS[SAVE_WAYP_CMD] = new Command("Save waypoint",Command.ITEM, 7);
CMDS[ENTER_WAYP_CMD] = new Command("Enter waypoint",Command.ITEM, 7);
CMDS[MAN_WAYP_CMD] = new Command("Manage waypoints",Command.ITEM, 7);
CMDS[ROUTE_TO_CMD] = new Command("Route",Command.ITEM, 3);
CMDS[CAMERA_CMD] = new Command("Camera",Command.ITEM, 9);
CMDS[CLEARTARGET_CMD] = new Command("Clear Target",Command.ITEM, 10);
CMDS[SETTARGET_CMD] = new Command("As Target",Command.ITEM, 11);
CMDS[MAPFEATURES_CMD] = new Command("Map Features",Command.ITEM, 12);
CMDS[RECORDINGS_CMD] = new Command("Recordings...",Command.ITEM, 4);
CMDS[ROUTINGS_CMD] = new Command("Routing...",Command.ITEM, 3);
CMDS[OK_CMD] = new Command("OK",Command.OK, 14);
CMDS[BACK_CMD] = new Command("Back",Command.BACK, 15);
CMDS[ZOOM_IN_CMD] = new Command("Zoom in",Command.ITEM, 100);
CMDS[ZOOM_OUT_CMD] = new Command("Zoom out",Command.ITEM, 100);
CMDS[MANUAL_ROTATION_MODE_CMD] = new Command("Manual Rotation Mode",Command.ITEM, 100);
CMDS[TOGGLE_OVERLAY_CMD] = new Command("Next overlay",Command.ITEM, 100);
CMDS[TOGGLE_BACKLIGHT_CMD] = new Command("Keep backlight on/off",Command.ITEM, 100);
CMDS[TOGGLE_FULLSCREEN_CMD] = new Command("Switch to fullscreen",Command.ITEM, 100);
CMDS[TOGGLE_MAP_PROJ_CMD] = new Command("Next map projection",Command.ITEM, 100);
CMDS[TOGGLE_KEY_LOCK_CMD] = new Command("(De)Activate Keylock",Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_CMD] = new Command("(De)Activate recording",Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_SUSP_CMD] = new Command("Suspend recording",Command.ITEM, 100);
CMDS[RECENTER_GPS_CMD] = new Command("Recenter on GPS",Command.ITEM, 100);
CMDS[DATASCREEN_CMD] = new Command("Tacho",Command.ITEM, 100);
CMDS[OVERVIEW_MAP_CMD] = new Command("Overview/Filter Map",Command.ITEM, 200);
CMDS[RETRIEVE_XML] = new Command("Retrieve XML",Command.ITEM, 200);
CMDS[PAN_LEFT25_CMD] = new Command("left 25%",Command.ITEM, 100);
CMDS[PAN_RIGHT25_CMD] = new Command("right 25%",Command.ITEM, 100);
CMDS[PAN_UP25_CMD] = new Command("up 25%",Command.ITEM, 100);
CMDS[PAN_DOWN25_CMD] = new Command("down 25%",Command.ITEM, 100);
CMDS[PAN_LEFT2_CMD] = new Command("left 2",Command.ITEM, 100);
CMDS[PAN_RIGHT2_CMD] = new Command("right 2",Command.ITEM, 100);
CMDS[PAN_UP2_CMD] = new Command("up 2",Command.ITEM, 100);
CMDS[PAN_DOWN2_CMD] = new Command("down 2",Command.ITEM, 100);
CMDS[TOGGLE_AUDIO_REC] = new Command("Audio recording",Command.ITEM, 100);
//#if polish.api.wmapi
CMDS[SEND_MESSAGE_CMD] = new Command("Send SMS (map pos)",Command.ITEM, 200);
//#endif
addCommand(CMDS[EXIT_CMD]);
addCommand(CMDS[SEARCH_CMD]);
addCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[MANAGE_TRACKS_CMD]);
addCommand(CMDS[MAN_WAYP_CMD]);
addCommand(CMDS[MAPFEATURES_CMD]);
addCommand(CMDS[RECORDINGS_CMD]);
addCommand(CMDS[ROUTINGS_CMD]);
addCommand(CMDS[DATASCREEN_CMD]);
//#if polish.api.osm-editing
addCommand(CMDS[RETRIEVE_XML]);
//#endif
setCommandListener(this);
Configuration.loadKeyShortcuts(gameKeyCommand, singleKeyPressCommand,
repeatableKeyPressCommand, doubleKeyPressCommand, longKeyPressCommand,
nonReleasableKeyPressCommand, CMDS);
try {
startup();
} catch (Exception e) {
logger.fatal("Got an exception during startup: " + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
/**
* Returns the instance of the map screen. If non exists yet,
* start a new instance.
* @return
*/
public static Trace getInstance() {
if (traceInstance == null) {
try {
traceInstance = new Trace();
} catch (Exception e) {
logger.exception("Failed to initialise Map screen", e);
}
}
return traceInstance;
}
// start the LocationProvider in background
public void run() {
try {
if (running){
receiveMessage("GPS starter already running");
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null) {
receiveMessage("Location provider already running");
return;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
receiveMessage("No location provider");
return;
}
running=true;
int locprov = Configuration.getLocationProvider();
receiveMessage("Connect to "+Configuration.LOCATIONPROVIDER[locprov]);
switch (locprov){
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_SECELL:
locationProducer = new SECellID();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
/**
* Some phones throw exceptions if trying to access properties that don't
* exist, so we have to catch these and just ignore them.
*/
} catch (Exception e) {
/**
* See above
*/
}
if (jsr179Version != null && jsr179Version.length() > 0) {
Class jsr179Class = Class.forName("de.ueller.gps.jsr179.JSR179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
}
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception("Your phone does not support JSR179, please use a different location provider", cnfe);
running = false;
return;
}
//#else
// keep eclipse happy
if (true){
logger.error("JSR179 is not compiled in this version of GpsMid");
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = Configuration.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (url != null) {
try {
if (Configuration.getGpsRawLoggerEnable()) {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
javax.microedition.io.Connection logCon = Connector.open(url);
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists())
fileCon.create();
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Raw logging of NMEA is only to filesystem supported");
}
}
/**
* Help out the OpenCellId.org project by gathering and logging
* data of cell ids together with current Gps location. This information
* can then be uploaded to their web site to determine the position of the
* cell towers. It currently only works for SE phones
*/
if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
SECellLocLogger secl = new SECellLocLogger();
if (secl.init()) {
locationProducer.addLocationMsgReceiver(secl);
}
}
} catch (IOException ioe) {
logger.exception("Couldn't open file for raw logging of Gps data",ioe);
} catch (SecurityException se) {
logger.error("Permission to write data for NMEA raw logging was denied");
}
}
//#endif
if (locationProducer == null) {
logger.error("Your phone does not seem to support this method of location input, please choose a different one");
running = false;
return;
}
if (!locationProducer.init(this)) {
logger.info("Failed to initialise location producer");
running = false;
return;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
GpsMid.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[DISCONNECT_GPS_CMD]);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal("Trace thread crashed as out of memory: " + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal("Trace thread crashed unexpectadly with error " + e.getMessage());
e.printStackTrace();
} finally {
running = false;
}
running = false;
}
public synchronized void pause(){
logger.debug("Pausing application");
if (imageCollector != null) {
imageCollector.suspend();
}
if (locationProducer != null){
locationProducer.close();
} else {
return;
}
while (locationProducer != null){
try {
wait(200);
} catch (InterruptedException e) {
}
}
}
public void resume(){
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this);
thread.start();
}
public void autoRouteRecalculate() {
if ( gpsRecenter && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC) ) {
if (Math.abs(System.currentTimeMillis()-oldRecalculationTime) >= 7000 ) {
// if map is gps-centered recalculate route
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
GpsMid.mNoiseMaker.playSound("ROUTE_RECALCULATION", (byte) 5, (byte) 1 );
}
commandAction(CMDS[ROUTE_TO_CMD],(Displayable) null);
}
}
}
public void commandAction(Command c, Displayable d) {
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD]) || (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD]) || (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 1000)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
parent.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else {
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording would not be stopped when returning to map
if (gpx.isRecordingTrk()) {
alert("Record Mode", "Please stop recording before returning to the main screen." , 5000);
return;
}
// shutdown();
pause();
parent.show();
return;
}
if (! routeCalc) {
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk();
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk();
addCommand(CMDS[MANAGE_TRACKS_CMD]);
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk()) {
alert("Record Mode", "You need to stop recording before managing tracks." , 5000);
return;
}
GuiGpx gpx = new GuiGpx(this);
gpx.show();
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
Thread thread = new Thread(this);
thread.start();
}
}
if (c == CMDS[SEARCH_CMD]){
GuiSearch search = new GuiSearch(this);
search.show();
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null){
locationProducer.close();
}
}
if (c == CMDS[ROUTE_TO_CMD]) {
routeCalc = true;
if (Configuration.isStopAllWhileRouteing()) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
logger.info("Routing source: " + source);
routeNodes=new Vector();
routeEngine = new Routing(t,this);
routeEngine.solve(source, target);
// resume();
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
if (gpsRecenter) {
// TODO: Should we block waypoint saving if we have no GPS fix?
guiWaypointSave.setData(new PositionMark(
pos.latitude * MoreMath.FAC_DECTORAD,
pos.longitude * MoreMath.FAC_DECTORAD,
(int)pos.altitude, pos.date,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1));
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
guiWaypointSave.setData(new PositionMark(center.radlat,
center.radlon, PositionMark.INVALID_ELEVATION,
pos.date, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1));
}
guiWaypointSave.show();
}
}
if (c == CMDS[ENTER_WAYP_CMD]) {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
if (c == CMDS[MAN_WAYP_CMD]) {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
noElements++;
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = "Stop Gpx tracklog";
} else {
elements[idx++] = "Start Gpx tracklog";
}
elements[idx++] = "Add waypoint";
elements[idx++] = "Enter waypoint";
//#if polish.api.mmapi
elements[idx++] = "Take pictures";
if (audioRec.isRecording()) {
elements[idx++] = "Stop audio recording";
} else {
elements[idx++] = "Start audio recording";
}
//#endif
//#if polish.api.wmapi
if (Configuration.hasDeviceJSR120()) {
elements[idx++] = "Send SMS (map pos)";
}
//#endif
recordingsMenu = new List("Recordings...",Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = {"Calculate route", "Set target" , "Clear target"};
routingsMenu = new List("Routing..", Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
}
if (c == CMDS[BACK_CMD]) {
show();
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if (!gpx.isRecordingTrk()){
gpx.newTrk();
} else {
gpx.saveTrk();
}
show();
break;
}
case 1: {
commandAction(CMDS[SAVE_WAYP_CMD], null);
break;
}
case 2: {
commandAction(CMDS[ENTER_WAYP_CMD], null);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CMDS[CAMERA_CMD], null);
break;
}
case 4: {
show();
commandAction(CMDS[TOGGLE_AUDIO_REC], null);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
commandAction(CMDS[ROUTE_TO_CMD], null);
break;
}
case 1: {
commandAction(CMDS[SETTARGET_CMD], null);
break;
}
case 2: {
commandAction(CMDS[CLEARTARGET_CMD], null);
break;
}
}
}
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]){
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe);
}
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
}
//#endif
if (c == CMDS[CLEARTARGET_CMD]) {
setTarget(null);
} else if (c == CMDS[SETTARGET_CMD]) {
if (source != null) {
setTarget(source);
}
} else if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
} else if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
} else if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
alert("Manual Rotation", "Change course with left/right keys", 3000);
} else {
alert("Manual Rotation", "Off", 1000);
}
} else if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
} else if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
} else if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
} else if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP ) {
ProjFactory.setProj(ProjFactory.MOVE_UP);
alert("Map Rotation", "Driving Direction", 750);
} else {
if (manualRotationMode) {
course = 0;
alert("Manual Rotation", "to North", 750);
} else {
ProjFactory.setProj(ProjFactory.NORTH_UP);
alert("Map Rotation", "NORTH UP", 750);
}
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
} else if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert("GpsMid", "Keys unlocked", 1000);
}
} else if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
alert("Gps track recording", "Stopping to record", 2000);
commandAction(CMDS[STOP_RECORD_CMD],(Displayable) null);
} else {
alert("Gps track recording", "Starting to record", 2000);
commandAction(CMDS[START_RECORD_CMD],(Displayable) null);
}
} else if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert("Gps track recording", "Resuming recording", 2000);
gpx.resumTrk();
} else {
alert("Gps track recording", "Suspending recording", 2000);
gpx.suspendTrk();
}
}
} else if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
newDataReady();
} else if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
}
//#if polish.api.osm-editing
else if (c == CMDS[RETRIEVE_XML]) {
if (C.enableEdits) {
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
//#endif
} else {
- logger.error(" currently in route Caclulation");
+ alert("Error", "currently in route calculation", 1000);
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images i;
i = new Images();
pc = new PaintContext(this, i);
pc.c = GpsMid.c;
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
imageCollector = new ImageCollector(t, w, h, this,
i, pc.c);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.clone();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
new DictReader(this);
// Thread thread = new Thread(this);
// thread.start();
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
}
/* private void shutdown() {
stopImageCollector();
if (namesThread != null) {
namesThread.stop();
namesThread = null;
}
if (dictReader != null) {
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null){
locationProducer.close();
}
}*/
protected void sizeChanged(int w, int h) {
if (imageCollector != null){
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception("Could not reinitialise Image Collector after size change", e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(C.BACKGROUND_COLOR);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null){
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri!=null) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.xSize/2) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.ySize/2) < maxAllowedMapMoveOffs
) {
int yPos=pc.ySize;
yPos-=imageCollector.statusFontHeight;
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, source, drawnCenter, yPos);
}
}
}
/*
* beginning of voice instructions started from overlay code (besides showRoute above)
*/
// determine if we are at the target
if (target != null) {
float distance = ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon);
atTarget = (distance < 25);
if (atTarget) {
if (movedAwayFromTarget && Configuration.getCfgBitState(Configuration.CFGBIT_SND_TARGETREACHED)) {
GpsMid.mNoiseMaker.playSound("TARGET_REACHED", (byte) 7, (byte) 1);
}
} else if (!movedAwayFromTarget) {
movedAwayFromTarget=true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
if (actualWay != null) {
maxSpeed = actualWay.getMaxSpeed();
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound("SPEED_LIMIT");
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
showScale(pc);
}
if (ProjFactory.getProj() == ProjFactory.MOVE_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)
) {
showPointOfTheCompass(pc);
}
}
showMovement(g);
g.setColor(0, 0, 0);
if (locationProducer != null){
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (fontHeight == 0) {
fontHeight = g.getFont().getHeight();
}
if (gpx.isRecordingTrkSuspended()) {
g.setColor(0, 0, 255);
} else {
g.setColor(255, 0, 0);
}
g.drawString(gpx.recorded + "r", getWidth() - 1, 1 + fontHeight,
Graphics.TOP | Graphics.RIGHT);
g.setColor(0);
}
g.drawString(solution, getWidth() - 1, 1, Graphics.TOP | Graphics.RIGHT);
} else {
g.drawString("Off", getWidth() - 1, 1, Graphics.TOP | Graphics.RIGHT);
}
if (pc != null){
showTarget(pc);
}
showSpeedingSign(g, maxSpeed);
if (hasPointerEvents()) {
showZoomButtons(pc);
}
if (currentTitleMsgOpenCount != 0) {
if (compassRectHeight == 0) {
compassRectHeight = g.getFont().getHeight()-2;
}
g.setColor(255,255,255);
g.fillRect(0,0, getWidth(), compassRectHeight + 2);
g.setColor(0,0,0);
if (g.getFont().stringWidth(currentTitleMsg) < getWidth()) {
g.drawString(currentTitleMsg,
getWidth()/2, 0, Graphics.TOP|Graphics.HCENTER);
} else {
g.drawString(currentTitleMsg,
0, 0, Graphics.TOP|Graphics.LEFT);
}
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT;
Timer tm = new Timer();
timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
tm.schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
if (currentAlertsOpenCount > 0) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
int y = titleFont.getHeight() + 2 + fontHeight; // add alert title height plus extra space of one line for calculation of alertHeight
int extraWidth = font.charWidth('W'); // extra width for alert
int alertWidth = titleFont.stringWidth(currentAlertTitle); // alert is at least as wide as alert title
int maxWidth = getWidth() - extraWidth; // width each alert message line must fit in
for (int i = 0; i<=1; i++) { // two passes: 1st pass calculates placement and necessary size of alert, 2nd pass actually does the drawing
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// reduce line word by word or if not possible char by char until the remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i==0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(222, 222, 222);
g.fillRect(alertLeft, alertTop , alertWidth, alertHeight);
// background color for alert title
pc.g.setColor(255, 255, 255);
g.fillRect(alertLeft, alertTop , alertWidth, fontHeight + 3);
// alert border
g.setColor(0, 0, 0);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT;
Timer tm = new Timer();
timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
tm.schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
private void showSpeedingSign(Graphics g, int maxSpeed) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&& (
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
startTimeOfSpeedingSign = System.currentTimeMillis();
speedingSpeedLimit = maxSpeed;
}
String sSpeed = Integer.toString(speedingSpeedLimit);
int oldColor = g.getColor();
Font oldFont = g.getFont();
Font speedingFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE);
int w = speedingFont.stringWidth(sSpeed);
int w0 = speedingFont.charWidth('0');
int h0 = speedingFont.getHeight();
w += w0 * 4;
g.setColor(0x00FF0000);
int yPos = pc.ySize - w - (h0 / 2) - imageCollector.statusFontHeight - RouteInstructions.routeInstructionsHeight;
g.fillArc(0, yPos, w, w, 0, 360);
g.setColor(0x00FFFFFF);
g.fillArc(w0, yPos + w0, w - (w0 * 2), w - (w0 * 2), 0, 360);
g.setColor(0x00000000);
g.setFont(speedingFont);
g.drawString(sSpeed, w/2, yPos + w/2 - (h0 / 2), Graphics.TOP | Graphics.HCENTER);
g.setFont(oldFont);
g.setColor(oldColor);
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course=course;
pc.scale=scale;
pc.center=center.clone();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.target=target;
}
public void cleanup() {
namesThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
public void searchElement(PositionMark pm) throws Exception{
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
pc.searchLD=nld;
pc.searchRU=nru;
pc.target=pm;
pc.setP(new Proj2D(new Node(pm.lat,pm.lon, true),5000,100,100));
for (int i=0; i<4; i++){
t[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
}
}
public void searchNextRoutableWay(PositionMark pm) throws Exception{
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
pc.searchLD=nld;
pc.searchRU=nru;
pc.squareDstToRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
pc.setP(new Proj2D(new Node(pm.lat,pm.lon, true),5000,100,100));
for (int i=0; i<4; i++){
t[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
Way w = pc.nearestRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void showPointOfTheCompass(PaintContext pc) {
if (compassRectHeight == 0) {
compassRectHeight = pc.g.getFont().getHeight()-2;
}
String c = Configuration.getCompassDirection(course);
int compassRectWidth = pc.g.getFont().stringWidth(c);
pc.g.setColor(255, 255, 150);
pc.g.fillRect(getWidth()/2 - compassRectWidth / 2 , 0,
compassRectWidth, compassRectHeight);
pc.g.setColor(0, 0, 0);
pc.g.drawString(c, getWidth()/2, 0 , Graphics.HCENTER | Graphics.TOP);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
g.setColor(0, 0, 0);
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showTarget(PaintContext pc){
if (target != null){
pc.getP().forward(target.lat, target.lon, pc.lineP2);
// System.out.println(target.toString());
pc.g.drawImage(pc.images.IMG_TARGET,pc.lineP2.x,pc.lineP2.y,CENTERPOS);
pc.g.setColor(0,0,0);
if (target.displayName != null)
pc.g.drawString(target.displayName, pc.lineP2.x, pc.lineP2.y+8,
Graphics.TOP | Graphics.HCENTER);
pc.g.setColor(255,50,50);
pc.g.setStrokeStyle(Graphics.DOTTED);
pc.g.drawLine(pc.lineP2.x,pc.lineP2.y,pc.xSize/2,pc.ySize/2);
}
}
public void showZoomButtons(PaintContext pc){
if (shapeZoomIn == null) {
shapeZoomIn = new Shape('+');
shapeZoomOut = new Shape('-');
}
pc.g.setColor(0);
pc.g.setStrokeStyle(Graphics.SOLID);
shapeZoomIn.drawShape(pc, pc.xSize - 3, pc.ySize / 2);
// draw zoom-out control below zoom-in control
shapeZoomOut.drawShape(pc, pc.xSize - 3, shapeZoomIn.getMaxY());
}
/**
* Draws a map scale onto screen.
* This calculation is currently horribly
* inefficient. There must be a better way
* than this.
*
* @param pc Paint context for drawing
*/
public void showScale(PaintContext pc) {
Node n1 = new Node();
Node n2 = new Node();
float scale;
int scalePx;
//Calculate the lat and lon coordinates of two
//points that are 35 pixels apart
pc.getP().inverse(10, 10, n1);
pc.getP().inverse(45, 10, n2);
//Calculate the distance between them in meters
float d = ProjMath.getDistance(n1, n2);
//round this distance up to the nearest 5 or 10
int ordMag = (int)(MoreMath.log(d)/MoreMath.log(10.0f));
if (d < 2.5*MoreMath.pow(10,ordMag)) {
scale = 2.5f*MoreMath.pow(10,ordMag);
} else if (d < 5*MoreMath.pow(10,ordMag)) {
scale = 5*MoreMath.pow(10,ordMag);
} else {
scale = 10*MoreMath.pow(10,ordMag);
}
//Calculate how many pixels this distance is apart
scalePx = (int)(35.0f*scale/d);
// TODO: explain What is the maximum width of the scale bar?
//Draw the scale bar
pc.g.setColor(0x00000000);
pc.g.drawLine(10,10, 10 + scalePx, 10);
pc.g.drawLine(10,11, 10 + scalePx, 11); //double line width
pc.g.drawLine(10, 8, 10, 13);
pc.g.drawLine(10 + scalePx, 8, 10 + scalePx, 13);
if (scale > 1000) {
pc.g.drawString(Integer.toString((int)(scale/1000.0f)) + "km", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP);
} else {
pc.g.drawString(Integer.toString((int)scale) + "m", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP);
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
g.setColor(0, 0, 0);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((float)(pos.latitude / 360.0 * 2 * Math.PI),
(float)(pos.longitude / 360.0 * 2 * Math.PI), p1);
posX = p1.getX();
posY = p1.getY();
} else {
posX = centerX;
posY = centerY;
}
float radc = (float) (course * Math.PI / 180d);
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
g.drawRect(posX - 2, posY - 2, 4, 4);
g.drawLine(posX, posY, px, py);
g.drawLine(centerX - 2, centerY - 2, centerX + 2, centerY + 2);
g.drawLine(centerX - 2, centerY + 2, centerX + 2, centerY - 2);
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0, 0, 0);
g.drawString("Freemem: " + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("Totmem: " + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("Percent: "
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Threads running: "
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Names: " + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Single T: " + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("File T: " + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LastMsg: " + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( "at " + lastTitleMsgTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(lastTitleMsgTime.get(Calendar.MINUTE)) + ":"
+ HelperRoutines.formatInt2(lastTitleMsgTime.get(Calendar.SECOND)), 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null){
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.clone();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
center.setLatLon(lat, lon, true);
this.scale = scale;
updatePosition();
}
public synchronized void receivePosition(Position pos) {
//#debug info
logger.info("New position: " + pos);
this.pos = pos;
collected++;
if (gpsRecenter) {
center.setLatLon(pos.latitude, pos.longitude);
if (speed > 2) {
/* don't rotate too fast
* FIXME: the following line to not rotate too fast
* is commented out because it causes the map to perform
* almost a 360 degree rotation when course and pos.course
* are on different sides of North, e.g. at 359 and 1 degrees
*/
// course = (int) ((pos.course * 3 + course) / 4)+360;
// use pos.course directly without rotation slow-down
course = (int) pos.course;
while (course > 360) {
course -= 360;
}
}
}
speed = (int) (pos.speed * 3.6f);
if (gpx.isRecordingTrk()) {
try {
gpx.addTrkPt(pos);
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgTime.setTime( new Date( System.currentTimeMillis() ) );
repaint();
}
public void receiveSatellites(Satelit[] sats) {
// Not interested
}
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
pointerDragAction = true;
// check for touchable buttons
if (shapeZoomIn.isInRectangleAroundPolygon(x, y)) {
commandAction(CMDS[ZOOM_IN_CMD], (Displayable) null);
repaint();
pointerDragAction = false;
}
if (shapeZoomOut.isInRectangleAroundPolygon(x, y)) {
commandAction(CMDS[ZOOM_OUT_CMD], (Displayable) null);
repaint();
pointerDragAction = false;
}
// remember positions for dragging
// remember position the pointer was pressed
Trace.touchX = x;
Trace.touchY = y;
// remember center when the pointer was pressed
centerPointerPressedN = center.clone();
}
protected void pointerReleased(int x, int y) {
if (pointerDragAction) {
pointerDragged(x , y);
}
}
protected void pointerDragged (int x, int y) {
if (imageCollector != null) {
// difference between where the pointer was pressed and is currently dragged
int diffX = Trace.touchX - x;
int diffY = Trace.touchY - y;
IntPoint centerPointerPressedP = new IntPoint();
imageCollector.getCurrentProjection().forward(centerPointerPressedN, centerPointerPressedP);
imageCollector.getCurrentProjection().inverse(centerPointerPressedP.x + diffX, centerPointerPressedP.y + diffY, center);
imageCollector.newDataReady();
gpsRecenter = false;
}
}
public Tile getDict(byte zl) {
return t[zl];
}
public void setDict(Tile dict, byte zl) {
t[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if(center.radlat==0.0f && center.radlon==0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
if (pc != null) {
pc.center = center.clone();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
if (gpx != null) {
/**
* Close and Save the gpx recording, to ensure we don't loose data
*/
gpx.saveTrk();
}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null){
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveSolution(String s) {
solution = s;
}
public String getName(int idx) {
if (idx < 0)
return null;
return namesThread.getName(idx);
}
public Vector fulltextSearch (String snippet) {
return namesThread.fulltextSearch(snippet);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null)
imageCollector.newDataReady();
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
repaint();
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getTarget() {
return target;
}
public void setTarget(PositionMark target) {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
setRoute(null);
setRouteNodes(null);
this.target = target;
pc.target = target;
if(target!=null) {
center.setLatLon(target.lat, target.lon,true);
pc.center = center.clone();
pc.scale = scale;
pc.course = course;
}
movedAwayFromTarget=false;
repaint();
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
if (route!=null) {
if (ri==null) {
ri = new RouteInstructions(this);
}
ri.newRoute(route, target);
oldRecalculationTime = System.currentTimeMillis();
RouteInstructions.resetOffRoute(route, center);
}
routeCalc=false;
routeEngine=null;
}
try {
if ((Configuration.isStopAllWhileRouteing())&&(imageCollector == null)){
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
}
repaint();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
logger.info("Hide notify has been called, screen will nolonger be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
logger.info("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
}
| true | true | public void commandAction(Command c, Displayable d) {
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD]) || (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD]) || (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 1000)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
parent.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else {
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording would not be stopped when returning to map
if (gpx.isRecordingTrk()) {
alert("Record Mode", "Please stop recording before returning to the main screen." , 5000);
return;
}
// shutdown();
pause();
parent.show();
return;
}
if (! routeCalc) {
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk();
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk();
addCommand(CMDS[MANAGE_TRACKS_CMD]);
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk()) {
alert("Record Mode", "You need to stop recording before managing tracks." , 5000);
return;
}
GuiGpx gpx = new GuiGpx(this);
gpx.show();
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
Thread thread = new Thread(this);
thread.start();
}
}
if (c == CMDS[SEARCH_CMD]){
GuiSearch search = new GuiSearch(this);
search.show();
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null){
locationProducer.close();
}
}
if (c == CMDS[ROUTE_TO_CMD]) {
routeCalc = true;
if (Configuration.isStopAllWhileRouteing()) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
logger.info("Routing source: " + source);
routeNodes=new Vector();
routeEngine = new Routing(t,this);
routeEngine.solve(source, target);
// resume();
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
if (gpsRecenter) {
// TODO: Should we block waypoint saving if we have no GPS fix?
guiWaypointSave.setData(new PositionMark(
pos.latitude * MoreMath.FAC_DECTORAD,
pos.longitude * MoreMath.FAC_DECTORAD,
(int)pos.altitude, pos.date,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1));
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
guiWaypointSave.setData(new PositionMark(center.radlat,
center.radlon, PositionMark.INVALID_ELEVATION,
pos.date, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1));
}
guiWaypointSave.show();
}
}
if (c == CMDS[ENTER_WAYP_CMD]) {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
if (c == CMDS[MAN_WAYP_CMD]) {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
noElements++;
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = "Stop Gpx tracklog";
} else {
elements[idx++] = "Start Gpx tracklog";
}
elements[idx++] = "Add waypoint";
elements[idx++] = "Enter waypoint";
//#if polish.api.mmapi
elements[idx++] = "Take pictures";
if (audioRec.isRecording()) {
elements[idx++] = "Stop audio recording";
} else {
elements[idx++] = "Start audio recording";
}
//#endif
//#if polish.api.wmapi
if (Configuration.hasDeviceJSR120()) {
elements[idx++] = "Send SMS (map pos)";
}
//#endif
recordingsMenu = new List("Recordings...",Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = {"Calculate route", "Set target" , "Clear target"};
routingsMenu = new List("Routing..", Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
}
if (c == CMDS[BACK_CMD]) {
show();
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if (!gpx.isRecordingTrk()){
gpx.newTrk();
} else {
gpx.saveTrk();
}
show();
break;
}
case 1: {
commandAction(CMDS[SAVE_WAYP_CMD], null);
break;
}
case 2: {
commandAction(CMDS[ENTER_WAYP_CMD], null);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CMDS[CAMERA_CMD], null);
break;
}
case 4: {
show();
commandAction(CMDS[TOGGLE_AUDIO_REC], null);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
commandAction(CMDS[ROUTE_TO_CMD], null);
break;
}
case 1: {
commandAction(CMDS[SETTARGET_CMD], null);
break;
}
case 2: {
commandAction(CMDS[CLEARTARGET_CMD], null);
break;
}
}
}
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]){
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe);
}
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
}
//#endif
if (c == CMDS[CLEARTARGET_CMD]) {
setTarget(null);
} else if (c == CMDS[SETTARGET_CMD]) {
if (source != null) {
setTarget(source);
}
} else if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
} else if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
} else if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
alert("Manual Rotation", "Change course with left/right keys", 3000);
} else {
alert("Manual Rotation", "Off", 1000);
}
} else if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
} else if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
} else if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
} else if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP ) {
ProjFactory.setProj(ProjFactory.MOVE_UP);
alert("Map Rotation", "Driving Direction", 750);
} else {
if (manualRotationMode) {
course = 0;
alert("Manual Rotation", "to North", 750);
} else {
ProjFactory.setProj(ProjFactory.NORTH_UP);
alert("Map Rotation", "NORTH UP", 750);
}
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
} else if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert("GpsMid", "Keys unlocked", 1000);
}
} else if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
alert("Gps track recording", "Stopping to record", 2000);
commandAction(CMDS[STOP_RECORD_CMD],(Displayable) null);
} else {
alert("Gps track recording", "Starting to record", 2000);
commandAction(CMDS[START_RECORD_CMD],(Displayable) null);
}
} else if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert("Gps track recording", "Resuming recording", 2000);
gpx.resumTrk();
} else {
alert("Gps track recording", "Suspending recording", 2000);
gpx.suspendTrk();
}
}
} else if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
newDataReady();
} else if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
}
//#if polish.api.osm-editing
else if (c == CMDS[RETRIEVE_XML]) {
if (C.enableEdits) {
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
//#endif
} else {
logger.error(" currently in route Caclulation");
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void commandAction(Command c, Displayable d) {
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD]) || (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD]) || (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 1000)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
parent.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else {
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording would not be stopped when returning to map
if (gpx.isRecordingTrk()) {
alert("Record Mode", "Please stop recording before returning to the main screen." , 5000);
return;
}
// shutdown();
pause();
parent.show();
return;
}
if (! routeCalc) {
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk();
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk();
addCommand(CMDS[MANAGE_TRACKS_CMD]);
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk()) {
alert("Record Mode", "You need to stop recording before managing tracks." , 5000);
return;
}
GuiGpx gpx = new GuiGpx(this);
gpx.show();
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
Thread thread = new Thread(this);
thread.start();
}
}
if (c == CMDS[SEARCH_CMD]){
GuiSearch search = new GuiSearch(this);
search.show();
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null){
locationProducer.close();
}
}
if (c == CMDS[ROUTE_TO_CMD]) {
routeCalc = true;
if (Configuration.isStopAllWhileRouteing()) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
logger.info("Routing source: " + source);
routeNodes=new Vector();
routeEngine = new Routing(t,this);
routeEngine.solve(source, target);
// resume();
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
if (gpsRecenter) {
// TODO: Should we block waypoint saving if we have no GPS fix?
guiWaypointSave.setData(new PositionMark(
pos.latitude * MoreMath.FAC_DECTORAD,
pos.longitude * MoreMath.FAC_DECTORAD,
(int)pos.altitude, pos.date,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1));
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
guiWaypointSave.setData(new PositionMark(center.radlat,
center.radlon, PositionMark.INVALID_ELEVATION,
pos.date, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1));
}
guiWaypointSave.show();
}
}
if (c == CMDS[ENTER_WAYP_CMD]) {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
if (c == CMDS[MAN_WAYP_CMD]) {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
int noElements = 3;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
noElements++;
//#endif
int idx = 0;
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[idx++] = "Stop Gpx tracklog";
} else {
elements[idx++] = "Start Gpx tracklog";
}
elements[idx++] = "Add waypoint";
elements[idx++] = "Enter waypoint";
//#if polish.api.mmapi
elements[idx++] = "Take pictures";
if (audioRec.isRecording()) {
elements[idx++] = "Stop audio recording";
} else {
elements[idx++] = "Start audio recording";
}
//#endif
//#if polish.api.wmapi
if (Configuration.hasDeviceJSR120()) {
elements[idx++] = "Send SMS (map pos)";
}
//#endif
recordingsMenu = new List("Recordings...",Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = {"Calculate route", "Set target" , "Clear target"};
routingsMenu = new List("Routing..", Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
}
if (c == CMDS[BACK_CMD]) {
show();
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if (!gpx.isRecordingTrk()){
gpx.newTrk();
} else {
gpx.saveTrk();
}
show();
break;
}
case 1: {
commandAction(CMDS[SAVE_WAYP_CMD], null);
break;
}
case 2: {
commandAction(CMDS[ENTER_WAYP_CMD], null);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CMDS[CAMERA_CMD], null);
break;
}
case 4: {
show();
commandAction(CMDS[TOGGLE_AUDIO_REC], null);
break;
}
//#endif
//#if polish.api.mmapi && polish.api.wmapi
case 5: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#elif polish.api.wmapi
case 3: {
commandAction(CMDS[SEND_MESSAGE_CMD], null);
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
commandAction(CMDS[ROUTE_TO_CMD], null);
break;
}
case 1: {
commandAction(CMDS[SETTARGET_CMD], null);
break;
}
case 2: {
commandAction(CMDS[CLEARTARGET_CMD], null);
break;
}
}
}
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]){
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe);
}
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
}
//#endif
if (c == CMDS[CLEARTARGET_CMD]) {
setTarget(null);
} else if (c == CMDS[SETTARGET_CMD]) {
if (source != null) {
setTarget(source);
}
} else if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
} else if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
} else if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
alert("Manual Rotation", "Change course with left/right keys", 3000);
} else {
alert("Manual Rotation", "Off", 1000);
}
} else if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
} else if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
} else if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
} else if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP ) {
ProjFactory.setProj(ProjFactory.MOVE_UP);
alert("Map Rotation", "Driving Direction", 750);
} else {
if (manualRotationMode) {
course = 0;
alert("Manual Rotation", "to North", 750);
} else {
ProjFactory.setProj(ProjFactory.NORTH_UP);
alert("Map Rotation", "NORTH UP", 750);
}
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
} else if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert("GpsMid", "Keys unlocked", 1000);
}
} else if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
alert("Gps track recording", "Stopping to record", 2000);
commandAction(CMDS[STOP_RECORD_CMD],(Displayable) null);
} else {
alert("Gps track recording", "Starting to record", 2000);
commandAction(CMDS[START_RECORD_CMD],(Displayable) null);
}
} else if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert("Gps track recording", "Resuming recording", 2000);
gpx.resumTrk();
} else {
alert("Gps track recording", "Suspending recording", 2000);
gpx.suspendTrk();
}
}
} else if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
newDataReady();
} else if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
}
//#if polish.api.osm-editing
else if (c == CMDS[RETRIEVE_XML]) {
if (C.enableEdits) {
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GUIosmWayDisplay guiWay = new GUIosmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
//#endif
} else {
alert("Error", "currently in route calculation", 1000);
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/integration/src/main/java/org/apache/mahout/utils/clustering/GraphMLClusterWriter.java b/integration/src/main/java/org/apache/mahout/utils/clustering/GraphMLClusterWriter.java
index e90fb0ce0..b561733f4 100644
--- a/integration/src/main/java/org/apache/mahout/utils/clustering/GraphMLClusterWriter.java
+++ b/integration/src/main/java/org/apache/mahout/utils/clustering/GraphMLClusterWriter.java
@@ -1,101 +1,101 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.utils.clustering;
import org.apache.mahout.clustering.Cluster;
import org.apache.mahout.clustering.WeightedVectorWritable;
import org.apache.mahout.math.NamedVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.utils.vectors.io.AbstractClusterWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* GraphML -- see http://gephi.org/users/supported-graph-formats/graphml-format/
*/
public class GraphMLClusterWriter extends AbstractClusterWriter {
private static final Pattern VEC_PATTERN = Pattern.compile("\\{|\\:|\\,|\\}");
public GraphMLClusterWriter(Writer writer, Map<Integer, List<WeightedVectorWritable>> clusterIdToPoints)
throws IOException {
super(writer, clusterIdToPoints);
writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.append("<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n" +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
"xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n" +
"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">");
writer.append("<graph edgedefault=\"undirected\">");
}
/*
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<graph id="G" edgedefault="undirected">
<node id="n0"/>
<node id="n1"/>
<edge id="e1" source="n0" target="n1"/>
</graph>
</graphml>
*/
@Override
public void write(Cluster cluster) throws IOException {
StringBuilder line = new StringBuilder();
line.append(createNode(String.valueOf(cluster.getId())));
List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId());
if (points != null) {
for (WeightedVectorWritable point : points) {
Vector theVec = point.getVector();
String vecStr;
if (theVec instanceof NamedVector) {
vecStr = ((NamedVector) theVec).getName();
line.append(createNode(vecStr));
} else {
vecStr = theVec.asFormatString();
//do some basic manipulations for display
vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_");
line.append(createNode(vecStr));
}
line.append(createEdge(String.valueOf(cluster.getId()), vecStr));
}
- getWriter().append(line).append("\n");
}
+ getWriter().append(line).append("\n");
}
private static String createEdge(String left, String right) {
return "<edge id=\"" + left + '_' + right + "\" source=\"" + left + "\" target=\"" + right + "\"/>";
}
private static String createNode(String s) {
return "<node id=\"" + s + "\"/>";
}
@Override
public void close() throws IOException {
getWriter().append("</graph>").append("</graphml>");
super.close();
}
}
| false | true | public void write(Cluster cluster) throws IOException {
StringBuilder line = new StringBuilder();
line.append(createNode(String.valueOf(cluster.getId())));
List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId());
if (points != null) {
for (WeightedVectorWritable point : points) {
Vector theVec = point.getVector();
String vecStr;
if (theVec instanceof NamedVector) {
vecStr = ((NamedVector) theVec).getName();
line.append(createNode(vecStr));
} else {
vecStr = theVec.asFormatString();
//do some basic manipulations for display
vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_");
line.append(createNode(vecStr));
}
line.append(createEdge(String.valueOf(cluster.getId()), vecStr));
}
getWriter().append(line).append("\n");
}
}
| public void write(Cluster cluster) throws IOException {
StringBuilder line = new StringBuilder();
line.append(createNode(String.valueOf(cluster.getId())));
List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId());
if (points != null) {
for (WeightedVectorWritable point : points) {
Vector theVec = point.getVector();
String vecStr;
if (theVec instanceof NamedVector) {
vecStr = ((NamedVector) theVec).getName();
line.append(createNode(vecStr));
} else {
vecStr = theVec.asFormatString();
//do some basic manipulations for display
vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_");
line.append(createNode(vecStr));
}
line.append(createEdge(String.valueOf(cluster.getId()), vecStr));
}
}
getWriter().append(line).append("\n");
}
|
diff --git a/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java b/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
index 79d6f7b..94ef04a 100644
--- a/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
+++ b/driver-one/src/main/java/com/telefonica/claudia/smi/provisioning/ONEProvisioningDriver.java
@@ -1,1530 +1,1530 @@
/*
* Claudia Project
* http://claudia.morfeo-project.org
*
* (C) Copyright 2010 Telefonica Investigacion y Desarrollo
* S.A.Unipersonal (Telefonica I+D)
*
* See CREDITS file for info about members and contributors.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License (AGPL) 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 Affero 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.
*
* If you want to use this software an plan to distribute a
* proprietary application in any way, and you are not licensing and
* distributing your source code under AGPL, you probably need to
* purchase a commercial license of the product. Please contact
* [email protected] for more information.
*/
package com.telefonica.claudia.smi.provisioning;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.dmtf.schemas.ovf.envelope._1.ContentType;
import org.dmtf.schemas.ovf.envelope._1.DiskSectionType;
import org.dmtf.schemas.ovf.envelope._1.EnvelopeType;
import org.dmtf.schemas.ovf.envelope._1.FileType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType;
import org.dmtf.schemas.ovf.envelope._1.RASDType;
import org.dmtf.schemas.ovf.envelope._1.ReferencesType;
import org.dmtf.schemas.ovf.envelope._1.VirtualDiskDescType;
import org.dmtf.schemas.ovf.envelope._1.VirtualHardwareSectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemCollectionType;
import org.dmtf.schemas.ovf.envelope._1.VirtualSystemType;
import org.dmtf.schemas.ovf.envelope._1.ProductSectionType.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.abiquo.ovf.OVFEnvelopeUtils;
import com.abiquo.ovf.exceptions.EmptyEnvelopeException;
import com.abiquo.ovf.section.OVFProductUtils;
import com.abiquo.ovf.xml.OVFSerializer;
import com.telefonica.claudia.smi.DataTypesUtils;
import com.telefonica.claudia.smi.Main;
import com.telefonica.claudia.smi.TCloudConstants;
import com.telefonica.claudia.smi.URICreation;
import com.telefonica.claudia.smi.task.Task;
import com.telefonica.claudia.smi.task.TaskManager;
public class ONEProvisioningDriver implements ProvisioningDriver {
public static enum ControlActionType {shutdown, hold, release, stop, suspend, resume, finalize};
//public static enum VmStateType {INIT, PENDING, HOLD, ACTIVE, STOPPED, SUSPENDED, DONE, FAILED};
private final static int INIT_STATE = 0;
private final static int PENDING_STATE = 1;
private final static int HOLD_STATE = 2;
private final static int ACTIVE_STATE = 3;
private final static int STOPPED_STATE = 4;
private final static int SUSPENDED_STATE = 5;
private final static int DONE_STATE = 6;
private final static int FAILED_STATE = 7;
// LCM_INIT, PROLOG, BOOT, RUNNING, MIGRATE, SAVE_STOP, SAVE_SUSPEND, SAVE_MIGRATE, PROLOG_MIGRATE, EPILOG_STOP, EPILOG, SHUTDOWN, CANCEL
private final static int INIT_SUBSTATE = 0;
private final static int PROLOG_SUBSTATE = 1;
private final static int BOOT_SUBSTATE = 2;
private final static int RUNNING_SUBSTATE = 3;
private final static int MIGRATE_SUBSTATE = 4;
private final static int SAVE_STOP_SUBSTATE = 5;
private final static int SAVE_SUSPEND_SUBSTATE = 6;
private final static int SAVE_MIGRATE_SUBSTATE = 7;
private final static int PROLOG_MIGRATE_SUBSTATE = 8;
private final static int PROLOG_RESUME_SUBSTATE = 9;
private final static int EPILOG_STOP_SUBSTATE = 10;
private final static int EPILOG_SUBSTATE = 11;
private final static int SHUDTOWN_SUBSTATE = 12;
private final static int CANCEL_SUBSTATE = 13;
private HashMap<String, String> text_migrability = new HashMap();
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("com.telefonica.claudia.smi.provisioning.ONEProvisioningDriver");
// Tag names of the returning info doc for Virtual machines
public static final String VM_STATE = "STATE";
public static final String VM_SUBSTATE = "LCM_STATE";
// XMLRPC commands to access OpenNebula features
private final static String VM_ALLOCATION_COMMAND = "one.vm.allocate";
private final static String VM_UPDATE_COMMAND = "one.vm.action";
private final static String VM_GETINFO_COMMAND = "one.vm.info";
private final static String VM_GETALL_COMMAND = "one.vmpool.info";
private final static String VM_DELETE_COMMAND = "one.vm.delete";
private final static String NET_ALLOCATION_COMMAND = "one.vn.allocate";
private final static String NET_GETINFO_COMMAND = "one.vn.info";
private final static String NET_GETALL_COMMAND = "one.vnpool.info";
private final static String NET_DELETE_COMMAND = "one.vn.delete";
private final static String DEBUGGING_CONSOLE = "RAW = [ type =\"kvm\", data =\"<devices><serial type='pty'><source path='/dev/pts/5'/><target port='0'/></serial><console type='pty' tty='/dev/pts/5'><source path='/dev/pts/5'/><target port='0'/></console></devices>\" ]";
/**
* Connection URL for OpenNebula. It defaults to localhost, but can be
* overriden with the property oneURL of the server configuration file.
*/
private String oneURL = "http://localhost:2633/RPC2";
/**
* Server configuration file URL property identifier.
*/
private final static String URL_PROPERTY = "oneUrl";
private final static String USER_PROPERTY = "oneUser";
private final static String PASSWORD_PROPERTY = "onePassword";
private static final String KERNEL_PROPERTY = "oneKernel";
private static final String INITRD_PROPERTY = "oneInitrd";
private static final String ARCH_PROPERTY = "arch";
private static final String ENVIRONMENT_PROPERTY = "oneEnvironmentPath";
private final static String SSHKEY_PROPERTY = "oneSshKey";
private final static String SCRIPTPATH_PROPERTY = "oneScriptPath";
private String oneSession = "oneadmin:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
private XmlRpcClient xmlRpcClient = null;
private static final String NETWORK_BRIDGE = "oneNetworkBridge";
private static final String XEN_DISK = "xendisk";
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idVmMap = new HashMap<String, Integer>();
/**
* Collection containing the mapping from fqns to ids. This mapped is used as a cache
* of the getVmId method (vm ids never change once assigned).
*/
private Map<String, Integer> idNetMap = new HashMap<String, Integer>();
private String hypervisorInitrd="";
private String arch="";
private String hypervisorKernel="";
private String customizationPort;
private String environmentRepositoryPath;
private static String networkBridge="";
private static String xendisk="";
private static String oneSshKey="";
private static String oneScriptPath="";
public static final String ASSIGNATION_SYMBOL = "=";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String ONE_VM_ID = "NAME";
public static final String ONE_VM_TYPE = "TYPE";
public static final String ONE_VM_STATE = "STATE";
public static final String ONE_VM_MEMORY = "MEMORY";
public static final String ONE_VM_NAME = "NAME";
public static final String ONE_VM_UUID = "UUID";
public static final String ONE_VM_CPU = "CPU";
public static final String ONE_VM_VCPU = "VCPU";
public static final String ONE_VM_RAW_VMI = "RAW_VMI";
public static final String ONE_VM_OS = "OS";
public static final String ONE_VM_OS_PARAM_KERNEL = "kernel";
public static final String ONE_VM_OS_PARAM_INITRD = "initrd";
public static final String ONE_VM_OS_PARAM_ROOT = "root";
public static final String ONE_VM_OS_PARAM_BOOT = "boot";
public static final String ONE_VM_GRAPHICS = "GRAPHICS";
public static final String ONE_VM_GRAPHICS_TYPE = "type";
public static final String ONE_VM_GRAPHICS_LISTEN = "listen";
public static final String ONE_VM_GRAPHICS_PORT = "port";
public static final String ONE_VM_DISK_COLLECTION = "DISKS";
public static final String ONE_VM_DISK = "DISK";
public static final String ONE_VM_DISK_PARAM_IMAGE = "source";
public static final String ONE_VM_DISK_PARAM_FORMAT = "format";
public static final String ONE_VM_DISK_PARAM_SIZE = "size";
public static final String ONE_VM_DISK_PARAM_TARGET = "target";
public static final String ONE_VM_DISK_PARAM_DIGEST = "digest";
public static final String ONE_VM_DISK_PARAM_TYPE = "type";
public static final String ONE_VM_DISK_PARAM_DRIVER = "driver";
public static final String ONE_VM_NIC_COLLECTION = "NICS";
public static final String ONE_VM_NIC = "NIC";
public static final String ONE_VM_NIC_PARAM_IP = "ip";
public static final String ONE_VM_NIC_PARAM_NETWORK = "NETWORK";
public static final String ONE_NET_ID = "ID";
public static final String ONE_NET_NAME = "NAME";
public static final String ONE_NET_BRIDGE = "BRIDGE";
public static final String ONE_NET_TYPE = "TYPE";
public static final String ONE_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String ONE_NET_SIZE = "NETWORK_SIZE";
public static final String ONE_NET_LEASES = "LEASES";
public static final String ONE_NET_IP = "IP";
public static final String ONE_NET_MAC = "MAC";
public static final String ONE_DISK_ID = "ID";
public static final String ONE_DISK_NAME = "NAME";
public static final String ONE_DISK_URL = "URL";
public static final String ONE_DISK_SIZE = "SIZE";
public static final String ONE_OVF_URL = "OVF";
public static final String ONE_CONTEXT = "CONTEXT";
public static final String RESULT_NET_ID = "ID";
public static final String RESULT_NET_NAME = "NAME";
public static final String RESULT_NET_ADDRESS = "NETWORK_ADDRESS";
public static final String RESULT_NET_BRIDGE = "BRIDGE";
public static final String RESULT_NET_TYPE = "TYPE";
public static final String MULT_CONF_LEFT_DELIMITER = "[";
public static final String MULT_CONF_RIGHT_DELIMITER = "]";
public static final String MULT_CONF_SEPARATOR = ",";
public static final String QUOTE = "\"";
private static final int ResourceTypeCPU = 3;
private static final int ResourceTypeMEMORY = 4;
private static final int ResourceTypeNIC = 10;
private static final int ResourceTypeDISK = 17;
public class DeployVMTask extends Task {
public static final long POLLING_INTERVAL= 10000;
private static final int MAX_CONNECTION_ATEMPTS = 5;
String fqnVm;
String ovf;
public DeployVMTask(String fqn, String ovf) {
super();
this.fqnVm = fqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
// Create the Virtual Machine
String result = createVirtualMachine();
if (result==null) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
// Wait until the state is RUNNING
this.status = TaskStatus.WAITING;
int connectionAttempts=0;
while (true) {
try {
Document vmInfo = getVirtualMachineState(result);
Integer state = Integer.parseInt(vmInfo.getElementsByTagName(VM_STATE).item(0).getTextContent());
Integer subState = Integer.parseInt(vmInfo.getElementsByTagName(VM_SUBSTATE).item(0).getTextContent());
if (state == ACTIVE_STATE && subState == RUNNING_SUBSTATE ) {
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
break;
} else if (state ==FAILED_STATE) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
}
connectionAttempts=0;
} catch (IOException ioe) {
if (connectionAttempts> MAX_CONNECTION_ATEMPTS) {
this.status= TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
break;
} else
connectionAttempts++;
log.warn("Connection exception accessing ONE. Trying again. Error: " + ioe.getMessage());
}
Thread.sleep(POLLING_INTERVAL);
}
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unexpected error creating VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
public String createVirtualMachine() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONEVM(ovf, fqnVm));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error on allocation of VEE replica , XMLRPC call failed: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Request succeded. Returining: \n\n" + ((Integer)result[1]).toString() + "\n\n");
this.returnMsg = "Virtual machine internal id: " + ((Integer)result[1]).toString();
return ((Integer)result[1]).toString();
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return null;
}
}
}
public class DeployNetworkTask extends Task {
String fqnNet;
String ovf;
public DeployNetworkTask(String netFqn, String ovf) {
this.fqnNet = netFqn;
this.ovf = ovf;
}
@Override
public void execute() {
this.status = TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
try {
if (!createNetwork()) {
this.status= TaskStatus.ERROR;
return;
}
this.status= TaskStatus.SUCCESS;
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
return;
} catch (Exception e) {
log.error("Unknown error creating network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.endTime = System.currentTimeMillis();
this.status = TaskStatus.ERROR;
}
}
public boolean createNetwork() throws Exception {
List<String> rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(TCloud2ONENet(ovf));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_ALLOCATION_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error. Could not reach ONE host: " + ex.getMessage());
throw new IOException ("Error on allocation of the new network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
log.debug("Network creation request succeded: " + result[1]);
this.returnMsg = ((Integer)result[1]).toString();
return true;
} else {
log.error("Error recieved from ONE: " + (String)result[1]);
this.error = new TaskError();
this.error.message = (String)result[1];
return false;
}
}
}
public class UndeployVMTask extends Task {
String fqnVm;
public UndeployVMTask(String vmFqn) {
this.fqnVm = vmFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
String id = getVmId(fqnVm).toString();
deleteVirtualMachine(id);
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying VM: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public boolean deleteVirtualMachine(String id) throws IOException {
List rpcParams = new ArrayList ();
ControlActionType controlAction = ControlActionType.finalize;
log.info("PONG deleteVirtualMachine id: "+ id);
rpcParams.add(oneSession);
rpcParams.add(controlAction.toString());
rpcParams.add(Integer.parseInt(id));
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_UPDATE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to update VM: " + ex.getMessage());
throw new IOException ("Error updating VEE replica , XMLRPC call failed", ex);
}
if (result==null) {
throw new IOException("No result returned from XMLRPC call");
} else {
return (Boolean)result[0];
}
}
}
public class UndeployNetworkTask extends Task {
String fqnNet;
public UndeployNetworkTask(String netFqn) {
this.fqnNet = netFqn;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
deleteNetwork(getNetId(fqnNet).toString());
this.status= TaskStatus.SUCCESS;
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to ONE: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error undeploying Network: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
@SuppressWarnings("unchecked")
public void deleteNetwork(String id) throws IOException {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id) );
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_DELETE_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error deleting the network , XMLRPC call failed", ex);
}
boolean success = (Boolean)result[0];
if(success) {
} else {
throw new IOException("Unknown error trying to delete network: " + (String)result[1]);
}
}
}
public class ActionVMTask extends Task {
String fqnVM;
String action;
String errorMessage="";
public ActionVMTask(String fqnVM, String action) {
this.fqnVM = fqnVM;
this.action = action;
}
@Override
public void execute() {
this.status= TaskStatus.RUNNING;
this.startTime = System.currentTimeMillis();
// Undeploy the VM
try {
boolean result = doAction();
if (result)
this.status= TaskStatus.SUCCESS;
else {
this.status = TaskStatus.ERROR;
this.error = new TaskError();
this.error.message = errorMessage;
}
this.endTime = System.currentTimeMillis();
} catch (IOException e) {
log.error("Error connecting to VMWare: " + e.getMessage());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
} catch (Exception e) {
log.error("Unknown error executing action" + action + ": " + e.getMessage() + " -> " + e.getClass().getCanonicalName());
this.error = new TaskError();
this.error.message = e.getMessage();
this.status = TaskStatus.ERROR;
this.endTime = System.currentTimeMillis();
return;
}
}
public boolean doAction() throws Exception {
System.out.println("Executing action: " + action);
return true;
}
}
protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
ProductSectionType productSection;
try
{
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dc"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
- for (int k = 0; k < quantity; k++) {
+ // for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
- }
+ // }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
throw new IllegalArgumentException("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONEVM2TCloud(String ONETemplate) {
// TODO: ONE Template to TCloud translation
return "";
}
protected static String TCloud2ONENet(String xml) throws Exception {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
Element root = (Element) doc.getFirstChild();
String fqn = root.getAttribute(TCloudConstants.ATTR_NETWORK_NAME);
NodeList macEnabled = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC_ENABLED);
Element firstmacenElement = (Element)macEnabled.item(0);
NodeList textMacenList = firstmacenElement.getChildNodes();
String macenabled= ((Node)textMacenList.item(0)).getNodeValue().trim();
NodeList netmaskList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_NETMASK);
NodeList baseAddressList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_BASE_ADDRESS);
StringBuffer allParametersString = new StringBuffer();
String privateNet = null;
if (root.getAttribute(TCloudConstants.ATTR_NETWORK_TYPE).equals("true"))
privateNet = "private";
else
privateNet ="public";
// If there is a netmask, calculate the size of the net counting it's bits.
if (netmaskList.getLength() >0) {
Element netmask = (Element) netmaskList.item(0);
if (!netmask.getTextContent().matches("\\d+\\.\\d+\\.\\d+\\.\\d+"))
throw new IllegalArgumentException("Wrong IPv4 format. Expected example: 192.168.0.0 Got: " + netmask.getTextContent());
String[] ipBytes = netmask.getTextContent().split("\\.");
short[] result = new short[4];
for (int i=0; i < 4; i++) {
try {
result[i] = Short.parseShort(ipBytes[i]);
if (result[i]>255) throw new NumberFormatException("Should be in the range [0-255].");
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Number out of bounds. Bytes should be on the range 0-255.");
}
}
// The network can host 2^n where n is the number of bits in the network address,
// substracting the broadcast and the network value (all 1s and all 0s).
int size = (int) Math.pow(2, 32.0-getBitNumber(result));
if (size < 8)
size = 8;
else
size -= 2;
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_SIZE).append(ASSIGNATION_SYMBOL).append(size).append(LINE_SEPARATOR);
}
if (baseAddressList.getLength()>0) {
if (macenabled.equals("false"))
allParametersString.append(ONE_NET_ADDRESS).append(ASSIGNATION_SYMBOL).append(baseAddressList.item(0).getTextContent()).append(LINE_SEPARATOR);
}
// Translate the simple data to RPC format
allParametersString.append(ONE_NET_NAME).append(ASSIGNATION_SYMBOL).append(fqn).append(LINE_SEPARATOR);
// Add the net Type
if (macenabled.equals("false")) {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("RANGED").append(LINE_SEPARATOR);
}
else {
allParametersString.append(ONE_NET_TYPE).append(ASSIGNATION_SYMBOL).append("FIXED").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(LINE_SEPARATOR);
NodeList ipLeaseList = doc.getElementsByTagName(TCloudConstants.TAG_NETWORK_IPLEASES);
for (int i=0; i<ipLeaseList .getLength(); i++){
Node firstIpLeaseNode = ipLeaseList.item(i);
if (firstIpLeaseNode.getNodeType() == Node.ELEMENT_NODE){
Element firstIpLeaseElement = (Element)firstIpLeaseNode;
NodeList ipList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_IP);
Element firstIpElement = (Element)ipList.item(0);
NodeList textIpList = firstIpElement.getChildNodes();
String ipString = ("IP="+((Node)textIpList.item(0)).getNodeValue().trim());
NodeList macList =firstIpLeaseElement.getElementsByTagName(TCloudConstants.TAG_NETWORK_MAC);
Element firstMacElement = (Element)macList.item(0);
NodeList textMacList = firstMacElement.getChildNodes();
String macString = ("MAC="+((Node)textMacList.item(0)).getNodeValue().trim());
allParametersString.append(ONE_NET_LEASES).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ipString).append(MULT_CONF_SEPARATOR).append(macString).append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
}
}
log.debug("Network data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
protected static String ONENet2TCloud(String ONETemplate) {
return "";
}
/**
* Get the number of bits with value 1 in the given IP.
*
* @return
*/
public static int getBitNumber (short[] ip) {
if (ip == null || ip.length != 4)
return 0;
int bits=0;
for (int i=0; i < 4; i++)
for (int j=0; j< 15; j++)
bits += ( ((short)Math.pow(2, j))& ip[i]) / Math.pow(2, j);
return bits;
}
/**
* Retrieve the virtual network id given its fqn.
*
* @param fqn
* FQN of the Virtual Network (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Network if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getNetId(String fqn) throws Exception {
if (!idNetMap.containsKey(fqn))
idNetMap = getNetworkIds();
if (idNetMap.containsKey(fqn))
return idNetMap.get(fqn);
else
return -1;
}
/**
* Retrieve the vm's id given its fqn.
*
* @param fqn
* FQN of the Virtual Machine (mapped to its name property in ONE).
*
* @return
* The internal id of the Virtual Machine if it exists or -1 otherwise.
*
* @throws Exception
*
*/
protected Integer getVmId(String fqn) throws Exception {
if (!idVmMap.containsKey(fqn))
idVmMap = getVmIds();
if (idVmMap.containsKey(fqn))
return idVmMap.get(fqn);
else
return -1;
}
/**
* Retrieve a map of the currently deployed VMs, and its ids.
*
* @return
* A map where the key is the VM's FQN and the value the VM's id.
* @throws Exception
*/
@SuppressWarnings("unchecked")
protected Map<String, Integer> getVmIds() throws Exception {
List rpcParams = new ArrayList<String>();
rpcParams.add(oneSession);
rpcParams.add(-2);
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the VM list: " + ex.getMessage(), ex);
}
boolean success = (Boolean)result[0];
if(success) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VM");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
log.error("Parser Configuration Error: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error reading the answer: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("Error recieved from ONE: " + result[1]);
throw new Exception("Error recieved from ONE: " + result[1]);
}
}
@SuppressWarnings("unchecked")
protected HashMap<String, Integer> getNetworkIds() throws IOException {
List rpcParams = new ArrayList();
rpcParams.add(oneSession);
rpcParams.add(-2);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(NET_GETALL_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
throw new IOException ("Error obtaining the network list", ex);
}
boolean success = (Boolean)result[0];
if(success) {
HashMap<String, Integer> mapResult = new HashMap<String, Integer>();
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
NodeList vmList = doc.getElementsByTagName("VNET");
for (int i=0; i < vmList.getLength(); i++) {
Element vm = (Element) vmList.item(i);
String fqn = ((Element)vm.getElementsByTagName("NAME").item(0)).getTextContent();
try {
Integer value = Integer.parseInt(((Element)vm.getElementsByTagName("ID").item(0)).getTextContent());
mapResult.put(fqn, value);
} catch(NumberFormatException nfe) {
log.warn("Numerical id expected, got [" + ((Element)vm.getElementsByTagName("ID").item(0)).getTextContent() + "]");
continue;
}
}
return mapResult;
} catch (ParserConfigurationException e) {
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
throw new IOException ("XML Parse error", e);
}
} else {
throw new IOException("Error recieved from ONE: " +(String)result[1]);
}
}
public ONEProvisioningDriver(Properties prop) {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
log.info("Creating OpenNebula conector");
if (prop.containsKey(URL_PROPERTY)) {
oneURL = (String) prop.get(URL_PROPERTY);
log.info("URL created: " + oneURL);
}
if (prop.containsKey(USER_PROPERTY)&&prop.containsKey(PASSWORD_PROPERTY)) {
oneSession = ((String) prop.get(USER_PROPERTY)) + ":" + ((String) prop.get(PASSWORD_PROPERTY));
log.info("Session created: " + oneSession);
}
if (prop.containsKey(KERNEL_PROPERTY)) {
hypervisorKernel = ((String) prop.get(KERNEL_PROPERTY));
}
if (prop.containsKey(INITRD_PROPERTY)) {
hypervisorInitrd = ((String) prop.get(INITRD_PROPERTY));
}
if (prop.containsKey(ARCH_PROPERTY)) {
arch = ((String) prop.get(ARCH_PROPERTY));
}
if (prop.containsKey(Main.CUSTOMIZATION_PORT_PROPERTY)) {
customizationPort = ((String) prop.get(Main.CUSTOMIZATION_PORT_PROPERTY));
}
if (prop.containsKey(ENVIRONMENT_PROPERTY)) {
environmentRepositoryPath = (String) prop.get(ENVIRONMENT_PROPERTY);
}
if (prop.containsKey(NETWORK_BRIDGE)) {
networkBridge = ((String) prop.get(NETWORK_BRIDGE));
}
if (prop.containsKey(XEN_DISK)) {
xendisk = ((String) prop.get(XEN_DISK));
}
if (prop.containsKey(SSHKEY_PROPERTY)) {
oneSshKey = ((String) prop.get(SSHKEY_PROPERTY));
}
if (prop.containsKey(SCRIPTPATH_PROPERTY)) {
oneScriptPath = ((String) prop.get(SCRIPTPATH_PROPERTY));
}
try {
config.setServerURL(new URL(oneURL));
} catch (MalformedURLException e) {
log.error("Malformed URL: " + oneURL);
throw new RuntimeException(e);
}
xmlRpcClient = new XmlRpcClient();
log.info("XMLRPC client created");
xmlRpcClient.setConfig(config);
log.info("XMLRPC client configured");
/* MIGRABILITY TAG */
text_migrability.put("cross-host", "HOST");
text_migrability.put("cross-sitehost", "SITE");
text_migrability.put("none", "NONE");
// FULL??
}
@SuppressWarnings("unchecked")
public Document getVirtualMachineState(String id) throws IOException {
List rpcParams = new ArrayList ();
rpcParams.add(oneSession);
rpcParams.add(new Integer(id));
log.debug("Virtual machine info requested for id: " + id);
Object[] result = null;
try {
result = (Object[])xmlRpcClient.execute(VM_GETINFO_COMMAND, rpcParams);
} catch (XmlRpcException ex) {
log.error("Connection error trying to get VM information: " + ex.getMessage());
throw new IOException ("Error on reading VM state , XMLRPC call failed", ex);
}
boolean completed = (Boolean) result[0];
if (completed) {
String resultList = (String) result[1];
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// RESERVOIR ONLY: the info cames with a XML inside the element RAW_VMI, WITH HEADERS
if (resultList.contains("<RAW_VMI>")) {
resultList = resultList.replace(resultList.substring(resultList.indexOf("<RAW_VMI>"), resultList.indexOf("</RAW_VMI>") + 10), "");
}
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(resultList.getBytes()));
log.debug("VM Info request succeded");
return doc;
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new IOException ("Parser Configuration Error", e);
} catch (SAXException e) {
log.error("Parse error obtaining info: " + e.getMessage());
throw new IOException ("XML Parse error", e);
}
} else {
log.error("VM Info request failed: " + result[1]);
return null;
}
}
public String getAtributeVirtualSystem(VirtualSystemType vs, String attribute) throws NumberFormatException {
Iterator itr = vs.getOtherAttributes().entrySet().iterator();
while (itr.hasNext()) {
Map.Entry e = (Map.Entry)itr.next();
if ((e.getKey()).equals(new QName ("http://schemas.telefonica.com/claudia/ovf", attribute)))
return (String)e.getValue();
}
return "";
}
public ArrayList<VirtualSystemType> getVirtualSystem (EnvelopeType envelope) throws Exception {
ContentType entityInstance = null;
ArrayList<VirtualSystemType> virtualSystems = new ArrayList ();
try {
entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
} catch (EmptyEnvelopeException e) {
log.error(e);
}
HashMap<String,VirtualSystemType> virtualsystems = new HashMap();
if (entityInstance instanceof VirtualSystemType) {
virtualSystems.add((VirtualSystemType)entityInstance);
} else if (entityInstance instanceof VirtualSystemCollectionType) {
VirtualSystemCollectionType virtualSystemCollectionType = (VirtualSystemCollectionType) entityInstance;
for (VirtualSystemType vs : OVFEnvelopeUtils.getVirtualSystems(virtualSystemCollectionType))
{
virtualSystems.add(vs);
}
}//End for
return virtualSystems;
}
@Override
public long deleteNetwork(String netFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployNetworkTask(netFqn), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deleteVirtualMachine(String vmFqn) throws IOException {
return TaskManager.getInstance().addTask(new UndeployVMTask(vmFqn), URICreation.getVDC(vmFqn)).getTaskId();
}
@Override
public long deployNetwork(String netFqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployNetworkTask(netFqn, ovf), URICreation.getVDC(netFqn)).getTaskId();
}
@Override
public long deployVirtualMachine(String fqn, String ovf) throws IOException {
return TaskManager.getInstance().addTask(new DeployVMTask(fqn, ovf), URICreation.getVDC(fqn)).getTaskId();
}
public long powerActionVirtualMachine(String fqn, String action) throws IOException {
return TaskManager.getInstance().addTask(new ActionVMTask(fqn, action), URICreation.getVDC(fqn)).getTaskId();
}
public String getNetwork(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNetworkList() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getVirtualMachine(String fqn) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
| false | true | protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
ProductSectionType productSection;
try
{
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dc"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
}
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
throw new IllegalArgumentException("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
| protected String TCloud2ONEVM(String xml, String veeFqn) throws Exception {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
if (!doc.getFirstChild().getNodeName().equals(TCloudConstants.TAG_INSTANTIATE_OVF)) {
log.error("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
throw new Exception("Element <"+TCloudConstants.TAG_INSTANTIATE_OVF+"> not found.");
}
Element root = (Element) doc.getFirstChild();
String replicaName = root.getAttribute("name");
NodeList envelopeItems = doc.getElementsByTagNameNS("*", "Envelope");
if (envelopeItems.getLength() != 1) {
log.error("Envelope items not found.");
throw new Exception("Envelope items not found.");
}
// Extract the IP from the aspects section
Map<String, String> ipOnNetworkMap = new HashMap<String, String>();
NodeList aspects = doc.getElementsByTagNameNS("*", "Aspect");
for (int i=0; i < aspects.getLength(); i++) {
Element aspect = (Element) aspects.item(i);
if (aspect.getAttribute("name").equals("IP Config")) {
NodeList properties = aspect.getElementsByTagNameNS("*", "Property");
for (int j=0; j < properties.getLength(); j++) {
Element property = (Element) properties.item(j);
NodeList keys = property.getElementsByTagNameNS("*", "Key");
NodeList values = property.getElementsByTagNameNS("*", "Value");
if (keys.getLength() >0 && values.getLength()>0) {
ipOnNetworkMap.put(keys.item(0).getTextContent(), values.item(0).getTextContent());
}
}
}
}
// Extract the ovf sections and pass them to the OVF manager to be processed.
Document ovfDoc = builder.newDocument();
ovfDoc.appendChild(ovfDoc.importNode(envelopeItems.item(0), true));
OVFSerializer ovfSerializer = OVFSerializer.getInstance();
ovfSerializer.setValidateXML(false);
EnvelopeType envelope = ovfSerializer.readXMLEnvelope(new ByteArrayInputStream(DataTypesUtils.serializeXML(ovfDoc).getBytes()));
ContentType entityInstance = OVFEnvelopeUtils.getTopLevelVirtualSystemContent(envelope);
if (entityInstance instanceof VirtualSystemType) {
VirtualSystemType vs = (VirtualSystemType) entityInstance;
VirtualHardwareSectionType vh = OVFEnvelopeUtils.getSection(vs, VirtualHardwareSectionType.class);
String virtualizationType = vh.getSystem().getVirtualSystemType().getValue();
String scriptListProp = null;
String scriptListTemplate = "";
ProductSectionType productSection;
try
{
productSection = OVFEnvelopeUtils.getSection(vs, ProductSectionType.class);
Property prop = OVFProductUtils.getProperty(productSection, "SCRIPT_LIST");
scriptListProp = prop.getValue().toString();
String[] scriptList = scriptListProp.split("/");
scriptListTemplate = "";
for (String scrt: scriptList){
scriptListTemplate = scriptListTemplate + " "+oneScriptPath+"/"+scrt;
}
}
catch (Exception e)
{
//TODO throw PropertyNotFoundException
//logger.error(e);
scriptListProp="";
scriptListTemplate = "";
}
StringBuffer allParametersString = new StringBuffer();
// Migrability ....
allParametersString.append(ONE_VM_NAME).append(ASSIGNATION_SYMBOL).append(replicaName).append(LINE_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"kvm\\\"\"").append(LINE_SEPARATOR);
} else if (virtualizationType.toLowerCase().equals("xen")) {
allParametersString.append("REQUIREMENTS").append(ASSIGNATION_SYMBOL).append("\"HYPERVISOR=\\\"xen\\\"\"").append(LINE_SEPARATOR);
}
allParametersString.append(ONE_VM_OS).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
String diskRoot;
if (virtualizationType.toLowerCase().equals("kvm")) {
diskRoot = "h";
allParametersString.append(ONE_VM_OS_PARAM_BOOT).append(ASSIGNATION_SYMBOL).append("hd").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
} else {
diskRoot = xendisk;
allParametersString.append(ONE_VM_OS_PARAM_INITRD).append(ASSIGNATION_SYMBOL).append(hypervisorInitrd).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_KERNEL).append(ASSIGNATION_SYMBOL).append(hypervisorKernel).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
}
if(arch.length()>0)
allParametersString.append("ARCH").append(ASSIGNATION_SYMBOL).append("\"").append(arch).append("\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_OS_PARAM_ROOT).append(ASSIGNATION_SYMBOL).append(diskRoot + "da1").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_CONTEXT).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append("public_key").append(ASSIGNATION_SYMBOL).append(oneSshKey).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("CustomizationUrl").append(ASSIGNATION_SYMBOL).append("\"" + Main.PROTOCOL + Main.serverHost + ":" + customizationPort + "/"+ replicaName+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("files").append(ASSIGNATION_SYMBOL).append("\"" + environmentRepositoryPath + "/"+ replicaName + "/ovf-env.xml" +scriptListTemplate+ "\"").append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR);
allParametersString.append("target").append(ASSIGNATION_SYMBOL).append("\"" + diskRoot + "dc"+ "\"").append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
if (vh.getSystem() != null && vh.getSystem().getVirtualSystemType()!= null &&
vh.getSystem().getVirtualSystemType().getValue() != null &&
vh.getSystem().getVirtualSystemType().getValue().equals("vjsc"))
{
allParametersString.append("HYPERVISOR").append(ASSIGNATION_SYMBOL).append("VJSC").append(LINE_SEPARATOR);
}
char sdaId = 'a';
List<RASDType> items = vh.getItem();
for (Iterator<RASDType> iteratorRASD = items.iterator(); iteratorRASD.hasNext();) {
RASDType item = (RASDType) iteratorRASD.next();
/* Get the resource type and process it accordingly */
int rsType = new Integer(item.getResourceType().getValue());
int quantity = 1;
if (item.getVirtualQuantity() != null) {
quantity = item.getVirtualQuantity().getValue().intValue();
}
switch (rsType) {
case ResourceTypeCPU:
// for (int k = 0; k < quantity; k++) {
allParametersString.append(ONE_VM_CPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
allParametersString.append(ONE_VM_VCPU).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
// }
break;
case ResourceTypeDISK:
/*
* The rasd:HostResource will follow the pattern
* 'ovf://disk/<id>' where id is the ovf:diskId of some
* <Disk>
*/
String hostRes = item.getHostResource().get(0).getValue();
StringTokenizer st = new StringTokenizer(hostRes, "/");
/*
* Only ovf:/<file|disk>/<n> format is valid, accodring
* OVF spec
*/
if (st.countTokens() != 3) {
throw new IllegalArgumentException("malformed HostResource value (" + hostRes + ")");
}
if (!(st.nextToken().equals("ovf:"))) {
throw new IllegalArgumentException("HostResource must start with ovf: (" + hostRes + ")");
}
String hostResType = st.nextToken();
if (!(hostResType.equals("disk") || hostResType.equals("file"))) {
throw new IllegalArgumentException("HostResource type must be either disk or file: (" + hostRes + ")");
}
String hostResId = st.nextToken();
String fileRef = null;
String capacity = null;
String format = null;
if (hostResType.equals("disk")) {
/* This type involves an indirection level */
DiskSectionType ds = null;
ds = OVFEnvelopeUtils.getSection(envelope, DiskSectionType.class);
List<VirtualDiskDescType> disks = ds.getDisk();
for (Iterator<VirtualDiskDescType> iteratorDk = disks.iterator(); iteratorDk.hasNext();) {
VirtualDiskDescType disk = iteratorDk.next();
String diskId = disk.getDiskId();
if (diskId.equals(hostResId)) {
fileRef = disk.getFileRef();
capacity = disk.getCapacity();
format = disk.getFormat();
break;
}
}
} else {
throw new IllegalArgumentException("File type not supported in Disk sections.");
}
/* Throw exceptions in the case of missing information */
if (fileRef == null) {
throw new IllegalArgumentException("file reference can not be found for disk: " + hostRes);
}
URL url = null;
String digest = null;
String driver = null;
ReferencesType ref = envelope.getReferences();
List<FileType> files = ref.getFile();
for (Iterator<FileType> iteratorFl = files.iterator(); iteratorFl.hasNext();) {
FileType fl = iteratorFl.next();
if (fl.getId().equals(fileRef)) {
try {
url = new URL(fl.getHref());
} catch (MalformedURLException e) {
throw new IllegalArgumentException("problems parsing disk href: " + e.getMessage());
}
/*
* If capacity was not set using ovf:capacity in
* <Disk>, try to get it know frm <File>
* ovf:size
*/
if (capacity == null && fl.getSize() != null) {
capacity = fl.getSize().toString();
}
/* Try to get the digest */
Map<QName, String> attributesFile = fl.getOtherAttributes();
QName digestAtt = new QName("http://schemas.telefonica.com/claudia/ovf","digest");
digest = attributesFile.get(digestAtt);
Map<QName, String> attributesFile2 = fl.getOtherAttributes();
QName driverAtt = new QName("http://schemas.telefonica.com/claudia/ovf","driver");
driver = attributesFile.get(driverAtt);
break;
}
}
/* Throw exceptions in the case of missing information */
if (capacity == null) {
throw new IllegalArgumentException("capacity can not be set for disk " + hostRes);
}
if (url == null) {
throw new IllegalArgumentException("url can not be set for disk " + hostRes);
}
if (digest == null) {
log.debug("md5sum digest was not found for disk " + hostRes);
}
String urlDisk = url.toString();
if (urlDisk.contains("file:/"))
urlDisk = urlDisk.replace("file:/", "file:///");
File filesystem = new File("/dev/" + diskRoot + "d" + sdaId);
allParametersString.append(ONE_VM_DISK).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER);
allParametersString.append(ONE_VM_DISK_PARAM_IMAGE).append(ASSIGNATION_SYMBOL).append(urlDisk).append(MULT_CONF_SEPARATOR);
if (virtualizationType.toLowerCase().equals("kvm")) {
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(diskRoot + "d" + sdaId).append(MULT_CONF_SEPARATOR);
} else
allParametersString.append(ONE_VM_DISK_PARAM_TARGET).append(ASSIGNATION_SYMBOL).append(filesystem.getAbsolutePath()).append(MULT_CONF_SEPARATOR);
if (format!=null)
{
if (format.equals("ext3"))
{
allParametersString.append(ONE_VM_DISK_PARAM_TYPE).append(ASSIGNATION_SYMBOL).append("fs").append(MULT_CONF_SEPARATOR);
}
allParametersString.append(ONE_VM_DISK_PARAM_FORMAT).append(ASSIGNATION_SYMBOL).append(format).append(MULT_CONF_SEPARATOR);
}
if (driver!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DRIVER).append(ASSIGNATION_SYMBOL).append(driver).append(MULT_CONF_SEPARATOR);
if (digest!=null)
allParametersString.append(ONE_VM_DISK_PARAM_DIGEST).append(ASSIGNATION_SYMBOL).append(digest).append(MULT_CONF_SEPARATOR);
allParametersString.append(ONE_VM_DISK_PARAM_SIZE).append(ASSIGNATION_SYMBOL).append(capacity);
allParametersString.append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
sdaId++;
break;
case ResourceTypeMEMORY:
allParametersString.append(ONE_VM_MEMORY).append(ASSIGNATION_SYMBOL).append(quantity).append(LINE_SEPARATOR);
break;
case ResourceTypeNIC:
String fqnNet = URICreation.getService(veeFqn) + ".networks." + item.getConnection().get(0).getValue();
allParametersString.append(ONE_VM_NIC).append(ASSIGNATION_SYMBOL).append(MULT_CONF_LEFT_DELIMITER).append(LINE_SEPARATOR);
allParametersString.append(ONE_NET_BRIDGE).append(ASSIGNATION_SYMBOL).append(networkBridge).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_NETWORK).append(ASSIGNATION_SYMBOL).append(fqnNet).append(MULT_CONF_SEPARATOR).append(LINE_SEPARATOR).
append(ONE_VM_NIC_PARAM_IP).append(ASSIGNATION_SYMBOL).append(ipOnNetworkMap.get(fqnNet)).append(LINE_SEPARATOR).
append(MULT_CONF_RIGHT_DELIMITER).append(LINE_SEPARATOR);
break;
default:
throw new IllegalArgumentException("unknown hw type: " + rsType);
}
}
allParametersString.append(LINE_SEPARATOR).append(DEBUGGING_CONSOLE).append(LINE_SEPARATOR);
log.debug("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
System.out.println("VM data sent:\n\n" + allParametersString.toString() + "\n\n");
return allParametersString.toString();
} else {
throw new IllegalArgumentException("OVF malformed. No VirtualSystemType found.");
}
} catch (IOException e1) {
log.error("OVF of the virtual machine was not well formed or it contained some errors.");
throw new Exception("OVF of the virtual machine was not well formed or it contained some errors: " + e1.getMessage());
} catch (ParserConfigurationException e) {
log.error("Error configuring parser: " + e.getMessage());
throw new Exception("Error configuring parser: " + e.getMessage());
} catch (FactoryConfigurationError e) {
log.error("Error retrieving parser: " + e.getMessage());
throw new Exception("Error retrieving parser: " + e.getMessage());
} catch (Exception e) {
log.error("Error configuring a XML Builder.");
throw new Exception("Error configuring a XML Builder: " + e.getMessage());
}
}
|
diff --git a/src/main/java/org/realityforge/tarrabah/SyslogHandler.java b/src/main/java/org/realityforge/tarrabah/SyslogHandler.java
index 2667e9b..23cfd90 100644
--- a/src/main/java/org/realityforge/tarrabah/SyslogHandler.java
+++ b/src/main/java/org/realityforge/tarrabah/SyslogHandler.java
@@ -1,137 +1,137 @@
package org.realityforge.tarrabah;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.joda.time.DateTime;
import org.realityforge.jsyslog.message.Facility;
import org.realityforge.jsyslog.message.Severity;
import org.realityforge.jsyslog.message.StructuredDataParameter;
import org.realityforge.jsyslog.message.SyslogMessage;
public final class SyslogHandler
extends BaseInputHandler
{
@Inject
private Logger _logger;
@Override
public void messageReceived( final ChannelHandlerContext context,
final MessageEvent e )
throws Exception
{
final InetSocketAddress remoteAddress = (InetSocketAddress) e.getRemoteAddress();
final ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
final byte[] readable = new byte[ buffer.readableBytes() ];
buffer.toByteBuffer().get( readable, buffer.readerIndex(), buffer.readableBytes() );
final SocketAddress localAddress = context.getChannel().getLocalAddress();
final String rawMessage = new String( readable );
processSyslogMessage( remoteAddress, localAddress, rawMessage );
}
@Override
public void exceptionCaught( final ChannelHandlerContext context, final ExceptionEvent e )
throws Exception
{
_logger.log( Level.WARNING, "Problem handling syslog packet.", e.getCause() );
}
void processSyslogMessage( final InetSocketAddress remoteAddress,
final SocketAddress localAddress,
final String rawMessage )
{
final SyslogMessage message = parseSyslogMessage( rawMessage );
final String source = "syslog:" + localAddress;
final JsonObject object = createBaseMessage( remoteAddress, source );
mergeSyslogFields( message, object );
final Gson gson = new GsonBuilder().create();
System.out.println( "Message: " + gson.toJson( object ) );
}
private void mergeSyslogFields( final SyslogMessage syslogMessage, final JsonObject object )
{
final String hostname = syslogMessage.getHostname();
if ( null != hostname )
{
- object.addProperty( "appName", hostname );
+ object.addProperty( "hostname", hostname );
}
final String appName = syslogMessage.getAppName();
if ( null != appName )
{
object.addProperty( "appName", appName );
}
final String message = syslogMessage.getMessage();
if ( null != message )
{
object.addProperty( "message", message );
}
final String msgId = syslogMessage.getMsgId();
if ( null != msgId )
{
object.addProperty( "msgId", msgId );
}
final String procId = syslogMessage.getProcId();
if ( null != procId )
{
object.addProperty( "procId", procId );
}
final Facility facility = syslogMessage.getFacility();
if ( null != facility )
{
object.addProperty( "facility", facility.name().toLowerCase() );
}
final Severity severity = syslogMessage.getLevel();
if ( null != severity )
{
object.addProperty( "severity", severity.name().toLowerCase() );
}
final DateTime timestamp = syslogMessage.getTimestamp();
if ( null != timestamp )
{
object.addProperty( "timestamp", timestamp.toString() );
object.addProperty( "timestamp_epoch", timestamp.toDate().getTime() / 1000 );
}
final Map<String, List<StructuredDataParameter>> structuredData = syslogMessage.getStructuredData();
if ( null != structuredData )
{
for ( final Entry<String, List<StructuredDataParameter>> entry : structuredData.entrySet() )
{
final JsonObject value = new JsonObject();
for ( final StructuredDataParameter parameter : entry.getValue() )
{
value.addProperty( parameter.getName(), parameter.getValue() );
}
object.add( "_" + entry.getKey(), value );
}
}
}
private SyslogMessage parseSyslogMessage( final String rawMessage )
{
try
{
return SyslogMessage.parseStructuredSyslogMessage( rawMessage );
}
catch ( final Exception e )
{
return SyslogMessage.parseRFC3164SyslogMessage( rawMessage );
}
}
}
| true | true | private void mergeSyslogFields( final SyslogMessage syslogMessage, final JsonObject object )
{
final String hostname = syslogMessage.getHostname();
if ( null != hostname )
{
object.addProperty( "appName", hostname );
}
final String appName = syslogMessage.getAppName();
if ( null != appName )
{
object.addProperty( "appName", appName );
}
final String message = syslogMessage.getMessage();
if ( null != message )
{
object.addProperty( "message", message );
}
final String msgId = syslogMessage.getMsgId();
if ( null != msgId )
{
object.addProperty( "msgId", msgId );
}
final String procId = syslogMessage.getProcId();
if ( null != procId )
{
object.addProperty( "procId", procId );
}
final Facility facility = syslogMessage.getFacility();
if ( null != facility )
{
object.addProperty( "facility", facility.name().toLowerCase() );
}
final Severity severity = syslogMessage.getLevel();
if ( null != severity )
{
object.addProperty( "severity", severity.name().toLowerCase() );
}
final DateTime timestamp = syslogMessage.getTimestamp();
if ( null != timestamp )
{
object.addProperty( "timestamp", timestamp.toString() );
object.addProperty( "timestamp_epoch", timestamp.toDate().getTime() / 1000 );
}
final Map<String, List<StructuredDataParameter>> structuredData = syslogMessage.getStructuredData();
if ( null != structuredData )
{
for ( final Entry<String, List<StructuredDataParameter>> entry : structuredData.entrySet() )
{
final JsonObject value = new JsonObject();
for ( final StructuredDataParameter parameter : entry.getValue() )
{
value.addProperty( parameter.getName(), parameter.getValue() );
}
object.add( "_" + entry.getKey(), value );
}
}
}
| private void mergeSyslogFields( final SyslogMessage syslogMessage, final JsonObject object )
{
final String hostname = syslogMessage.getHostname();
if ( null != hostname )
{
object.addProperty( "hostname", hostname );
}
final String appName = syslogMessage.getAppName();
if ( null != appName )
{
object.addProperty( "appName", appName );
}
final String message = syslogMessage.getMessage();
if ( null != message )
{
object.addProperty( "message", message );
}
final String msgId = syslogMessage.getMsgId();
if ( null != msgId )
{
object.addProperty( "msgId", msgId );
}
final String procId = syslogMessage.getProcId();
if ( null != procId )
{
object.addProperty( "procId", procId );
}
final Facility facility = syslogMessage.getFacility();
if ( null != facility )
{
object.addProperty( "facility", facility.name().toLowerCase() );
}
final Severity severity = syslogMessage.getLevel();
if ( null != severity )
{
object.addProperty( "severity", severity.name().toLowerCase() );
}
final DateTime timestamp = syslogMessage.getTimestamp();
if ( null != timestamp )
{
object.addProperty( "timestamp", timestamp.toString() );
object.addProperty( "timestamp_epoch", timestamp.toDate().getTime() / 1000 );
}
final Map<String, List<StructuredDataParameter>> structuredData = syslogMessage.getStructuredData();
if ( null != structuredData )
{
for ( final Entry<String, List<StructuredDataParameter>> entry : structuredData.entrySet() )
{
final JsonObject value = new JsonObject();
for ( final StructuredDataParameter parameter : entry.getValue() )
{
value.addProperty( parameter.getName(), parameter.getValue() );
}
object.add( "_" + entry.getKey(), value );
}
}
}
|
diff --git a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
index 0a791656c5..e48659db33 100644
--- a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
+++ b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java
@@ -1,521 +1,521 @@
package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.eclipse.imp.pdb.facts.IBool;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IInteger;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.IValueFactory;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.eclipse.imp.pdb.facts.type.TypeStore;
import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.Instructions.Opcode;
public class RVM {
public final IValueFactory vf;
private final IBool TRUE;
private final IBool FALSE;
private boolean debug = true;
private boolean listing = false;
private final ArrayList<Function> functionStore;
private final Map<String, Integer> functionMap;
private final TypeFactory tf = TypeFactory.getInstance();
private final TypeStore typeStore = new TypeStore();
private final Types types;
private final ArrayList<Type> constructorStore;
private final Map<String, Integer> constructorMap;
private PrintWriter stdout;
public RVM(IValueFactory vf, PrintWriter stdout, boolean debug) {
super();
this.vf = vf;
this.stdout = stdout;
this.debug = debug;
this.types = new Types(this.vf);
TRUE = vf.bool(true);
FALSE = vf.bool(false);
functionStore = new ArrayList<Function>();
constructorStore = new ArrayList<Type>();
functionMap = new HashMap<String, Integer>();
constructorMap = new HashMap<String, Integer>();
Primitive.init(vf);
}
public RVM(IValueFactory vf){
this(vf, new PrintWriter(System.out, true), false);
}
public void declare(Function f){
if(functionMap.get(f.name) != null){
throw new RuntimeException("PANIC: Double declaration of function: " + f.name);
}
functionMap.put(f.name, functionStore.size());
functionStore.add(f);
}
public void declareConstructor(IConstructor symbol) {
Type constr = types.symbolToType(symbol, typeStore);
constructorMap.put(constr.getName(), constructorStore.size());
constructorStore.add(constr);
}
public Type symbolToType(IConstructor symbol) {
return types.symbolToType(symbol, typeStore);
}
public Object executeProgram(String main, IValue[] args) {
// Finalize the instruction generation of all functions
for (Function f : functionStore) {
f.finalize(functionMap, constructorMap, listing);
}
// Search for the "#module_init" function and check arguments
Function init_function = functionStore.get(functionMap.get("#module_init"));
if (init_function == null) {
throw new RuntimeException("PANIC: Code for #module_init not found");
}
if (init_function.nformals != 0) {
throw new RuntimeException("PANIC: " + "function \"#module_init\" should have one argument");
}
// Search for the "main" function and check arguments
Function main_function = functionStore.get(functionMap.get("main"));
if (main_function == null) {
throw new RuntimeException("PANIC: No function \"main\" found");
}
if (main_function.nformals != 1) {
throw new RuntimeException("PANIC: function \"main\" should have one argument");
}
// Perform a call to #module_init" at scope level = 0
Frame cf = new Frame(0, null, init_function.maxstack, init_function);
Frame root = cf; // we need the notion of the root frame, which represents the root environment
Object[] stack = cf.stack;
stack[0] = args; // pass the program argument to #module_init
int[] instructions = init_function.codeblock.getInstructions();
int pc = 0;
int sp = init_function.nlocals;
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (i.e., the frame of the coroutine's main function) of the current active coroutine
try {
NEXT_INSTRUCTION: while (true) {
if(pc < 0 || pc >= instructions.length){
throw new RuntimeException("PANIC: " + main + " illegal pc: " + pc);
}
int op = instructions[pc++];
if (true) {
int startpc = pc - 1;
for (int i = 0; i < sp; i++) {
//stdout.println("\t" + i + ": " + stack[i]);
System.out.println("\t" + i + ": " + stack[i]);
}
//stdout.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
System.out.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
}
switch (op) {
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADTTYPE:
stack[sp++] = cf.function.typeConstantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(instructions[pc++]), root);
continue;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, gets the function code
Function fun = functionStore.get(instructions[pc++]);
int scope = instructions[pc++];
// Second, looks up the function environment frame into the stack of caller frames
for (Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scope) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOAD_NESTED_FUNCTION cannot find matching scope: " + scope);
}
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(instructions[pc++]);
case Opcode.OP_LOADLOC:
case Opcode.OP_LOADLOC_AS_REF:
stack[sp++] = (op == Opcode.OP_LOADLOC) ? stack[instructions[pc++]]
: new Reference(stack, instructions[pc++]);
continue;
case Opcode.OP_LOADLOCREF: {
Reference ref = (Reference) stack[instructions[pc++]];
stack[sp++] = ref.stack[ref.pos];
continue;
}
case Opcode.OP_LOADVARDYN:
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVAR_AS_REF: {
int s;
int pos;
if(op == Opcode.OP_LOADVARDYN){
s = ((IInteger)stack[-2]).intValue();
pos = ((IInteger)stack[-1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
stack[sp++] = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVAR cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARREF: {
int s = instructions[pc++];
int pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
Reference ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_STORELOC: {
stack[instructions[pc++]] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue;
}
case Opcode.OP_STORELOCREF:
Reference ref = (Reference) stack[instructions[pc++]];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp - 1; value remains on stack */
continue;
case Opcode.OP_STOREVARDYN:
case Opcode.OP_STOREVAR:
int s;
int pos;
if(op == Opcode.OP_STOREVARDYN){
s = ((IInteger)stack[sp - 2]).intValue();
pos = ((IInteger)stack[sp - 1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARREF:
s = instructions[pc++];
pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVARREF cannot find matching scope: " + s);
case Opcode.OP_JMP:
pc = instructions[pc];
continue;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_POP:
sp--;
continue;
case Opcode.OP_LABEL:
throw new RuntimeException("PANIC: label instruction at runtime");
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(instructions[pc++]);
int arity = constructor.getArity();
args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(instructions[pc++]);
previousScope = cf;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CALLDYN is executed");
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scope, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue;
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
Object rval = null;
boolean returns = op == Opcode.OP_RETURN1;
if(returns)
rval = stack[sp - 1];
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns)
return rval;
else
return vf.string("None");
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns)
stack[sp++] = rval;
continue;
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
stdout.println(((IString) stack[sp - 1]).getValue());
continue;
case Opcode.OP_CALLPRIM:
Primitive prim = Primitive.fromInteger(instructions[pc++]);
arity = instructions[pc++];
sp = prim.invoke(stack, sp, arity);
continue;
case Opcode.OP_INIT:
arity = instructions[pc++];
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scope, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("PANIC: unexpected argument type when INIT is executed.");
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp)
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp));
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
newCoroutine.suspend(newCoroutine.frame);
sp = sp - arity; /* CHANGED: place coroutine back on stack */
stack[sp++] = newCoroutine;
continue;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
- arity = instructions[pc++];
if(op == Opcode.OP_CREATE){
fun = functionStore.get(instructions[pc++]);
previousScope = null;
} else {
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CREATEDYN is executed.");
}
}
+ arity = instructions[pc++];
Frame frame = new Frame(fun.scope, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // CHANGED: yield now always leaves an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = (op == Opcode.OP_YIELD1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
//if(op == Opcode.OP_YIELD1 /* && rval != null */) { /* CHANGED */
stack[sp++] = rval; // corresponding next will always find an entry on the stack
//}
continue;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue;
default:
throw new RuntimeException("PANIC: RVM main loop -- cannot decode instruction");
}
}
} catch (Exception e) {
stdout.println("PANIC: exception caused by invoking a primitive or illegal instruction sequence: " + e);
e.printStackTrace();
}
return FALSE;
}
}
| false | true | public Object executeProgram(String main, IValue[] args) {
// Finalize the instruction generation of all functions
for (Function f : functionStore) {
f.finalize(functionMap, constructorMap, listing);
}
// Search for the "#module_init" function and check arguments
Function init_function = functionStore.get(functionMap.get("#module_init"));
if (init_function == null) {
throw new RuntimeException("PANIC: Code for #module_init not found");
}
if (init_function.nformals != 0) {
throw new RuntimeException("PANIC: " + "function \"#module_init\" should have one argument");
}
// Search for the "main" function and check arguments
Function main_function = functionStore.get(functionMap.get("main"));
if (main_function == null) {
throw new RuntimeException("PANIC: No function \"main\" found");
}
if (main_function.nformals != 1) {
throw new RuntimeException("PANIC: function \"main\" should have one argument");
}
// Perform a call to #module_init" at scope level = 0
Frame cf = new Frame(0, null, init_function.maxstack, init_function);
Frame root = cf; // we need the notion of the root frame, which represents the root environment
Object[] stack = cf.stack;
stack[0] = args; // pass the program argument to #module_init
int[] instructions = init_function.codeblock.getInstructions();
int pc = 0;
int sp = init_function.nlocals;
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (i.e., the frame of the coroutine's main function) of the current active coroutine
try {
NEXT_INSTRUCTION: while (true) {
if(pc < 0 || pc >= instructions.length){
throw new RuntimeException("PANIC: " + main + " illegal pc: " + pc);
}
int op = instructions[pc++];
if (true) {
int startpc = pc - 1;
for (int i = 0; i < sp; i++) {
//stdout.println("\t" + i + ": " + stack[i]);
System.out.println("\t" + i + ": " + stack[i]);
}
//stdout.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
System.out.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
}
switch (op) {
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADTTYPE:
stack[sp++] = cf.function.typeConstantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(instructions[pc++]), root);
continue;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, gets the function code
Function fun = functionStore.get(instructions[pc++]);
int scope = instructions[pc++];
// Second, looks up the function environment frame into the stack of caller frames
for (Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scope) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOAD_NESTED_FUNCTION cannot find matching scope: " + scope);
}
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(instructions[pc++]);
case Opcode.OP_LOADLOC:
case Opcode.OP_LOADLOC_AS_REF:
stack[sp++] = (op == Opcode.OP_LOADLOC) ? stack[instructions[pc++]]
: new Reference(stack, instructions[pc++]);
continue;
case Opcode.OP_LOADLOCREF: {
Reference ref = (Reference) stack[instructions[pc++]];
stack[sp++] = ref.stack[ref.pos];
continue;
}
case Opcode.OP_LOADVARDYN:
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVAR_AS_REF: {
int s;
int pos;
if(op == Opcode.OP_LOADVARDYN){
s = ((IInteger)stack[-2]).intValue();
pos = ((IInteger)stack[-1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
stack[sp++] = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVAR cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARREF: {
int s = instructions[pc++];
int pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
Reference ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_STORELOC: {
stack[instructions[pc++]] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue;
}
case Opcode.OP_STORELOCREF:
Reference ref = (Reference) stack[instructions[pc++]];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp - 1; value remains on stack */
continue;
case Opcode.OP_STOREVARDYN:
case Opcode.OP_STOREVAR:
int s;
int pos;
if(op == Opcode.OP_STOREVARDYN){
s = ((IInteger)stack[sp - 2]).intValue();
pos = ((IInteger)stack[sp - 1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARREF:
s = instructions[pc++];
pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVARREF cannot find matching scope: " + s);
case Opcode.OP_JMP:
pc = instructions[pc];
continue;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_POP:
sp--;
continue;
case Opcode.OP_LABEL:
throw new RuntimeException("PANIC: label instruction at runtime");
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(instructions[pc++]);
int arity = constructor.getArity();
args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(instructions[pc++]);
previousScope = cf;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CALLDYN is executed");
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scope, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue;
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
Object rval = null;
boolean returns = op == Opcode.OP_RETURN1;
if(returns)
rval = stack[sp - 1];
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns)
return rval;
else
return vf.string("None");
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns)
stack[sp++] = rval;
continue;
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
stdout.println(((IString) stack[sp - 1]).getValue());
continue;
case Opcode.OP_CALLPRIM:
Primitive prim = Primitive.fromInteger(instructions[pc++]);
arity = instructions[pc++];
sp = prim.invoke(stack, sp, arity);
continue;
case Opcode.OP_INIT:
arity = instructions[pc++];
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scope, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("PANIC: unexpected argument type when INIT is executed.");
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp)
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp));
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
newCoroutine.suspend(newCoroutine.frame);
sp = sp - arity; /* CHANGED: place coroutine back on stack */
stack[sp++] = newCoroutine;
continue;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
arity = instructions[pc++];
if(op == Opcode.OP_CREATE){
fun = functionStore.get(instructions[pc++]);
previousScope = null;
} else {
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CREATEDYN is executed.");
}
}
Frame frame = new Frame(fun.scope, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // CHANGED: yield now always leaves an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = (op == Opcode.OP_YIELD1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
//if(op == Opcode.OP_YIELD1 /* && rval != null */) { /* CHANGED */
stack[sp++] = rval; // corresponding next will always find an entry on the stack
//}
continue;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue;
default:
throw new RuntimeException("PANIC: RVM main loop -- cannot decode instruction");
}
}
} catch (Exception e) {
stdout.println("PANIC: exception caused by invoking a primitive or illegal instruction sequence: " + e);
e.printStackTrace();
}
return FALSE;
}
| public Object executeProgram(String main, IValue[] args) {
// Finalize the instruction generation of all functions
for (Function f : functionStore) {
f.finalize(functionMap, constructorMap, listing);
}
// Search for the "#module_init" function and check arguments
Function init_function = functionStore.get(functionMap.get("#module_init"));
if (init_function == null) {
throw new RuntimeException("PANIC: Code for #module_init not found");
}
if (init_function.nformals != 0) {
throw new RuntimeException("PANIC: " + "function \"#module_init\" should have one argument");
}
// Search for the "main" function and check arguments
Function main_function = functionStore.get(functionMap.get("main"));
if (main_function == null) {
throw new RuntimeException("PANIC: No function \"main\" found");
}
if (main_function.nformals != 1) {
throw new RuntimeException("PANIC: function \"main\" should have one argument");
}
// Perform a call to #module_init" at scope level = 0
Frame cf = new Frame(0, null, init_function.maxstack, init_function);
Frame root = cf; // we need the notion of the root frame, which represents the root environment
Object[] stack = cf.stack;
stack[0] = args; // pass the program argument to #module_init
int[] instructions = init_function.codeblock.getInstructions();
int pc = 0;
int sp = init_function.nlocals;
Stack<Coroutine> activeCoroutines = new Stack<>();
Frame ccf = null; // the start frame (i.e., the frame of the coroutine's main function) of the current active coroutine
try {
NEXT_INSTRUCTION: while (true) {
if(pc < 0 || pc >= instructions.length){
throw new RuntimeException("PANIC: " + main + " illegal pc: " + pc);
}
int op = instructions[pc++];
if (true) {
int startpc = pc - 1;
for (int i = 0; i < sp; i++) {
//stdout.println("\t" + i + ": " + stack[i]);
System.out.println("\t" + i + ": " + stack[i]);
}
//stdout.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
System.out.println(cf.function.name + "[" + startpc + "] " + cf.function.codeblock.toString(startpc));
}
switch (op) {
case Opcode.OP_LOADCON:
stack[sp++] = cf.function.constantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADTTYPE:
stack[sp++] = cf.function.typeConstantStore[instructions[pc++]];
continue;
case Opcode.OP_LOADFUN:
// Loads functions that are defined at the root
stack[sp++] = new FunctionInstance(functionStore.get(instructions[pc++]), root);
continue;
case Opcode.OP_LOAD_NESTED_FUN: {
// Loads nested functions and closures (anonymous nested functions):
// First, gets the function code
Function fun = functionStore.get(instructions[pc++]);
int scope = instructions[pc++];
// Second, looks up the function environment frame into the stack of caller frames
for (Frame env = cf; env != null; env = env.previousCallFrame) {
if (env.scopeId == scope) {
stack[sp++] = new FunctionInstance(fun, env);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOAD_NESTED_FUNCTION cannot find matching scope: " + scope);
}
case Opcode.OP_LOADCONSTR:
Type constructor = constructorStore.get(instructions[pc++]);
case Opcode.OP_LOADLOC:
case Opcode.OP_LOADLOC_AS_REF:
stack[sp++] = (op == Opcode.OP_LOADLOC) ? stack[instructions[pc++]]
: new Reference(stack, instructions[pc++]);
continue;
case Opcode.OP_LOADLOCREF: {
Reference ref = (Reference) stack[instructions[pc++]];
stack[sp++] = ref.stack[ref.pos];
continue;
}
case Opcode.OP_LOADVARDYN:
case Opcode.OP_LOADVAR:
case Opcode.OP_LOADVAR_AS_REF: {
int s;
int pos;
if(op == Opcode.OP_LOADVARDYN){
s = ((IInteger)stack[-2]).intValue();
pos = ((IInteger)stack[-1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
stack[sp++] = (op == Opcode.OP_LOADVAR) ? fr.stack[pos]
: new Reference(fr.stack, pos);
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVAR cannot find matching scope: " + s);
}
case Opcode.OP_LOADVARREF: {
int s = instructions[pc++];
int pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
Reference ref = (Reference) fr.stack[pos];
stack[sp++] = ref.stack[ref.pos];
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: LOADVARREF cannot find matching scope: " + s);
}
case Opcode.OP_STORELOC: {
stack[instructions[pc++]] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue;
}
case Opcode.OP_STORELOCREF:
Reference ref = (Reference) stack[instructions[pc++]];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp - 1; value remains on stack */
continue;
case Opcode.OP_STOREVARDYN:
case Opcode.OP_STOREVAR:
int s;
int pos;
if(op == Opcode.OP_STOREVARDYN){
s = ((IInteger)stack[sp - 2]).intValue();
pos = ((IInteger)stack[sp - 1]).intValue();
sp -= 2;
} else {
s = instructions[pc++];
pos = instructions[pc++];
}
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
fr.stack[pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVAR cannot find matching scope: " + s);
case Opcode.OP_STOREVARREF:
s = instructions[pc++];
pos = instructions[pc++];
for (Frame fr = cf; fr != null; fr = fr.previousScope) {
if (fr.scopeId == s) {
ref = (Reference) fr.stack[pos];
ref.stack[ref.pos] = stack[sp - 1]; /* CHANGED: --sp to sp -1; value remains on stack */
continue NEXT_INSTRUCTION;
}
}
throw new RuntimeException("PANIC: STOREVARREF cannot find matching scope: " + s);
case Opcode.OP_JMP:
pc = instructions[pc];
continue;
case Opcode.OP_JMPTRUE:
if (stack[sp - 1].equals(TRUE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_JMPFALSE:
if (stack[sp - 1].equals(FALSE)) {
pc = instructions[pc];
} else
pc++;
sp--;
continue;
case Opcode.OP_POP:
sp--;
continue;
case Opcode.OP_LABEL:
throw new RuntimeException("PANIC: label instruction at runtime");
case Opcode.OP_CALLCONSTR:
constructor = constructorStore.get(instructions[pc++]);
int arity = constructor.getArity();
args = new IValue[arity];
for(int i = 0; i < arity; i++) {
args[arity - 1 - i] = (IValue) stack[--sp];
}
stack[sp++] = vf.constructor(constructor, args);
continue;
case Opcode.OP_CALLDYN:
case Opcode.OP_CALL:
// In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) {
Type constr = (Type) stack[--sp];
arity = constr.getArity();
args = new IValue[arity];
for(int i = arity - 1; i >=0; i--) {
args[i] = (IValue) stack[sp - arity + i];
}
sp = sp - arity;
stack[sp++] = vf.constructor(constr, args);
continue NEXT_INSTRUCTION;
}
Function fun = null;
Frame previousScope = null;
if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){
FunctionInstance fun_instance = (FunctionInstance) stack[--sp];
fun = fun_instance.function;
previousScope = fun_instance.env;
} else if(op == Opcode.OP_CALL) {
fun = functionStore.get(instructions[pc++]);
previousScope = cf;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CALLDYN is executed");
}
instructions = fun.codeblock.getInstructions();
Frame nextFrame = new Frame(fun.scope, cf, previousScope, fun.maxstack, fun);
for (int i = fun.nformals - 1; i >= 0; i--) {
nextFrame.stack[i] = stack[sp - fun.nformals + i];
}
cf.pc = pc;
cf.sp = sp - fun.nformals;
cf = nextFrame;
stack = cf.stack;
sp = fun.nlocals;
pc = 0;
continue;
case Opcode.OP_RETURN0:
case Opcode.OP_RETURN1:
Object rval = null;
boolean returns = op == Opcode.OP_RETURN1;
if(returns)
rval = stack[sp - 1];
// if the current frame is the frame of a top active coroutine,
// then pop this coroutine from the stack of active coroutines
if(cf == ccf) {
activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
}
cf = cf.previousCallFrame;
if(cf == null) {
if(returns)
return rval;
else
return vf.string("None");
}
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
if(returns)
stack[sp++] = rval;
continue;
case Opcode.OP_HALT:
if (debug) {
stdout.println("Program halted:");
for (int i = 0; i < sp; i++) {
stdout.println(i + ": " + stack[i]);
}
}
return stack[sp - 1];
case Opcode.OP_PRINTLN:
stdout.println(((IString) stack[sp - 1]).getValue());
continue;
case Opcode.OP_CALLPRIM:
Primitive prim = Primitive.fromInteger(instructions[pc++]);
arity = instructions[pc++];
sp = prim.invoke(stack, sp, arity);
continue;
case Opcode.OP_INIT:
arity = instructions[pc++];
Object src = stack[--sp];
Coroutine coroutine;
if(src instanceof Coroutine){
coroutine = (Coroutine) src;
fun = coroutine.frame.function;
} else if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
Frame frame = new Frame(fun.scope, null, fun_instance.env, fun.maxstack, fun);
coroutine = new Coroutine(frame);
} else {
throw new RuntimeException("PANIC: unexpected argument type when INIT is executed.");
}
// the main function of coroutine may have formal parameters,
// therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE
if(arity != fun.nformals - coroutine.frame.sp)
throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp));
Coroutine newCoroutine = coroutine.copy();
for (int i = arity - 1; i >= 0; i--) {
newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i];
}
newCoroutine.frame.sp = fun.nlocals;
newCoroutine.suspend(newCoroutine.frame);
sp = sp - arity; /* CHANGED: place coroutine back on stack */
stack[sp++] = newCoroutine;
continue;
case Opcode.OP_CREATE:
case Opcode.OP_CREATEDYN:
if(op == Opcode.OP_CREATE){
fun = functionStore.get(instructions[pc++]);
previousScope = null;
} else {
src = stack[--sp];
if(src instanceof FunctionInstance) {
FunctionInstance fun_instance = (FunctionInstance) src;
fun = fun_instance.function;
previousScope = fun_instance.env;
} else {
throw new RuntimeException("PANIC: unexpected argument type when CREATEDYN is executed.");
}
}
arity = instructions[pc++];
Frame frame = new Frame(fun.scope, null, previousScope, fun.maxstack, fun);
// the main function of coroutine may have formal parameters,
// therefore, CREATE may take a number of arguments <= formal parameters
if(arity > fun.nformals)
throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals);
for (int i = arity - 1; i >= 0; i--) {
frame.stack[i] = stack[sp - arity + i];
}
frame.sp = arity;
coroutine = new Coroutine(frame);
sp = sp - arity;
stack[sp++] = coroutine;
continue;
case Opcode.OP_NEXT0:
case Opcode.OP_NEXT1:
coroutine = (Coroutine) stack[--sp];
// put the coroutine onto the stack of active coroutines
activeCoroutines.push(coroutine);
ccf = coroutine.start;
coroutine.next(cf);
fun = coroutine.frame.function;
instructions = coroutine.frame.function.codeblock.getInstructions();
coroutine.frame.stack[coroutine.frame.sp++] = // CHANGED: yield now always leaves an entry on the stack
(op == Opcode.OP_NEXT1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
cf = coroutine.frame;
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
continue;
case Opcode.OP_YIELD0:
case Opcode.OP_YIELD1:
coroutine = activeCoroutines.pop();
ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start;
Frame prev = coroutine.start.previousCallFrame;
rval = (op == Opcode.OP_YIELD1) ? stack[--sp] : null;
cf.pc = pc;
cf.sp = sp;
coroutine.suspend(cf);
cf = prev;
if(op == Opcode.OP_YIELD1 && cf == null)
return rval;
instructions = cf.function.codeblock.getInstructions();
stack = cf.stack;
sp = cf.sp;
pc = cf.pc;
//if(op == Opcode.OP_YIELD1 /* && rval != null */) { /* CHANGED */
stack[sp++] = rval; // corresponding next will always find an entry on the stack
//}
continue;
case Opcode.OP_HASNEXT:
coroutine = (Coroutine) stack[--sp];
stack[sp++] = coroutine.hasNext() ? TRUE : FALSE;
continue;
default:
throw new RuntimeException("PANIC: RVM main loop -- cannot decode instruction");
}
}
} catch (Exception e) {
stdout.println("PANIC: exception caused by invoking a primitive or illegal instruction sequence: " + e);
e.printStackTrace();
}
return FALSE;
}
|
diff --git a/src/org/omegat/gui/tagvalidation/TagValidationTool.java b/src/org/omegat/gui/tagvalidation/TagValidationTool.java
index 58745082..de0c6f78 100644
--- a/src/org/omegat/gui/tagvalidation/TagValidationTool.java
+++ b/src/org/omegat/gui/tagvalidation/TagValidationTool.java
@@ -1,231 +1,231 @@
/**************************************************************************
OmegaT - Computer Assisted Translation (CAT) tool
with fuzzy matching, translation memory, keyword search,
glossaries, and translation leveraging into updated projects.
Copyright (C) 2008 Alex Buloichik, Martin Fleurke
2009 Martin Fleurke
Home page: http://www.omegat.org/
Support center: http://groups.yahoo.com/group/OmegaT/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**************************************************************************/
package org.omegat.gui.tagvalidation;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.omegat.core.Core;
import org.omegat.core.CoreEvents;
import org.omegat.core.data.IProject.FileInfo;
import org.omegat.core.data.SourceTextEntry;
import org.omegat.core.data.TMXEntry;
import org.omegat.core.events.IProjectEventListener;
import org.omegat.gui.main.MainWindow;
import org.omegat.util.OStrings;
import org.omegat.util.PatternConsts;
import org.omegat.util.Preferences;
import org.omegat.util.StaticUtils;
/**
* Class for show tag validation results.
*
* @author Alex Buloichik ([email protected])
* @author Martin Fleurke
*/
public class TagValidationTool implements ITagValidation, IProjectEventListener {
private TagValidationFrame m_tagWin;
private MainWindow mainWindow;
public TagValidationTool(final MainWindow mainWindow) {
this.mainWindow = mainWindow;
CoreEvents.registerProjectChangeListener(this);
}
public void validateTags() {
List<SourceTextEntry> suspects = listInvalidTags();
if (suspects.size() > 0) {
// create a tag validation window if necessary
if (m_tagWin == null) {
m_tagWin = new TagValidationFrame(mainWindow);
m_tagWin.setFont(Core.getMainWindow().getApplicationFont());
} else {
// close tag validation window if present
m_tagWin.dispose();
}
// display list of suspect strings
m_tagWin.setVisible(true);
m_tagWin.displayStringList(suspects);
} else {
// close tag validation window if present
if (m_tagWin != null)
m_tagWin.dispose();
// show dialog saying all is OK
JOptionPane.showMessageDialog(Core.getMainWindow().getApplicationFrame(),
OStrings.getString("TF_NOTICE_OK_TAGS"), OStrings.getString("TF_NOTICE_TITLE_TAGS"),
JOptionPane.INFORMATION_MESSAGE);
}
}
public void onProjectChanged(final IProjectEventListener.PROJECT_CHANGE_TYPE eventType) {
switch (eventType) {
case CLOSE:
if (m_tagWin != null)
m_tagWin.dispose();
break;
}
}
/**
* Scans project and builds the list of entries which are suspected of
* having changed (possibly invalid) tag structures.
*/
private List<SourceTextEntry> listInvalidTags() {
int j;
String s;
TMXEntry te;
List<String> srcTags = new ArrayList<String>(32);
List<String> locTags = new ArrayList<String>(32);
List<SourceTextEntry> suspects = new ArrayList<SourceTextEntry>(16);
// programming language validation: pattern to detect printf variables
// (%s and %n\$s)
Pattern printfPattern = null;
if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_ALL_PRINTF_TAGS))) {
printfPattern = PatternConsts.PRINTF_VARS;
} else if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_SIMPLE_PRINTF_TAGS))) {
printfPattern = PatternConsts.SIMPLE_PRINTF_VARS;
}
for (FileInfo fi : Core.getProject().getProjectFiles()) {
for (SourceTextEntry ste : fi.entries) {
s = ste.getSrcText();
te = Core.getProject().getTranslation(ste);
// if there's no translation, skip the string
// bugfix for
// http://sourceforge.net/support/tracker.php?aid=1209839
- if (te == null) {
+ if (te == null || te.translation == null) {
continue;
}
if (printfPattern != null) {
// printf variables should be equal.
// we check this by adding the string "index+typespecifier"
// of every
// found variable to a set.
// If the sets of the source and target are not equal, then
// there is
// a problem: either missing or extra variables, or the
// typespecifier
// has changed for the variable at the given index.
HashSet<String> printfSourceSet = new HashSet<String>();
Matcher printfMatcher = printfPattern.matcher(s);
int index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfSourceSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfSourceSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
HashSet<String> printfTargetSet = new HashSet<String>();
printfMatcher = printfPattern.matcher(te.translation);
index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfTargetSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfTargetSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
if (!printfSourceSet.equals(printfTargetSet)) {
suspects.add(ste);
continue;
}
}
// Extra checks for PO files:
if (fi.filePath.endsWith(".po") || fi.filePath.endsWith(".pot")) { // TODO:
// check
// with
// source-files
// settings
// for
// PO
// instead
// of
// hardcoded?
// check PO line ending:
Boolean s_ends_lf = s.endsWith("\n");
Boolean t_ends_lf = te.translation.endsWith("\n");
if (s_ends_lf && !t_ends_lf || !s_ends_lf && t_ends_lf) {
suspects.add(ste);
continue;
}
}
// OmegaT tags check:
// extract tags from src and loc string
StaticUtils.buildTagList(s, srcTags);
StaticUtils.buildTagList(te.translation, locTags);
// make sure lists match
// for now, insist on exact match
if (srcTags.size() != locTags.size())
suspects.add(ste);
else {
// compare one by one
for (j = 0; j < srcTags.size(); j++) {
s = srcTags.get(j);
String t = locTags.get(j);
if (!s.equals(t)) {
suspects.add(ste);
break;
}
}
}
srcTags.clear();
locTags.clear();
}
}
return suspects;
}
}
| true | true | private List<SourceTextEntry> listInvalidTags() {
int j;
String s;
TMXEntry te;
List<String> srcTags = new ArrayList<String>(32);
List<String> locTags = new ArrayList<String>(32);
List<SourceTextEntry> suspects = new ArrayList<SourceTextEntry>(16);
// programming language validation: pattern to detect printf variables
// (%s and %n\$s)
Pattern printfPattern = null;
if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_ALL_PRINTF_TAGS))) {
printfPattern = PatternConsts.PRINTF_VARS;
} else if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_SIMPLE_PRINTF_TAGS))) {
printfPattern = PatternConsts.SIMPLE_PRINTF_VARS;
}
for (FileInfo fi : Core.getProject().getProjectFiles()) {
for (SourceTextEntry ste : fi.entries) {
s = ste.getSrcText();
te = Core.getProject().getTranslation(ste);
// if there's no translation, skip the string
// bugfix for
// http://sourceforge.net/support/tracker.php?aid=1209839
if (te == null) {
continue;
}
if (printfPattern != null) {
// printf variables should be equal.
// we check this by adding the string "index+typespecifier"
// of every
// found variable to a set.
// If the sets of the source and target are not equal, then
// there is
// a problem: either missing or extra variables, or the
// typespecifier
// has changed for the variable at the given index.
HashSet<String> printfSourceSet = new HashSet<String>();
Matcher printfMatcher = printfPattern.matcher(s);
int index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfSourceSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfSourceSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
HashSet<String> printfTargetSet = new HashSet<String>();
printfMatcher = printfPattern.matcher(te.translation);
index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfTargetSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfTargetSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
if (!printfSourceSet.equals(printfTargetSet)) {
suspects.add(ste);
continue;
}
}
// Extra checks for PO files:
if (fi.filePath.endsWith(".po") || fi.filePath.endsWith(".pot")) { // TODO:
// check
// with
// source-files
// settings
// for
// PO
// instead
// of
// hardcoded?
// check PO line ending:
Boolean s_ends_lf = s.endsWith("\n");
Boolean t_ends_lf = te.translation.endsWith("\n");
if (s_ends_lf && !t_ends_lf || !s_ends_lf && t_ends_lf) {
suspects.add(ste);
continue;
}
}
// OmegaT tags check:
// extract tags from src and loc string
StaticUtils.buildTagList(s, srcTags);
StaticUtils.buildTagList(te.translation, locTags);
// make sure lists match
// for now, insist on exact match
if (srcTags.size() != locTags.size())
suspects.add(ste);
else {
// compare one by one
for (j = 0; j < srcTags.size(); j++) {
s = srcTags.get(j);
String t = locTags.get(j);
if (!s.equals(t)) {
suspects.add(ste);
break;
}
}
}
srcTags.clear();
locTags.clear();
}
}
return suspects;
}
| private List<SourceTextEntry> listInvalidTags() {
int j;
String s;
TMXEntry te;
List<String> srcTags = new ArrayList<String>(32);
List<String> locTags = new ArrayList<String>(32);
List<SourceTextEntry> suspects = new ArrayList<SourceTextEntry>(16);
// programming language validation: pattern to detect printf variables
// (%s and %n\$s)
Pattern printfPattern = null;
if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_ALL_PRINTF_TAGS))) {
printfPattern = PatternConsts.PRINTF_VARS;
} else if ("true".equalsIgnoreCase(Preferences.getPreference(Preferences.CHECK_SIMPLE_PRINTF_TAGS))) {
printfPattern = PatternConsts.SIMPLE_PRINTF_VARS;
}
for (FileInfo fi : Core.getProject().getProjectFiles()) {
for (SourceTextEntry ste : fi.entries) {
s = ste.getSrcText();
te = Core.getProject().getTranslation(ste);
// if there's no translation, skip the string
// bugfix for
// http://sourceforge.net/support/tracker.php?aid=1209839
if (te == null || te.translation == null) {
continue;
}
if (printfPattern != null) {
// printf variables should be equal.
// we check this by adding the string "index+typespecifier"
// of every
// found variable to a set.
// If the sets of the source and target are not equal, then
// there is
// a problem: either missing or extra variables, or the
// typespecifier
// has changed for the variable at the given index.
HashSet<String> printfSourceSet = new HashSet<String>();
Matcher printfMatcher = printfPattern.matcher(s);
int index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfSourceSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfSourceSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
HashSet<String> printfTargetSet = new HashSet<String>();
printfMatcher = printfPattern.matcher(te.translation);
index = 1;
while (printfMatcher.find()) {
String printfVariable = printfMatcher.group(0);
String argumentswapspecifier = printfMatcher.group(1);
if (argumentswapspecifier != null && argumentswapspecifier.endsWith("$")) {
printfTargetSet.add(""
+ argumentswapspecifier.substring(0, argumentswapspecifier.length() - 1)
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
} else {
printfTargetSet.add(""
+ index
+ printfVariable.substring(printfVariable.length() - 1,
printfVariable.length()));
index++;
}
}
if (!printfSourceSet.equals(printfTargetSet)) {
suspects.add(ste);
continue;
}
}
// Extra checks for PO files:
if (fi.filePath.endsWith(".po") || fi.filePath.endsWith(".pot")) { // TODO:
// check
// with
// source-files
// settings
// for
// PO
// instead
// of
// hardcoded?
// check PO line ending:
Boolean s_ends_lf = s.endsWith("\n");
Boolean t_ends_lf = te.translation.endsWith("\n");
if (s_ends_lf && !t_ends_lf || !s_ends_lf && t_ends_lf) {
suspects.add(ste);
continue;
}
}
// OmegaT tags check:
// extract tags from src and loc string
StaticUtils.buildTagList(s, srcTags);
StaticUtils.buildTagList(te.translation, locTags);
// make sure lists match
// for now, insist on exact match
if (srcTags.size() != locTags.size())
suspects.add(ste);
else {
// compare one by one
for (j = 0; j < srcTags.size(); j++) {
s = srcTags.get(j);
String t = locTags.get(j);
if (!s.equals(t)) {
suspects.add(ste);
break;
}
}
}
srcTags.clear();
locTags.clear();
}
}
return suspects;
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/aot/LLVMBackend.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/aot/LLVMBackend.java
index bfb06a7a1..29f7d9e2e 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/aot/LLVMBackend.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/aot/LLVMBackend.java
@@ -1,256 +1,256 @@
/*
* Copyright (c) 2009-2011, Artemis SudParis-IETR/INSA of Rennes
* 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 IETR/INSA of Rennes 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 OWNER 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.sf.orcc.backends.llvm.aot;
import static net.sf.orcc.OrccLaunchConstants.NO_LIBRARY_EXPORT;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.orcc.backends.AbstractBackend;
import net.sf.orcc.backends.llvm.transform.ListInitializer;
import net.sf.orcc.backends.llvm.transform.StringTransformation;
import net.sf.orcc.backends.llvm.transform.TemplateInfoComputing;
import net.sf.orcc.backends.transform.CastAdder;
import net.sf.orcc.backends.transform.DisconnectedOutputPortRemoval;
import net.sf.orcc.backends.transform.EmptyBlockRemover;
import net.sf.orcc.backends.transform.InstPhiTransformation;
import net.sf.orcc.backends.transform.Multi2MonoToken;
import net.sf.orcc.backends.transform.ShortCircuitTransformation;
import net.sf.orcc.backends.transform.ssa.ConstantPropagator;
import net.sf.orcc.backends.transform.ssa.CopyPropagator;
import net.sf.orcc.backends.util.Validator;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Instance;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.transform.Instantiator;
import net.sf.orcc.df.transform.NetworkFlattener;
import net.sf.orcc.df.transform.TypeResizer;
import net.sf.orcc.df.transform.UnitImporter;
import net.sf.orcc.df.util.DfSwitch;
import net.sf.orcc.df.util.DfVisitor;
import net.sf.orcc.ir.CfgNode;
import net.sf.orcc.ir.Expression;
import net.sf.orcc.ir.transform.BlockCombine;
import net.sf.orcc.ir.transform.ControlFlowAnalyzer;
import net.sf.orcc.ir.transform.DeadCodeElimination;
import net.sf.orcc.ir.transform.DeadGlobalElimination;
import net.sf.orcc.ir.transform.DeadVariableRemoval;
import net.sf.orcc.ir.transform.RenameTransformation;
import net.sf.orcc.ir.transform.SSATransformation;
import net.sf.orcc.ir.transform.TacTransformation;
import net.sf.orcc.ir.util.IrUtil;
import net.sf.orcc.tools.classifier.Classifier;
import net.sf.orcc.tools.merger.action.ActionMerger;
import net.sf.orcc.tools.merger.actor.ActorMerger;
import net.sf.orcc.util.OrccLogger;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
/**
* LLVM back-end.
*
* @author Herve Yviquel
*
*/
public class LLVMBackend extends AbstractBackend {
/**
* Path to target "src" folder
*/
private String srcPath;
/**
* Path to target "lib" folder
*/
private String libPath;
protected final Map<String, String> renameMap;
/**
* Creates a new instance of the LLVM back-end. Initializes the
* transformation hash map.
*/
public LLVMBackend() {
renameMap = new HashMap<String, String>();
renameMap.put("abs", "abs_");
renameMap.put("getw", "getw_");
renameMap.put("index", "index_");
renameMap.put("min", "min_");
renameMap.put("max", "max_");
renameMap.put("select", "select_");
}
@Override
protected void doInitializeOptions() {
// Set build and src directory
File srcDir = new File(path + File.separator + "src");
File buildDir = new File(path + File.separator + "build");
File binDir = new File(path + File.separator + "bin");
// If directories don't exist, create them
if (!srcDir.exists()) {
srcDir.mkdirs();
}
if (!buildDir.exists()) {
buildDir.mkdirs();
}
if (!binDir.exists()) {
binDir.mkdirs();
}
// Set src directory as path
srcPath = srcDir.getAbsolutePath();
libPath = path + File.separator + "libs";
}
@Override
protected void doTransformActor(Actor actor) {
// do not transform actor
}
protected void doTransformNetwork(Network network) {
OrccLogger.traceln("Analyze and transform the network...");
List<DfSwitch<?>> visitors = new ArrayList<DfSwitch<?>>();
visitors.add(new Instantiator(!debug, fifoSize));
visitors.add(new NetworkFlattener());
visitors.add(new UnitImporter());
if (classify) {
visitors.add(new Classifier());
}
if (mergeActions) {
visitors.add(new ActionMerger());
}
if (mergeActors) {
visitors.add(new ActorMerger());
}
if (convertMulti2Mono) {
visitors.add(new Multi2MonoToken());
}
visitors.add(new DisconnectedOutputPortRemoval());
- visitors.add(new TypeResizer(true, true, false, false));
+ visitors.add(new TypeResizer(true, false, false, false));
visitors.add(new StringTransformation());
visitors.add(new DfVisitor<Expression>(new ShortCircuitTransformation()));
visitors.add(new DfVisitor<Void>(new SSATransformation()));
visitors.add(new DeadGlobalElimination());
visitors.add(new DfVisitor<Void>(new DeadCodeElimination()));
visitors.add(new DfVisitor<Void>(new DeadVariableRemoval()));
visitors.add(new RenameTransformation(this.renameMap));
visitors.add(new DfVisitor<Expression>(new TacTransformation()));
visitors.add(new DfVisitor<Void>(new CopyPropagator()));
visitors.add(new DfVisitor<Void>(new ConstantPropagator()));
visitors.add(new DfVisitor<Void>(new InstPhiTransformation()));
visitors.add(new DfVisitor<Expression>(new CastAdder(false, true)));
visitors.add(new DfVisitor<Void>(new EmptyBlockRemover()));
visitors.add(new DfVisitor<Void>(new BlockCombine()));
visitors.add(new DfVisitor<CfgNode>(new ControlFlowAnalyzer()));
visitors.add(new DfVisitor<Void>(new ListInitializer()));
for (DfSwitch<?> transfo : visitors) {
transfo.doSwitch(network);
if (debug) {
ResourceSet set = new ResourceSetImpl();
for (Actor actor : network.getAllActors()) {
if (actor.getFileName() != null
&& !IrUtil.serializeActor(set, srcPath, actor)) {
OrccLogger.warnln("Transformation" + transfo
+ " on actor " + actor.getName());
}
}
}
}
new DfVisitor<Void>(new TemplateInfoComputing()).doSwitch(network);
network.computeTemplateMaps();
}
@Override
protected void doVtlCodeGeneration(List<IFile> files) {
// do not generate a VTL
}
@Override
protected void doXdfCodeGeneration(Network network) {
Validator.checkTopLevel(network);
Validator.checkMinimalFifoSize(network, fifoSize);
doTransformNetwork(network);
// print instances and entities
printChildren(network);
// print network
OrccLogger.traceln("Printing network...");
new NetworkPrinter(network, options).print(srcPath);
new CMakePrinter(network, options).printFiles(path);
}
@Override
protected boolean exportRuntimeLibrary() {
if (!getAttribute(NO_LIBRARY_EXPORT, false)) {
// Copy specific windows batch file
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
copyFileToFilesystem("/runtime/C/run_cmake_with_VS_env.bat",
path + File.separator + "run_cmake_with_VS_env.bat",
debug);
}
OrccLogger.trace("Export libraries sources into " + libPath
+ "... ");
if (copyFolderToFileSystem("/runtime/C/libs", libPath, debug)) {
OrccLogger.traceRaw("OK" + "\n");
return true;
} else {
OrccLogger.warnRaw("Error" + "\n");
return false;
}
}
return false;
}
@Override
protected boolean printInstance(Instance instance) {
return new InstancePrinter(options).print(srcPath, instance) > 0;
}
@Override
protected boolean printActor(Actor actor) {
return new InstancePrinter(options).print(srcPath, actor) > 0;
}
}
| true | true | protected void doTransformNetwork(Network network) {
OrccLogger.traceln("Analyze and transform the network...");
List<DfSwitch<?>> visitors = new ArrayList<DfSwitch<?>>();
visitors.add(new Instantiator(!debug, fifoSize));
visitors.add(new NetworkFlattener());
visitors.add(new UnitImporter());
if (classify) {
visitors.add(new Classifier());
}
if (mergeActions) {
visitors.add(new ActionMerger());
}
if (mergeActors) {
visitors.add(new ActorMerger());
}
if (convertMulti2Mono) {
visitors.add(new Multi2MonoToken());
}
visitors.add(new DisconnectedOutputPortRemoval());
visitors.add(new TypeResizer(true, true, false, false));
visitors.add(new StringTransformation());
visitors.add(new DfVisitor<Expression>(new ShortCircuitTransformation()));
visitors.add(new DfVisitor<Void>(new SSATransformation()));
visitors.add(new DeadGlobalElimination());
visitors.add(new DfVisitor<Void>(new DeadCodeElimination()));
visitors.add(new DfVisitor<Void>(new DeadVariableRemoval()));
visitors.add(new RenameTransformation(this.renameMap));
visitors.add(new DfVisitor<Expression>(new TacTransformation()));
visitors.add(new DfVisitor<Void>(new CopyPropagator()));
visitors.add(new DfVisitor<Void>(new ConstantPropagator()));
visitors.add(new DfVisitor<Void>(new InstPhiTransformation()));
visitors.add(new DfVisitor<Expression>(new CastAdder(false, true)));
visitors.add(new DfVisitor<Void>(new EmptyBlockRemover()));
visitors.add(new DfVisitor<Void>(new BlockCombine()));
visitors.add(new DfVisitor<CfgNode>(new ControlFlowAnalyzer()));
visitors.add(new DfVisitor<Void>(new ListInitializer()));
for (DfSwitch<?> transfo : visitors) {
transfo.doSwitch(network);
if (debug) {
ResourceSet set = new ResourceSetImpl();
for (Actor actor : network.getAllActors()) {
if (actor.getFileName() != null
&& !IrUtil.serializeActor(set, srcPath, actor)) {
OrccLogger.warnln("Transformation" + transfo
+ " on actor " + actor.getName());
}
}
}
}
new DfVisitor<Void>(new TemplateInfoComputing()).doSwitch(network);
network.computeTemplateMaps();
}
| protected void doTransformNetwork(Network network) {
OrccLogger.traceln("Analyze and transform the network...");
List<DfSwitch<?>> visitors = new ArrayList<DfSwitch<?>>();
visitors.add(new Instantiator(!debug, fifoSize));
visitors.add(new NetworkFlattener());
visitors.add(new UnitImporter());
if (classify) {
visitors.add(new Classifier());
}
if (mergeActions) {
visitors.add(new ActionMerger());
}
if (mergeActors) {
visitors.add(new ActorMerger());
}
if (convertMulti2Mono) {
visitors.add(new Multi2MonoToken());
}
visitors.add(new DisconnectedOutputPortRemoval());
visitors.add(new TypeResizer(true, false, false, false));
visitors.add(new StringTransformation());
visitors.add(new DfVisitor<Expression>(new ShortCircuitTransformation()));
visitors.add(new DfVisitor<Void>(new SSATransformation()));
visitors.add(new DeadGlobalElimination());
visitors.add(new DfVisitor<Void>(new DeadCodeElimination()));
visitors.add(new DfVisitor<Void>(new DeadVariableRemoval()));
visitors.add(new RenameTransformation(this.renameMap));
visitors.add(new DfVisitor<Expression>(new TacTransformation()));
visitors.add(new DfVisitor<Void>(new CopyPropagator()));
visitors.add(new DfVisitor<Void>(new ConstantPropagator()));
visitors.add(new DfVisitor<Void>(new InstPhiTransformation()));
visitors.add(new DfVisitor<Expression>(new CastAdder(false, true)));
visitors.add(new DfVisitor<Void>(new EmptyBlockRemover()));
visitors.add(new DfVisitor<Void>(new BlockCombine()));
visitors.add(new DfVisitor<CfgNode>(new ControlFlowAnalyzer()));
visitors.add(new DfVisitor<Void>(new ListInitializer()));
for (DfSwitch<?> transfo : visitors) {
transfo.doSwitch(network);
if (debug) {
ResourceSet set = new ResourceSetImpl();
for (Actor actor : network.getAllActors()) {
if (actor.getFileName() != null
&& !IrUtil.serializeActor(set, srcPath, actor)) {
OrccLogger.warnln("Transformation" + transfo
+ " on actor " + actor.getName());
}
}
}
}
new DfVisitor<Void>(new TemplateInfoComputing()).doSwitch(network);
network.computeTemplateMaps();
}
|
diff --git a/framework/src/main/java/org/richfaces/fileUpload/FileUploadFacesContextFactory.java b/framework/src/main/java/org/richfaces/fileUpload/FileUploadFacesContextFactory.java
index 760600bc8..38b9c1a1a 100644
--- a/framework/src/main/java/org/richfaces/fileUpload/FileUploadFacesContextFactory.java
+++ b/framework/src/main/java/org/richfaces/fileUpload/FileUploadFacesContextFactory.java
@@ -1,230 +1,230 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, 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.richfaces.fileUpload;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Pattern;
import javax.faces.FacesException;
import javax.faces.FacesWrapper;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.context.FacesContextWrapper;
import javax.faces.lifecycle.Lifecycle;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.richfaces.ServletVersion;
import org.richfaces.log.Logger;
import org.richfaces.log.RichfacesLogger;
import org.richfaces.request.MultipartRequest;
import org.richfaces.request.MultipartRequest25;
import org.richfaces.request.MultipartRequest30;
import org.richfaces.request.MultipartRequestParser;
import org.richfaces.request.MultipartRequestSizeExceeded;
import org.richfaces.request.ProgressControl;
/**
* @author Nick Belaevski
*
*/
public class FileUploadFacesContextFactory extends FacesContextFactory implements FacesWrapper<FacesContextFactory> {
private static final class FileUploadFacesContext extends FacesContextWrapper {
private FacesContext facesContext;
public FileUploadFacesContext(FacesContext facesContext) {
super();
this.facesContext = facesContext;
}
@Override
public FacesContext getWrapped() {
return facesContext;
}
@Override
public void release() {
MultipartRequest multipartRequest = (MultipartRequest) getExternalContext().getRequestMap().get(
MultipartRequest.REQUEST_ATTRIBUTE_NAME);
if (multipartRequest != null) {
multipartRequest.release();
}
super.release();
}
}
public static final String UID_KEY = "rf_fu_uid";
private static final Logger LOGGER = RichfacesLogger.CONTEXT.getLogger();
private static final Pattern AMPERSAND = Pattern.compile("&+");
private FacesContextFactory wrappedFactory;
public FileUploadFacesContextFactory(FacesContextFactory wrappedFactory) {
super();
this.wrappedFactory = wrappedFactory;
}
@Override
public FacesContextFactory getWrapped() {
return wrappedFactory;
}
private String getParameterValueFromQueryString(String queryString, String paramName) {
if (queryString != null) {
String[] nvPairs = AMPERSAND.split(queryString);
for (String nvPair : nvPairs) {
if (nvPair.length() == 0) {
continue;
}
int eqIdx = nvPair.indexOf('=');
if (eqIdx >= 0) {
try {
String name = URLDecoder.decode(nvPair.substring(0, eqIdx), "UTF-8");
if (paramName.equals(name)) {
return URLDecoder.decode(nvPair.substring(eqIdx + 1), "UTF-8");
}
} catch (UnsupportedEncodingException e) {
// log warning and skip this parameter
LOGGER.debug(e.getMessage(), e);
}
}
}
}
return null;
}
@Override
public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getContentType() != null && httpRequest.getContentType().startsWith("multipart/")) {
String uid = getParameterValueFromQueryString(httpRequest.getQueryString(), UID_KEY);
if (uid != null) {
long contentLength = Long.parseLong(httpRequest.getHeader("Content-Length"));
ProgressControl progressControl = new ProgressControl(uid, contentLength);
- httpRequest.getParameterNames(); // hack for WildFly 8 Final
+ httpRequest.getParameterNames(); // hack for WildFly 8 Final, UNDERTOW-202
HttpServletRequest wrappedRequest;
if (ServletVersion.getCurrent().isCompliantWith(ServletVersion.SERVLET_3_0)) {
wrappedRequest = wrapMultipartRequestServlet30((ServletContext) context, httpRequest, uid,
contentLength, progressControl);
} else {
wrappedRequest = wrapMultipartRequestServlet25((ServletContext) context, httpRequest,
uid, contentLength, progressControl);
}
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
private boolean isCreateTempFiles(ServletContext servletContext) {
String param = servletContext.getInitParameter("org.richfaces.fileUpload.createTempFiles");
if (param != null) {
return Boolean.parseBoolean(param);
}
return true;
}
private String getTempFilesDirectory(ServletContext servletContext) {
String result = servletContext.getInitParameter("org.richfaces.fileUpload.tempFilesDirectory");
if (result == null) {
File servletTempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
if (servletTempDir != null) {
result = servletTempDir.getAbsolutePath();
}
}
if (result == null) {
result = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
}
return result;
}
private long getMaxRequestSize(ServletContext servletContext) {
String param = servletContext.getInitParameter("org.richfaces.fileUpload.maxRequestSize");
if (param != null) {
return Long.parseLong(param);
}
return 0;
}
private HttpServletRequest wrapMultipartRequestServlet25(ServletContext servletContext, HttpServletRequest request,
String uploadId, long contentLength, ProgressControl progressControl) {
HttpServletRequest multipartRequest;
long maxRequestSize = getMaxRequestSize(servletContext);
if (maxRequestSize == 0 || contentLength <= maxRequestSize) {
boolean createTempFiles = isCreateTempFiles(servletContext);
String tempFilesDirectory = getTempFilesDirectory(servletContext);
MultipartRequestParser requestParser = new MultipartRequestParser(request, createTempFiles, tempFilesDirectory,
progressControl);
multipartRequest = new MultipartRequest25(request, uploadId, progressControl, requestParser);
} else {
multipartRequest = new MultipartRequestSizeExceeded(request, uploadId, progressControl);
}
request.setAttribute(MultipartRequest.REQUEST_ATTRIBUTE_NAME, multipartRequest);
return multipartRequest;
}
private HttpServletRequest wrapMultipartRequestServlet30(ServletContext servletContext, HttpServletRequest request,
String uploadId, long contentLength, ProgressControl progressControl) {
HttpServletRequest multipartRequest;
long maxRequestSize = getMaxRequestSize(servletContext);
if (maxRequestSize == 0 || contentLength <= maxRequestSize) {
multipartRequest = new MultipartRequest30(request, uploadId, progressControl);
} else {
multipartRequest = new MultipartRequestSizeExceeded(request, uploadId, progressControl);
}
request.setAttribute(MultipartRequest.REQUEST_ATTRIBUTE_NAME, multipartRequest);
return multipartRequest;
}
}
| true | true | public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getContentType() != null && httpRequest.getContentType().startsWith("multipart/")) {
String uid = getParameterValueFromQueryString(httpRequest.getQueryString(), UID_KEY);
if (uid != null) {
long contentLength = Long.parseLong(httpRequest.getHeader("Content-Length"));
ProgressControl progressControl = new ProgressControl(uid, contentLength);
httpRequest.getParameterNames(); // hack for WildFly 8 Final
HttpServletRequest wrappedRequest;
if (ServletVersion.getCurrent().isCompliantWith(ServletVersion.SERVLET_3_0)) {
wrappedRequest = wrapMultipartRequestServlet30((ServletContext) context, httpRequest, uid,
contentLength, progressControl);
} else {
wrappedRequest = wrapMultipartRequestServlet25((ServletContext) context, httpRequest,
uid, contentLength, progressControl);
}
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
| public FacesContext getFacesContext(Object context, Object request, Object response, Lifecycle lifecycle)
throws FacesException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getContentType() != null && httpRequest.getContentType().startsWith("multipart/")) {
String uid = getParameterValueFromQueryString(httpRequest.getQueryString(), UID_KEY);
if (uid != null) {
long contentLength = Long.parseLong(httpRequest.getHeader("Content-Length"));
ProgressControl progressControl = new ProgressControl(uid, contentLength);
httpRequest.getParameterNames(); // hack for WildFly 8 Final, UNDERTOW-202
HttpServletRequest wrappedRequest;
if (ServletVersion.getCurrent().isCompliantWith(ServletVersion.SERVLET_3_0)) {
wrappedRequest = wrapMultipartRequestServlet30((ServletContext) context, httpRequest, uid,
contentLength, progressControl);
} else {
wrappedRequest = wrapMultipartRequestServlet25((ServletContext) context, httpRequest,
uid, contentLength, progressControl);
}
FacesContext facesContext = wrappedFactory.getFacesContext(context, wrappedRequest, response, lifecycle);
progressControl.setContextMap(facesContext.getExternalContext().getSessionMap());
return new FileUploadFacesContext(facesContext);
}
}
}
return wrappedFactory.getFacesContext(context, request, response, lifecycle);
}
|
diff --git a/src/main/java/fr/ippon/tatami/security/TatamiLdapAuthenticationProvider.java b/src/main/java/fr/ippon/tatami/security/TatamiLdapAuthenticationProvider.java
index 0894d5c..3373d39 100644
--- a/src/main/java/fr/ippon/tatami/security/TatamiLdapAuthenticationProvider.java
+++ b/src/main/java/fr/ippon/tatami/security/TatamiLdapAuthenticationProvider.java
@@ -1,106 +1,106 @@
package fr.ippon.tatami.security;
import fr.ippon.tatami.config.Constants;
import fr.ippon.tatami.domain.User;
import fr.ippon.tatami.repository.DomainRepository;
import fr.ippon.tatami.service.UserService;
import fr.ippon.tatami.service.util.DomainUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.authentication.LdapAuthenticator;
import javax.inject.Inject;
/**
* Tatami specific LdapAuthenticationProvider.
*
* @author Julien Dubois
*/
public class TatamiLdapAuthenticationProvider extends LdapAuthenticationProvider {
private final Log log = LogFactory.getLog(TatamiLdapAuthenticationProvider.class);
@Inject
private UserService userService;
@Inject
private DomainRepository domainRepository;
@Inject
private TatamiUserDetailsService userDetailsService; // => handles grantedAuthorities
/**
* The domain on which this provider is suitable to authenticate user
*/
private String managedDomain;
public TatamiLdapAuthenticationProvider(LdapAuthenticator authenticator, String managedDomain) {
super(authenticator);
if (StringUtils.isEmpty(managedDomain)) {
throw new IllegalArgumentException("You must provide a managedDomain on this TatamiLdapAuthenticationProvider");
}
this.managedDomain = managedDomain;
}
private boolean canHandleAuthentication(Authentication authentication) {
String login = authentication.getName();
if (!login.contains("@")) {
if (log.isDebugEnabled()) {
log.debug("User login " + login + " is incorrect.");
}
throw new BadCredentialsException(messages.getMessage(
"LdapAuthenticationProvider.badCredentials", "Bad credentials"));
}
String domain = DomainUtil.getDomainFromLogin(login);
return domain.equalsIgnoreCase(managedDomain);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!canHandleAuthentication(authentication)) {
return null; // this provider is not suitable for this domain
}
- String login = authentication.getName();
+ String login = authentication.getName().toLowerCase();
String username = DomainUtil.getUsernameFromLogin(login);
// Use temporary token to use username, and not login to authenticate on ldap :
UsernamePasswordAuthenticationToken tmpAuthentication =
new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(), null);
super.authenticate(tmpAuthentication);
//Automatically create LDAP users in Tatami
User user = userService.getUserByLogin(login);
if (user == null) {
user = new User();
user.setLogin(login);
user.setTheme(Constants.DEFAULT_THEME);
userService.createUser(user);
} else {
// ensure that this user has access to its domain if it has been created before
domainRepository.updateUserInDomain(user.getDomain(), user.getLogin());
}
// The real authentication object uses the login, and not the username
TatamiUserDetails realUser = userDetailsService.getTatamiUserDetails(login,
authentication.getCredentials().toString());
if (user.getTheme() == null) {
user.setTheme(Constants.DEFAULT_THEME);
}
realUser.setTheme(user.getTheme());
UsernamePasswordAuthenticationToken realAuthentication =
new UsernamePasswordAuthenticationToken(realUser, authentication.getCredentials(),
realUser.getAuthorities());
return realAuthentication;
}
}
| true | true | public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!canHandleAuthentication(authentication)) {
return null; // this provider is not suitable for this domain
}
String login = authentication.getName();
String username = DomainUtil.getUsernameFromLogin(login);
// Use temporary token to use username, and not login to authenticate on ldap :
UsernamePasswordAuthenticationToken tmpAuthentication =
new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(), null);
super.authenticate(tmpAuthentication);
//Automatically create LDAP users in Tatami
User user = userService.getUserByLogin(login);
if (user == null) {
user = new User();
user.setLogin(login);
user.setTheme(Constants.DEFAULT_THEME);
userService.createUser(user);
} else {
// ensure that this user has access to its domain if it has been created before
domainRepository.updateUserInDomain(user.getDomain(), user.getLogin());
}
// The real authentication object uses the login, and not the username
TatamiUserDetails realUser = userDetailsService.getTatamiUserDetails(login,
authentication.getCredentials().toString());
if (user.getTheme() == null) {
user.setTheme(Constants.DEFAULT_THEME);
}
realUser.setTheme(user.getTheme());
UsernamePasswordAuthenticationToken realAuthentication =
new UsernamePasswordAuthenticationToken(realUser, authentication.getCredentials(),
realUser.getAuthorities());
return realAuthentication;
}
| public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!canHandleAuthentication(authentication)) {
return null; // this provider is not suitable for this domain
}
String login = authentication.getName().toLowerCase();
String username = DomainUtil.getUsernameFromLogin(login);
// Use temporary token to use username, and not login to authenticate on ldap :
UsernamePasswordAuthenticationToken tmpAuthentication =
new UsernamePasswordAuthenticationToken(username, authentication.getCredentials(), null);
super.authenticate(tmpAuthentication);
//Automatically create LDAP users in Tatami
User user = userService.getUserByLogin(login);
if (user == null) {
user = new User();
user.setLogin(login);
user.setTheme(Constants.DEFAULT_THEME);
userService.createUser(user);
} else {
// ensure that this user has access to its domain if it has been created before
domainRepository.updateUserInDomain(user.getDomain(), user.getLogin());
}
// The real authentication object uses the login, and not the username
TatamiUserDetails realUser = userDetailsService.getTatamiUserDetails(login,
authentication.getCredentials().toString());
if (user.getTheme() == null) {
user.setTheme(Constants.DEFAULT_THEME);
}
realUser.setTheme(user.getTheme());
UsernamePasswordAuthenticationToken realAuthentication =
new UsernamePasswordAuthenticationToken(realUser, authentication.getCredentials(),
realUser.getAuthorities());
return realAuthentication;
}
|
diff --git a/mpxg2-sysex/src/test/java/info/carlwithak/mpxg2/sysex/effects/algorithms/TwoBandDualParserTest.java b/mpxg2-sysex/src/test/java/info/carlwithak/mpxg2/sysex/effects/algorithms/TwoBandDualParserTest.java
index 6137e14b..351a8d8a 100644
--- a/mpxg2-sysex/src/test/java/info/carlwithak/mpxg2/sysex/effects/algorithms/TwoBandDualParserTest.java
+++ b/mpxg2-sysex/src/test/java/info/carlwithak/mpxg2/sysex/effects/algorithms/TwoBandDualParserTest.java
@@ -1,57 +1,57 @@
/*
* Copyright (C) 2012 Carl Green
*
* 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 info.carlwithak.mpxg2.sysex.effects.algorithms;
import info.carlwithak.mpxg2.model.effects.algorithms.TwoBandDual;
import org.junit.Test;
import static info.carlwithak.mpxg2.test.IsValue.value;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
*
* @author Carl Green
*/
public class TwoBandDualParserTest {
@Test
- public void testParse_SpaceEcho() {
+ public void testParse_SoloRoom() {
byte[] effectParameters = {4, 6, 0, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 2, 5, 3, 0, 7, 0, 2, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 4, 10, 6, 0, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
TwoBandDual twoBandDual = TwoBandDualParser.parse(effectParameters);
assertThat(twoBandDual.mix, is(value(100)));
assertThat(twoBandDual.level, is(value(0)));
assertThat(twoBandDual.gainLeft1, is(value(-30)));
assertThat(twoBandDual.fcLeft1, is(value(110)));
assertThat(twoBandDual.qLeft1, is(value(0.7)));
assertThat(twoBandDual.modeLeft1, is(value(0))); // LShlf
assertThat(twoBandDual.gainLeft2, is(value(-30)));
assertThat(twoBandDual.fcLeft2, is(value(850)));
assertThat(twoBandDual.qLeft2, is(value(0.7)));
assertThat(twoBandDual.modeLeft2, is(value(2))); // HShlf
assertThat(twoBandDual.gainRight1, is(value(-30)));
assertThat(twoBandDual.fcRight1, is(value(110)));
assertThat(twoBandDual.qRight1, is(value(0.7)));
assertThat(twoBandDual.modeRight1, is(value(0))); // LShlf
assertThat(twoBandDual.gainRight2, is(value(-30)));
assertThat(twoBandDual.fcRight2, is(value(1700)));
assertThat(twoBandDual.qRight2, is(value(0.7)));
assertThat(twoBandDual.modeRight2, is(value(2))); // HShlf
}
}
| true | true | public void testParse_SpaceEcho() {
byte[] effectParameters = {4, 6, 0, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 2, 5, 3, 0, 7, 0, 2, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 4, 10, 6, 0, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
TwoBandDual twoBandDual = TwoBandDualParser.parse(effectParameters);
assertThat(twoBandDual.mix, is(value(100)));
assertThat(twoBandDual.level, is(value(0)));
assertThat(twoBandDual.gainLeft1, is(value(-30)));
assertThat(twoBandDual.fcLeft1, is(value(110)));
assertThat(twoBandDual.qLeft1, is(value(0.7)));
assertThat(twoBandDual.modeLeft1, is(value(0))); // LShlf
assertThat(twoBandDual.gainLeft2, is(value(-30)));
assertThat(twoBandDual.fcLeft2, is(value(850)));
assertThat(twoBandDual.qLeft2, is(value(0.7)));
assertThat(twoBandDual.modeLeft2, is(value(2))); // HShlf
assertThat(twoBandDual.gainRight1, is(value(-30)));
assertThat(twoBandDual.fcRight1, is(value(110)));
assertThat(twoBandDual.qRight1, is(value(0.7)));
assertThat(twoBandDual.modeRight1, is(value(0))); // LShlf
assertThat(twoBandDual.gainRight2, is(value(-30)));
assertThat(twoBandDual.fcRight2, is(value(1700)));
assertThat(twoBandDual.qRight2, is(value(0.7)));
assertThat(twoBandDual.modeRight2, is(value(2))); // HShlf
}
| public void testParse_SoloRoom() {
byte[] effectParameters = {4, 6, 0, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 2, 5, 3, 0, 7, 0, 2, 0, 2, 14, 14, 6, 0, 0, 7, 0, 0, 0, 2, 14, 4, 10, 6, 0, 7, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
TwoBandDual twoBandDual = TwoBandDualParser.parse(effectParameters);
assertThat(twoBandDual.mix, is(value(100)));
assertThat(twoBandDual.level, is(value(0)));
assertThat(twoBandDual.gainLeft1, is(value(-30)));
assertThat(twoBandDual.fcLeft1, is(value(110)));
assertThat(twoBandDual.qLeft1, is(value(0.7)));
assertThat(twoBandDual.modeLeft1, is(value(0))); // LShlf
assertThat(twoBandDual.gainLeft2, is(value(-30)));
assertThat(twoBandDual.fcLeft2, is(value(850)));
assertThat(twoBandDual.qLeft2, is(value(0.7)));
assertThat(twoBandDual.modeLeft2, is(value(2))); // HShlf
assertThat(twoBandDual.gainRight1, is(value(-30)));
assertThat(twoBandDual.fcRight1, is(value(110)));
assertThat(twoBandDual.qRight1, is(value(0.7)));
assertThat(twoBandDual.modeRight1, is(value(0))); // LShlf
assertThat(twoBandDual.gainRight2, is(value(-30)));
assertThat(twoBandDual.fcRight2, is(value(1700)));
assertThat(twoBandDual.qRight2, is(value(0.7)));
assertThat(twoBandDual.modeRight2, is(value(2))); // HShlf
}
|
diff --git a/backend/src/com/mymed/controller/core/requesthandler/AuthenticationRequestHandler.java b/backend/src/com/mymed/controller/core/requesthandler/AuthenticationRequestHandler.java
index f326283e8..303e1e153 100644
--- a/backend/src/com/mymed/controller/core/requesthandler/AuthenticationRequestHandler.java
+++ b/backend/src/com/mymed/controller/core/requesthandler/AuthenticationRequestHandler.java
@@ -1,211 +1,211 @@
package com.mymed.controller.core.requesthandler;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.JsonSyntaxException;
import com.mymed.controller.core.exception.AbstractMymedException;
import com.mymed.controller.core.exception.InternalBackEndException;
import com.mymed.controller.core.manager.authentication.AuthenticationManager;
import com.mymed.controller.core.manager.authentication.IAuthenticationManager;
import com.mymed.controller.core.manager.profile.IProfileManager;
import com.mymed.controller.core.manager.profile.ProfileManager;
import com.mymed.controller.core.manager.session.ISessionManager;
import com.mymed.controller.core.manager.session.SessionManager;
import com.mymed.controller.core.requesthandler.message.JsonMessage;
import com.mymed.model.data.session.MAuthenticationBean;
import com.mymed.model.data.session.MSessionBean;
import com.mymed.model.data.user.MUserBean;
import edu.lognet.core.tools.HashFunction;
/**
* Servlet implementation class AuthenticationRequestHandler
*/
public class AuthenticationRequestHandler extends AbstractRequestHandler {
/* --------------------------------------------------------- */
/* Attributes */
/* --------------------------------------------------------- */
private static final long serialVersionUID = 1L;
private IAuthenticationManager authenticationManager;
private ISessionManager sessionManager;
private IProfileManager profileManager;
/* --------------------------------------------------------- */
/* Constructors */
/* --------------------------------------------------------- */
/**
* @see HttpServlet#HttpServlet()
*/
public AuthenticationRequestHandler() throws ServletException {
super();
try {
authenticationManager = new AuthenticationManager();
sessionManager = new SessionManager();
profileManager = new ProfileManager();
} catch (final InternalBackEndException e) {
throw new ServletException("AuthenticationManager is not accessible because: " + e.getMessage());
}
}
/* --------------------------------------------------------- */
/* extends AbstractRequestHandler */
/* --------------------------------------------------------- */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
final JsonMessage message = new JsonMessage(200, this.getClass().getName());
try {
final Map<String, String> parameters = getParameters(request);
final RequestCode code = requestCodeMap.get(parameters.get("code"));
final String login = parameters.get("login");
final String password = parameters.get("password");
switch (code) {
case READ :
message.setMethod("READ");
if (login == null) {
throw new InternalBackEndException("Argument login is missing!");
} else if (password == null) {
throw new InternalBackEndException("Argument password is missing!");
} else {
message.addData("warning", "METHOD DEPRECATED - Post method should be used instead of Get!");
final MUserBean userBean = authenticationManager.read(login, password);
message.setDescription("Successfully authenticated");
message.addData("user", getGson().toJson(userBean));
}
break;
case DELETE :
throw new InternalBackEndException("not implemented yet...");
default :
throw new InternalBackEndException("AuthenticationRequestHandler(" + code + ") not exist!");
}
} catch (final AbstractMymedException e) {
LOGGER.info("Error in doGet operation", e.getCause());
LOGGER.debug("Error in doGet operation", e.getCause());
message.setStatus(e.getStatus());
message.setDescription(e.getMessage());
}
printJSonResponse(message, response);
}
@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
final JsonMessage message = new JsonMessage(200, this.getClass().getName());
try {
final Map<String, String> parameters = getParameters(request);
final RequestCode code = requestCodeMap.get(parameters.get("code"));
final String authentication = parameters.get("authentication");
final String user = parameters.get("user");
final String login = parameters.get("login");
final String password = parameters.get("password");
final String id = parameters.get("id");
switch (code) {
case CREATE :
message.setMethod("CREATE");
if (authentication == null) {
throw new InternalBackEndException("Argument 'authentication' is missing!");
} else if (user == null) {
throw new InternalBackEndException("Argument 'user' is missing!");
} else {
try {
MUserBean userBean = getGson().fromJson(user, MUserBean.class);
userBean.setSocialNetworkID("MYMED");
userBean.setSocialNetworkName("myMed");
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to create a new user:\n {}", userBean.toString());
userBean = authenticationManager.create(userBean, authenticationBean);
LOGGER.info("User created");
message.setDescription("User created");
message.addData("user", getGson().toJson(userBean));
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("User/Authentication jSon format is not valid");
}
}
break;
case READ :
message.setMethod("READ");
if (login == null) {
throw new InternalBackEndException("login argument missing!");
} else if (password == null) {
throw new InternalBackEndException("password argument missing!");
} else {
final MUserBean userBean = authenticationManager.read(login, password);
message.setDescription("Successfully authenticated");
// TODO Remove this parameter
message.addData("user", getGson().toJson(userBean));
// Create a new session
final MSessionBean sessionBean = new MSessionBean();
sessionBean.setIp(request.getRemoteAddr());
sessionBean.setUser(userBean.getId());
sessionBean.setCurrentApplications("");
sessionBean.setP2P(false);
// TODO Use The Cassandra Timeout mechanism
sessionBean.setTimeout(System.currentTimeMillis());
final HashFunction h = new HashFunction("myMed");
final String accessToken = h.SHA1ToString(login + password + sessionBean.getTimeout());
sessionBean.setAccessToken(accessToken);
sessionBean.setId(accessToken);
sessionManager.create(sessionBean);
// Update the profile with the new session
userBean.setSession(accessToken);
profileManager.update(userBean);
- LOGGER.info("Session {} created -> LOGIN", accessToken);
+ LOGGER.info("Session '{}' created -> LOGIN", accessToken);
// TODO Find a better way to get the URL
message.addData("url", "http://" + InetAddress.getLocalHost().getHostAddress() + "/mobile");
message.addData("accessToken", accessToken);
}
break;
case UPDATE :
if (id == null) {
throw new InternalBackEndException("Missing id argument!");
} else if (authentication == null) {
throw new InternalBackEndException("Missing authentication argument!");
} else {
try {
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to update authentication:\n {}", authenticationBean.toString());
authenticationManager.update(id, authenticationBean);
LOGGER.info("Authentication updated!");
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("Authentication jSon format is not valid");
}
}
break;
default :
throw new InternalBackEndException("AuthenticationRequestHandler(" + code + ") not exist!");
}
} catch (final AbstractMymedException e) {
LOGGER.info("Error in doPost operation");
LOGGER.debug("Error in doPost operation", e.getCause());
message.setStatus(e.getStatus());
message.setDescription(e.getMessage());
}
printJSonResponse(message, response);
}
}
| true | true | public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
final JsonMessage message = new JsonMessage(200, this.getClass().getName());
try {
final Map<String, String> parameters = getParameters(request);
final RequestCode code = requestCodeMap.get(parameters.get("code"));
final String authentication = parameters.get("authentication");
final String user = parameters.get("user");
final String login = parameters.get("login");
final String password = parameters.get("password");
final String id = parameters.get("id");
switch (code) {
case CREATE :
message.setMethod("CREATE");
if (authentication == null) {
throw new InternalBackEndException("Argument 'authentication' is missing!");
} else if (user == null) {
throw new InternalBackEndException("Argument 'user' is missing!");
} else {
try {
MUserBean userBean = getGson().fromJson(user, MUserBean.class);
userBean.setSocialNetworkID("MYMED");
userBean.setSocialNetworkName("myMed");
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to create a new user:\n {}", userBean.toString());
userBean = authenticationManager.create(userBean, authenticationBean);
LOGGER.info("User created");
message.setDescription("User created");
message.addData("user", getGson().toJson(userBean));
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("User/Authentication jSon format is not valid");
}
}
break;
case READ :
message.setMethod("READ");
if (login == null) {
throw new InternalBackEndException("login argument missing!");
} else if (password == null) {
throw new InternalBackEndException("password argument missing!");
} else {
final MUserBean userBean = authenticationManager.read(login, password);
message.setDescription("Successfully authenticated");
// TODO Remove this parameter
message.addData("user", getGson().toJson(userBean));
// Create a new session
final MSessionBean sessionBean = new MSessionBean();
sessionBean.setIp(request.getRemoteAddr());
sessionBean.setUser(userBean.getId());
sessionBean.setCurrentApplications("");
sessionBean.setP2P(false);
// TODO Use The Cassandra Timeout mechanism
sessionBean.setTimeout(System.currentTimeMillis());
final HashFunction h = new HashFunction("myMed");
final String accessToken = h.SHA1ToString(login + password + sessionBean.getTimeout());
sessionBean.setAccessToken(accessToken);
sessionBean.setId(accessToken);
sessionManager.create(sessionBean);
// Update the profile with the new session
userBean.setSession(accessToken);
profileManager.update(userBean);
LOGGER.info("Session {} created -> LOGIN", accessToken);
// TODO Find a better way to get the URL
message.addData("url", "http://" + InetAddress.getLocalHost().getHostAddress() + "/mobile");
message.addData("accessToken", accessToken);
}
break;
case UPDATE :
if (id == null) {
throw new InternalBackEndException("Missing id argument!");
} else if (authentication == null) {
throw new InternalBackEndException("Missing authentication argument!");
} else {
try {
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to update authentication:\n {}", authenticationBean.toString());
authenticationManager.update(id, authenticationBean);
LOGGER.info("Authentication updated!");
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("Authentication jSon format is not valid");
}
}
break;
default :
throw new InternalBackEndException("AuthenticationRequestHandler(" + code + ") not exist!");
}
} catch (final AbstractMymedException e) {
LOGGER.info("Error in doPost operation");
LOGGER.debug("Error in doPost operation", e.getCause());
message.setStatus(e.getStatus());
message.setDescription(e.getMessage());
}
printJSonResponse(message, response);
}
| public void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException,
IOException {
final JsonMessage message = new JsonMessage(200, this.getClass().getName());
try {
final Map<String, String> parameters = getParameters(request);
final RequestCode code = requestCodeMap.get(parameters.get("code"));
final String authentication = parameters.get("authentication");
final String user = parameters.get("user");
final String login = parameters.get("login");
final String password = parameters.get("password");
final String id = parameters.get("id");
switch (code) {
case CREATE :
message.setMethod("CREATE");
if (authentication == null) {
throw new InternalBackEndException("Argument 'authentication' is missing!");
} else if (user == null) {
throw new InternalBackEndException("Argument 'user' is missing!");
} else {
try {
MUserBean userBean = getGson().fromJson(user, MUserBean.class);
userBean.setSocialNetworkID("MYMED");
userBean.setSocialNetworkName("myMed");
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to create a new user:\n {}", userBean.toString());
userBean = authenticationManager.create(userBean, authenticationBean);
LOGGER.info("User created");
message.setDescription("User created");
message.addData("user", getGson().toJson(userBean));
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("User/Authentication jSon format is not valid");
}
}
break;
case READ :
message.setMethod("READ");
if (login == null) {
throw new InternalBackEndException("login argument missing!");
} else if (password == null) {
throw new InternalBackEndException("password argument missing!");
} else {
final MUserBean userBean = authenticationManager.read(login, password);
message.setDescription("Successfully authenticated");
// TODO Remove this parameter
message.addData("user", getGson().toJson(userBean));
// Create a new session
final MSessionBean sessionBean = new MSessionBean();
sessionBean.setIp(request.getRemoteAddr());
sessionBean.setUser(userBean.getId());
sessionBean.setCurrentApplications("");
sessionBean.setP2P(false);
// TODO Use The Cassandra Timeout mechanism
sessionBean.setTimeout(System.currentTimeMillis());
final HashFunction h = new HashFunction("myMed");
final String accessToken = h.SHA1ToString(login + password + sessionBean.getTimeout());
sessionBean.setAccessToken(accessToken);
sessionBean.setId(accessToken);
sessionManager.create(sessionBean);
// Update the profile with the new session
userBean.setSession(accessToken);
profileManager.update(userBean);
LOGGER.info("Session '{}' created -> LOGIN", accessToken);
// TODO Find a better way to get the URL
message.addData("url", "http://" + InetAddress.getLocalHost().getHostAddress() + "/mobile");
message.addData("accessToken", accessToken);
}
break;
case UPDATE :
if (id == null) {
throw new InternalBackEndException("Missing id argument!");
} else if (authentication == null) {
throw new InternalBackEndException("Missing authentication argument!");
} else {
try {
final MAuthenticationBean authenticationBean = getGson().fromJson(authentication,
MAuthenticationBean.class);
LOGGER.info("Trying to update authentication:\n {}", authenticationBean.toString());
authenticationManager.update(id, authenticationBean);
LOGGER.info("Authentication updated!");
} catch (final JsonSyntaxException e) {
throw new InternalBackEndException("Authentication jSon format is not valid");
}
}
break;
default :
throw new InternalBackEndException("AuthenticationRequestHandler(" + code + ") not exist!");
}
} catch (final AbstractMymedException e) {
LOGGER.info("Error in doPost operation");
LOGGER.debug("Error in doPost operation", e.getCause());
message.setStatus(e.getStatus());
message.setDescription(e.getMessage());
}
printJSonResponse(message, response);
}
|
diff --git a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/SWTJBTExt.java b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/SWTJBTExt.java
index 2efb6bca..c4d32f5c 100644
--- a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/SWTJBTExt.java
+++ b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/SWTJBTExt.java
@@ -1,676 +1,676 @@
/*******************************************************************************
* Copyright (c) 2007-2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributor:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ui.bot.ext;
import static org.jboss.tools.ui.bot.ext.SWTTestExt.eclipse;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEclipseEditor;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
import org.eclipse.swtbot.swt.finder.results.WidgetResult;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotCheckBox;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotMenu;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.eclipse.swtbot.swt.finder.widgets.TimeoutException;
import org.jboss.tools.ui.bot.ext.gen.ActionItem;
import org.jboss.tools.ui.bot.ext.helper.ContextMenuHelper;
import org.jboss.tools.ui.bot.ext.types.IDELabel;
import org.jboss.tools.ui.bot.ext.types.IDELabel.PreferencesDialog;
import org.jboss.tools.ui.bot.ext.types.ViewType;
import org.osgi.framework.Version;
/**
* Provides JBoss Tools common operations based on SWTBot element operations
* @author Vladimir Pakan
*
*/
public class SWTJBTExt {
private static final long DEFAULT_UI_TIMEOUT = 1000L;
private static final boolean runningOnMacOs = Platform.getOS().equalsIgnoreCase("macosx");
SWTWorkbenchBot bot;
static Logger log = Logger.getLogger(SWTJBTExt.class);
public SWTJBTExt(SWTWorkbenchBot bot) {
this.bot = bot;
}
/**
* Check if JBoss Developer Studio Is Running
* Dynamic version of isJBDSRun Method
* @return
*/
public static boolean isJBDSRun (){
IProduct prod = Platform.getProduct();
return ((prod != null) && (prod.getId().startsWith("com.jboss.jbds.")));
}
/*
*
* check if JBoss Developer Studio is running
*/
@Deprecated
public static boolean isJBDSRun(SWTBot bot) {
return isJBDSRun();
}
/**
* Returns JBT version (taken from version of org.jboss.tools.common plugin version)
* @return
*/
public Version getJBTVersion() {
return Platform.getBundle("org.jboss.tools.common").getVersion();
}
/**
* Returns true when in Web Page of Wizard is defined at least one Server Runtime Instance
* @param bot
* @return
*/
public static boolean isServerDefinedInWebWizardPage(SWTWorkbenchBot bot){
boolean isServerDefined = false;
try{
bot.label(IDELabel.ImportJSFProjectDialog.CHOICE_LIST_IS_EMPTY);
} catch (WidgetNotFoundException wnfe){
isServerDefined = true;
}
return isServerDefined;
}
/**
* Return true when in Web Page of Wizard is defined at least one Server Runtime Instance
* Dynamic version of isServerDefinedInWebWizardPage
* @return
*/
public boolean isServerDefinedInWebWizardPage(){
return SWTJBTExt.isServerDefinedInWebWizardPage(bot);
}
/**
* Starts Application Server in Server View on position specified by index
* Dynamic version of startApplicationServer
* @param index - zero based Position of Server within Server Tree
* @param uiTimeOut
*/
public void startApplicationServer(int index, long uiTimeOut){
SWTJBTExt.startApplicationServer(bot, index, uiTimeOut);
}
/**
* Starts Application Server in Server View on position specified by index
* @param bot
* @param index - zero based Position of Server within Server Tree
* @param uiTimeOut
*/
public static void startApplicationServer(SWTWorkbenchBot bot , int index, long uiTimeOut){
SWTJBTExt.chooseServerPopupMenu(bot,index, IDELabel.Menu.START,120*1000L,uiTimeOut);
bot.sleep(10*1000L);
}
/**
* Starts Application Server in Server View on position specified by index
* Dynamic version of startApplicationServer with default UI TimeOut
* @param index - zero based Position of Server within Server Tree
*/
public void startApplicationServer(int index){
SWTJBTExt.startApplicationServer(bot, index, SWTJBTExt.DEFAULT_UI_TIMEOUT);
}
/**
* Starts Application Server in Server View on position specified by index
* with default UI TimeOut
* @param bot
* @param index - zero based Position of Server within Server Tree
*/
public static void startApplicationServer(SWTWorkbenchBot bot , int index){
startApplicationServer(bot , index, SWTJBTExt.DEFAULT_UI_TIMEOUT);
}
/**
* Stops Application Server in Server View on position specified by index
* with default UI TimeOut
* Dynamic version of stopApplicationServer
* @param index - zero based Position of Server within Server Tree
*/
public void stopApplicationServer(int index){
SWTJBTExt.stopApplicationServer(bot, index, SWTJBTExt.DEFAULT_UI_TIMEOUT);
}
/**
* Stops Application Server in Server View on position specified by index
* Dynamic version of stopApplicationServer
* @param index - zero based Position of Server within Server Tree
* @param uiTimeOut
*/
public void stopApplicationServer(int index,long uiTimeOut){
SWTJBTExt.stopApplicationServer(bot, index);
}
/**
* Stops Application Server in Server View on position specified by index
* with default UI TimeOut
* @param bot
* @param index - zero based Position of Server within Server Tree
*/
public static void stopApplicationServer(SWTWorkbenchBot bot , int index){
SWTJBTExt.chooseServerPopupMenu(bot,index, IDELabel.Menu.STOP,20*1000L);
}
/**
* Stops Application Server in Server View on position specified by index
* @param bot
* @param index - zero based Position of Server within Server Tree
* @param iuTimeOut
*/
public static void stopApplicationServer(SWTWorkbenchBot bot , int index,long uiTimeOut){
SWTJBTExt.chooseServerPopupMenu(bot,index, IDELabel.Menu.STOP,20*1000L,uiTimeOut);
}
/**
* Choose Server Popup Menu with specified label on Server with position specified by index
* @param bot
* @param index
* @param menuLabel
* @param timeOut
* @param uiTimeOut
*/
public static void chooseServerPopupMenu(SWTWorkbenchBot bot , int index, String menuLabel, long timeOut, long uiTimeOut){
SWTEclipseExt swtEclipseExt = new SWTEclipseExt();
SWTBot servers = swtEclipseExt.showView(ViewType.SERVERS);
SWTBotTree serverTree = servers.tree();
ContextMenuHelper.prepareTreeItemForContextMenu(serverTree, index);
SWTTestExt.util.waitForAll(uiTimeOut);
SWTBotMenu menu = new SWTBotMenu(ContextMenuHelper.getContextMenu(serverTree,
menuLabel, false));
SWTTestExt.util.waitForAll(uiTimeOut);
menu.click();
SWTTestExt.util.waitForAll(timeOut);
}
/**
* Choose Server Popup Menu with specified label on Server with position specified by index
* with defaul UI TimeOut
* @param bot
* @param index
* @param menuLabel
* @param timeOut
*/
public static void chooseServerPopupMenu(SWTWorkbenchBot bot , int index, String menuLabel, long timeOut){
chooseServerPopupMenu(bot,index,menuLabel,timeOut,SWTJBTExt.DEFAULT_UI_TIMEOUT);
}
/**
* Deletes Application Server in Server View on position specified by index
* Dynamic version of deleteApplicationServer
* @param index - zero based Position of Server within Server Tree
*/
public void deleteApplicationServer(int index){
SWTJBTExt.deleteApplicationServer(bot, index);
}
/**
* Deletes Application Server in Server View on position specified by index
* @param bot
* @param index - zero based Position of Server within Server Tree
*/
public static void deleteApplicationServer(SWTWorkbenchBot bot , int index){
SWTJBTExt.chooseServerPopupMenu(bot,index, IDELabel.Menu.DELETE,10*1000L);
bot.shell(IDELabel.Shell.DELETE_SERVER).activate();
bot.button(IDELabel.Button.OK).click();
}
/**
* Remove Project from all Servers
* @param projectName
*/
public void removeProjectFromServers(String projectName){
removeProjectFromServers(projectName, null);
}
/**
* Remove Project from all Servers
* @param projectName
* @param stringToContain
*/
public void removeProjectFromServers(String projectName , String stringToContain){
eclipse.showView(ViewType.SERVERS);
delay();
try{
SWTBotTree serverTree = bot.viewByTitle(IDELabel.View.SERVERS).bot().tree();
delay();
// Expand All
for (SWTBotTreeItem serverTreeItem : serverTree.getAllItems()){
serverTreeItem.expand();
// if JSF Test Project is deployed to server remove it
SWTBotTreeItem[] serverTreeItemChildren = serverTreeItem.getItems();
if (serverTreeItemChildren != null && serverTreeItemChildren.length > 0){
int itemIndex = 0;
boolean found = false;
String treeItemlabel = null;
do{
treeItemlabel = serverTreeItemChildren[itemIndex].getText();
found = treeItemlabel.startsWith(projectName)
&& (stringToContain == null || treeItemlabel.indexOf(stringToContain) >= 0);
} while (!found && ++itemIndex < serverTreeItemChildren.length);
// Server Tree Item has Child with Text equal to JSF TEst Project
if (found){
log.info("Found project to be removed from server: " + treeItemlabel);
ContextMenuHelper.prepareTreeItemForContextMenu(serverTree,serverTreeItemChildren[itemIndex]);
new SWTBotMenu(ContextMenuHelper.getContextMenu(serverTree, IDELabel.Menu.REMOVE, false)).click();
bot.shell("Server").activate();
bot.button(IDELabel.Button.OK).click();
log.info("Removed project from server: " + treeItemlabel);
bot.sleep(10*1000L);
}
}
}
delay();
} catch (WidgetNotFoundException wnfe){
// do nothing it means there is no server defined
}
}
public void delay() {
bot.sleep(500);
}
/**
* Delete Project from workspace
* @param projectName
*/
public void deleteProject(String projectName) {
removeProjectFromServers(projectName);
SWTBot packageExplorer = eclipse.showView(ViewType.PACKAGE_EXPLORER);
delay();
SWTBotTree tree = packageExplorer.tree();
delay();
ContextMenuHelper.prepareTreeItemForContextMenu(tree,
tree.getTreeItem(projectName));
new SWTBotMenu(ContextMenuHelper.getContextMenu(tree,
IDELabel.Menu.DELETE, false)).click();
bot.shell(IDELabel.Shell.DELETE_RESOURCES).activate();
bot.button(IDELabel.Button.OK).click();
new SWTUtilExt(bot).waitForNonIgnoredJobs();
}
/**
* Choose Run On Server menu for specified project
* @param bot
* @param projectName
*/
public static void runProjectOnServer(SWTWorkbenchBot bot, String projectName){
SWTBotTree packageExplorerTree = eclipse.showView(ViewType.PACKAGE_EXPLORER).tree();
packageExplorerTree.setFocus();
SWTBotTreeItem packageExplorerTreeItem = packageExplorerTree
.getTreeItem(projectName);
packageExplorerTreeItem.select();
packageExplorerTreeItem.click();
// Search for Menu Item with Run on Server substring within label
final SWTBotMenu menuRunAs = bot.menu(IDELabel.Menu.RUN).menu(IDELabel.Menu.RUN_AS);
final MenuItem menuItem = UIThreadRunnable
.syncExec(new WidgetResult<MenuItem>() {
public MenuItem run() {
int menuItemIndex = 0;
MenuItem menuItem = null;
final MenuItem[] menuItems = menuRunAs.widget.getMenu().getItems();
while (menuItem == null && menuItemIndex < menuItems.length){
if (menuItems[menuItemIndex].getText().indexOf("Run on Server") > - 1){
menuItem = menuItems[menuItemIndex];
}
else{
menuItemIndex++;
}
}
return menuItem;
}
});
if (menuItem != null){
new SWTBotMenu(menuItem).click();
bot.shell(IDELabel.Shell.RUN_ON_SERVER).activate();
bot.button(IDELabel.Button.FINISH).click();
SWTUtilExt swtUtil = new SWTUtilExt(bot);
swtUtil.waitForAll(10*1000L);
}
else{
throw new WidgetNotFoundException("Unable to find Menu Item with Label 'Run on Server'");
}
}
/**
* Choose Run On Server menu for specified project
* @param projectName
*/
public void runProjectOnServer(String projectName){
runProjectOnServer(bot,projectName);
}
/**
* Creates new Server within Server View when Wizard for new Project is called
* @param bot
* @param serverGroup
* @param serverType
*/
public static void addServerToServerViewOnWizardPage (SWTWorkbenchBot bot,String serverGroup , String serverType){
// Check if there is defined Application Server if not create one
if (!SWTJBTExt.isServerDefinedInWebWizardPage(bot)){
// Specify Application Server for Deployment
bot.button(IDELabel.Button.NEW, 1).click();
bot.shell(IDELabel.Shell.NEW_SERVER).activate();
bot.tree().select(serverGroup);
bot.tree().expandNode(serverGroup)
.select(serverType);
bot.button(IDELabel.Button.FINISH).click();
}
}
/**
* Creates new Server within Server View when Wizard for new Project is called
* @param serverGroup
* @param serverType
*/
public void addServerToServerViewOnWizardPage (String serverGroup , String serverType){
addServerToServerViewOnWizardPage (bot,serverGroup , serverType);
}
/**
* Returns true if runtimeName Server Runtime is defined
* @param runtimeName
* @return
*/
public boolean isServerRuntimeDefined(String runtimeName){
return SWTJBTExt.isServerRuntimeDefined(bot,runtimeName);
}
/**
* Returns true if runtimeName Server Runtime is defined
* @param bot
* @param runtimeName
* @return
*/
public static boolean isServerRuntimeDefined(SWTWorkbenchBot bot,String runtimeName){
boolean serverRuntimeNotDefined = true;
bot.menu(IDELabel.Menu.WINDOW).menu(IDELabel.Menu.PREFERENCES).click();
bot.shell(IDELabel.Shell.PREFERENCES).activate();
bot.tree().expandNode(IDELabel.PreferencesDialog.SERVER_GROUP).select(
PreferencesDialog.RUNTIME_ENVIRONMENTS);
SWTBotTable tbRuntimeEnvironments = bot.table();
int numRows = tbRuntimeEnvironments.rowCount();
if (numRows > 0) {
int currentRow = 0;
while (serverRuntimeNotDefined && currentRow < numRows) {
if (tbRuntimeEnvironments.cell(currentRow, 0).equalsIgnoreCase(
runtimeName)) {
serverRuntimeNotDefined = false;
} else {
currentRow++;
}
}
}
bot.button(IDELabel.Button.OK).click();
return !serverRuntimeNotDefined;
}
/**
* Returns true if any Server Runtime is defined
* @param bot
* @return
*/
public static boolean isServerRuntimeDefined(SWTWorkbenchBot bot){
bot.menu(IDELabel.Menu.WINDOW).menu(IDELabel.Menu.PREFERENCES).click();
bot.shell(IDELabel.Shell.PREFERENCES).activate();
bot.tree().expandNode(IDELabel.PreferencesDialog.SERVER_GROUP).select(
PreferencesDialog.RUNTIME_ENVIRONMENTS);
boolean isServerRuntimeDefined = bot.table().rowCount() > 0;
bot.button(IDELabel.Button.OK).click();
return isServerRuntimeDefined;
}
/**
* Returns true if any Server Runtime is defined
* @param bot
* @return
*/
public boolean isServerRuntimeDefined(){
return SWTJBTExt.isServerRuntimeDefined(bot);
}
public void removeSeamProjectFromServers(String projectName){
removeProjectFromServers(projectName);
removeProjectFromServers("/" + projectName,"-ds.xml");
}
/**
* Returns string representing version of defined Server Runtime on rowIndex position in Defined Server Runtime table
* @param bot
* @param rowIndex
* @return null when no server runtime is specified, "unknown when not possible to determine server runtime version" or server runtime version
*/
public static String getDefinedServerRuntimeVersion(SWTWorkbenchBot bot , int rowIndex){
String result = null;
bot.menu(IDELabel.Menu.WINDOW).menu(IDELabel.Menu.PREFERENCES).click();
bot.shell(IDELabel.Shell.PREFERENCES).activate();
bot.tree().expandNode(IDELabel.PreferencesDialog.SERVER_GROUP).select(
PreferencesDialog.RUNTIME_ENVIRONMENTS);
SWTBotTable serverRuntimesTable = bot.table();
if (serverRuntimesTable.rowCount() > rowIndex){
String[] splitServerRuntimeType = serverRuntimesTable.cell(rowIndex, 1).split(" ");
int index = 0;
while (index < splitServerRuntimeType.length && result == null){
if (splitServerRuntimeType[index].length() > 0 &&
splitServerRuntimeType[index].charAt(0) >= '0' &&
splitServerRuntimeType[index].charAt(0) <= '9'){
result = splitServerRuntimeType[index].trim();
}
else{
index++;
}
}
}
bot.button(IDELabel.Button.OK).click();
return result;
}
/**
* Returns string representing version of defined Server Runtime on index position in Defined Server Runtime table
* @param rowIndex
* @return null when no server runtime is specified, "unknown when not possible to determine server runtime version" or server runtime version
*/
public String getDefinedServerRuntimeVersion(int index){
return SWTJBTExt.getDefinedServerRuntimeVersion(bot,index);
}
/**
* Closes Report Usage Windows and enable Atlassian Connector Usage Reporting Window.
* Did not find other way how to disable Atlassian Connector Usage Reporting Window displaying
* @param reportJbtUsage
* @param reportSubclipseUsage
*/
public static void manageBlockingWidows(boolean reportJbtUsage,
boolean reportSubclipseUsage) {
// Manage JBT/JBDS and Subclipse Usage Reporting
SWTWorkbenchBot bot = new SWTWorkbenchBot();
SWTBotShell shJbtUsage = null;
SWTBotShell shSubclipseUsage = null;
bot.sleep(Timing.time1S());
new SWTUtilExt(bot).waitForNonIgnoredJobs();
SWTBotShell[] shells = bot.shells();
int index = 0;
while ((shJbtUsage == null || shSubclipseUsage == null)
&& index < shells.length) {
if (shells[index].getText().equals(IDELabel.Shell.JBOSS_DEVELOPER_STUDIO_USAGE)
|| shells[index].getText().equals(IDELabel.Shell.JBOSS_TOOLS_USAGE)) {
shJbtUsage = shells[index];
} else if (shells[index].getText().equals(IDELabel.Shell.SUBCLIPSE_USAGE)) {
shSubclipseUsage = shells[index];
}
index++;
}
if (shJbtUsage != null && shJbtUsage.isActive()) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
if (shSubclipseUsage != null) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
}
} else if (shSubclipseUsage != null && shSubclipseUsage.isActive()) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
if (shJbtUsage != null) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
}
}
// Manage Atlassian Connector Usage Reporting
try{
SWTBot prefBot = new SWTOpenExt(new SWTBotExt())
.preferenceOpen(ActionItem.Preference.AtlassianConnectorUsageData.LABEL);
SWTBotCheckBox chbEnableMonitoring = prefBot.checkBox();
if (!chbEnableMonitoring.isChecked()){
chbEnableMonitoring.click();
}
prefBot.button(IDELabel.Button.OK).click();
} catch (WidgetNotFoundException wnfe){
// do nothing there is no Atlassian Connector installed
}
// Get rid of welcome screen. Simple close did not work when run in maven
try {
SWTBotShell shell = bot.activeShell();
bot.menu("Window").menu("Close Perspective").click();
shell.setFocus();
- SWTBotFactory.getOpen().perspective(ActionItem.Perspective.JAVA.LABEL);
+ SWTBotFactory.getOpen().perspective(ActionItem.Perspective.RESOURCE.LABEL);
} catch (WidgetNotFoundException e){
// ok, Welcome screen not present
log.info("Welcome window not present");
}
}
/**
* Closes JBoss Tools / JBoss Developer Studio Report Usage Window
* @param shell
* @param report
*/
private static void closeJBossToolsUsageWindow(SWTBotShell shell , boolean report) {
shell.bot().button(report ? IDELabel.Button.YES : IDELabel.Button.NO).click();
log.info("JBT/JBDS Report Usage window closed");
}
/**
* Closes Subclipse Report Usage Window
* @param shell
* @param report
*/
private static void closeSubclipseUsageWindow(SWTBotShell shell , boolean report) {
SWTBot shellBot = shell.bot();
SWTBotCheckBox chbReportUsage = shellBot
.checkBox(IDELabel.SubclipseUsageDialog.REPORT_USAGE_CHECK_BOX);
if ((report && (!chbReportUsage.isChecked())) ||
((!report) && chbReportUsage.isChecked())) {
chbReportUsage.click();
}
shellBot.button(IDELabel.Button.OK).click();
log.info("Sublcipse Report Usage window closed");
}
/**
* Selects textToSelect within Source Pane of editor with title editorTitle
* @param bot
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @return SWTBotEclipseEditor
*/
public static SWTBotEclipseEditor selectTextInSourcePane(SWTBotExt bot,
String editorTitle, String textToSelect ,
int selectionOffset , int selectionLength , int textToSelectIndex) {
SWTBotEclipseEditor editor = bot.editorByTitle(editorTitle).toTextEditor();
String editorText = editor.getText();
boolean found = false;
int iStartIndex = 0;
int iRow = 0;
if (editorText != null && editorText.length() > 0 && editorText.contains(textToSelect)){
int iOccurenceIndex = 0;
while (!found && iRow < editor.getLineCount()){
String lineText = editor.getTextOnLine(iRow);
iStartIndex = 0;
while (!found && lineText.contains(textToSelect)){
if (iOccurenceIndex == textToSelectIndex){
found = true;
iStartIndex += lineText.indexOf(textToSelect);
}
else{
iOccurenceIndex++;
int iNewStartIndex = lineText.indexOf(textToSelect) + textToSelect.length();
iStartIndex += iNewStartIndex;
lineText = lineText.substring(iNewStartIndex);
}
}
if (!found){
iRow++;
}
}
}
if (found) {
editor.selectRange(iRow, iStartIndex + selectionOffset, selectionLength);
}
else{
throw new SelectTextInSourcePaneException ("Wrong parameters specified for method selectTextInSourcePane.\n" +
"Unable to select required text '" + textToSelect +
"' within editor with title " + editorTitle + ".\n" +
"Editor text is: " + editorText);
}
return editor;
}
/**
* Selects textToSelect within Source Pane of editor with title editorTitle
* @param bot
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @return SWTBotEclipseEditor
*/
public static SWTBotEclipseEditor selectTextInSourcePane(SWTBotExt bot,
String editorTitle, String textToSelect ,
int selectionOffset , int selectionLength) {
return SWTJBTExt.selectTextInSourcePane(bot, editorTitle, textToSelect,
selectionOffset, selectionLength, 0);
}
/**
* Returns true when test is running on Mac OS
* @return
*/
public static boolean isRunningOnMacOs(){
return runningOnMacOs;
}
}
| true | true | public static void manageBlockingWidows(boolean reportJbtUsage,
boolean reportSubclipseUsage) {
// Manage JBT/JBDS and Subclipse Usage Reporting
SWTWorkbenchBot bot = new SWTWorkbenchBot();
SWTBotShell shJbtUsage = null;
SWTBotShell shSubclipseUsage = null;
bot.sleep(Timing.time1S());
new SWTUtilExt(bot).waitForNonIgnoredJobs();
SWTBotShell[] shells = bot.shells();
int index = 0;
while ((shJbtUsage == null || shSubclipseUsage == null)
&& index < shells.length) {
if (shells[index].getText().equals(IDELabel.Shell.JBOSS_DEVELOPER_STUDIO_USAGE)
|| shells[index].getText().equals(IDELabel.Shell.JBOSS_TOOLS_USAGE)) {
shJbtUsage = shells[index];
} else if (shells[index].getText().equals(IDELabel.Shell.SUBCLIPSE_USAGE)) {
shSubclipseUsage = shells[index];
}
index++;
}
if (shJbtUsage != null && shJbtUsage.isActive()) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
if (shSubclipseUsage != null) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
}
} else if (shSubclipseUsage != null && shSubclipseUsage.isActive()) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
if (shJbtUsage != null) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
}
}
// Manage Atlassian Connector Usage Reporting
try{
SWTBot prefBot = new SWTOpenExt(new SWTBotExt())
.preferenceOpen(ActionItem.Preference.AtlassianConnectorUsageData.LABEL);
SWTBotCheckBox chbEnableMonitoring = prefBot.checkBox();
if (!chbEnableMonitoring.isChecked()){
chbEnableMonitoring.click();
}
prefBot.button(IDELabel.Button.OK).click();
} catch (WidgetNotFoundException wnfe){
// do nothing there is no Atlassian Connector installed
}
// Get rid of welcome screen. Simple close did not work when run in maven
try {
SWTBotShell shell = bot.activeShell();
bot.menu("Window").menu("Close Perspective").click();
shell.setFocus();
SWTBotFactory.getOpen().perspective(ActionItem.Perspective.JAVA.LABEL);
} catch (WidgetNotFoundException e){
// ok, Welcome screen not present
log.info("Welcome window not present");
}
}
| public static void manageBlockingWidows(boolean reportJbtUsage,
boolean reportSubclipseUsage) {
// Manage JBT/JBDS and Subclipse Usage Reporting
SWTWorkbenchBot bot = new SWTWorkbenchBot();
SWTBotShell shJbtUsage = null;
SWTBotShell shSubclipseUsage = null;
bot.sleep(Timing.time1S());
new SWTUtilExt(bot).waitForNonIgnoredJobs();
SWTBotShell[] shells = bot.shells();
int index = 0;
while ((shJbtUsage == null || shSubclipseUsage == null)
&& index < shells.length) {
if (shells[index].getText().equals(IDELabel.Shell.JBOSS_DEVELOPER_STUDIO_USAGE)
|| shells[index].getText().equals(IDELabel.Shell.JBOSS_TOOLS_USAGE)) {
shJbtUsage = shells[index];
} else if (shells[index].getText().equals(IDELabel.Shell.SUBCLIPSE_USAGE)) {
shSubclipseUsage = shells[index];
}
index++;
}
if (shJbtUsage != null && shJbtUsage.isActive()) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
if (shSubclipseUsage != null) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
}
} else if (shSubclipseUsage != null && shSubclipseUsage.isActive()) {
closeSubclipseUsageWindow(shSubclipseUsage, reportSubclipseUsage);
if (shJbtUsage != null) {
closeJBossToolsUsageWindow(shJbtUsage, reportJbtUsage);
}
}
// Manage Atlassian Connector Usage Reporting
try{
SWTBot prefBot = new SWTOpenExt(new SWTBotExt())
.preferenceOpen(ActionItem.Preference.AtlassianConnectorUsageData.LABEL);
SWTBotCheckBox chbEnableMonitoring = prefBot.checkBox();
if (!chbEnableMonitoring.isChecked()){
chbEnableMonitoring.click();
}
prefBot.button(IDELabel.Button.OK).click();
} catch (WidgetNotFoundException wnfe){
// do nothing there is no Atlassian Connector installed
}
// Get rid of welcome screen. Simple close did not work when run in maven
try {
SWTBotShell shell = bot.activeShell();
bot.menu("Window").menu("Close Perspective").click();
shell.setFocus();
SWTBotFactory.getOpen().perspective(ActionItem.Perspective.RESOURCE.LABEL);
} catch (WidgetNotFoundException e){
// ok, Welcome screen not present
log.info("Welcome window not present");
}
}
|
diff --git a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java
index 5f33ffa6..f3802096 100644
--- a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java
+++ b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/BadHexadecimalConversionDetector.java
@@ -1,97 +1,97 @@
/**
* Find Security Bugs
* Copyright (c) 2013, Philippe Arteau, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 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.
*/
package com.h3xstream.findsecbugs.crypto;
import com.h3xstream.findsecbugs.common.ByteCode;
import edu.umd.cs.findbugs.Priorities;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.ba.ClassContext;
public class BadHexadecimalConversionDetector implements Detector {
private static final boolean DEBUG = false;
private static final String BAD_HEXA_CONVERSION_TYPE = "BAD_HEXA_CONVERSION";
private BugReporter bugReporter;
public BadHexadecimalConversionDetector(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void visitClassContext(ClassContext classContext) {
JavaClass javaClass = classContext.getJavaClass();
Method[] methodList = javaClass.getMethods();
for (Method m : methodList) {
MethodGen methodGen = classContext.getMethodGen(m);
if (DEBUG) {
System.out.println(">>> Method: " + m.getName());
}
//To suspect that an invalid String representation is being build,
//we identify the construction of a MessageDigest and
//the use of a function that trim leading 0.
boolean invokeMessageDigest = false;
boolean invokeToHexString = false;
ConstantPoolGen cpg = classContext.getConstantPoolGen();
- if(methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) {
+ if(methodGen == null || methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) {
continue; //No instruction .. nothing to do
}
for (Instruction inst : methodGen.getInstructionList().getInstructions()) {
if (DEBUG) {
ByteCode.printOpCode(inst, cpg);
}
if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called
INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) {
invokeMessageDigest = true;
}
} else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created
INVOKESTATIC invoke = (INVOKESTATIC) inst;
if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) {
invokeToHexString = true;
}
}
}
if (invokeMessageDigest && invokeToHexString) {
bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) //
.addClassAndMethod(javaClass, m));
}
}
}
@Override
public void report() {
}
}
| true | true | public void visitClassContext(ClassContext classContext) {
JavaClass javaClass = classContext.getJavaClass();
Method[] methodList = javaClass.getMethods();
for (Method m : methodList) {
MethodGen methodGen = classContext.getMethodGen(m);
if (DEBUG) {
System.out.println(">>> Method: " + m.getName());
}
//To suspect that an invalid String representation is being build,
//we identify the construction of a MessageDigest and
//the use of a function that trim leading 0.
boolean invokeMessageDigest = false;
boolean invokeToHexString = false;
ConstantPoolGen cpg = classContext.getConstantPoolGen();
if(methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) {
continue; //No instruction .. nothing to do
}
for (Instruction inst : methodGen.getInstructionList().getInstructions()) {
if (DEBUG) {
ByteCode.printOpCode(inst, cpg);
}
if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called
INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) {
invokeMessageDigest = true;
}
} else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created
INVOKESTATIC invoke = (INVOKESTATIC) inst;
if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) {
invokeToHexString = true;
}
}
}
if (invokeMessageDigest && invokeToHexString) {
bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) //
.addClassAndMethod(javaClass, m));
}
}
}
| public void visitClassContext(ClassContext classContext) {
JavaClass javaClass = classContext.getJavaClass();
Method[] methodList = javaClass.getMethods();
for (Method m : methodList) {
MethodGen methodGen = classContext.getMethodGen(m);
if (DEBUG) {
System.out.println(">>> Method: " + m.getName());
}
//To suspect that an invalid String representation is being build,
//we identify the construction of a MessageDigest and
//the use of a function that trim leading 0.
boolean invokeMessageDigest = false;
boolean invokeToHexString = false;
ConstantPoolGen cpg = classContext.getConstantPoolGen();
if(methodGen == null || methodGen.getInstructionList() == null || methodGen.getInstructionList().getInstructions() == null) {
continue; //No instruction .. nothing to do
}
for (Instruction inst : methodGen.getInstructionList().getInstructions()) {
if (DEBUG) {
ByteCode.printOpCode(inst, cpg);
}
if (inst instanceof INVOKEVIRTUAL) { //MessageDigest.digest is called
INVOKEVIRTUAL invoke = (INVOKEVIRTUAL) inst;
if ("java.security.MessageDigest".equals(invoke.getClassName(cpg)) && "digest".equals(invoke.getMethodName(cpg))) {
invokeMessageDigest = true;
}
} else if (inst instanceof INVOKESTATIC && invokeMessageDigest) { //The conversion must occurs after the digest was created
INVOKESTATIC invoke = (INVOKESTATIC) inst;
if ("java.lang.Integer".equals(invoke.getClassName(cpg)) && "toHexString".equals(invoke.getMethodName(cpg))) {
invokeToHexString = true;
}
}
}
if (invokeMessageDigest && invokeToHexString) {
bugReporter.reportBug(new BugInstance(this, BAD_HEXA_CONVERSION_TYPE, Priorities.NORMAL_PRIORITY) //
.addClassAndMethod(javaClass, m));
}
}
}
|
diff --git a/src/main/java/net/bobosse/gwt/rulesengine/client/impl/SingleFactRulesEngineImpl.java b/src/main/java/net/bobosse/gwt/rulesengine/client/impl/SingleFactRulesEngineImpl.java
index da40679..c067da9 100644
--- a/src/main/java/net/bobosse/gwt/rulesengine/client/impl/SingleFactRulesEngineImpl.java
+++ b/src/main/java/net/bobosse/gwt/rulesengine/client/impl/SingleFactRulesEngineImpl.java
@@ -1,161 +1,161 @@
package net.bobosse.gwt.rulesengine.client.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.bobosse.gwt.rulesengine.client.Report;
import net.bobosse.gwt.rulesengine.client.Rule;
import net.bobosse.gwt.rulesengine.client.RuleHandler;
import net.bobosse.gwt.rulesengine.client.RulesEngine;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.TextBox;
/**
* This engine aims single fact processing. It could be used to trigger various
* actions when an user types into a {@link TextBox}, using a {@link SuggestBox}
* that uses more that one {@link SuggestOracle}, for example. This simple rule
* engine could help to delegate to the right {@link SuggestOracle}.
*
* @author sesa202001
*
*/
public class SingleFactRulesEngineImpl implements RulesEngine
{
private final Map<Integer, RuleHandler> rulesMap = new HashMap<Integer, RuleHandler>();
private Report report;
/**
* {@link RuleHandler} implementation for {@link SingleFactRulesEngineImpl}
*
* @author sesa202001
*
*/
public class RuleHandlerImpl implements RuleHandler
{
private Rule rule;
private RulesEngine engine;
protected RuleHandlerImpl (Rule rule, RulesEngine engine)
{
this.rule = rule;
this.engine = engine;
}
@Override
public void dispose()
{
rule.passivate();
rule.clearCommands();
((SingleFactRulesEngineImpl) engine).removeRule(rule);
}
@Override
public Rule getRule()
{
return rule;
}
}
public SingleFactRulesEngineImpl ()
{
this.report = new Report();
}
@Override
public RuleHandler addRule(Rule rule)
{
RuleHandlerImpl handler = new RuleHandlerImpl(rule, this);
getRulesMap().put(getRulesMap().size(), handler);
return handler;
}
/**
* removeRule may only be used trough {@link RuleHandler}
*
* @param rule
* to remove
*/
private synchronized void removeRule(Rule rule)
{
synchronized (rulesMap)
{
boolean found = false;
int i = -1;
- for(i = rulesMap.size() - 1; i >= 0; i--)
+ for(i = 0; i <= rulesMap.size()-1; i++)
{
if(rulesMap.get(i).getRule().equals(rule))
{
found = true;
break;
}
}
if(found)
{
getRulesMap().remove(i);
}
}
}
@Override
public void processFact(Object fact)
{
processFact(fact, getReport());
}
@Override
public void processFact(Object fact, Report report)
{
for(Rule rule: getOrderedRules())
{
Log.debug("#processFact() executes rule " + rule);
rule.execute(fact, report);
}
}
/**
* package protected
*
* @return
*/
private Map<Integer, RuleHandler> getRulesMap()
{
return rulesMap;
}
/**
*
* @return rules list in the order they where inserted
*/
public List<Rule> getOrderedRules()
{
ArrayList<Rule> rules = new ArrayList<Rule>();
rulesMap.values();
for(int i = rulesMap.size() - 1; i >= 0; i--)
{
rules.add(rulesMap.get(i).getRule());
}
return rules;
}
@Override
public Report getReport()
{
return report;
}
@Override
public void clearReport()
{
report = new Report();
}
}
| true | true | private synchronized void removeRule(Rule rule)
{
synchronized (rulesMap)
{
boolean found = false;
int i = -1;
for(i = rulesMap.size() - 1; i >= 0; i--)
{
if(rulesMap.get(i).getRule().equals(rule))
{
found = true;
break;
}
}
if(found)
{
getRulesMap().remove(i);
}
}
}
| private synchronized void removeRule(Rule rule)
{
synchronized (rulesMap)
{
boolean found = false;
int i = -1;
for(i = 0; i <= rulesMap.size()-1; i++)
{
if(rulesMap.get(i).getRule().equals(rule))
{
found = true;
break;
}
}
if(found)
{
getRulesMap().remove(i);
}
}
}
|
diff --git a/src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoThriftB64LineRecordReader.java b/src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoThriftB64LineRecordReader.java
index 2d097438..a1431ada 100644
--- a/src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoThriftB64LineRecordReader.java
+++ b/src/java/com/twitter/elephantbird/mapred/input/DeprecatedLzoThriftB64LineRecordReader.java
@@ -1,78 +1,79 @@
package com.twitter.elephantbird.mapred.input;
import com.twitter.elephantbird.mapred.input.DeprecatedLzoLineRecordReader;
import com.twitter.elephantbird.mapreduce.io.BinaryConverter;
import com.twitter.elephantbird.mapreduce.io.ThriftConverter;
import com.twitter.elephantbird.mapreduce.io.ThriftWritable;
import com.twitter.elephantbird.util.Codecs;
import com.twitter.elephantbird.util.TypeRef;
import org.apache.commons.codec.binary.Base64;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.thrift.TBase;
import java.io.IOException;
/**
* Decode a lzo compressed line, apply b64 decoding then deserialize into
* prescribed thrift object.
*
* @author Yifan SHi
*/
public class DeprecatedLzoThriftB64LineRecordReader<M extends TBase<?, ?>>
implements RecordReader<LongWritable, ThriftWritable<M>> {
private DeprecatedLzoLineRecordReader textReader;
private TypeRef<M> typeRef_;
private final ThriftWritable<M> value_;
private final Base64 base64_ = Codecs.createStandardBase64();
private final ThriftConverter<M> converter_;
public DeprecatedLzoThriftB64LineRecordReader(
Configuration conf, FileSplit split, TypeRef<M> typeRef) throws IOException {
textReader = new DeprecatedLzoLineRecordReader(conf, split);
typeRef_ = typeRef;
converter_ = new ThriftConverter<M>(typeRef);
value_ = new ThriftWritable<M>(typeRef);
}
public void close() throws IOException {
textReader.close();
}
public LongWritable createKey() {
return textReader.createKey();
}
public ThriftWritable<M> createValue() {
return new ThriftWritable<M>();
}
public long getPos() throws IOException {
return textReader.getPos();
}
public float getProgress() throws IOException {
return textReader.getProgress();
}
public boolean next(LongWritable key, ThriftWritable<M> value) throws IOException {
Text text = new Text();
if (textReader.next(key, text)) {
byte[] lineBytes = text.toString().getBytes("UTF-8");
M tValue = converter_.fromBytes(base64_.decode(lineBytes));
if (tValue != null) {
value.set(tValue);
+ return true;
}
}
return false;
}
}
| true | true | public boolean next(LongWritable key, ThriftWritable<M> value) throws IOException {
Text text = new Text();
if (textReader.next(key, text)) {
byte[] lineBytes = text.toString().getBytes("UTF-8");
M tValue = converter_.fromBytes(base64_.decode(lineBytes));
if (tValue != null) {
value.set(tValue);
}
}
return false;
}
| public boolean next(LongWritable key, ThriftWritable<M> value) throws IOException {
Text text = new Text();
if (textReader.next(key, text)) {
byte[] lineBytes = text.toString().getBytes("UTF-8");
M tValue = converter_.fromBytes(base64_.decode(lineBytes));
if (tValue != null) {
value.set(tValue);
return true;
}
}
return false;
}
|
diff --git a/psl-core/src/main/java/edu/umd/cs/psl/application/learning/weight/VotedPerceptron.java b/psl-core/src/main/java/edu/umd/cs/psl/application/learning/weight/VotedPerceptron.java
index d06e1730..21e20a20 100644
--- a/psl-core/src/main/java/edu/umd/cs/psl/application/learning/weight/VotedPerceptron.java
+++ b/psl-core/src/main/java/edu/umd/cs/psl/application/learning/weight/VotedPerceptron.java
@@ -1,247 +1,247 @@
/*
* This file is part of the PSL software.
* Copyright 2011 University of Maryland
*
* 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 edu.umd.cs.psl.application.learning.weight;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Iterables;
import edu.umd.cs.psl.application.ModelApplication;
import edu.umd.cs.psl.application.util.Grounding;
import edu.umd.cs.psl.config.ConfigBundle;
import edu.umd.cs.psl.config.ConfigManager;
import edu.umd.cs.psl.config.Factory;
import edu.umd.cs.psl.database.Database;
import edu.umd.cs.psl.database.DatabasePopulator;
import edu.umd.cs.psl.evaluation.process.RunningProcess;
import edu.umd.cs.psl.evaluation.process.local.LocalProcessMonitor;
import edu.umd.cs.psl.model.Model;
import edu.umd.cs.psl.model.atom.ObservedAtom;
import edu.umd.cs.psl.model.atom.RandomVariableAtom;
import edu.umd.cs.psl.model.kernel.CompatibilityKernel;
import edu.umd.cs.psl.model.kernel.GroundKernel;
import edu.umd.cs.psl.model.parameters.PositiveWeight;
import edu.umd.cs.psl.reasoner.Reasoner;
import edu.umd.cs.psl.reasoner.ReasonerFactory;
import edu.umd.cs.psl.reasoner.admm.ADMMReasonerFactory;
/**
* Learns new weights for the {@link CompatibilityKernel CompatibilityKernels}
* in a {@link Model} using the voted perceptron algorithm.
* <p>
* The weight-learning objective is to maximize the likelihood according to the
* distribution:
* <p>
* p(X) = 1 / Z(w) * exp{-sum[w * f(X)]}
* <p>
* where X is the set of RandomVariableAtoms, f(X) the incompatibility of
* each GroundKernel, w is the weight of that GroundKernel, and Z(w)
* is a normalization factor.
* <p>
* The voted perceptron algorithm starts at the current weights and at each step
* computes the gradient of the objective, takes that step multiplied by a step size
* (possibly truncated to stay in the region of feasible weights), and
* saves the new weights. The learned weights are the averages of the saved weights.
* <p>
* In the gradient of the objective, the expected total incompatibility is
* approximated by the total incompatibility at the most-probable assignment
* to the random variables given the current weights.
*
* @author Stephen Bach <[email protected]>
*/
public abstract class VotedPerceptron implements ModelApplication {
private static final Logger log = LoggerFactory.getLogger(VotedPerceptron.class);
/**
* Prefix of property keys used by this class.
*
* @see ConfigManager
*/
public static final String CONFIG_PREFIX = "votedperceptron";
/**
* Key for positive double property which will be multiplied with the
* objective gradient to compute a step.
*/
public static final String STEP_SIZE_KEY = CONFIG_PREFIX + ".stepsize";
/** Default value for STEP_SIZE_KEY */
public static final double STEP_SIZE_DEFAULT = 1.0;
/**
* Key for positive integer property. VotedPerceptron will take this many
* steps to learn weights.
*/
public static final String NUM_STEPS_KEY = CONFIG_PREFIX + ".numsteps";
/** Default value for NUM_STEPS_KEY */
public static final int NUM_STEPS_DEFAULT = 10;
/**
* Key for {@link Factory} or String property.
* <p>
* Should be set to a {@link ReasonerFactory} or the fully qualified
* name of one. Will be used to instantiate a {@link Reasoner}.
*/
public static final String REASONER_KEY = CONFIG_PREFIX + ".reasoner";
/**
* Default value for REASONER_KEY.
* <p>
* Value is instance of {@link ADMMReasonerFactory}.
*/
public static final ReasonerFactory REASONER_DEFAULT = new ADMMReasonerFactory();
protected Model model;
protected Database rvDB, observedDB;
protected ConfigBundle config;
private final double stepSize;
private final int numSteps;
public VotedPerceptron(Model model, Database rvDB, Database observedDB, ConfigBundle config) {
this.model = model;
this.rvDB = rvDB;
this.observedDB = observedDB;
this.config = config;
stepSize = config.getDouble(STEP_SIZE_KEY, STEP_SIZE_DEFAULT);
if (stepSize <= 0)
throw new IllegalArgumentException("Step size must be positive.");
numSteps = config.getInt(NUM_STEPS_KEY, NUM_STEPS_DEFAULT);
if (numSteps <= 0)
throw new IllegalArgumentException("Number of steps must be positive.");
}
/**
* TODO
* <p>
* The {@link RandomVariableAtom RandomVariableAtoms} in the distribution are those
* persisted in the Database when this method is called. All RandomVariableAtoms
* which the Model might access must be persisted in the Database.
*
* @see DatabasePopulator
*/
public void learn()
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
RunningProcess proc = LocalProcessMonitor.get().startProcess();
List<CompatibilityKernel> kernels = new ArrayList<CompatibilityKernel>();
double[] weights;
double[] avgWeights;
int[] numGroundings;
double[] truthIncompatibility;
double[] marginals;
/* Gathers the CompatibilityKernels */
for (CompatibilityKernel k : Iterables.filter(model.getKernels(), CompatibilityKernel.class))
kernels.add(k);
weights = new double[kernels.size()];
avgWeights = new double[kernels.size()];
numGroundings = new int[kernels.size()];
truthIncompatibility = new double[kernels.size()];
marginals = new double[kernels.size()];
/* Sets up the ground model */
TrainingMap trainingMap = new TrainingMap(rvDB, observedDB);
Reasoner reasoner = ((ReasonerFactory) config.getFactory(REASONER_KEY, REASONER_DEFAULT)).getReasoner(config);
initGroundModel(model, trainingMap, reasoner);
/* Computes the observed incompatibility */
for (Map.Entry<RandomVariableAtom, ObservedAtom> e : trainingMap.getTrainingMap().entrySet()) {
e.getKey().setValue(e.getValue().getValue());
}
for (int i = 0; i < kernels.size(); i++) {
for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
truthIncompatibility[i] += gk.getIncompatibility();
numGroundings[i]++;
}
/* Initializes the current weights */
weights[i] = kernels.get(i).getWeight().getWeight();
}
/* Computes the Perceptron steps */
for (int step = 0; step < numSteps; step++) {
/* Compute the marginals */
computeMarginals(kernels, marginals);
/* Update weights */
for (int i = 0; i < kernels.size(); i++) {
- double curStep = stepSize / numGroundings[i] * (truthIncompatibility[i] - marginals[i]);
+ double curStep = stepSize / numGroundings[i] * (marginals[i] - truthIncompatibility[i]);
log.debug("Step of {} for kernel {}", curStep, kernels.get(i));
log.debug(" --- Truth: {}, Marginals: {}", truthIncompatibility[i], marginals[i]);
weights[i] = weights[i] + curStep;
weights[i] = Math.max(weights[i], 0.0);
avgWeights[i] += weights[i];
kernels.get(i).setWeight(new PositiveWeight(weights[i]));
}
reasoner.changedKernelWeights();
// OLD STUFF. Keep it around for the time being.
// reasoner.optimize();
//
// for (int i = 0; i < kernels.size(); i++) {
// oldWeights[i] = newWeights[i];
// mpeIncompatibility = 0.0;
//
// for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
// mpeIncompatibility += gk.getIncompatibility();
// }
//
// newWeights[i] = oldWeights[i] + stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]);
// log.debug("Step of {} for kernel {}", stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]), kernels.get(i));
// log.debug(" --- MPE incomp.: {}, Truth incomp.: {}", mpeIncompatibility, truthIncompatibility[i]);
// newWeights[i] = Math.max(newWeights[i], 0.0);
// avgWeights[i] += newWeights[i];
//
// kernels.get(i).setWeight(new PositiveWeight(newWeights[i]));
// }
// reasoner.changedKernelWeights();
}
/* Sets the weights to their averages */
for (int i = 0; i < kernels.size(); i++) {
kernels.get(i).setWeight(new PositiveWeight(avgWeights[i] / numSteps));
}
proc.terminate();
}
protected void initGroundModel(Model m, TrainingMap tMap, Reasoner reasoner) {
if (tMap.getLatentVariables().size() > 0)
throw new IllegalArgumentException("All RandomVariableAtoms must have " +
"corresponding ObservedAtoms. Latent variables are not supported " +
"by VotedPerceptron. Example latent variable: " + tMap.getLatentVariables().iterator().next());
Grounding.groundAll(model, tMap, reasoner);
}
protected abstract void computeMarginals(List<CompatibilityKernel> kernels, double[] marginals);
@Override
public void close() {
model = null;
rvDB = null;
config = null;
}
}
| true | true | public void learn()
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
RunningProcess proc = LocalProcessMonitor.get().startProcess();
List<CompatibilityKernel> kernels = new ArrayList<CompatibilityKernel>();
double[] weights;
double[] avgWeights;
int[] numGroundings;
double[] truthIncompatibility;
double[] marginals;
/* Gathers the CompatibilityKernels */
for (CompatibilityKernel k : Iterables.filter(model.getKernels(), CompatibilityKernel.class))
kernels.add(k);
weights = new double[kernels.size()];
avgWeights = new double[kernels.size()];
numGroundings = new int[kernels.size()];
truthIncompatibility = new double[kernels.size()];
marginals = new double[kernels.size()];
/* Sets up the ground model */
TrainingMap trainingMap = new TrainingMap(rvDB, observedDB);
Reasoner reasoner = ((ReasonerFactory) config.getFactory(REASONER_KEY, REASONER_DEFAULT)).getReasoner(config);
initGroundModel(model, trainingMap, reasoner);
/* Computes the observed incompatibility */
for (Map.Entry<RandomVariableAtom, ObservedAtom> e : trainingMap.getTrainingMap().entrySet()) {
e.getKey().setValue(e.getValue().getValue());
}
for (int i = 0; i < kernels.size(); i++) {
for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
truthIncompatibility[i] += gk.getIncompatibility();
numGroundings[i]++;
}
/* Initializes the current weights */
weights[i] = kernels.get(i).getWeight().getWeight();
}
/* Computes the Perceptron steps */
for (int step = 0; step < numSteps; step++) {
/* Compute the marginals */
computeMarginals(kernels, marginals);
/* Update weights */
for (int i = 0; i < kernels.size(); i++) {
double curStep = stepSize / numGroundings[i] * (truthIncompatibility[i] - marginals[i]);
log.debug("Step of {} for kernel {}", curStep, kernels.get(i));
log.debug(" --- Truth: {}, Marginals: {}", truthIncompatibility[i], marginals[i]);
weights[i] = weights[i] + curStep;
weights[i] = Math.max(weights[i], 0.0);
avgWeights[i] += weights[i];
kernels.get(i).setWeight(new PositiveWeight(weights[i]));
}
reasoner.changedKernelWeights();
// OLD STUFF. Keep it around for the time being.
// reasoner.optimize();
//
// for (int i = 0; i < kernels.size(); i++) {
// oldWeights[i] = newWeights[i];
// mpeIncompatibility = 0.0;
//
// for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
// mpeIncompatibility += gk.getIncompatibility();
// }
//
// newWeights[i] = oldWeights[i] + stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]);
// log.debug("Step of {} for kernel {}", stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]), kernels.get(i));
// log.debug(" --- MPE incomp.: {}, Truth incomp.: {}", mpeIncompatibility, truthIncompatibility[i]);
// newWeights[i] = Math.max(newWeights[i], 0.0);
// avgWeights[i] += newWeights[i];
//
// kernels.get(i).setWeight(new PositiveWeight(newWeights[i]));
// }
// reasoner.changedKernelWeights();
}
/* Sets the weights to their averages */
for (int i = 0; i < kernels.size(); i++) {
kernels.get(i).setWeight(new PositiveWeight(avgWeights[i] / numSteps));
}
proc.terminate();
}
| public void learn()
throws ClassNotFoundException, IllegalAccessException, InstantiationException {
RunningProcess proc = LocalProcessMonitor.get().startProcess();
List<CompatibilityKernel> kernels = new ArrayList<CompatibilityKernel>();
double[] weights;
double[] avgWeights;
int[] numGroundings;
double[] truthIncompatibility;
double[] marginals;
/* Gathers the CompatibilityKernels */
for (CompatibilityKernel k : Iterables.filter(model.getKernels(), CompatibilityKernel.class))
kernels.add(k);
weights = new double[kernels.size()];
avgWeights = new double[kernels.size()];
numGroundings = new int[kernels.size()];
truthIncompatibility = new double[kernels.size()];
marginals = new double[kernels.size()];
/* Sets up the ground model */
TrainingMap trainingMap = new TrainingMap(rvDB, observedDB);
Reasoner reasoner = ((ReasonerFactory) config.getFactory(REASONER_KEY, REASONER_DEFAULT)).getReasoner(config);
initGroundModel(model, trainingMap, reasoner);
/* Computes the observed incompatibility */
for (Map.Entry<RandomVariableAtom, ObservedAtom> e : trainingMap.getTrainingMap().entrySet()) {
e.getKey().setValue(e.getValue().getValue());
}
for (int i = 0; i < kernels.size(); i++) {
for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
truthIncompatibility[i] += gk.getIncompatibility();
numGroundings[i]++;
}
/* Initializes the current weights */
weights[i] = kernels.get(i).getWeight().getWeight();
}
/* Computes the Perceptron steps */
for (int step = 0; step < numSteps; step++) {
/* Compute the marginals */
computeMarginals(kernels, marginals);
/* Update weights */
for (int i = 0; i < kernels.size(); i++) {
double curStep = stepSize / numGroundings[i] * (marginals[i] - truthIncompatibility[i]);
log.debug("Step of {} for kernel {}", curStep, kernels.get(i));
log.debug(" --- Truth: {}, Marginals: {}", truthIncompatibility[i], marginals[i]);
weights[i] = weights[i] + curStep;
weights[i] = Math.max(weights[i], 0.0);
avgWeights[i] += weights[i];
kernels.get(i).setWeight(new PositiveWeight(weights[i]));
}
reasoner.changedKernelWeights();
// OLD STUFF. Keep it around for the time being.
// reasoner.optimize();
//
// for (int i = 0; i < kernels.size(); i++) {
// oldWeights[i] = newWeights[i];
// mpeIncompatibility = 0.0;
//
// for (GroundKernel gk : reasoner.getGroundKernels(kernels.get(i))) {
// mpeIncompatibility += gk.getIncompatibility();
// }
//
// newWeights[i] = oldWeights[i] + stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]);
// log.debug("Step of {} for kernel {}", stepSize / numGroundings[i] * (mpeIncompatibility - truthIncompatibility[i]), kernels.get(i));
// log.debug(" --- MPE incomp.: {}, Truth incomp.: {}", mpeIncompatibility, truthIncompatibility[i]);
// newWeights[i] = Math.max(newWeights[i], 0.0);
// avgWeights[i] += newWeights[i];
//
// kernels.get(i).setWeight(new PositiveWeight(newWeights[i]));
// }
// reasoner.changedKernelWeights();
}
/* Sets the weights to their averages */
for (int i = 0; i < kernels.size(); i++) {
kernels.get(i).setWeight(new PositiveWeight(avgWeights[i] / numSteps));
}
proc.terminate();
}
|
diff --git a/bundles/org.eclipse.core.boot/src/org/eclipse/core/internal/boot/DelegatingURLClassLoader.java b/bundles/org.eclipse.core.boot/src/org/eclipse/core/internal/boot/DelegatingURLClassLoader.java
index 10d97d39d..1c2aa841e 100644
--- a/bundles/org.eclipse.core.boot/src/org/eclipse/core/internal/boot/DelegatingURLClassLoader.java
+++ b/bundles/org.eclipse.core.boot/src/org/eclipse/core/internal/boot/DelegatingURLClassLoader.java
@@ -1,721 +1,721 @@
package org.eclipse.core.internal.boot;
/*
* Licensed Materials - Property of IBM,
* WebSphere Studio Workbench
* (c) Copyright IBM Corp 2000
*/
import java.net.*;
import java.util.*;
import java.io.*;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import org.eclipse.core.boot.BootLoader;
import com.ibm.oti.vm.VM;
public abstract class DelegatingURLClassLoader extends URLClassLoader {
// loader base
protected URL base;
// delegation chain
protected DelegateLoader[] imports = null;
// extra resource class loader
protected URLClassLoader resourceLoader = null;
// filter table
private Hashtable filterTable = new Hashtable();
// development mode class path additions
public static String devClassPath = null;
// native library loading
private static String libPrefix;
private static String libSuffix;
private static final String WIN_LIBRARY_PREFIX = "";
private static final String WIN_LIBRARY_SUFFIX = ".dll";
private static final String UNIX_LIBRARY_PREFIX = "lib";
private static final String UNIX_LIBRARY_SUFFIX = ".so";
private Hashtable nativeLibs = new Hashtable();
private static final int BUF_SIZE = 32768;
// control class load tracing
public static boolean DEBUG = false;
public static boolean DEBUG_SHOW_CREATE = true;
public static boolean DEBUG_SHOW_ACTIVATE = true;
public static boolean DEBUG_SHOW_ACTIONS = true;
public static boolean DEBUG_SHOW_SUCCESS = true;
public static boolean DEBUG_SHOW_FAILURE = true;
public static String[] DEBUG_FILTER_CLASS = new String[0];
public static String[] DEBUG_FILTER_LOADER = new String[0];
public static String[] DEBUG_FILTER_RESOURCE = new String[0];
public static String[] DEBUG_FILTER_NATIVE = new String[0];
private static boolean isHotSwapEnabled = InternalBootLoader.inDevelopmentMode();
// DelegateLoader. Represents a single class loader this loader delegates to.
protected static class DelegateLoader {
private DelegatingURLClassLoader loader;
private boolean isExported;
public DelegateLoader(DelegatingURLClassLoader loader, boolean isExported) {
this.loader = loader;
this.isExported = isExported;
}
public Class loadClass(String name, DelegatingURLClassLoader current, DelegatingURLClassLoader requestor, Vector seen) {
if (isExported || current == requestor)
return loader.loadClass(name, false, requestor, seen, false);
else
return null;
}
public URL findResource(String name, DelegatingURLClassLoader current, DelegatingURLClassLoader requestor, Vector seen) {
if (isExported || current == requestor)
return loader.findResource(name, requestor, seen);
else
return null;
}
public Enumeration findResources(String name, DelegatingURLClassLoader current, DelegatingURLClassLoader requestor, Vector seen) {
if (isExported || current == requestor)
return loader.findResources(name, requestor, seen);
else
return null;
}
}
// unchecked DelegatingLoaderException
protected static class DelegatingLoaderException extends RuntimeException {
Exception e = null;
public DelegatingLoaderException() {
super();
}
public DelegatingLoaderException(String message) {
super(message);
}
public DelegatingLoaderException(String message, Exception e) {
super(message);
this.e = e;
}
public Throwable getException() {
return e;
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintStream output) {
synchronized (output) {
if (e != null) {
output.print("org.eclipse.core.internal.boot.DelegatingLoaderException: ");
e.printStackTrace(output);
} else
super.printStackTrace(output);
}
}
public void printStackTrace(PrintWriter output) {
synchronized (output) {
if (e != null) {
output.print("org.eclipse.core.internal.boot.DelegatingLoaderException: ");
e.printStackTrace(output);
} else
super.printStackTrace(output);
}
}
}
public DelegatingURLClassLoader(URL[] codePath, URLContentFilter[] codeFilters, URL[] resourcePath, URLContentFilter[] resourceFilters, ClassLoader parent) {
super(codePath, parent);
initialize();
if (resourcePath != null && resourcePath.length > 0)
resourceLoader = new ResourceLoader(resourcePath);
if (codePath != null) {
if (codeFilters == null || codeFilters.length != codePath.length)
throw new DelegatingLoaderException();
setJ9HotSwapPath(this, codePath);
for (int i = 0; i < codePath.length; i++) {
if (codeFilters[i] != null)
filterTable.put(codePath[i], codeFilters[i]);
}
}
if (resourcePath != null) {
if (resourceFilters == null || resourceFilters.length != resourcePath.length)
throw new DelegatingLoaderException();
for (int i = 0; i < resourcePath.length; i++) {
if (resourceFilters[i] != null)
filterTable.put(resourcePath[i], resourceFilters[i]);
}
}
}
/**
* Returns the given class or <code>null</code> if the class is not visible to the
* given requestor. The <code>inCache</code> flag controls how this action is
* reported if in debug mode.
*/
protected Class checkClassVisibility(Class result, DelegatingURLClassLoader requestor, boolean inCache) {
if (result == null)
return null;
if (isClassVisible(result, requestor)) {
if (DEBUG && DEBUG_SHOW_SUCCESS && debugClass(result.getName()))
debug("found " + result.getName() + " in " + (inCache ? "cache" : getURLforClass(result).toExternalForm()));
} else {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugClass(result.getName()))
debug("skip " + result.getName() + " in " + (inCache ? "cache" : getURLforClass(result).toExternalForm()));
return null;
}
return result;
}
/**
* Returns the given resource URL or <code>null</code> if the resource is not visible to the
* given requestor.
*/
protected URL checkResourceVisibility(String name, URL result, DelegatingURLClassLoader requestor) {
if (result == null)
return null;
if (isResourceVisible(name, result, requestor)) {
if (DEBUG && DEBUG_SHOW_SUCCESS && debugResource(name))
debug("found " + result);
} else {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugResource(name))
debug("skip " + result);
result = null;
}
return result;
}
protected void debug(String s) {
System.out.println(toString()+"^"+Integer.toHexString(Thread.currentThread().hashCode())+" "+s);
}
protected boolean debugClass(String name) {
if (debugLoader()) {
return debugMatchesFilter(name,DEBUG_FILTER_CLASS);
}
return false;
}
protected void debugConstruction() {
if (DEBUG && DEBUG_SHOW_CREATE && debugLoader()) {
URL[] urls = getURLs();
debug("Class Loader Created");
debug("> baseURL=" + base);
if (urls == null || urls.length == 0)
debug("> empty search path");
else {
URLContentFilter filter;
for (int i = 0; i < urls.length; i++) {
debug("> searchURL=" + urls[i].toString());
filter = (URLContentFilter) filterTable.get(urls[i]);
if (filter != null)
debug("> export=" + filter.toString());
}
}
}
}
protected String debugId() {
return "";
}
protected boolean debugLoader() {
return debugMatchesFilter(debugId(),DEBUG_FILTER_LOADER);
}
private boolean debugMatchesFilter(String name, String[] filter) {
if (filter.length==0) return false;
for (int i=0; i<filter.length; i++) {
if (filter[i].equals("*")) return true;
if (name.startsWith(filter[i])) return true;
}
return false;
}
protected boolean debugNative(String name) {
if (debugLoader()) {
return debugMatchesFilter(name,DEBUG_FILTER_NATIVE);
}
return false;
}
protected boolean debugResource(String name) {
if (debugLoader()) {
return debugMatchesFilter(name,DEBUG_FILTER_RESOURCE);
}
return false;
}
/**
* Looks for the requested class in the parent of this loader using
* standard Java protocols. If the parent is null then the system class
* loader is consulted. <code>null</code> is returned if the class could
* not be found.
*/
protected Class findClassParents(String name, boolean resolve) {
try {
ClassLoader parent = getParent();
if (parent == null)
return findSystemClass(name);
return parent.loadClass(name);
} catch (ClassNotFoundException e) {
}
return null;
}
/**
* Finds and loads the class with the specified name from the URL search
* path. Any URLs referring to JAR files are loaded and opened as needed
* until the class is found. Search on the parent chain and then self.
*
* Subclasses should implement this method.
*
* @param name the name of the class
* @param resolve whether or not to resolve the class if found
* @param requestor class loader originating the request
* @param checkParents whether the parent of this loader should be consulted
* @return the resulting class
*/
protected abstract Class findClassParentsSelf(String name, boolean resolve, DelegatingURLClassLoader requestor, boolean checkParents);
/**
* Finds and loads the class with the specified name from the URL search
* path. Any URLs referring to JAR files are loaded and opened as needed
* until the class is found. This method consults only the platform class loader.
*
* @param name the name of the class
* @param resolve whether or not to resolve the class if found
* @param requestor class loader originating the request
* @param checkParents whether the parent of this loader should be consulted
* @return the resulting class
*/
protected Class findClassPlatform(String name, boolean resolve, DelegatingURLClassLoader requestor, boolean checkParents) {
DelegatingURLClassLoader platform = PlatformClassLoader.getDefault();
if (this == platform)
return null;
return platform.findClassParentsSelf(name, resolve, requestor, false);
}
/**
* Finds and loads the class with the specified name from the URL search
* path. Any URLs referring to JAR files are loaded and opened as needed
* until the class is found. This method considers only the classes loadable
* by its explicit prerequisite loaders.
*
* @param name the name of the class
* @param requestor class loader originating the request
* @param seen list of delegated class loaders already searched
* @return the resulting class
*/
protected Class findClassPrerequisites(final String name, DelegatingURLClassLoader requestor, Vector seen) {
if (imports == null)
return null;
if (seen == null)
seen = new Vector(); // guard against delegation loops
seen.addElement(this);
// Grab onto the imports value to protect against concurrent write.
DelegateLoader[] loaders = imports;
for (int i = 0; i < loaders.length; i++) {
Class result = loaders[i].loadClass(name, this, requestor, seen);
if (result != null)
return result;
}
return null;
}
/**
* Finds the resource with the specified name on the URL search path.
* This method is used specifically to find the file containing a class to verify
* that the class exists without having to load it.
* Returns a URL for the resource. Searches only this loader's classpath.
* <code>null</code> is returned if the resource cannot be found.
*
* @param name the name of the resource
*/
protected URL findClassResource(String name) {
return super.findResource(name);
}
/**
* Returns the absolute path name of a native library. The VM
* invokes this method to locate the native libraries that belong
* to classes loaded with this class loader. If this method returns
* <code>null</code>, the VM searches the library along the path
* specified as the <code>java.library.path</code> property.
*
* @param libname the library name
* @return the absolute path of the native library
*/
protected String basicFindLibrary(String libName) {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugNative(libName))
debug("findLibrary(" + libName + ")");
if (base == null)
return null;
// wrap the last segment of the name with OS appropriate decorations
int i = libName.lastIndexOf('/');
String first = "";
String rest = "";
if (i == -1)
- first = libName;
+ rest = libName;
else {
first = libName.substring(0, i + 1);
rest = libName.substring(i + 1);
}
String osLibFileName = first + libPrefix + rest + libSuffix;
File libFile = null;
if (base.getProtocol().equals(PlatformURLHandler.FILE) || base.getProtocol().equals(PlatformURLHandler.VA)) {
// directly access library
String libFileName = (base.getFile() + osLibFileName).replace('/', File.separatorChar);
libFile = new File(libFileName);
} else
if (base.getProtocol().equals(PlatformURLHandler.PROTOCOL))
// access library through eclipse URL
libFile = getNativeLibraryAsLocal(osLibFileName);
if (libFile == null)
return null;
if (!libFile.exists()) {
if (DEBUG && DEBUG_SHOW_FAILURE && debugNative(libName))
debug("not found " + libName);
return null; // can't find the file
}
if (DEBUG && DEBUG_SHOW_SUCCESS && debugNative(libName))
debug("found " + libName + " as " + libFile.getAbsolutePath());
return libFile.getAbsolutePath();
}
protected String findLibrary(String libName) {
if (libName.length() == 0)
return null;
if (libName.charAt(0) != '$')
return basicFindLibrary(libName);
int i = libName.indexOf('/', 1);
String first = "";
String rest = "";
String result = null;
if (i == -1)
first = libName;
else {
first = libName.substring(0, i);
rest = libName.substring(i);
}
if (first.equalsIgnoreCase("$ws$"))
result = basicFindLibrary("ws/" + InternalBootLoader.getWS() + rest);
else
if (first.equalsIgnoreCase("$os$"))
result = basicFindLibrary("os/" + InternalBootLoader.getOS() + rest);
else
if (first.equalsIgnoreCase("$nl$"))
result = findLibraryNL(rest);
return result != null ? result : basicFindLibrary(rest);
}
/**
* Scan all the possible NL-based locations in which there might be a
* requested library.
*/
private String findLibraryNL(String libName) {
String nl = InternalBootLoader.getNL();
String result = null;
while (result == null && nl.length() > 0) {
String location = "nl/" + nl + libName;
result = basicFindLibrary(location);
int i = nl.lastIndexOf('_');
if (i < 0)
nl = "";
else
nl = nl.substring(0, i);
}
return result;
}
/**
* Finds the resource with the specified name on the URL search path.
* Returns a URL for the resource. If resource is not found in own
* URL search path, delegates search to prerequisite loaders.
* Null is returned if none of the loaders find the resource.
*
* @param name the name of the resource
*/
public URL findResource(String name) {
return findResource(name, this, null);
}
/**
* Delegated resource access call.
* Does not check prerequisite loader parent chain.
*/
protected URL findResource(String name, DelegatingURLClassLoader requestor, Vector seen) {
// guard against delegation loops
if (seen != null && seen.contains(this))
return null;
if (DEBUG && DEBUG_SHOW_ACTIONS && debugResource(name))
debug("findResource(" + name + ")");
// check the normal class path for self
URL result = super.findResource(name);
result = checkResourceVisibility(name, result, requestor);
if (result != null)
return result;
// check our extra resource path if any
if (resourceLoader != null) {
result = resourceLoader.findResource(name);
result = checkResourceVisibility(name, result, requestor);
if (result != null)
return result;
}
// delegate down the prerequisite chain if we haven't found anything yet.
if (imports != null) {
if (seen == null)
seen = new Vector(); // guard against delegation loops
seen.addElement(this);
for (int i = 0; i < imports.length && result == null; i++)
result = imports[i].findResource(name, this, requestor, seen);
}
return result;
}
/**
* Returns an Enumeration of URLs representing all of the resources
* on the URL search path having the specified name.
*
* @param name the resource name
*/
public Enumeration findResources(String name) throws IOException {
return findResources(name, this, null);
}
/**
* Delegated call to locate all named resources.
* Does not check prerequisite loader parent chain.
*/
private Enumeration findResources(String name, DelegatingURLClassLoader requestor, Vector seen) {
// guard against delegation loops
if (seen != null && seen.contains(this))
return null;
if (DEBUG && DEBUG_SHOW_ACTIONS && debugResource(name))
debug("findResources(" + name + ")");
// check own URL search path
Enumeration e = null;
try {
e = super.findResources(name);
} catch (IOException ioe) {
}
ResourceEnumeration result = new ResourceEnumeration(name, e, this, requestor);
// delegate down the prerequisite chain
if (imports != null) {
if (seen == null)
seen = new Vector(); // guard against delegation loops
seen.addElement(this);
for (int i = 0; i < imports.length; i++)
result.add(imports[i].findResources(name, this, requestor, seen));
}
return result;
}
private File getNativeLibraryAsLocal(String osname) {
File result = null;
try {
URL liburl = new URL(base, osname);
PlatformURLConnection c = (PlatformURLConnection) liburl.openConnection();
URL localName = c.getURLAsLocal();
result = new File(localName.getFile());
} catch (IOException e) {
}
return result;
}
public URL getResource(String name) {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugResource(name))
debug("getResource(" + name + ")");
URL result = super.getResource(name);
if (result == null) {
if (DEBUG && DEBUG_SHOW_FAILURE && debugResource(name))
debug("not found " + name);
}
return result;
}
private URL getURLforClass(Class clazz) {
ProtectionDomain pd = clazz.getProtectionDomain();
if (pd != null) {
CodeSource cs = pd.getCodeSource();
if (cs != null)
return cs.getLocation();
}
if (DEBUG && DEBUG_SHOW_ACTIONS && debugClass(clazz.getName()))
debug("*** " + clazz.getName());
return null;
}
private void initialize() {
if (BootLoader.getOS().equals(BootLoader.OS_WIN32)) {
libPrefix = WIN_LIBRARY_PREFIX;
libSuffix = WIN_LIBRARY_SUFFIX;
} else {
libPrefix = UNIX_LIBRARY_PREFIX;
libSuffix = UNIX_LIBRARY_SUFFIX;
}
}
public void initializeImportedLoaders() {
}
/**
* check to see if class is visible (exported)
*/
boolean isClassVisible(Class clazz, DelegatingURLClassLoader requestor) {
URL lib = getURLforClass(clazz);
if (lib == null)
return true; // have a system class (see comment below)
URLContentFilter filter = (URLContentFilter) filterTable.get(lib);
if (filter == null) {
// This code path is being executed because some VMs (eg. Sun JVM)
// return from the class cache classes that were not loaded
// by this class loader. Consequently we do not find the
// corresponding jar filter. This appears to be a performance
// optimization that we are defeating with our filtering scheme.
// We return the class if it is a system class (see above). Otherwise
// we reject the class which caused the load to be
// delegated down the prerequisite chain until we find the
// correct loader.
if (DEBUG && DEBUG_SHOW_ACTIONS && debugClass(clazz.getName()))
debug("*** Unable to find library filter for " + clazz.getName() + " from " + lib);
return false;
} else
return filter.isClassVisible(clazz, this, requestor);
}
/**
* check to see if resource is visible (exported)
*/
boolean isResourceVisible(String name, URL resource, DelegatingURLClassLoader requestor) {
URL lib = null;
String file = resource.getFile();
try {
lib = new URL(resource.getProtocol(), resource.getHost(), file.substring(0, file.length() - name.length()));
} catch (MalformedURLException e) {
if (DEBUG)
debug("Unable to determine resource lib for " + name + " from " + resource);
return false;
}
URLContentFilter filter = (URLContentFilter) filterTable.get(lib);
if (filter == null) {
if (DEBUG)
debug("Unable to find library filter for " + name + " from " + lib);
return false;
} else
return filter.isResourceVisible(name, this, requestor);
}
/**
* Non-delegated load call. This method is not synchronized. Implementations of
* findClassParentsSelf, and perhaps others, should synchronize themselves as
* required. Synchronizing this method is too coarse-grained. It results in plugin
* activation being synchronized and may cause deadlock.
*/
protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugClass(name))
debug("loadClass(" + name + ")");
Class result = loadClass(name, resolve, this, null, true);
if (result == null) {
if (DEBUG && DEBUG_SHOW_FAILURE && debugClass(name))
debug("not found " + name);
throw new ClassNotFoundException(name);
}
return result;
}
protected void enableJ9HotSwap(ClassLoader cl, Class clazz) {
if (isHotSwapEnabled)
VM.enableClassHotSwap(clazz);
}
/**
* Delegated load call. This method is not synchronized. Implementations of
* findClassParentsSelf, and perhaps others, should synchronize themselves as
* required. Synchronizing this method is too coarse-grained. It results in plugin
* activation being synchronized and may cause deadlock.
*/
private Class loadClass(String name, boolean resolve, DelegatingURLClassLoader requestor, Vector seen, boolean checkParents) {
// guard against delegation loops
if (seen != null && seen.contains(this))
return null;
// look in the parents and self
Class result = findClassParentsSelf(name, resolve, requestor, checkParents);
// search platform
if (result == null)
result = findClassPlatform(name, resolve, requestor, false);
// search prerequisites
if (result == null)
result = findClassPrerequisites(name, requestor, seen);
// if we found a class, consider resolving it
if (result != null && resolve)
resolveClass(result);
return result;
}
private void setJ9HotSwapPath(ClassLoader cl, URL[] urls) {
if (!isHotSwapEnabled)
return;
StringBuffer path = new StringBuffer();
for(int i = 0; i < urls.length; i++) {
String file = getFileFromURL (urls[i]);
if (file != null) {
if (file.charAt(0) == '/')
file = file.substring(1, file.length());
if (file.charAt(file.length() - 1) == '/')
file = file.substring(0, file.length() - 1);
if (path.length() > 0)
path.append(";");
path.append(file);
}
}
if (path.length() > 0)
VM.setClassPathImpl(cl, path.toString());
}
protected String getFileFromURL(URL target) {
String protocol = target.getProtocol();
if (protocol.equals(PlatformURLHandler.FILE))
return target.getFile();
// if (protocol.equals(PlatformURLHandler.VA))
// return target.getFile();
if (protocol.equals(PlatformURLHandler.JAR)) {
// strip off the jar separator at the end of the url then do a recursive call
// to interpret the sub URL.
String file = target.getFile();
file = file.substring(0, file.length() - PlatformURLHandler.JAR_SEPARATOR.length());
try {
return getFileFromURL(new URL(file));
} catch (MalformedURLException e) {
}
}
return null;
}
protected void setImportedLoaders(DelegateLoader[] loaders) {
imports = loaders;
if(DEBUG && DEBUG_SHOW_CREATE && debugLoader()) {
debug("Imports");
if (imports==null || imports.length==0) debug("> none");
else {
for (int i=0; i<imports.length; i++) {
debug("> " + imports[i].loader.toString() + " export=" + imports[i].isExported);
}
}
}
}
public String toString() {
return "Loader [" + debugId() + "]";
}
}
| true | true | protected String basicFindLibrary(String libName) {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugNative(libName))
debug("findLibrary(" + libName + ")");
if (base == null)
return null;
// wrap the last segment of the name with OS appropriate decorations
int i = libName.lastIndexOf('/');
String first = "";
String rest = "";
if (i == -1)
first = libName;
else {
first = libName.substring(0, i + 1);
rest = libName.substring(i + 1);
}
String osLibFileName = first + libPrefix + rest + libSuffix;
File libFile = null;
if (base.getProtocol().equals(PlatformURLHandler.FILE) || base.getProtocol().equals(PlatformURLHandler.VA)) {
// directly access library
String libFileName = (base.getFile() + osLibFileName).replace('/', File.separatorChar);
libFile = new File(libFileName);
} else
if (base.getProtocol().equals(PlatformURLHandler.PROTOCOL))
// access library through eclipse URL
libFile = getNativeLibraryAsLocal(osLibFileName);
if (libFile == null)
return null;
if (!libFile.exists()) {
if (DEBUG && DEBUG_SHOW_FAILURE && debugNative(libName))
debug("not found " + libName);
return null; // can't find the file
}
if (DEBUG && DEBUG_SHOW_SUCCESS && debugNative(libName))
debug("found " + libName + " as " + libFile.getAbsolutePath());
return libFile.getAbsolutePath();
}
| protected String basicFindLibrary(String libName) {
if (DEBUG && DEBUG_SHOW_ACTIONS && debugNative(libName))
debug("findLibrary(" + libName + ")");
if (base == null)
return null;
// wrap the last segment of the name with OS appropriate decorations
int i = libName.lastIndexOf('/');
String first = "";
String rest = "";
if (i == -1)
rest = libName;
else {
first = libName.substring(0, i + 1);
rest = libName.substring(i + 1);
}
String osLibFileName = first + libPrefix + rest + libSuffix;
File libFile = null;
if (base.getProtocol().equals(PlatformURLHandler.FILE) || base.getProtocol().equals(PlatformURLHandler.VA)) {
// directly access library
String libFileName = (base.getFile() + osLibFileName).replace('/', File.separatorChar);
libFile = new File(libFileName);
} else
if (base.getProtocol().equals(PlatformURLHandler.PROTOCOL))
// access library through eclipse URL
libFile = getNativeLibraryAsLocal(osLibFileName);
if (libFile == null)
return null;
if (!libFile.exists()) {
if (DEBUG && DEBUG_SHOW_FAILURE && debugNative(libName))
debug("not found " + libName);
return null; // can't find the file
}
if (DEBUG && DEBUG_SHOW_SUCCESS && debugNative(libName))
debug("found " + libName + " as " + libFile.getAbsolutePath());
return libFile.getAbsolutePath();
}
|
diff --git a/jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/instance/list/ProcessInstanceListViewImpl.java b/jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/instance/list/ProcessInstanceListViewImpl.java
index 7ea4dda22..60c91efa0 100644
--- a/jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/instance/list/ProcessInstanceListViewImpl.java
+++ b/jbpm-console-ng-process-runtime/jbpm-console-ng-process-runtime-client/src/main/java/org/jbpm/console/ng/pr/client/editors/instance/list/ProcessInstanceListViewImpl.java
@@ -1,653 +1,661 @@
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.console.ng.pr.client.editors.instance.list;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.enterprise.context.Dependent;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import com.github.gwtbootstrap.client.ui.DataGrid;
import com.github.gwtbootstrap.client.ui.Label;
import com.github.gwtbootstrap.client.ui.NavLink;
import com.github.gwtbootstrap.client.ui.SimplePager;
import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.ActionCell.Delegate;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.CompositeCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.cell.client.HasCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import java.util.Date;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.jbpm.console.ng.pr.client.i18n.Constants;
import org.jbpm.console.ng.pr.client.resources.ProcessRuntimeImages;
import org.jbpm.console.ng.pr.client.util.DataGridUtils;
import org.jbpm.console.ng.pr.client.util.ResizableHeader;
import org.jbpm.console.ng.pr.model.ProcessInstanceSummary;
import org.jbpm.console.ng.pr.model.events.ProcessInstanceSelectionEvent;
import org.jbpm.console.ng.pr.model.events.ProcessInstanceStyleEvent;
import org.jbpm.console.ng.pr.model.events.ProcessInstancesWithDetailsRequestEvent;
import org.kie.api.runtime.process.ProcessInstance;
import org.uberfire.client.mvp.PlaceManager;
import org.uberfire.client.mvp.PlaceStatus;
import org.uberfire.mvp.PlaceRequest;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.security.Identity;
import org.uberfire.workbench.events.BeforeClosePlaceEvent;
import org.uberfire.workbench.events.NotificationEvent;
@Dependent
@Templated(value = "ProcessInstanceListViewImpl.html")
public class ProcessInstanceListViewImpl extends Composite implements ProcessInstanceListPresenter.ProcessInstanceListView, RequiresResize {
private Constants constants = GWT.create(Constants.class);
private ProcessRuntimeImages images = GWT.create(ProcessRuntimeImages.class);
@Inject
private Identity identity;
@Inject
private PlaceManager placeManager;
private ProcessInstanceListPresenter presenter;
private String currentFilter = "";
@Inject
@DataField
public LayoutPanel listContainer;
@Inject
@DataField
public NavLink showAllLink;
@Inject
@DataField
public NavLink showCompletedLink;
@Inject
@DataField
public NavLink showAbortedLink;
@Inject
@DataField
public NavLink showRelatedToMeLink;
@Inject
@DataField
public NavLink fiterLabel;
@Inject
@DataField
public DataGrid<ProcessInstanceSummary> processInstanceListGrid;
@DataField
public SimplePager pager;
private Set<ProcessInstanceSummary> selectedProcessInstances;
@Inject
private Event<NotificationEvent> notification;
@Inject
private Event<ProcessInstanceSelectionEvent> processInstanceSelected;
private ListHandler<ProcessInstanceSummary> sortHandler;
public ProcessInstanceListViewImpl() {
pager = new SimplePager(SimplePager.TextLocation.LEFT, false, true);
}
public String getCurrentFilter() {
return currentFilter;
}
public void setCurrentFilter(String currentFilter) {
this.currentFilter = currentFilter;
}
@Override
public void init(final ProcessInstanceListPresenter presenter) {
this.presenter = presenter;
listContainer.add(processInstanceListGrid);
pager.setDisplay(processInstanceListGrid);
pager.setPageSize(10);
fiterLabel.setText(constants.Showing());
showAllLink.setText(constants.Active());
showAllLink.setStyleName("active");
showAllLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
showAllLink.setStyleName("active");
showCompletedLink.setStyleName("");
showAbortedLink.setStyleName("");
showRelatedToMeLink.setStyleName("");
presenter.refreshActiveProcessList();
}
});
showCompletedLink.setText(constants.Completed());
showCompletedLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
showAllLink.setStyleName("");
showCompletedLink.setStyleName("active");
showAbortedLink.setStyleName("");
showRelatedToMeLink.setStyleName("");
presenter.refreshCompletedProcessList();
}
});
showAbortedLink.setText(constants.Aborted());
showAbortedLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
showAllLink.setStyleName("");
showCompletedLink.setStyleName("");
showAbortedLink.setStyleName("active");
showRelatedToMeLink.setStyleName("");
presenter.refreshAbortedProcessList();
}
});
showRelatedToMeLink.setText(constants.Related_To_Me());
showRelatedToMeLink.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
showAllLink.setStyleName("");
showCompletedLink.setStyleName("");
showAbortedLink.setStyleName("");
showRelatedToMeLink.setStyleName("active");
presenter.refreshRelatedToMeProcessList();
}
});
// Set the message to display when the table is empty.
Label emptyTable = new Label(constants.No_Process_Instances_Found());
emptyTable.setStyleName("");
processInstanceListGrid.setEmptyTableWidget(emptyTable);
// Attach a column sort handler to the ListDataProvider to sort the list.
sortHandler = new ListHandler<ProcessInstanceSummary>(presenter.getDataProvider().getList());
processInstanceListGrid.addColumnSortHandler(sortHandler);
// Create a Pager to control the table.
pager.setDisplay(processInstanceListGrid);
pager.setPageSize(10);
// Add a selection model so we can select cells.
final MultiSelectionModel<ProcessInstanceSummary> selectionModel = new MultiSelectionModel<ProcessInstanceSummary>();
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
@Override
public void onSelectionChange(SelectionChangeEvent event) {
selectedProcessInstances = selectionModel.getSelectedSet();
}
});
processInstanceListGrid.setSelectionModel(selectionModel,
DefaultSelectionEventManager.<ProcessInstanceSummary>createCheckboxManager());
initTableColumns(selectionModel);
presenter.addDataDisplay(processInstanceListGrid);
}
@Override
public DataGrid<ProcessInstanceSummary> getProcessInstanceListGrid() {
return processInstanceListGrid;
}
@Override
public Set<ProcessInstanceSummary> getSelectedProcessInstances() {
return selectedProcessInstances;
}
public void onProcessInstanceSelectionEvent(@Observes ProcessInstancesWithDetailsRequestEvent event) {
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(event.getDeploymentId(), event.getProcessInstanceId(), event.getProcessDefId()));
}
private void initTableColumns(final SelectionModel<ProcessInstanceSummary> selectionModel) {
processInstanceListGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<ProcessInstanceSummary>() {
@Override
public void onCellPreview(final CellPreviewEvent<ProcessInstanceSummary> event) {
ProcessInstanceSummary processInstance = null;
if (BrowserEvents.CLICK.equalsIgnoreCase(event.getNativeEvent().getType())) {
int column = event.getColumn();
int columnCount = processInstanceListGrid.getColumnCount();
if (column != columnCount - 1) {
processInstance = event.getValue();
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
}
}
if (BrowserEvents.FOCUS.equalsIgnoreCase(event.getNativeEvent().getType())) {
if (DataGridUtils.newProcessInstanceId != null) {
changeRowSelected(new ProcessInstanceStyleEvent(DataGridUtils.newProcessInstanceId,
DataGridUtils.newProcessInstanceDefName,
DataGridUtils.newProcessInstanceDefVersion,
DataGridUtils.newProcessInstanceStartDate));
}
}
}
});
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call dataGrid.setSelectionEnabled(true) to enable
// mouse selection.
Column<ProcessInstanceSummary, Boolean> checkColumn = new Column<ProcessInstanceSummary, Boolean>(new CheckboxCell(
true, false)) {
@Override
public Boolean getValue(ProcessInstanceSummary object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
processInstanceListGrid.addColumn(checkColumn, new ResizableHeader("", processInstanceListGrid,
checkColumn));
processInstanceListGrid.setColumnWidth(checkColumn, "40px");
// Process Instance Id.
Column<ProcessInstanceSummary, String> processInstanceIdColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return String.valueOf(object.getId());
}
};
processInstanceIdColumn.setSortable(true);
sortHandler.setComparator(processInstanceIdColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Long.valueOf(o1.getId()).compareTo(o2.getId());
}
});
processInstanceListGrid.addColumn(processInstanceIdColumn, new ResizableHeader(constants.Id(), processInstanceListGrid,
processInstanceIdColumn));
// Process Name.
Column<ProcessInstanceSummary, String> processNameColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessName();
}
};
processNameColumn.setSortable(true);
sortHandler.setComparator(processNameColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
- return o1.getProcessId().compareTo(o2.getProcessId());
+ return o1.getProcessName().toLowerCase().compareTo(o2.getProcessName().toLowerCase());
}
});
processInstanceListGrid.addColumn(processNameColumn, new ResizableHeader(constants.Name(), processInstanceListGrid,
processNameColumn));
Column<ProcessInstanceSummary, String> processInitiatorColumn = new Column<ProcessInstanceSummary, String>(
new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getInitiator();
}
};
processInitiatorColumn.setSortable(true);
sortHandler.setComparator(processInitiatorColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getInitiator().compareTo(o2.getInitiator());
}
});
processInstanceListGrid.addColumn(processInitiatorColumn, new ResizableHeader(constants.Initiator(),
processInstanceListGrid, processInitiatorColumn));
// Process Version.
Column<ProcessInstanceSummary, String> processVersionColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessVersion();
}
};
processVersionColumn.setSortable(true);
sortHandler.setComparator(processVersionColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
- return o1.getProcessVersion().compareTo(o2.getProcessVersion());
+ Integer version1;
+ Integer version2;
+ try{
+ version1 = Integer.valueOf(o1.getProcessVersion());
+ version2 = Integer.valueOf(o2.getProcessVersion());
+ return version1.compareTo(version2);
+ }catch(NumberFormatException nfe){
+ return o1.getProcessVersion().compareTo(o2.getProcessVersion());
+ }
}
});
processInstanceListGrid.addColumn(processVersionColumn, new ResizableHeader(constants.Version(),
processInstanceListGrid, processVersionColumn));
processInstanceListGrid.setColumnWidth(processVersionColumn, "90px");
// Process State
Column<ProcessInstanceSummary, String> processStateColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
String statusStr = constants.Unknown();
switch (object.getState()) {
case ProcessInstance.STATE_ACTIVE:
statusStr = constants.Active();
break;
case ProcessInstance.STATE_ABORTED:
statusStr = constants.Aborted();
break;
case ProcessInstance.STATE_COMPLETED:
statusStr = constants.Completed();
break;
case ProcessInstance.STATE_PENDING:
statusStr = constants.Pending();
break;
case ProcessInstance.STATE_SUSPENDED:
statusStr = constants.Suspended();
break;
default:
break;
}
return statusStr;
}
};
processStateColumn.setSortable(true);
sortHandler.setComparator(processStateColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Integer.valueOf(o1.getState()).compareTo(o2.getState());
}
});
processInstanceListGrid.addColumn(processStateColumn, new ResizableHeader(constants.State(), processInstanceListGrid,
processStateColumn));
processInstanceListGrid.setColumnWidth(processStateColumn, "100px");
// start time
Column<ProcessInstanceSummary, String> startTimeColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
Date expirationTime = object.getStartTime();
DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm");
return format.format(expirationTime);
}
};
startTimeColumn.setSortable(true);
sortHandler.setComparator(startTimeColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getStartTime().compareTo(o2.getStartTime());
}
});
processInstanceListGrid.addColumn(startTimeColumn, new ResizableHeader(constants.Start_Date(), processInstanceListGrid,
startTimeColumn));
List<HasCell<ProcessInstanceSummary, ?>> cells = new LinkedList<HasCell<ProcessInstanceSummary, ?>>();
cells.add(new DetailsActionHasCell("Details", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceStatus status = placeManager.getStatus(new DefaultPlaceRequest("Process Instance Details"));
String nameSelected = DataGridUtils.getProcessInstanceNameRowSelected(processInstanceListGrid);
String versionSelected = DataGridUtils.getProcessInstanceVersionRowSelected(processInstanceListGrid);
String startDateSelected = DataGridUtils.getProcessInstanceStartDateRowSelected(processInstanceListGrid);
if (status == PlaceStatus.CLOSE || !(processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
} else if (status == PlaceStatus.OPEN || (processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.closePlace(new DefaultPlaceRequest("Process Instance Details"));
}
}
}));
cells.add(new SignalActionHasCell("Singal", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceRequest placeRequestImpl = new DefaultPlaceRequest("Signal Process Popup");
placeRequestImpl.addParameter("processInstanceId", Long.toString(processInstance.getId()));
placeManager.goTo(placeRequestImpl);
}
}));
cells.add(new AbortActionHasCell("Abort", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
if (Window.confirm("Are you sure that you want to abort the process instance?")) {
presenter.abortProcessInstance(processInstance.getId());
}
}
}));
CompositeCell<ProcessInstanceSummary> cell = new CompositeCell<ProcessInstanceSummary>(cells);
Column<ProcessInstanceSummary, ProcessInstanceSummary> actionsColumn = new Column<ProcessInstanceSummary, ProcessInstanceSummary>(
cell) {
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
};
processInstanceListGrid.addColumn(actionsColumn, new ResizableHeader(constants.Actions(), processInstanceListGrid,
actionsColumn));
processInstanceListGrid.setColumnWidth(actionsColumn, "100px");
}
public void changeRowSelected(@Observes ProcessInstanceStyleEvent processInstanceStyleEvent) {
if (processInstanceStyleEvent.getProcessInstanceId() != null) {
DataGridUtils.paintInstanceRowSelected(processInstanceListGrid,
processInstanceStyleEvent.getProcessInstanceId());
processInstanceListGrid.setFocus(true);
}
}
@Override
public void displayNotification(String text) {
notification.fire(new NotificationEvent(text));
}
@Override
public DataGrid<ProcessInstanceSummary> getDataGrid() {
return processInstanceListGrid;
}
public ListHandler<ProcessInstanceSummary> getSortHandler() {
return sortHandler;
}
@Override
public void onResize() {
if ((getParent().getOffsetHeight() - 120) > 0) {
listContainer.setHeight(getParent().getOffsetHeight() - 120 + "px");
}
}
private class DetailsActionHasCell implements HasCell<ProcessInstanceSummary, ProcessInstanceSummary> {
private ActionCell<ProcessInstanceSummary> cell;
public DetailsActionHasCell(String text,
Delegate<ProcessInstanceSummary> delegate) {
cell = new ActionCell<ProcessInstanceSummary>(text, delegate) {
@Override
public void render(Cell.Context context,
ProcessInstanceSummary value,
SafeHtmlBuilder sb) {
AbstractImagePrototype imageProto = AbstractImagePrototype.create(images.detailsGridIcon());
SafeHtmlBuilder mysb = new SafeHtmlBuilder();
mysb.appendHtmlConstant("<span title='" + constants.Details() + "' style='margin-right:5px;'>");
mysb.append(imageProto.getSafeHtml());
mysb.appendHtmlConstant("</span>");
sb.append(mysb.toSafeHtml());
}
};
}
@Override
public Cell<ProcessInstanceSummary> getCell() {
return cell;
}
@Override
public FieldUpdater<ProcessInstanceSummary, ProcessInstanceSummary> getFieldUpdater() {
return null;
}
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
}
private class AbortActionHasCell implements HasCell<ProcessInstanceSummary, ProcessInstanceSummary> {
private ActionCell<ProcessInstanceSummary> cell;
public AbortActionHasCell(String text,
Delegate<ProcessInstanceSummary> delegate) {
cell = new ActionCell<ProcessInstanceSummary>(text, delegate) {
@Override
public void render(Cell.Context context,
ProcessInstanceSummary value,
SafeHtmlBuilder sb) {
if (value.getState() == ProcessInstance.STATE_ACTIVE) {
AbstractImagePrototype imageProto = AbstractImagePrototype.create(images.abortGridIcon());
SafeHtmlBuilder mysb = new SafeHtmlBuilder();
mysb.appendHtmlConstant("<span title='" + constants.Abort() + "' style='margin-right:5px;'>");
mysb.append(imageProto.getSafeHtml());
mysb.appendHtmlConstant("</span>");
sb.append(mysb.toSafeHtml());
}
}
};
}
@Override
public Cell<ProcessInstanceSummary> getCell() {
return cell;
}
@Override
public FieldUpdater<ProcessInstanceSummary, ProcessInstanceSummary> getFieldUpdater() {
return null;
}
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
}
private class SignalActionHasCell implements HasCell<ProcessInstanceSummary, ProcessInstanceSummary> {
private ActionCell<ProcessInstanceSummary> cell;
public SignalActionHasCell(String text,
Delegate<ProcessInstanceSummary> delegate) {
cell = new ActionCell<ProcessInstanceSummary>(text, delegate) {
@Override
public void render(Cell.Context context,
ProcessInstanceSummary value,
SafeHtmlBuilder sb) {
if (value.getState() == ProcessInstance.STATE_ACTIVE) {
AbstractImagePrototype imageProto = AbstractImagePrototype.create(images.signalGridIcon());
SafeHtmlBuilder mysb = new SafeHtmlBuilder();
mysb.appendHtmlConstant("<span title='" + constants.Signal() + "' style='margin-right:5px;'>");
mysb.append(imageProto.getSafeHtml());
mysb.appendHtmlConstant("</span>");
sb.append(mysb.toSafeHtml());
}
}
};
}
@Override
public Cell<ProcessInstanceSummary> getCell() {
return cell;
}
@Override
public FieldUpdater<ProcessInstanceSummary, ProcessInstanceSummary> getFieldUpdater() {
return null;
}
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
}
public void formClosed(@Observes BeforeClosePlaceEvent closed) {
if ("Signal Process Popup".equals(closed.getPlace().getIdentifier())) {
presenter.refreshActiveProcessList();
}
}
public NavLink getShowAllLink() {
return showAllLink;
}
public NavLink getShowCompletedLink() {
return showCompletedLink;
}
public NavLink getShowAbortedLink() {
return showAbortedLink;
}
public NavLink getShowRelatedToMeLink() {
return showRelatedToMeLink;
}
}
| false | true | private void initTableColumns(final SelectionModel<ProcessInstanceSummary> selectionModel) {
processInstanceListGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<ProcessInstanceSummary>() {
@Override
public void onCellPreview(final CellPreviewEvent<ProcessInstanceSummary> event) {
ProcessInstanceSummary processInstance = null;
if (BrowserEvents.CLICK.equalsIgnoreCase(event.getNativeEvent().getType())) {
int column = event.getColumn();
int columnCount = processInstanceListGrid.getColumnCount();
if (column != columnCount - 1) {
processInstance = event.getValue();
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
}
}
if (BrowserEvents.FOCUS.equalsIgnoreCase(event.getNativeEvent().getType())) {
if (DataGridUtils.newProcessInstanceId != null) {
changeRowSelected(new ProcessInstanceStyleEvent(DataGridUtils.newProcessInstanceId,
DataGridUtils.newProcessInstanceDefName,
DataGridUtils.newProcessInstanceDefVersion,
DataGridUtils.newProcessInstanceStartDate));
}
}
}
});
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call dataGrid.setSelectionEnabled(true) to enable
// mouse selection.
Column<ProcessInstanceSummary, Boolean> checkColumn = new Column<ProcessInstanceSummary, Boolean>(new CheckboxCell(
true, false)) {
@Override
public Boolean getValue(ProcessInstanceSummary object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
processInstanceListGrid.addColumn(checkColumn, new ResizableHeader("", processInstanceListGrid,
checkColumn));
processInstanceListGrid.setColumnWidth(checkColumn, "40px");
// Process Instance Id.
Column<ProcessInstanceSummary, String> processInstanceIdColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return String.valueOf(object.getId());
}
};
processInstanceIdColumn.setSortable(true);
sortHandler.setComparator(processInstanceIdColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Long.valueOf(o1.getId()).compareTo(o2.getId());
}
});
processInstanceListGrid.addColumn(processInstanceIdColumn, new ResizableHeader(constants.Id(), processInstanceListGrid,
processInstanceIdColumn));
// Process Name.
Column<ProcessInstanceSummary, String> processNameColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessName();
}
};
processNameColumn.setSortable(true);
sortHandler.setComparator(processNameColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getProcessId().compareTo(o2.getProcessId());
}
});
processInstanceListGrid.addColumn(processNameColumn, new ResizableHeader(constants.Name(), processInstanceListGrid,
processNameColumn));
Column<ProcessInstanceSummary, String> processInitiatorColumn = new Column<ProcessInstanceSummary, String>(
new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getInitiator();
}
};
processInitiatorColumn.setSortable(true);
sortHandler.setComparator(processInitiatorColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getInitiator().compareTo(o2.getInitiator());
}
});
processInstanceListGrid.addColumn(processInitiatorColumn, new ResizableHeader(constants.Initiator(),
processInstanceListGrid, processInitiatorColumn));
// Process Version.
Column<ProcessInstanceSummary, String> processVersionColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessVersion();
}
};
processVersionColumn.setSortable(true);
sortHandler.setComparator(processVersionColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getProcessVersion().compareTo(o2.getProcessVersion());
}
});
processInstanceListGrid.addColumn(processVersionColumn, new ResizableHeader(constants.Version(),
processInstanceListGrid, processVersionColumn));
processInstanceListGrid.setColumnWidth(processVersionColumn, "90px");
// Process State
Column<ProcessInstanceSummary, String> processStateColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
String statusStr = constants.Unknown();
switch (object.getState()) {
case ProcessInstance.STATE_ACTIVE:
statusStr = constants.Active();
break;
case ProcessInstance.STATE_ABORTED:
statusStr = constants.Aborted();
break;
case ProcessInstance.STATE_COMPLETED:
statusStr = constants.Completed();
break;
case ProcessInstance.STATE_PENDING:
statusStr = constants.Pending();
break;
case ProcessInstance.STATE_SUSPENDED:
statusStr = constants.Suspended();
break;
default:
break;
}
return statusStr;
}
};
processStateColumn.setSortable(true);
sortHandler.setComparator(processStateColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Integer.valueOf(o1.getState()).compareTo(o2.getState());
}
});
processInstanceListGrid.addColumn(processStateColumn, new ResizableHeader(constants.State(), processInstanceListGrid,
processStateColumn));
processInstanceListGrid.setColumnWidth(processStateColumn, "100px");
// start time
Column<ProcessInstanceSummary, String> startTimeColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
Date expirationTime = object.getStartTime();
DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm");
return format.format(expirationTime);
}
};
startTimeColumn.setSortable(true);
sortHandler.setComparator(startTimeColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getStartTime().compareTo(o2.getStartTime());
}
});
processInstanceListGrid.addColumn(startTimeColumn, new ResizableHeader(constants.Start_Date(), processInstanceListGrid,
startTimeColumn));
List<HasCell<ProcessInstanceSummary, ?>> cells = new LinkedList<HasCell<ProcessInstanceSummary, ?>>();
cells.add(new DetailsActionHasCell("Details", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceStatus status = placeManager.getStatus(new DefaultPlaceRequest("Process Instance Details"));
String nameSelected = DataGridUtils.getProcessInstanceNameRowSelected(processInstanceListGrid);
String versionSelected = DataGridUtils.getProcessInstanceVersionRowSelected(processInstanceListGrid);
String startDateSelected = DataGridUtils.getProcessInstanceStartDateRowSelected(processInstanceListGrid);
if (status == PlaceStatus.CLOSE || !(processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
} else if (status == PlaceStatus.OPEN || (processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.closePlace(new DefaultPlaceRequest("Process Instance Details"));
}
}
}));
cells.add(new SignalActionHasCell("Singal", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceRequest placeRequestImpl = new DefaultPlaceRequest("Signal Process Popup");
placeRequestImpl.addParameter("processInstanceId", Long.toString(processInstance.getId()));
placeManager.goTo(placeRequestImpl);
}
}));
cells.add(new AbortActionHasCell("Abort", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
if (Window.confirm("Are you sure that you want to abort the process instance?")) {
presenter.abortProcessInstance(processInstance.getId());
}
}
}));
CompositeCell<ProcessInstanceSummary> cell = new CompositeCell<ProcessInstanceSummary>(cells);
Column<ProcessInstanceSummary, ProcessInstanceSummary> actionsColumn = new Column<ProcessInstanceSummary, ProcessInstanceSummary>(
cell) {
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
};
processInstanceListGrid.addColumn(actionsColumn, new ResizableHeader(constants.Actions(), processInstanceListGrid,
actionsColumn));
processInstanceListGrid.setColumnWidth(actionsColumn, "100px");
}
| private void initTableColumns(final SelectionModel<ProcessInstanceSummary> selectionModel) {
processInstanceListGrid.addCellPreviewHandler(new CellPreviewEvent.Handler<ProcessInstanceSummary>() {
@Override
public void onCellPreview(final CellPreviewEvent<ProcessInstanceSummary> event) {
ProcessInstanceSummary processInstance = null;
if (BrowserEvents.CLICK.equalsIgnoreCase(event.getNativeEvent().getType())) {
int column = event.getColumn();
int columnCount = processInstanceListGrid.getColumnCount();
if (column != columnCount - 1) {
processInstance = event.getValue();
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
}
}
if (BrowserEvents.FOCUS.equalsIgnoreCase(event.getNativeEvent().getType())) {
if (DataGridUtils.newProcessInstanceId != null) {
changeRowSelected(new ProcessInstanceStyleEvent(DataGridUtils.newProcessInstanceId,
DataGridUtils.newProcessInstanceDefName,
DataGridUtils.newProcessInstanceDefVersion,
DataGridUtils.newProcessInstanceStartDate));
}
}
}
});
// Checkbox column. This table will uses a checkbox column for selection.
// Alternatively, you can call dataGrid.setSelectionEnabled(true) to enable
// mouse selection.
Column<ProcessInstanceSummary, Boolean> checkColumn = new Column<ProcessInstanceSummary, Boolean>(new CheckboxCell(
true, false)) {
@Override
public Boolean getValue(ProcessInstanceSummary object) {
// Get the value from the selection model.
return selectionModel.isSelected(object);
}
};
processInstanceListGrid.addColumn(checkColumn, new ResizableHeader("", processInstanceListGrid,
checkColumn));
processInstanceListGrid.setColumnWidth(checkColumn, "40px");
// Process Instance Id.
Column<ProcessInstanceSummary, String> processInstanceIdColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return String.valueOf(object.getId());
}
};
processInstanceIdColumn.setSortable(true);
sortHandler.setComparator(processInstanceIdColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Long.valueOf(o1.getId()).compareTo(o2.getId());
}
});
processInstanceListGrid.addColumn(processInstanceIdColumn, new ResizableHeader(constants.Id(), processInstanceListGrid,
processInstanceIdColumn));
// Process Name.
Column<ProcessInstanceSummary, String> processNameColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessName();
}
};
processNameColumn.setSortable(true);
sortHandler.setComparator(processNameColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getProcessName().toLowerCase().compareTo(o2.getProcessName().toLowerCase());
}
});
processInstanceListGrid.addColumn(processNameColumn, new ResizableHeader(constants.Name(), processInstanceListGrid,
processNameColumn));
Column<ProcessInstanceSummary, String> processInitiatorColumn = new Column<ProcessInstanceSummary, String>(
new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getInitiator();
}
};
processInitiatorColumn.setSortable(true);
sortHandler.setComparator(processInitiatorColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getInitiator().compareTo(o2.getInitiator());
}
});
processInstanceListGrid.addColumn(processInitiatorColumn, new ResizableHeader(constants.Initiator(),
processInstanceListGrid, processInitiatorColumn));
// Process Version.
Column<ProcessInstanceSummary, String> processVersionColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
return object.getProcessVersion();
}
};
processVersionColumn.setSortable(true);
sortHandler.setComparator(processVersionColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
Integer version1;
Integer version2;
try{
version1 = Integer.valueOf(o1.getProcessVersion());
version2 = Integer.valueOf(o2.getProcessVersion());
return version1.compareTo(version2);
}catch(NumberFormatException nfe){
return o1.getProcessVersion().compareTo(o2.getProcessVersion());
}
}
});
processInstanceListGrid.addColumn(processVersionColumn, new ResizableHeader(constants.Version(),
processInstanceListGrid, processVersionColumn));
processInstanceListGrid.setColumnWidth(processVersionColumn, "90px");
// Process State
Column<ProcessInstanceSummary, String> processStateColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
String statusStr = constants.Unknown();
switch (object.getState()) {
case ProcessInstance.STATE_ACTIVE:
statusStr = constants.Active();
break;
case ProcessInstance.STATE_ABORTED:
statusStr = constants.Aborted();
break;
case ProcessInstance.STATE_COMPLETED:
statusStr = constants.Completed();
break;
case ProcessInstance.STATE_PENDING:
statusStr = constants.Pending();
break;
case ProcessInstance.STATE_SUSPENDED:
statusStr = constants.Suspended();
break;
default:
break;
}
return statusStr;
}
};
processStateColumn.setSortable(true);
sortHandler.setComparator(processStateColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return Integer.valueOf(o1.getState()).compareTo(o2.getState());
}
});
processInstanceListGrid.addColumn(processStateColumn, new ResizableHeader(constants.State(), processInstanceListGrid,
processStateColumn));
processInstanceListGrid.setColumnWidth(processStateColumn, "100px");
// start time
Column<ProcessInstanceSummary, String> startTimeColumn = new Column<ProcessInstanceSummary, String>(new TextCell()) {
@Override
public String getValue(ProcessInstanceSummary object) {
Date expirationTime = object.getStartTime();
DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm");
return format.format(expirationTime);
}
};
startTimeColumn.setSortable(true);
sortHandler.setComparator(startTimeColumn, new Comparator<ProcessInstanceSummary>() {
@Override
public int compare(ProcessInstanceSummary o1,
ProcessInstanceSummary o2) {
return o1.getStartTime().compareTo(o2.getStartTime());
}
});
processInstanceListGrid.addColumn(startTimeColumn, new ResizableHeader(constants.Start_Date(), processInstanceListGrid,
startTimeColumn));
List<HasCell<ProcessInstanceSummary, ?>> cells = new LinkedList<HasCell<ProcessInstanceSummary, ?>>();
cells.add(new DetailsActionHasCell("Details", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceStatus status = placeManager.getStatus(new DefaultPlaceRequest("Process Instance Details"));
String nameSelected = DataGridUtils.getProcessInstanceNameRowSelected(processInstanceListGrid);
String versionSelected = DataGridUtils.getProcessInstanceVersionRowSelected(processInstanceListGrid);
String startDateSelected = DataGridUtils.getProcessInstanceStartDateRowSelected(processInstanceListGrid);
if (status == PlaceStatus.CLOSE || !(processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.goTo("Process Instance Details");
processInstanceSelected.fire(new ProcessInstanceSelectionEvent(processInstance.getDeploymentId(),
processInstance.getId(), processInstance.getProcessId()));
} else if (status == PlaceStatus.OPEN || (processInstance.getProcessName().equals(nameSelected)
&& processInstance.getProcessVersion().equals(versionSelected)
&& processInstance.getStartTime().equals(startDateSelected))) {
placeManager.closePlace(new DefaultPlaceRequest("Process Instance Details"));
}
}
}));
cells.add(new SignalActionHasCell("Singal", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
PlaceRequest placeRequestImpl = new DefaultPlaceRequest("Signal Process Popup");
placeRequestImpl.addParameter("processInstanceId", Long.toString(processInstance.getId()));
placeManager.goTo(placeRequestImpl);
}
}));
cells.add(new AbortActionHasCell("Abort", new Delegate<ProcessInstanceSummary>() {
@Override
public void execute(ProcessInstanceSummary processInstance) {
if (Window.confirm("Are you sure that you want to abort the process instance?")) {
presenter.abortProcessInstance(processInstance.getId());
}
}
}));
CompositeCell<ProcessInstanceSummary> cell = new CompositeCell<ProcessInstanceSummary>(cells);
Column<ProcessInstanceSummary, ProcessInstanceSummary> actionsColumn = new Column<ProcessInstanceSummary, ProcessInstanceSummary>(
cell) {
@Override
public ProcessInstanceSummary getValue(ProcessInstanceSummary object) {
return object;
}
};
processInstanceListGrid.addColumn(actionsColumn, new ResizableHeader(constants.Actions(), processInstanceListGrid,
actionsColumn));
processInstanceListGrid.setColumnWidth(actionsColumn, "100px");
}
|
diff --git a/stanford-sw/src/edu/stanford/Item.java b/stanford-sw/src/edu/stanford/Item.java
index c498439..f554f92 100644
--- a/stanford-sw/src/edu/stanford/Item.java
+++ b/stanford-sw/src/edu/stanford/Item.java
@@ -1,517 +1,517 @@
package edu.stanford;
import java.util.regex.Pattern;
import org.marc4j.marc.DataField;
import org.solrmarc.tools.CallNumUtils;
import org.solrmarc.tools.MarcUtils;
import edu.stanford.enumValues.CallNumberType;
/**
* Item object for Stanford SolrMarc
* @author Naomi Dushay
*/
public class Item {
/** call number for SUL online items */
public final static String ECALLNUM = "INTERNET RESOURCE";
/** location code for online items */
public final static String ELOC = "INTERNET";
/** temporary call numbers (in process, on order ..) should start with this prefix */
public final static String TMP_CALLNUM_PREFIX = "XX";
/* immutable instance variables */
private final String recId;
private final String barcode;
private final String library;
private final String itemType;
private final boolean shouldBeSkipped;
private final boolean hasGovDocLoc;
private final boolean isOnline;
private final boolean hasShelbyLoc;
private final boolean hasBizShelbyLoc;
/* normal instance variables */
private CallNumberType callnumType;
private String homeLoc;
private String currLoc;
private String normCallnum;
private boolean isOnOrder = false;
private boolean isInProcess = false;
private boolean hasIgnoredCallnum = false;
private boolean hasBadLcLaneCallnum = false;
private boolean isMissingLost = false;
private boolean hasSeparateBrowseCallnum = false;
/** call number with volume suffix lopped off the end. Used to remove
* noise in search results and in browsing */
private String loppedCallnum = null;
/** set when there is a callnumber for browsing different from that in the 999 */
private String browseCallnum = null;
/** sortable version of lopped call number */
private String loppedShelfkey = null;
/** reverse sorted version of loppedShelfkey - the last call number shall
* be first, etc. */
private String reverseLoppedShelfkey = null;
/** sortable full call number, where, for serials, any volume suffix will sort
* in descending order. Non-serial volumes will sort in ascending order. */
private String callnumVolSort = null;
/**
* initialize object from 999 DataField, which has the following subfields
* <ul>
* <li>a - call num</li>
* <li>i - barcode</li>
* <li>k - current location</li>
* <li>l - home location</li>
* <li>m - library code</li>
* <li>o - public note</li>
* <li>t - item type</li>
* <li>w - call num scheme</li>
* </ul>
*/
public Item(DataField f999, String recId) {
// set all the immutable variables
this.recId = recId;
barcode = MarcUtils.getSubfieldTrimmed(f999, 'i');
currLoc = MarcUtils.getSubfieldTrimmed(f999, 'k');
homeLoc = MarcUtils.getSubfieldTrimmed(f999, 'l');
library = MarcUtils.getSubfieldTrimmed(f999, 'm');
itemType = MarcUtils.getSubfieldTrimmed(f999, 't');
String scheme = MarcUtils.getSubfieldTrimmed(f999, 'w');
String rawCallnum = MarcUtils.getSubfieldTrimmed(f999, 'a');
if (StanfordIndexer.SKIPPED_LOCS.contains(currLoc)
|| StanfordIndexer.SKIPPED_LOCS.contains(homeLoc)
|| itemType.equals("EDI-REMOVE"))
shouldBeSkipped = true;
else
shouldBeSkipped = false;
if (StanfordIndexer.GOV_DOC_LOCS.contains(currLoc)
|| StanfordIndexer.GOV_DOC_LOCS.contains(homeLoc) )
hasGovDocLoc = true;
else
hasGovDocLoc = false;
if (StanfordIndexer.MISSING_LOCS.contains(currLoc)
|| StanfordIndexer.MISSING_LOCS.contains(homeLoc) )
isMissingLost = true;
else
isMissingLost = false;
- if (library == "BUSINESS"
+ if (library.equals("BUSINESS")
&& (StanfordIndexer.BIZ_SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.BIZ_SHELBY_LOCS.contains(homeLoc) ) )
hasBizShelbyLoc = true;
else
hasBizShelbyLoc = false;
if (StanfordIndexer.SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.SHELBY_LOCS.contains(homeLoc) )
hasShelbyLoc = true;
else if (hasBizShelbyLoc)
hasShelbyLoc = true;
else
hasShelbyLoc = false;
if (StanfordIndexer.SKIPPED_CALLNUMS.contains(rawCallnum)
|| rawCallnum.startsWith(ECALLNUM)
|| rawCallnum.startsWith(TMP_CALLNUM_PREFIX))
hasIgnoredCallnum = true;
else
hasIgnoredCallnum = false;
assignCallnumType(scheme);
if (!hasIgnoredCallnum) {
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
normCallnum = CallNumUtils.normalizeCallnum(rawCallnum);
else
normCallnum = rawCallnum.trim();
validateCallnum(recId);
}
else
normCallnum = rawCallnum.trim();
// isOnline is immutable so must be set here
if (StanfordIndexer.ONLINE_LOCS.contains(currLoc)
|| StanfordIndexer.ONLINE_LOCS.contains(homeLoc) //) {
|| normCallnum.startsWith(ECALLNUM) ) {
isOnline = true;
}
else
isOnline = false;
dealWithXXCallnums(recId);
}
public String getBarcode() {
return barcode;
}
public String getLibrary() {
return library;
}
public String getHomeLoc() {
return homeLoc;
}
public String getCurrLoc() {
return currLoc;
}
public String getType() {
return itemType;
}
public String getCallnum() {
return normCallnum;
}
public CallNumberType getCallnumType() {
return callnumType;
}
public void setCallnumType(CallNumberType callnumType) {
this.callnumType = callnumType;
}
/**
* @return true if this item has a current or home location indicating it
* should be skipped (e.g. "WITHDRAWN" or a shadowed location) or has
* a type of "EDI-REMOVE")
*/
public boolean shouldBeSkipped() {
return shouldBeSkipped;
}
/**
* @return true if item location indicating it is missing or lost
*/
public boolean isMissingOrLost() {
return isMissingLost;
}
/**
* @return true if item has a government doc location
*/
public boolean hasGovDocLoc() {
return hasGovDocLoc;
}
/**
* return true if item has a callnumber or location code indicating it is online
*/
public boolean isOnline() {
if (normCallnum.startsWith(ECALLNUM) || homeLoc.equals(ELOC) || currLoc.equals(ELOC))
return true;
else
return isOnline;
}
/**
* @return true if item is on order
*/
public boolean isOnOrder() {
return isOnOrder;
}
/**
* @return true if item is in process
*/
public boolean isInProcess() {
return isInProcess;
}
/**
* return true if item has a shelby location (current or home)
*/
public boolean hasShelbyLoc() {
return hasShelbyLoc;
}
/**
* return true if item has a business library only shelby location (current or home)
*/
public boolean hasBizShelbyLoc() {
return hasBizShelbyLoc;
}
/**
* @return true if call number is to be ignored in some contexts
* (e.g. "NO CALL NUMBER" or "XX(blah)")
*/
public boolean hasIgnoredCallnum() {
return hasIgnoredCallnum;
}
/**
* @return true if call number is Lane (Law) invalid LC callnum
*/
public boolean hasBadLcLaneCallnum() {
return hasBadLcLaneCallnum;
}
/**
* @return true if item has a call number from the bib fields
*/
public boolean hasSeparateBrowseCallnum() {
return hasSeparateBrowseCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will NOT set the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum() {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return loppedCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will SET the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum(boolean isSerial) {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return getLoppedCallnum(isSerial);
}
/**
* for resources that have items without browsable call numbers
* (SUL INTERNET RESOURCE), we look for a call number in the bib record
* fields (050, 090, 086 ...) for browse nearby and for call number facets.
* If one is found, this method is used.
*/
public void setBrowseCallnum(String callnum) {
hasSeparateBrowseCallnum = true;
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
browseCallnum = CallNumUtils.normalizeCallnum(callnum);
else
browseCallnum = callnum.trim();
}
/**
* get the lopped call number (any volume suffix is lopped off the end.)
* This will remove noise in search results and in browsing.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
public String getLoppedCallnum(boolean isSerial) {
if (loppedCallnum == null)
setLoppedCallnum(isSerial);
return loppedCallnum;
}
/**
* sets the private field loppedCallnum to contain the call number without
* any volume suffix information.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
private void setLoppedCallnum(boolean isSerial) {
loppedCallnum = edu.stanford.CallNumUtils.getLoppedCallnum(normCallnum, callnumType, isSerial);
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
loppedCallnum = loppedCallnum + " ...";
}
/**
* sets the private field loppedCallnum to the passed value. Used when
* lopping must be dictated elsewhere.
*/
void setLoppedCallnum(String loppedCallnum) {
this.loppedCallnum = loppedCallnum;
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
this.loppedCallnum = loppedCallnum + " ...";
}
/**
* get the sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
return loppedShelfkey;
}
/**
* sets the private field loppedShelfkey (and loppedCallnum if it's not
* already set). loppedShelfkey will contain the sortable version of the
* lopped call number
* @param isSerial - true if item is for a serial.
*/
private void setShelfkey(boolean isSerial) {
if (loppedShelfkey == null) {
String skeyCallnum = getBrowseCallnum(isSerial);
if (skeyCallnum != null && skeyCallnum.length() > 0
&& !StanfordIndexer.SKIPPED_CALLNUMS.contains(skeyCallnum)
&& !skeyCallnum.startsWith(ECALLNUM)
&& !skeyCallnum.startsWith(TMP_CALLNUM_PREFIX) )
loppedShelfkey = edu.stanford.CallNumUtils.getShelfKey(skeyCallnum, callnumType, recId);
}
}
/**
* get the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getReverseShelfkey(boolean isSerial) {
if (reverseLoppedShelfkey == null)
setReverseShelfkey(isSerial);
return reverseLoppedShelfkey;
}
/**
* sets the private field reverseLoppedShelfkey (and loppedShelfkey and
* loppedCallnum if they're not already set). reverseLoppedShelfkey will
* contain the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
private void setReverseShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
reverseLoppedShelfkey = CallNumUtils.getReverseShelfKey(loppedShelfkey);
}
/**
* get the sortable full call number, where, for serials, any volume suffix
* will sort in descending order. Non-serial volumes will sort in ascending
* order.
* @param isSerial - true if item is for a serial.
*/
public String getCallnumVolSort(boolean isSerial) {
if (callnumVolSort == null)
setCallnumVolSort(isSerial);
return callnumVolSort;
}
/**
* sets the private field callnumVolSort (and loppedShelfkey and
* loppedCallnum if they're not already set.) callnumVolSort will contain
* the sortable full call number, where, for serials, any volume suffix
* will sort in descending order.
* @param isSerial - true if item is for a serial.
*/
private void setCallnumVolSort(boolean isSerial) {
if (loppedShelfkey == null)
// note: setting loppedShelfkey will also set loppedCallnum
loppedShelfkey = getShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
callnumVolSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(
normCallnum, loppedCallnum, loppedShelfkey, callnumType, isSerial, recId);
}
/** call numbers must start with a letter or digit */
private static final Pattern STRANGE_CALLNUM_START_CHARS = Pattern.compile("^\\p{Alnum}");
/**
* output an error message if the call number is supposed to be LC or DEWEY
* but is invalid
* @param recId the id of the record, used in error message
*/
private void validateCallnum(String recId) {
if (callnumType == CallNumberType.LC
&& !CallNumUtils.isValidLC(normCallnum)) {
if (!library.equals("LANE-MED"))
System.err.println("record " + recId + " has invalid LC callnumber: " + normCallnum);
adjustLCCallnumType(recId);
}
if (callnumType == CallNumberType.DEWEY
&& !CallNumUtils.isValidDeweyWithCutter(normCallnum)) {
System.err.println("record " + recId + " has invalid DEWEY callnumber: " + normCallnum);
callnumType = CallNumberType.OTHER;
}
else if (STRANGE_CALLNUM_START_CHARS.matcher(normCallnum).matches())
System.err.println("record " + recId + " has strange callnumber: " + normCallnum);
}
/**
* LC is default call number scheme assigned; change it if assigned
* incorrectly to a Dewey or ALPHANUM call number. Called after
* printMsgIfInvalidCallnum has already found invalid LC call number
*/
private void adjustLCCallnumType(String id) {
if (callnumType == CallNumberType.LC) {
if (CallNumUtils.isValidDeweyWithCutter(normCallnum))
callnumType = CallNumberType.DEWEY;
else
{
// FIXME: this is no good if the call number is SUDOC but mislabeled LC ...
callnumType = CallNumberType.OTHER;
if (library.equals("LANE-MED"))
hasBadLcLaneCallnum = true;
}
}
}
/**
* if item has XX call number
* if home location or current location is INPROCESS or ON-ORDER, do
* the obvious thing
* if no home or current location, item is on order.
* o.w. if the current location isn't shadowed, it is an error;
* print an error message and fake "ON-ORDER"
* @param recId - for error message
*/
private void dealWithXXCallnums(String recId) {
if (normCallnum.startsWith(TMP_CALLNUM_PREFIX))
{
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else if (currLoc.equals("INPROCESS"))
isInProcess = true;
else if (shouldBeSkipped || currLoc.equals("LAC") || homeLoc.equals("LAC"))
; // we're okay
else if (currLoc.length() > 0) {
System.err.println("record " + recId + " has XX callnumber but current location is not ON-ORDER or INPROCESS or shadowy");
if (homeLoc.equals("ON-ORDER") || homeLoc.equals("INPROCESS")) {
currLoc = homeLoc;
homeLoc = "";
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else
isInProcess = true;
}
else {
currLoc = "ON-ORDER";
isOnOrder = true;
}
}
}
}
/**
* assign a value to callnumType based on scheme ...
* LCPER --> LC; DEWEYPER --> DEWEY
*/
private void assignCallnumType(String scheme) {
if (scheme.startsWith("LC"))
callnumType = CallNumberType.LC;
else if (scheme.startsWith("DEWEY"))
callnumType = CallNumberType.DEWEY;
else if (scheme.equals("SUDOC"))
callnumType = CallNumberType.SUDOC;
else
callnumType = CallNumberType.OTHER;
}
}
| true | true | public Item(DataField f999, String recId) {
// set all the immutable variables
this.recId = recId;
barcode = MarcUtils.getSubfieldTrimmed(f999, 'i');
currLoc = MarcUtils.getSubfieldTrimmed(f999, 'k');
homeLoc = MarcUtils.getSubfieldTrimmed(f999, 'l');
library = MarcUtils.getSubfieldTrimmed(f999, 'm');
itemType = MarcUtils.getSubfieldTrimmed(f999, 't');
String scheme = MarcUtils.getSubfieldTrimmed(f999, 'w');
String rawCallnum = MarcUtils.getSubfieldTrimmed(f999, 'a');
if (StanfordIndexer.SKIPPED_LOCS.contains(currLoc)
|| StanfordIndexer.SKIPPED_LOCS.contains(homeLoc)
|| itemType.equals("EDI-REMOVE"))
shouldBeSkipped = true;
else
shouldBeSkipped = false;
if (StanfordIndexer.GOV_DOC_LOCS.contains(currLoc)
|| StanfordIndexer.GOV_DOC_LOCS.contains(homeLoc) )
hasGovDocLoc = true;
else
hasGovDocLoc = false;
if (StanfordIndexer.MISSING_LOCS.contains(currLoc)
|| StanfordIndexer.MISSING_LOCS.contains(homeLoc) )
isMissingLost = true;
else
isMissingLost = false;
if (library == "BUSINESS"
&& (StanfordIndexer.BIZ_SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.BIZ_SHELBY_LOCS.contains(homeLoc) ) )
hasBizShelbyLoc = true;
else
hasBizShelbyLoc = false;
if (StanfordIndexer.SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.SHELBY_LOCS.contains(homeLoc) )
hasShelbyLoc = true;
else if (hasBizShelbyLoc)
hasShelbyLoc = true;
else
hasShelbyLoc = false;
if (StanfordIndexer.SKIPPED_CALLNUMS.contains(rawCallnum)
|| rawCallnum.startsWith(ECALLNUM)
|| rawCallnum.startsWith(TMP_CALLNUM_PREFIX))
hasIgnoredCallnum = true;
else
hasIgnoredCallnum = false;
assignCallnumType(scheme);
if (!hasIgnoredCallnum) {
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
normCallnum = CallNumUtils.normalizeCallnum(rawCallnum);
else
normCallnum = rawCallnum.trim();
validateCallnum(recId);
}
else
normCallnum = rawCallnum.trim();
// isOnline is immutable so must be set here
if (StanfordIndexer.ONLINE_LOCS.contains(currLoc)
|| StanfordIndexer.ONLINE_LOCS.contains(homeLoc) //) {
|| normCallnum.startsWith(ECALLNUM) ) {
isOnline = true;
}
else
isOnline = false;
dealWithXXCallnums(recId);
}
public String getBarcode() {
return barcode;
}
public String getLibrary() {
return library;
}
public String getHomeLoc() {
return homeLoc;
}
public String getCurrLoc() {
return currLoc;
}
public String getType() {
return itemType;
}
public String getCallnum() {
return normCallnum;
}
public CallNumberType getCallnumType() {
return callnumType;
}
public void setCallnumType(CallNumberType callnumType) {
this.callnumType = callnumType;
}
/**
* @return true if this item has a current or home location indicating it
* should be skipped (e.g. "WITHDRAWN" or a shadowed location) or has
* a type of "EDI-REMOVE")
*/
public boolean shouldBeSkipped() {
return shouldBeSkipped;
}
/**
* @return true if item location indicating it is missing or lost
*/
public boolean isMissingOrLost() {
return isMissingLost;
}
/**
* @return true if item has a government doc location
*/
public boolean hasGovDocLoc() {
return hasGovDocLoc;
}
/**
* return true if item has a callnumber or location code indicating it is online
*/
public boolean isOnline() {
if (normCallnum.startsWith(ECALLNUM) || homeLoc.equals(ELOC) || currLoc.equals(ELOC))
return true;
else
return isOnline;
}
/**
* @return true if item is on order
*/
public boolean isOnOrder() {
return isOnOrder;
}
/**
* @return true if item is in process
*/
public boolean isInProcess() {
return isInProcess;
}
/**
* return true if item has a shelby location (current or home)
*/
public boolean hasShelbyLoc() {
return hasShelbyLoc;
}
/**
* return true if item has a business library only shelby location (current or home)
*/
public boolean hasBizShelbyLoc() {
return hasBizShelbyLoc;
}
/**
* @return true if call number is to be ignored in some contexts
* (e.g. "NO CALL NUMBER" or "XX(blah)")
*/
public boolean hasIgnoredCallnum() {
return hasIgnoredCallnum;
}
/**
* @return true if call number is Lane (Law) invalid LC callnum
*/
public boolean hasBadLcLaneCallnum() {
return hasBadLcLaneCallnum;
}
/**
* @return true if item has a call number from the bib fields
*/
public boolean hasSeparateBrowseCallnum() {
return hasSeparateBrowseCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will NOT set the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum() {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return loppedCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will SET the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum(boolean isSerial) {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return getLoppedCallnum(isSerial);
}
/**
* for resources that have items without browsable call numbers
* (SUL INTERNET RESOURCE), we look for a call number in the bib record
* fields (050, 090, 086 ...) for browse nearby and for call number facets.
* If one is found, this method is used.
*/
public void setBrowseCallnum(String callnum) {
hasSeparateBrowseCallnum = true;
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
browseCallnum = CallNumUtils.normalizeCallnum(callnum);
else
browseCallnum = callnum.trim();
}
/**
* get the lopped call number (any volume suffix is lopped off the end.)
* This will remove noise in search results and in browsing.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
public String getLoppedCallnum(boolean isSerial) {
if (loppedCallnum == null)
setLoppedCallnum(isSerial);
return loppedCallnum;
}
/**
* sets the private field loppedCallnum to contain the call number without
* any volume suffix information.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
private void setLoppedCallnum(boolean isSerial) {
loppedCallnum = edu.stanford.CallNumUtils.getLoppedCallnum(normCallnum, callnumType, isSerial);
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
loppedCallnum = loppedCallnum + " ...";
}
/**
* sets the private field loppedCallnum to the passed value. Used when
* lopping must be dictated elsewhere.
*/
void setLoppedCallnum(String loppedCallnum) {
this.loppedCallnum = loppedCallnum;
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
this.loppedCallnum = loppedCallnum + " ...";
}
/**
* get the sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
return loppedShelfkey;
}
/**
* sets the private field loppedShelfkey (and loppedCallnum if it's not
* already set). loppedShelfkey will contain the sortable version of the
* lopped call number
* @param isSerial - true if item is for a serial.
*/
private void setShelfkey(boolean isSerial) {
if (loppedShelfkey == null) {
String skeyCallnum = getBrowseCallnum(isSerial);
if (skeyCallnum != null && skeyCallnum.length() > 0
&& !StanfordIndexer.SKIPPED_CALLNUMS.contains(skeyCallnum)
&& !skeyCallnum.startsWith(ECALLNUM)
&& !skeyCallnum.startsWith(TMP_CALLNUM_PREFIX) )
loppedShelfkey = edu.stanford.CallNumUtils.getShelfKey(skeyCallnum, callnumType, recId);
}
}
/**
* get the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getReverseShelfkey(boolean isSerial) {
if (reverseLoppedShelfkey == null)
setReverseShelfkey(isSerial);
return reverseLoppedShelfkey;
}
/**
* sets the private field reverseLoppedShelfkey (and loppedShelfkey and
* loppedCallnum if they're not already set). reverseLoppedShelfkey will
* contain the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
private void setReverseShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
reverseLoppedShelfkey = CallNumUtils.getReverseShelfKey(loppedShelfkey);
}
/**
* get the sortable full call number, where, for serials, any volume suffix
* will sort in descending order. Non-serial volumes will sort in ascending
* order.
* @param isSerial - true if item is for a serial.
*/
public String getCallnumVolSort(boolean isSerial) {
if (callnumVolSort == null)
setCallnumVolSort(isSerial);
return callnumVolSort;
}
/**
* sets the private field callnumVolSort (and loppedShelfkey and
* loppedCallnum if they're not already set.) callnumVolSort will contain
* the sortable full call number, where, for serials, any volume suffix
* will sort in descending order.
* @param isSerial - true if item is for a serial.
*/
private void setCallnumVolSort(boolean isSerial) {
if (loppedShelfkey == null)
// note: setting loppedShelfkey will also set loppedCallnum
loppedShelfkey = getShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
callnumVolSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(
normCallnum, loppedCallnum, loppedShelfkey, callnumType, isSerial, recId);
}
/** call numbers must start with a letter or digit */
private static final Pattern STRANGE_CALLNUM_START_CHARS = Pattern.compile("^\\p{Alnum}");
/**
* output an error message if the call number is supposed to be LC or DEWEY
* but is invalid
* @param recId the id of the record, used in error message
*/
private void validateCallnum(String recId) {
if (callnumType == CallNumberType.LC
&& !CallNumUtils.isValidLC(normCallnum)) {
if (!library.equals("LANE-MED"))
System.err.println("record " + recId + " has invalid LC callnumber: " + normCallnum);
adjustLCCallnumType(recId);
}
if (callnumType == CallNumberType.DEWEY
&& !CallNumUtils.isValidDeweyWithCutter(normCallnum)) {
System.err.println("record " + recId + " has invalid DEWEY callnumber: " + normCallnum);
callnumType = CallNumberType.OTHER;
}
else if (STRANGE_CALLNUM_START_CHARS.matcher(normCallnum).matches())
System.err.println("record " + recId + " has strange callnumber: " + normCallnum);
}
/**
* LC is default call number scheme assigned; change it if assigned
* incorrectly to a Dewey or ALPHANUM call number. Called after
* printMsgIfInvalidCallnum has already found invalid LC call number
*/
private void adjustLCCallnumType(String id) {
if (callnumType == CallNumberType.LC) {
if (CallNumUtils.isValidDeweyWithCutter(normCallnum))
callnumType = CallNumberType.DEWEY;
else
{
// FIXME: this is no good if the call number is SUDOC but mislabeled LC ...
callnumType = CallNumberType.OTHER;
if (library.equals("LANE-MED"))
hasBadLcLaneCallnum = true;
}
}
}
/**
* if item has XX call number
* if home location or current location is INPROCESS or ON-ORDER, do
* the obvious thing
* if no home or current location, item is on order.
* o.w. if the current location isn't shadowed, it is an error;
* print an error message and fake "ON-ORDER"
* @param recId - for error message
*/
private void dealWithXXCallnums(String recId) {
if (normCallnum.startsWith(TMP_CALLNUM_PREFIX))
{
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else if (currLoc.equals("INPROCESS"))
isInProcess = true;
else if (shouldBeSkipped || currLoc.equals("LAC") || homeLoc.equals("LAC"))
; // we're okay
else if (currLoc.length() > 0) {
System.err.println("record " + recId + " has XX callnumber but current location is not ON-ORDER or INPROCESS or shadowy");
if (homeLoc.equals("ON-ORDER") || homeLoc.equals("INPROCESS")) {
currLoc = homeLoc;
homeLoc = "";
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else
isInProcess = true;
}
else {
currLoc = "ON-ORDER";
isOnOrder = true;
}
}
}
}
/**
* assign a value to callnumType based on scheme ...
* LCPER --> LC; DEWEYPER --> DEWEY
*/
private void assignCallnumType(String scheme) {
if (scheme.startsWith("LC"))
callnumType = CallNumberType.LC;
else if (scheme.startsWith("DEWEY"))
callnumType = CallNumberType.DEWEY;
else if (scheme.equals("SUDOC"))
callnumType = CallNumberType.SUDOC;
else
callnumType = CallNumberType.OTHER;
}
}
| public Item(DataField f999, String recId) {
// set all the immutable variables
this.recId = recId;
barcode = MarcUtils.getSubfieldTrimmed(f999, 'i');
currLoc = MarcUtils.getSubfieldTrimmed(f999, 'k');
homeLoc = MarcUtils.getSubfieldTrimmed(f999, 'l');
library = MarcUtils.getSubfieldTrimmed(f999, 'm');
itemType = MarcUtils.getSubfieldTrimmed(f999, 't');
String scheme = MarcUtils.getSubfieldTrimmed(f999, 'w');
String rawCallnum = MarcUtils.getSubfieldTrimmed(f999, 'a');
if (StanfordIndexer.SKIPPED_LOCS.contains(currLoc)
|| StanfordIndexer.SKIPPED_LOCS.contains(homeLoc)
|| itemType.equals("EDI-REMOVE"))
shouldBeSkipped = true;
else
shouldBeSkipped = false;
if (StanfordIndexer.GOV_DOC_LOCS.contains(currLoc)
|| StanfordIndexer.GOV_DOC_LOCS.contains(homeLoc) )
hasGovDocLoc = true;
else
hasGovDocLoc = false;
if (StanfordIndexer.MISSING_LOCS.contains(currLoc)
|| StanfordIndexer.MISSING_LOCS.contains(homeLoc) )
isMissingLost = true;
else
isMissingLost = false;
if (library.equals("BUSINESS")
&& (StanfordIndexer.BIZ_SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.BIZ_SHELBY_LOCS.contains(homeLoc) ) )
hasBizShelbyLoc = true;
else
hasBizShelbyLoc = false;
if (StanfordIndexer.SHELBY_LOCS.contains(currLoc)
|| StanfordIndexer.SHELBY_LOCS.contains(homeLoc) )
hasShelbyLoc = true;
else if (hasBizShelbyLoc)
hasShelbyLoc = true;
else
hasShelbyLoc = false;
if (StanfordIndexer.SKIPPED_CALLNUMS.contains(rawCallnum)
|| rawCallnum.startsWith(ECALLNUM)
|| rawCallnum.startsWith(TMP_CALLNUM_PREFIX))
hasIgnoredCallnum = true;
else
hasIgnoredCallnum = false;
assignCallnumType(scheme);
if (!hasIgnoredCallnum) {
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
normCallnum = CallNumUtils.normalizeCallnum(rawCallnum);
else
normCallnum = rawCallnum.trim();
validateCallnum(recId);
}
else
normCallnum = rawCallnum.trim();
// isOnline is immutable so must be set here
if (StanfordIndexer.ONLINE_LOCS.contains(currLoc)
|| StanfordIndexer.ONLINE_LOCS.contains(homeLoc) //) {
|| normCallnum.startsWith(ECALLNUM) ) {
isOnline = true;
}
else
isOnline = false;
dealWithXXCallnums(recId);
}
public String getBarcode() {
return barcode;
}
public String getLibrary() {
return library;
}
public String getHomeLoc() {
return homeLoc;
}
public String getCurrLoc() {
return currLoc;
}
public String getType() {
return itemType;
}
public String getCallnum() {
return normCallnum;
}
public CallNumberType getCallnumType() {
return callnumType;
}
public void setCallnumType(CallNumberType callnumType) {
this.callnumType = callnumType;
}
/**
* @return true if this item has a current or home location indicating it
* should be skipped (e.g. "WITHDRAWN" or a shadowed location) or has
* a type of "EDI-REMOVE")
*/
public boolean shouldBeSkipped() {
return shouldBeSkipped;
}
/**
* @return true if item location indicating it is missing or lost
*/
public boolean isMissingOrLost() {
return isMissingLost;
}
/**
* @return true if item has a government doc location
*/
public boolean hasGovDocLoc() {
return hasGovDocLoc;
}
/**
* return true if item has a callnumber or location code indicating it is online
*/
public boolean isOnline() {
if (normCallnum.startsWith(ECALLNUM) || homeLoc.equals(ELOC) || currLoc.equals(ELOC))
return true;
else
return isOnline;
}
/**
* @return true if item is on order
*/
public boolean isOnOrder() {
return isOnOrder;
}
/**
* @return true if item is in process
*/
public boolean isInProcess() {
return isInProcess;
}
/**
* return true if item has a shelby location (current or home)
*/
public boolean hasShelbyLoc() {
return hasShelbyLoc;
}
/**
* return true if item has a business library only shelby location (current or home)
*/
public boolean hasBizShelbyLoc() {
return hasBizShelbyLoc;
}
/**
* @return true if call number is to be ignored in some contexts
* (e.g. "NO CALL NUMBER" or "XX(blah)")
*/
public boolean hasIgnoredCallnum() {
return hasIgnoredCallnum;
}
/**
* @return true if call number is Lane (Law) invalid LC callnum
*/
public boolean hasBadLcLaneCallnum() {
return hasBadLcLaneCallnum;
}
/**
* @return true if item has a call number from the bib fields
*/
public boolean hasSeparateBrowseCallnum() {
return hasSeparateBrowseCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will NOT set the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum() {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return loppedCallnum;
}
/**
* return the call number for browsing - it could be a call number provided
* outside of the item record. This method will SET the lopped call
* number if the raw call number is from the item record and no
* lopped call number has been set yet.
*/
public String getBrowseCallnum(boolean isSerial) {
if (hasSeparateBrowseCallnum)
return browseCallnum;
else
return getLoppedCallnum(isSerial);
}
/**
* for resources that have items without browsable call numbers
* (SUL INTERNET RESOURCE), we look for a call number in the bib record
* fields (050, 090, 086 ...) for browse nearby and for call number facets.
* If one is found, this method is used.
*/
public void setBrowseCallnum(String callnum) {
hasSeparateBrowseCallnum = true;
if (callnumType == CallNumberType.LC || callnumType == CallNumberType.DEWEY)
browseCallnum = CallNumUtils.normalizeCallnum(callnum);
else
browseCallnum = callnum.trim();
}
/**
* get the lopped call number (any volume suffix is lopped off the end.)
* This will remove noise in search results and in browsing.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
public String getLoppedCallnum(boolean isSerial) {
if (loppedCallnum == null)
setLoppedCallnum(isSerial);
return loppedCallnum;
}
/**
* sets the private field loppedCallnum to contain the call number without
* any volume suffix information.
* @param isSerial - true if item is for a serial. Used to determine if
* year suffix should be lopped in addition to regular volume lopping.
*/
private void setLoppedCallnum(boolean isSerial) {
loppedCallnum = edu.stanford.CallNumUtils.getLoppedCallnum(normCallnum, callnumType, isSerial);
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
loppedCallnum = loppedCallnum + " ...";
}
/**
* sets the private field loppedCallnum to the passed value. Used when
* lopping must be dictated elsewhere.
*/
void setLoppedCallnum(String loppedCallnum) {
this.loppedCallnum = loppedCallnum;
if (!loppedCallnum.endsWith(" ...") && !loppedCallnum.equals(normCallnum))
this.loppedCallnum = loppedCallnum + " ...";
}
/**
* get the sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
return loppedShelfkey;
}
/**
* sets the private field loppedShelfkey (and loppedCallnum if it's not
* already set). loppedShelfkey will contain the sortable version of the
* lopped call number
* @param isSerial - true if item is for a serial.
*/
private void setShelfkey(boolean isSerial) {
if (loppedShelfkey == null) {
String skeyCallnum = getBrowseCallnum(isSerial);
if (skeyCallnum != null && skeyCallnum.length() > 0
&& !StanfordIndexer.SKIPPED_CALLNUMS.contains(skeyCallnum)
&& !skeyCallnum.startsWith(ECALLNUM)
&& !skeyCallnum.startsWith(TMP_CALLNUM_PREFIX) )
loppedShelfkey = edu.stanford.CallNumUtils.getShelfKey(skeyCallnum, callnumType, recId);
}
}
/**
* get the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
public String getReverseShelfkey(boolean isSerial) {
if (reverseLoppedShelfkey == null)
setReverseShelfkey(isSerial);
return reverseLoppedShelfkey;
}
/**
* sets the private field reverseLoppedShelfkey (and loppedShelfkey and
* loppedCallnum if they're not already set). reverseLoppedShelfkey will
* contain the reverse sortable version of the lopped call number.
* @param isSerial - true if item is for a serial.
*/
private void setReverseShelfkey(boolean isSerial) {
if (loppedShelfkey == null)
setShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
reverseLoppedShelfkey = CallNumUtils.getReverseShelfKey(loppedShelfkey);
}
/**
* get the sortable full call number, where, for serials, any volume suffix
* will sort in descending order. Non-serial volumes will sort in ascending
* order.
* @param isSerial - true if item is for a serial.
*/
public String getCallnumVolSort(boolean isSerial) {
if (callnumVolSort == null)
setCallnumVolSort(isSerial);
return callnumVolSort;
}
/**
* sets the private field callnumVolSort (and loppedShelfkey and
* loppedCallnum if they're not already set.) callnumVolSort will contain
* the sortable full call number, where, for serials, any volume suffix
* will sort in descending order.
* @param isSerial - true if item is for a serial.
*/
private void setCallnumVolSort(boolean isSerial) {
if (loppedShelfkey == null)
// note: setting loppedShelfkey will also set loppedCallnum
loppedShelfkey = getShelfkey(isSerial);
if (loppedShelfkey != null && loppedShelfkey.length() > 0)
callnumVolSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(
normCallnum, loppedCallnum, loppedShelfkey, callnumType, isSerial, recId);
}
/** call numbers must start with a letter or digit */
private static final Pattern STRANGE_CALLNUM_START_CHARS = Pattern.compile("^\\p{Alnum}");
/**
* output an error message if the call number is supposed to be LC or DEWEY
* but is invalid
* @param recId the id of the record, used in error message
*/
private void validateCallnum(String recId) {
if (callnumType == CallNumberType.LC
&& !CallNumUtils.isValidLC(normCallnum)) {
if (!library.equals("LANE-MED"))
System.err.println("record " + recId + " has invalid LC callnumber: " + normCallnum);
adjustLCCallnumType(recId);
}
if (callnumType == CallNumberType.DEWEY
&& !CallNumUtils.isValidDeweyWithCutter(normCallnum)) {
System.err.println("record " + recId + " has invalid DEWEY callnumber: " + normCallnum);
callnumType = CallNumberType.OTHER;
}
else if (STRANGE_CALLNUM_START_CHARS.matcher(normCallnum).matches())
System.err.println("record " + recId + " has strange callnumber: " + normCallnum);
}
/**
* LC is default call number scheme assigned; change it if assigned
* incorrectly to a Dewey or ALPHANUM call number. Called after
* printMsgIfInvalidCallnum has already found invalid LC call number
*/
private void adjustLCCallnumType(String id) {
if (callnumType == CallNumberType.LC) {
if (CallNumUtils.isValidDeweyWithCutter(normCallnum))
callnumType = CallNumberType.DEWEY;
else
{
// FIXME: this is no good if the call number is SUDOC but mislabeled LC ...
callnumType = CallNumberType.OTHER;
if (library.equals("LANE-MED"))
hasBadLcLaneCallnum = true;
}
}
}
/**
* if item has XX call number
* if home location or current location is INPROCESS or ON-ORDER, do
* the obvious thing
* if no home or current location, item is on order.
* o.w. if the current location isn't shadowed, it is an error;
* print an error message and fake "ON-ORDER"
* @param recId - for error message
*/
private void dealWithXXCallnums(String recId) {
if (normCallnum.startsWith(TMP_CALLNUM_PREFIX))
{
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else if (currLoc.equals("INPROCESS"))
isInProcess = true;
else if (shouldBeSkipped || currLoc.equals("LAC") || homeLoc.equals("LAC"))
; // we're okay
else if (currLoc.length() > 0) {
System.err.println("record " + recId + " has XX callnumber but current location is not ON-ORDER or INPROCESS or shadowy");
if (homeLoc.equals("ON-ORDER") || homeLoc.equals("INPROCESS")) {
currLoc = homeLoc;
homeLoc = "";
if (currLoc.equals("ON-ORDER"))
isOnOrder = true;
else
isInProcess = true;
}
else {
currLoc = "ON-ORDER";
isOnOrder = true;
}
}
}
}
/**
* assign a value to callnumType based on scheme ...
* LCPER --> LC; DEWEYPER --> DEWEY
*/
private void assignCallnumType(String scheme) {
if (scheme.startsWith("LC"))
callnumType = CallNumberType.LC;
else if (scheme.startsWith("DEWEY"))
callnumType = CallNumberType.DEWEY;
else if (scheme.equals("SUDOC"))
callnumType = CallNumberType.SUDOC;
else
callnumType = CallNumberType.OTHER;
}
}
|
diff --git a/phresco-framework-web/src/test/java/com/photon/phresco/framework/actions/applications/PhrescoReportGenerationTest.java b/phresco-framework-web/src/test/java/com/photon/phresco/framework/actions/applications/PhrescoReportGenerationTest.java
index ac05524ff..f46d2da3a 100644
--- a/phresco-framework-web/src/test/java/com/photon/phresco/framework/actions/applications/PhrescoReportGenerationTest.java
+++ b/phresco-framework-web/src/test/java/com/photon/phresco/framework/actions/applications/PhrescoReportGenerationTest.java
@@ -1,486 +1,486 @@
package com.photon.phresco.framework.actions.applications;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.record.formula.functions.Mode;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sonar.wsclient.Host;
import org.sonar.wsclient.Sonar;
import org.sonar.wsclient.connectors.HttpClient4Connector;
import org.sonar.wsclient.services.Resource;
import org.sonar.wsclient.services.ResourceQuery;
import com.photon.phresco.commons.FrameworkConstants;
import com.photon.phresco.framework.FrameworkConfiguration;
import com.photon.phresco.framework.PhrescoFrameworkFactory;
import com.photon.phresco.framework.actions.FrameworkBaseAction;
import com.photon.phresco.framework.api.Project;
import com.photon.phresco.framework.api.ProjectAdministrator;
import com.photon.phresco.framework.commons.FrameworkUtil;
import com.photon.phresco.framework.commons.SonarReport;
import com.photon.phresco.util.TechnologyTypes;
import com.photon.phresco.util.Utility;
import com.phresco.pom.model.Model;
import com.phresco.pom.model.Model.Profiles;
import com.phresco.pom.model.Profile;
import com.phresco.pom.util.PomProcessor;
public class PhrescoReportGenerationTest extends FrameworkBaseAction implements FrameworkConstants {
/**
*
*/
private static final long serialVersionUID = 1L;
private ProjectAdministrator administrator = null;
private String projectCode = null;
private String report = null;
private static String FUNCTIONALTEST = "functional";
private PhrescoReportGeneration reportGen = new PhrescoReportGeneration();
@Before
public void setUp() throws Exception {
System.out.println("before !!!!!!!!!");
administrator = PhrescoFrameworkFactory.getProjectAdministrator();
}
@After
public void tearDown() throws Exception {
System.out.println("Tear down!!!!!");
if (administrator != null) {
administrator = null;
}
}
// @Test
public void readResources() throws IOException {
InputStream inStream = null;
OutputStream ps = null;
try {
// String resourceName = "framework.config";
String resourceName = "reports/jasper/report.jasper";
inStream = this.getClass().getClassLoader().getResourceAsStream(resourceName);
ps = System.out;
byte[] data = new byte[1024];
while (inStream.read(data) != -1) {
ps.write(data);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (ps != null) {
ps.close();
}
}
}
//@Test
public void testPhrescoReportGeneration() throws Exception {
Project project = administrator.getProject("PHR_phpnone");
System.out.println("project ===> " + project.getApplicationInfo().getTechInfo().getVersion());
// reportGen.compileReports();
// reportGen.cumulativePdfReport(project, "", "detail");
}
//@Test
public void sampleReportGenration() throws Exception {
InputStream is = null;
try {
System.out.println("Pdf report generation started!!!!!");
String outFileNamePDF = "/Users/kaleeswaran/Tried/JasperReportExample/samplePdf.pdf";
//
// JasperDesign jasperDesign = JRXmlLoader.load("/Users/kaleeswaran/Tried/JasperReportExample/report.jrxml");
// String desinationPath = "/Users/kaleeswaran/Tried/JasperReportExample/report.jasper";
// JasperCompileManager.compileReportToFile(jasperDesign, desinationPath);
// String outFileNamePDF = "/Users/kaleeswaran/Tried/JasperReportExample/mavenCompiled/samplePdf.pdf";
// FileInputStream fis = new FileInputStream("/Users/kaleeswaran/Tried/JasperReportExample/mavenCompiled/report.jasper");
boolean readFromClasspath = false;
is = readReportFile(readFromClasspath);
// BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
Map<String, Object> parameters = new HashMap<String,Object>();
List<Map<String, ?>> maps = new ArrayList<Map<String, ?>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("Name", "Kalees");
map.put("EmpId", "E3084");
maps.add(map);
}
JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(maps);
// JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
//
// String resourceName = "reports/jasper/report.jasper";
// URL resource = this.getClass().getClassLoader().getResource(resourceName);
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,outFileNamePDF);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
System.out.println("Completed!!!!!!!!!");
} catch (Exception e) {
System.out.println("Error in report!!!!");
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
}
}
public void compileReports() throws Exception {
//jrxml path!!!!!
File pdfFileDir = new File("/Users/kaleeswaran/work/boston-new/framework/phresco-framework-web/src/main/resources/reports/template");
File[] listFiles = pdfFileDir.listFiles(new FileExtensionFileFilter(".jrxml"));
for (File jrxmlFile : listFiles) {
// System.out.println("jrxmlFile ===> " + jrxmlFile.getName());
System.out.println("jrxmlFile ===> " + jrxmlFile.getAbsolutePath());
JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile.getAbsolutePath());
String desinationPath = "/Users/kaleeswaran/work/boston-new/framework/phresco-framework-web/src/main/resources/reports/jasper/" + FilenameUtils.removeExtension(jrxmlFile.getName()) + ".jasper";
System.out.println("desinationPath ====> " + desinationPath);
JasperCompileManager.compileReportToFile(jasperDesign, desinationPath);
}
}
private InputStream readReportFile(boolean readFromClasspath) throws IOException {
if (readFromClasspath) {
return readFromClasspath();
}
// FileInputStream fis = new FileInputStream("/Users/kaleeswaran/work/boston-new/framework/phresco-framework-web/src/main/resources/reports/jasper/report.jasper");
// FileInputStream fis = new FileInputStream("/Users/kaleeswaran/work/boston-new/framework/phresco-framework-web/target/classes/reports/jasper/report.jasper");
FileInputStream fis = new FileInputStream("/Users/kaleeswaran/softwares/apache-tomcat-7.0.25/webapps/phresco/WEB-INF/classes/reports/jasper/report.jasper");
// FileInputStream fis = new FileInputStream("/Users/kaleeswaran/Tried/JasperReportExample/report.jasper");
return fis;
}
private InputStream readFromClasspath() throws IOException {
String resourceName = "reports/jasper/report.jasper";
return this.getClass().getClassLoader().getResourceAsStream(resourceName);
}
public void reportGenerationTests(Project project, String testType) throws Exception {
InputStream reportStream = null;
try {
System.out.println("Pdf report generation started!!!!!");
String outFileNamePDF = "/Users/kaleeswaran/Tried/JasperReportExample/samplePdfPhresco.pdf";
// JasperDesign jasperDesign = JRXmlLoader.load("/reports/template/report.jrxml");
// String desinationPath = "/reports/jasper/report.jasper";
// JasperCompileManager.compileReportToFile(jasperDesign, desinationPath);
// FileInputStream fis = new FileInputStream("/reports/jasper/report.jasper");
boolean readFromClasspath = true;
reportStream = readReportFile(readFromClasspath);
Map<String, Object> parameters = new HashMap<String,Object>();
List<Map<String, ?>> maps = new ArrayList<Map<String, ?>>();
for (int i = 0; i < 10; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("Name", "Kalees");
map.put("EmpId", "E3084");
maps.add(map);
}
JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(maps);
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,outFileNamePDF);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.exportReport();
System.out.println("Pdf generation completed!!!!!!!!!!");
} catch (Exception e) {
System.out.println("Error pdf!!!!!!");
e.printStackTrace();
} finally {
if(reportStream != null) {
reportStream.close();
}
}
}
public void getSonarReports() {
try {
List<SonarReport> sonarReports = null;
sonarReports = new ArrayList<SonarReport>();
List<String> sonarTechReports = new ArrayList<String>(4);
ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
Project project = administrator.getProject("PHR_SonarAllReport");
projectCode = project.getApplicationInfo().getCode();
System.out.println(" projectcode ===========>" + projectCode);
String techId = project.getApplicationInfo().getTechInfo().getVersion();
System.out.println(" technology ===========>" + techId);
if (TechnologyTypes.HTML5_WIDGET.equals(techId) || TechnologyTypes.HTML5_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5.equals(techId) || TechnologyTypes.HTML5_JQUERY_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5_MULTICHANNEL_JQUERY_WIDGET.equals(techId) || TechnologyTypes.JAVA_WEBSERVICE.equals(techId)) {
System.out.println("java. js , web");
//sonarTechReports.add("java");
//sonarTechReports.add("js");
sonarTechReports.add("web");
} else {
// System.out.println("src");
//sonarTechReports.add("source");
}
//System.out.println("Functional");
//sonarTechReports.add("functional");
for (String sonarTechReport : sonarTechReports) {
SonarReport srcSonarReport = generateSonarReport(sonarTechReport, techId);
if(srcSonarReport != null) {
sonarReports.add(srcSonarReport);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public SonarReport generateSonarReport(String report, String techId) throws Exception {
SonarReport sonarReport = new SonarReport();
StringBuilder sb = new StringBuilder();
String technology = null;
try {
FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig();
String serverUrl = "";
if (StringUtils.isNotEmpty(frameworkConfig.getSonarUrl())) {
serverUrl = frameworkConfig.getSonarUrl();
} else {
serverUrl = getHttpRequest().getRequestURL().toString();
StringBuilder tobeRemoved = new StringBuilder();
tobeRemoved.append(getHttpRequest().getContextPath());
tobeRemoved.append(getHttpRequest().getServletPath());
Pattern pattern = Pattern.compile(tobeRemoved.toString());
Matcher matcher = pattern.matcher(serverUrl);
serverUrl = matcher.replaceAll("");
}
StringBuilder builder = new StringBuilder(Utility.getProjectHome());
builder.append(projectCode);
if (StringUtils.isNotEmpty(report) && FUNCTIONALTEST.equals(report)) {
FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
- builder.append(frameworkUtil.getFuncitonalTestDir(techId));
+// builder.append(frameworkUtil.getFuncitonalTestDir(techId));
}
builder.append(File.separatorChar);
builder.append(POM_XML);
File pomPath = new File(builder.toString());
System.out.println("pomPath path =========" + pomPath);
PomProcessor processor = new PomProcessor(pomPath);
String groupId = processor.getModel().getGroupId();
String artifactId = processor.getModel().getArtifactId();
Profile profiles = processor.getProfile("web");
System.out.println(" web -----------" + profiles.getId());
StringBuilder sbuild = new StringBuilder();
sbuild.append(groupId);
sbuild.append(COLON);
sbuild.append(artifactId);
if (StringUtils.isNotEmpty(report) && !SOURCE_DIR.equals(report)) {
sbuild.append(COLON);
sbuild.append(report);
}
String artifact = sbuild.toString();
System.out.println("report == " + report);
System.out.println("artifact == " + artifact);
Sonar sonar = new Sonar(new HttpClient4Connector(new Host(serverUrl)));
String metrickey[] = {"ncloc", "lines", "files", "comment_lines_density" , "comment_lines", "duplicated_lines_density", "duplicated_lines",
"duplicated_blocks", "duplicated_files", "function_complexity", "file_complexity", "violations_density", "blocker_violations",
"critical_violations", "major_violations", "minor_violations", "info_violations", "weighted_violations",
"classes", "functions",
"statements","packages", "accessors", "public_documented_api_density", "public_undocumented_api","package_tangle_index","package_cycles", "package_feedback_edges", "package_tangles", "lcom4", "rfc",
"directories", "class_complexity"};
Resource resrc = sonar.find(ResourceQuery.createForMetrics(artifact, metrickey));
System.out.println(" resrc value is "+ resrc);
System.out.println(" Metric key is " + metrickey[1]+ " "+resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[0] " + metrickey[0] + " " + resrc.getMeasure(metrickey[0]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[1] " + metrickey[1] + " " + resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[2] " + metrickey[2] + " " + resrc.getMeasure(metrickey[2]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[3] " + metrickey[3] + " " + resrc.getMeasure(metrickey[3]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[4] " + metrickey[4] + " " + resrc.getMeasure(metrickey[4]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[5] " + metrickey[5] + " " + resrc.getMeasure(metrickey[5]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[6] " + metrickey[6] + " " + resrc.getMeasure(metrickey[6]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[7] " + metrickey[7] + " " + resrc.getMeasure(metrickey[7]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[8] " + metrickey[8] + " " + resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[9] " + metrickey[9] + " " + resrc.getMeasure(metrickey[9]).getFormattedValue());
}
System.out.println("resrc.getMeasure(metrickey[10] " + metrickey[10] + " " + resrc.getMeasure(metrickey[10]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[11] " + metrickey[11] + " " + resrc.getMeasure(metrickey[11]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[12] " + metrickey[12] + " " + resrc.getMeasure(metrickey[12]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[13] " + metrickey[13] + " " + resrc.getMeasure(metrickey[13]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[14] " + metrickey[14] + " " + resrc.getMeasure(metrickey[14]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[15] " + metrickey[15] + " " + resrc.getMeasure(metrickey[15]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[16] " + metrickey[16] + " " + resrc.getMeasure(metrickey[16]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[17] " + metrickey[17] + " " + resrc.getMeasure(metrickey[17]).getFormattedValue());
sonarReport.setNonCommentLinesOfCode(resrc.getMeasure(metrickey[0]).getFormattedValue());
sonarReport.setLines(resrc.getMeasure(metrickey[1]).getFormattedValue());
sonarReport.setFiles(resrc.getMeasure(metrickey[2]).getFormattedValue());
sonarReport.setCommentLinesDensity(resrc.getMeasure(metrickey[3]).getFormattedValue());
sonarReport.setCommentLines(resrc.getMeasure(metrickey[4]).getFormattedValue());
sonarReport.setDuplicatedLinesDensity(resrc.getMeasure(metrickey[5]).getFormattedValue());
sonarReport.setDuplicatedLines(resrc.getMeasure(metrickey[6]).getFormattedValue());
sonarReport.setDuplicatedBlocks(resrc.getMeasure(metrickey[7]).getFormattedValue());
sonarReport.setDuplicatedFiles(resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
sonarReport.setFunctionComplexity(resrc.getMeasure(metrickey[9]).getFormattedValue());
}
sonarReport.setFileComplexity(resrc.getMeasure(metrickey[10]).getFormattedValue());
sonarReport.setViolationsDensity(resrc.getMeasure(metrickey[11]).getFormattedValue());
sonarReport.setBlockerViolations(resrc.getMeasure(metrickey[12]).getFormattedValue());
sonarReport.setCriticalViolations(resrc.getMeasure(metrickey[13]).getFormattedValue());
sonarReport.setMajorViolations(resrc.getMeasure(metrickey[14]).getFormattedValue());
sonarReport.setMinorViolations(resrc.getMeasure(metrickey[15]).getFormattedValue());
sonarReport.setInfoViolations(resrc.getMeasure(metrickey[16]).getFormattedValue());
sonarReport.setWeightedViolations(resrc.getMeasure(metrickey[17]).getFormattedValue());
if ((TechnologyTypes.HTML5_WIDGET.equals(techId) || TechnologyTypes.HTML5_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5.equals(techId) || TechnologyTypes.HTML5_JQUERY_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5_MULTICHANNEL_JQUERY_WIDGET.equals(techId) || TechnologyTypes.JAVA_WEBSERVICE.equals(techId)) && (JAVA.equals(report) || FUNCTIONAL.equals(report))){
System.out.println(" java ---------- " + report);
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18] +" " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19] +" " +resrc.getMeasure(metrickey[19]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[20] " + metrickey[20] +" " +resrc.getMeasure(metrickey[20]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[21] " + metrickey[21] +" " +resrc.getMeasure(metrickey[21]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[22] " + metrickey[22] +" " +resrc.getMeasure(metrickey[22]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[23] " + metrickey[23] +" " +resrc.getMeasure(metrickey[23]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[24] " + metrickey[24] +" " +resrc.getMeasure(metrickey[24]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[25] " + metrickey[25] +" "+resrc.getMeasure(metrickey[25]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[26] " + metrickey[26] +" " +resrc.getMeasure(metrickey[26]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[27] " + metrickey[27] +" " +resrc.getMeasure(metrickey[27]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[28] " + metrickey[28] +" " +resrc.getMeasure(metrickey[28]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[29] " + metrickey[29] +" " +resrc.getMeasure(metrickey[29]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[30] " + metrickey[30] +" " +resrc.getMeasure(metrickey[30]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[32] " + metrickey[32] +" " +resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setStatements(resrc.getMeasure(metrickey[20]).getFormattedValue());
sonarReport.setPackages(resrc.getMeasure(metrickey[21]).getFormattedValue());
sonarReport.setAccessors(resrc.getMeasure(metrickey[22]).getFormattedValue());
sonarReport.setPublicDocumentedApiDensity((resrc.getMeasure(metrickey[23]).getFormattedValue()));
sonarReport.setPublicUndocumentedApi(resrc.getMeasure(metrickey[24]).getFormattedValue());
sonarReport.setPackageTangleIndex(resrc.getMeasure(metrickey[25]).getFormattedValue());
sonarReport.setPackageCycles(resrc.getMeasure(metrickey[26]).getFormattedValue());
sonarReport.setPackageFeedbackEdges(resrc.getMeasure(metrickey[27]).getFormattedValue());
sonarReport.setPackageTangles(resrc.getMeasure(metrickey[28]).getFormattedValue());
sonarReport.setLackOfCohesionMethods(resrc.getMeasure(metrickey[29]).getFormattedValue());
sonarReport.setResponseForCode(resrc.getMeasure(metrickey[30]).getFormattedValue());
sonarReport.setClassComplexity(resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JAVA_FUNC);
} else if (SONAR_SOURCE.equals(report) || FUNCTIONAL.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18]+ " " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19]+ " " + resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_SRC_FUNC);
} else if (JS.equals(report) || WEB.equals(report)) {
System.out.println(" js ---------- " + report);
System.out.println("metrickey[31] " + metrickey[31] +" ");
sonarReport.setDirectories(resrc.getMeasure(metrickey[31]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JS_WEB);
}
sonarReport.setReportType(report);
sonarReport.setTechnology(technology);
return sonarReport;
} catch (Exception e) {
e.printStackTrace();
// throw new PhrescoException(e);
return null;
}
}
//@Test
public void getProfile() throws Exception {
StringBuilder builder = new StringBuilder(Utility.getProjectHome());
String techid = "web";
System.out.println(" builder ====> " + builder);
builder.append("PHR_SonarAllReport");
builder.append(File.separator);
builder.append(POM_XML);
File pomPath = new File(builder.toString());
System.out.println("pomPath ============" + pomPath);
PomProcessor path = new PomProcessor(pomPath);
Profile profiles = path.getProfile(techid);
System.out.println("path.getProfiles ---------->>>>>>>>> " + profiles.getId());
if (profiles.equals(profiles.getId())) {
System.out.println(" present " );
}
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
}
| true | true | public SonarReport generateSonarReport(String report, String techId) throws Exception {
SonarReport sonarReport = new SonarReport();
StringBuilder sb = new StringBuilder();
String technology = null;
try {
FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig();
String serverUrl = "";
if (StringUtils.isNotEmpty(frameworkConfig.getSonarUrl())) {
serverUrl = frameworkConfig.getSonarUrl();
} else {
serverUrl = getHttpRequest().getRequestURL().toString();
StringBuilder tobeRemoved = new StringBuilder();
tobeRemoved.append(getHttpRequest().getContextPath());
tobeRemoved.append(getHttpRequest().getServletPath());
Pattern pattern = Pattern.compile(tobeRemoved.toString());
Matcher matcher = pattern.matcher(serverUrl);
serverUrl = matcher.replaceAll("");
}
StringBuilder builder = new StringBuilder(Utility.getProjectHome());
builder.append(projectCode);
if (StringUtils.isNotEmpty(report) && FUNCTIONALTEST.equals(report)) {
FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
builder.append(frameworkUtil.getFuncitonalTestDir(techId));
}
builder.append(File.separatorChar);
builder.append(POM_XML);
File pomPath = new File(builder.toString());
System.out.println("pomPath path =========" + pomPath);
PomProcessor processor = new PomProcessor(pomPath);
String groupId = processor.getModel().getGroupId();
String artifactId = processor.getModel().getArtifactId();
Profile profiles = processor.getProfile("web");
System.out.println(" web -----------" + profiles.getId());
StringBuilder sbuild = new StringBuilder();
sbuild.append(groupId);
sbuild.append(COLON);
sbuild.append(artifactId);
if (StringUtils.isNotEmpty(report) && !SOURCE_DIR.equals(report)) {
sbuild.append(COLON);
sbuild.append(report);
}
String artifact = sbuild.toString();
System.out.println("report == " + report);
System.out.println("artifact == " + artifact);
Sonar sonar = new Sonar(new HttpClient4Connector(new Host(serverUrl)));
String metrickey[] = {"ncloc", "lines", "files", "comment_lines_density" , "comment_lines", "duplicated_lines_density", "duplicated_lines",
"duplicated_blocks", "duplicated_files", "function_complexity", "file_complexity", "violations_density", "blocker_violations",
"critical_violations", "major_violations", "minor_violations", "info_violations", "weighted_violations",
"classes", "functions",
"statements","packages", "accessors", "public_documented_api_density", "public_undocumented_api","package_tangle_index","package_cycles", "package_feedback_edges", "package_tangles", "lcom4", "rfc",
"directories", "class_complexity"};
Resource resrc = sonar.find(ResourceQuery.createForMetrics(artifact, metrickey));
System.out.println(" resrc value is "+ resrc);
System.out.println(" Metric key is " + metrickey[1]+ " "+resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[0] " + metrickey[0] + " " + resrc.getMeasure(metrickey[0]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[1] " + metrickey[1] + " " + resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[2] " + metrickey[2] + " " + resrc.getMeasure(metrickey[2]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[3] " + metrickey[3] + " " + resrc.getMeasure(metrickey[3]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[4] " + metrickey[4] + " " + resrc.getMeasure(metrickey[4]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[5] " + metrickey[5] + " " + resrc.getMeasure(metrickey[5]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[6] " + metrickey[6] + " " + resrc.getMeasure(metrickey[6]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[7] " + metrickey[7] + " " + resrc.getMeasure(metrickey[7]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[8] " + metrickey[8] + " " + resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[9] " + metrickey[9] + " " + resrc.getMeasure(metrickey[9]).getFormattedValue());
}
System.out.println("resrc.getMeasure(metrickey[10] " + metrickey[10] + " " + resrc.getMeasure(metrickey[10]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[11] " + metrickey[11] + " " + resrc.getMeasure(metrickey[11]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[12] " + metrickey[12] + " " + resrc.getMeasure(metrickey[12]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[13] " + metrickey[13] + " " + resrc.getMeasure(metrickey[13]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[14] " + metrickey[14] + " " + resrc.getMeasure(metrickey[14]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[15] " + metrickey[15] + " " + resrc.getMeasure(metrickey[15]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[16] " + metrickey[16] + " " + resrc.getMeasure(metrickey[16]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[17] " + metrickey[17] + " " + resrc.getMeasure(metrickey[17]).getFormattedValue());
sonarReport.setNonCommentLinesOfCode(resrc.getMeasure(metrickey[0]).getFormattedValue());
sonarReport.setLines(resrc.getMeasure(metrickey[1]).getFormattedValue());
sonarReport.setFiles(resrc.getMeasure(metrickey[2]).getFormattedValue());
sonarReport.setCommentLinesDensity(resrc.getMeasure(metrickey[3]).getFormattedValue());
sonarReport.setCommentLines(resrc.getMeasure(metrickey[4]).getFormattedValue());
sonarReport.setDuplicatedLinesDensity(resrc.getMeasure(metrickey[5]).getFormattedValue());
sonarReport.setDuplicatedLines(resrc.getMeasure(metrickey[6]).getFormattedValue());
sonarReport.setDuplicatedBlocks(resrc.getMeasure(metrickey[7]).getFormattedValue());
sonarReport.setDuplicatedFiles(resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
sonarReport.setFunctionComplexity(resrc.getMeasure(metrickey[9]).getFormattedValue());
}
sonarReport.setFileComplexity(resrc.getMeasure(metrickey[10]).getFormattedValue());
sonarReport.setViolationsDensity(resrc.getMeasure(metrickey[11]).getFormattedValue());
sonarReport.setBlockerViolations(resrc.getMeasure(metrickey[12]).getFormattedValue());
sonarReport.setCriticalViolations(resrc.getMeasure(metrickey[13]).getFormattedValue());
sonarReport.setMajorViolations(resrc.getMeasure(metrickey[14]).getFormattedValue());
sonarReport.setMinorViolations(resrc.getMeasure(metrickey[15]).getFormattedValue());
sonarReport.setInfoViolations(resrc.getMeasure(metrickey[16]).getFormattedValue());
sonarReport.setWeightedViolations(resrc.getMeasure(metrickey[17]).getFormattedValue());
if ((TechnologyTypes.HTML5_WIDGET.equals(techId) || TechnologyTypes.HTML5_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5.equals(techId) || TechnologyTypes.HTML5_JQUERY_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5_MULTICHANNEL_JQUERY_WIDGET.equals(techId) || TechnologyTypes.JAVA_WEBSERVICE.equals(techId)) && (JAVA.equals(report) || FUNCTIONAL.equals(report))){
System.out.println(" java ---------- " + report);
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18] +" " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19] +" " +resrc.getMeasure(metrickey[19]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[20] " + metrickey[20] +" " +resrc.getMeasure(metrickey[20]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[21] " + metrickey[21] +" " +resrc.getMeasure(metrickey[21]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[22] " + metrickey[22] +" " +resrc.getMeasure(metrickey[22]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[23] " + metrickey[23] +" " +resrc.getMeasure(metrickey[23]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[24] " + metrickey[24] +" " +resrc.getMeasure(metrickey[24]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[25] " + metrickey[25] +" "+resrc.getMeasure(metrickey[25]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[26] " + metrickey[26] +" " +resrc.getMeasure(metrickey[26]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[27] " + metrickey[27] +" " +resrc.getMeasure(metrickey[27]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[28] " + metrickey[28] +" " +resrc.getMeasure(metrickey[28]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[29] " + metrickey[29] +" " +resrc.getMeasure(metrickey[29]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[30] " + metrickey[30] +" " +resrc.getMeasure(metrickey[30]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[32] " + metrickey[32] +" " +resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setStatements(resrc.getMeasure(metrickey[20]).getFormattedValue());
sonarReport.setPackages(resrc.getMeasure(metrickey[21]).getFormattedValue());
sonarReport.setAccessors(resrc.getMeasure(metrickey[22]).getFormattedValue());
sonarReport.setPublicDocumentedApiDensity((resrc.getMeasure(metrickey[23]).getFormattedValue()));
sonarReport.setPublicUndocumentedApi(resrc.getMeasure(metrickey[24]).getFormattedValue());
sonarReport.setPackageTangleIndex(resrc.getMeasure(metrickey[25]).getFormattedValue());
sonarReport.setPackageCycles(resrc.getMeasure(metrickey[26]).getFormattedValue());
sonarReport.setPackageFeedbackEdges(resrc.getMeasure(metrickey[27]).getFormattedValue());
sonarReport.setPackageTangles(resrc.getMeasure(metrickey[28]).getFormattedValue());
sonarReport.setLackOfCohesionMethods(resrc.getMeasure(metrickey[29]).getFormattedValue());
sonarReport.setResponseForCode(resrc.getMeasure(metrickey[30]).getFormattedValue());
sonarReport.setClassComplexity(resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JAVA_FUNC);
} else if (SONAR_SOURCE.equals(report) || FUNCTIONAL.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18]+ " " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19]+ " " + resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_SRC_FUNC);
} else if (JS.equals(report) || WEB.equals(report)) {
System.out.println(" js ---------- " + report);
System.out.println("metrickey[31] " + metrickey[31] +" ");
sonarReport.setDirectories(resrc.getMeasure(metrickey[31]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JS_WEB);
}
sonarReport.setReportType(report);
sonarReport.setTechnology(technology);
return sonarReport;
} catch (Exception e) {
e.printStackTrace();
// throw new PhrescoException(e);
return null;
}
}
| public SonarReport generateSonarReport(String report, String techId) throws Exception {
SonarReport sonarReport = new SonarReport();
StringBuilder sb = new StringBuilder();
String technology = null;
try {
FrameworkConfiguration frameworkConfig = PhrescoFrameworkFactory.getFrameworkConfig();
String serverUrl = "";
if (StringUtils.isNotEmpty(frameworkConfig.getSonarUrl())) {
serverUrl = frameworkConfig.getSonarUrl();
} else {
serverUrl = getHttpRequest().getRequestURL().toString();
StringBuilder tobeRemoved = new StringBuilder();
tobeRemoved.append(getHttpRequest().getContextPath());
tobeRemoved.append(getHttpRequest().getServletPath());
Pattern pattern = Pattern.compile(tobeRemoved.toString());
Matcher matcher = pattern.matcher(serverUrl);
serverUrl = matcher.replaceAll("");
}
StringBuilder builder = new StringBuilder(Utility.getProjectHome());
builder.append(projectCode);
if (StringUtils.isNotEmpty(report) && FUNCTIONALTEST.equals(report)) {
FrameworkUtil frameworkUtil = FrameworkUtil.getInstance();
// builder.append(frameworkUtil.getFuncitonalTestDir(techId));
}
builder.append(File.separatorChar);
builder.append(POM_XML);
File pomPath = new File(builder.toString());
System.out.println("pomPath path =========" + pomPath);
PomProcessor processor = new PomProcessor(pomPath);
String groupId = processor.getModel().getGroupId();
String artifactId = processor.getModel().getArtifactId();
Profile profiles = processor.getProfile("web");
System.out.println(" web -----------" + profiles.getId());
StringBuilder sbuild = new StringBuilder();
sbuild.append(groupId);
sbuild.append(COLON);
sbuild.append(artifactId);
if (StringUtils.isNotEmpty(report) && !SOURCE_DIR.equals(report)) {
sbuild.append(COLON);
sbuild.append(report);
}
String artifact = sbuild.toString();
System.out.println("report == " + report);
System.out.println("artifact == " + artifact);
Sonar sonar = new Sonar(new HttpClient4Connector(new Host(serverUrl)));
String metrickey[] = {"ncloc", "lines", "files", "comment_lines_density" , "comment_lines", "duplicated_lines_density", "duplicated_lines",
"duplicated_blocks", "duplicated_files", "function_complexity", "file_complexity", "violations_density", "blocker_violations",
"critical_violations", "major_violations", "minor_violations", "info_violations", "weighted_violations",
"classes", "functions",
"statements","packages", "accessors", "public_documented_api_density", "public_undocumented_api","package_tangle_index","package_cycles", "package_feedback_edges", "package_tangles", "lcom4", "rfc",
"directories", "class_complexity"};
Resource resrc = sonar.find(ResourceQuery.createForMetrics(artifact, metrickey));
System.out.println(" resrc value is "+ resrc);
System.out.println(" Metric key is " + metrickey[1]+ " "+resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[0] " + metrickey[0] + " " + resrc.getMeasure(metrickey[0]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[1] " + metrickey[1] + " " + resrc.getMeasure(metrickey[1]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[2] " + metrickey[2] + " " + resrc.getMeasure(metrickey[2]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[3] " + metrickey[3] + " " + resrc.getMeasure(metrickey[3]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[4] " + metrickey[4] + " " + resrc.getMeasure(metrickey[4]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[5] " + metrickey[5] + " " + resrc.getMeasure(metrickey[5]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[6] " + metrickey[6] + " " + resrc.getMeasure(metrickey[6]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[7] " + metrickey[7] + " " + resrc.getMeasure(metrickey[7]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[8] " + metrickey[8] + " " + resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[9] " + metrickey[9] + " " + resrc.getMeasure(metrickey[9]).getFormattedValue());
}
System.out.println("resrc.getMeasure(metrickey[10] " + metrickey[10] + " " + resrc.getMeasure(metrickey[10]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[11] " + metrickey[11] + " " + resrc.getMeasure(metrickey[11]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[12] " + metrickey[12] + " " + resrc.getMeasure(metrickey[12]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[13] " + metrickey[13] + " " + resrc.getMeasure(metrickey[13]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[14] " + metrickey[14] + " " + resrc.getMeasure(metrickey[14]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[15] " + metrickey[15] + " " + resrc.getMeasure(metrickey[15]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[16] " + metrickey[16] + " " + resrc.getMeasure(metrickey[16]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[17] " + metrickey[17] + " " + resrc.getMeasure(metrickey[17]).getFormattedValue());
sonarReport.setNonCommentLinesOfCode(resrc.getMeasure(metrickey[0]).getFormattedValue());
sonarReport.setLines(resrc.getMeasure(metrickey[1]).getFormattedValue());
sonarReport.setFiles(resrc.getMeasure(metrickey[2]).getFormattedValue());
sonarReport.setCommentLinesDensity(resrc.getMeasure(metrickey[3]).getFormattedValue());
sonarReport.setCommentLines(resrc.getMeasure(metrickey[4]).getFormattedValue());
sonarReport.setDuplicatedLinesDensity(resrc.getMeasure(metrickey[5]).getFormattedValue());
sonarReport.setDuplicatedLines(resrc.getMeasure(metrickey[6]).getFormattedValue());
sonarReport.setDuplicatedBlocks(resrc.getMeasure(metrickey[7]).getFormattedValue());
sonarReport.setDuplicatedFiles(resrc.getMeasure(metrickey[8]).getFormattedValue());
if (!WEB.equals(report)) {
sonarReport.setFunctionComplexity(resrc.getMeasure(metrickey[9]).getFormattedValue());
}
sonarReport.setFileComplexity(resrc.getMeasure(metrickey[10]).getFormattedValue());
sonarReport.setViolationsDensity(resrc.getMeasure(metrickey[11]).getFormattedValue());
sonarReport.setBlockerViolations(resrc.getMeasure(metrickey[12]).getFormattedValue());
sonarReport.setCriticalViolations(resrc.getMeasure(metrickey[13]).getFormattedValue());
sonarReport.setMajorViolations(resrc.getMeasure(metrickey[14]).getFormattedValue());
sonarReport.setMinorViolations(resrc.getMeasure(metrickey[15]).getFormattedValue());
sonarReport.setInfoViolations(resrc.getMeasure(metrickey[16]).getFormattedValue());
sonarReport.setWeightedViolations(resrc.getMeasure(metrickey[17]).getFormattedValue());
if ((TechnologyTypes.HTML5_WIDGET.equals(techId) || TechnologyTypes.HTML5_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5.equals(techId) || TechnologyTypes.HTML5_JQUERY_MOBILE_WIDGET.equals(techId)
|| TechnologyTypes.HTML5_MULTICHANNEL_JQUERY_WIDGET.equals(techId) || TechnologyTypes.JAVA_WEBSERVICE.equals(techId)) && (JAVA.equals(report) || FUNCTIONAL.equals(report))){
System.out.println(" java ---------- " + report);
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18] +" " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19] +" " +resrc.getMeasure(metrickey[19]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[20] " + metrickey[20] +" " +resrc.getMeasure(metrickey[20]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[21] " + metrickey[21] +" " +resrc.getMeasure(metrickey[21]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[22] " + metrickey[22] +" " +resrc.getMeasure(metrickey[22]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[23] " + metrickey[23] +" " +resrc.getMeasure(metrickey[23]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[24] " + metrickey[24] +" " +resrc.getMeasure(metrickey[24]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[25] " + metrickey[25] +" "+resrc.getMeasure(metrickey[25]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[26] " + metrickey[26] +" " +resrc.getMeasure(metrickey[26]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[27] " + metrickey[27] +" " +resrc.getMeasure(metrickey[27]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[28] " + metrickey[28] +" " +resrc.getMeasure(metrickey[28]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[29] " + metrickey[29] +" " +resrc.getMeasure(metrickey[29]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[30] " + metrickey[30] +" " +resrc.getMeasure(metrickey[30]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[32] " + metrickey[32] +" " +resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setStatements(resrc.getMeasure(metrickey[20]).getFormattedValue());
sonarReport.setPackages(resrc.getMeasure(metrickey[21]).getFormattedValue());
sonarReport.setAccessors(resrc.getMeasure(metrickey[22]).getFormattedValue());
sonarReport.setPublicDocumentedApiDensity((resrc.getMeasure(metrickey[23]).getFormattedValue()));
sonarReport.setPublicUndocumentedApi(resrc.getMeasure(metrickey[24]).getFormattedValue());
sonarReport.setPackageTangleIndex(resrc.getMeasure(metrickey[25]).getFormattedValue());
sonarReport.setPackageCycles(resrc.getMeasure(metrickey[26]).getFormattedValue());
sonarReport.setPackageFeedbackEdges(resrc.getMeasure(metrickey[27]).getFormattedValue());
sonarReport.setPackageTangles(resrc.getMeasure(metrickey[28]).getFormattedValue());
sonarReport.setLackOfCohesionMethods(resrc.getMeasure(metrickey[29]).getFormattedValue());
sonarReport.setResponseForCode(resrc.getMeasure(metrickey[30]).getFormattedValue());
sonarReport.setClassComplexity(resrc.getMeasure(metrickey[32]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JAVA_FUNC);
} else if (SONAR_SOURCE.equals(report) || FUNCTIONAL.equals(report)) {
System.out.println("resrc.getMeasure(metrickey[18] " + metrickey[18]+ " " + resrc.getMeasure(metrickey[18]).getFormattedValue());
System.out.println("resrc.getMeasure(metrickey[19] " + metrickey[19]+ " " + resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setClasses(resrc.getMeasure(metrickey[18]).getFormattedValue());
sonarReport.setFunctions(resrc.getMeasure(metrickey[19]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_SRC_FUNC);
} else if (JS.equals(report) || WEB.equals(report)) {
System.out.println(" js ---------- " + report);
System.out.println("metrickey[31] " + metrickey[31] +" ");
sonarReport.setDirectories(resrc.getMeasure(metrickey[31]).getFormattedValue());
sonarReport.setShowDivElement(REPORT_ELEMENT_JS_WEB);
}
sonarReport.setReportType(report);
sonarReport.setTechnology(technology);
return sonarReport;
} catch (Exception e) {
e.printStackTrace();
// throw new PhrescoException(e);
return null;
}
}
|
diff --git a/src/main/java/be/Balor/Manager/Permissions/Plugins/VaultWrapperPermission.java b/src/main/java/be/Balor/Manager/Permissions/Plugins/VaultWrapperPermission.java
index d66cfd6a..f2bcedd7 100644
--- a/src/main/java/be/Balor/Manager/Permissions/Plugins/VaultWrapperPermission.java
+++ b/src/main/java/be/Balor/Manager/Permissions/Plugins/VaultWrapperPermission.java
@@ -1,182 +1,182 @@
/************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd 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.
*
* AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package be.Balor.Manager.Permissions.Plugins;
import java.util.Set;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.RegisteredServiceProvider;
import be.Balor.Manager.LocaleManager;
import be.Balor.Manager.Exceptions.NoPermissionsPlugin;
import be.Balor.Manager.Permissions.Group;
import be.Balor.bukkit.AdminCmd.ACPluginManager;
/**
* @author Antoine
*
*/
public class VaultWrapperPermission extends SuperPermissions {
protected net.milkbowl.vault.permission.Permission vaultPerm;
protected Chat vaultChat;
/**
*
*/
public VaultWrapperPermission() {
final RegisteredServiceProvider<Chat> rspChat = ACPluginManager
.getServer().getServicesManager().getRegistration(Chat.class);
- if (rspChat != null) {
+ if (rspChat != null && rspChat.getProvider() != null) {
vaultChat = rspChat.getProvider();
}
final RegisteredServiceProvider<net.milkbowl.vault.permission.Permission> rspPerm = ACPluginManager
.getServer()
.getServicesManager()
.getRegistration(net.milkbowl.vault.permission.Permission.class);
- if (rspPerm != null) {
+ if (rspPerm != null && rspPerm.getProvider() != null) {
vaultPerm = rspPerm.getProvider();
}
}
protected boolean isChatEnabled() {
return vaultChat != null && vaultChat.isEnabled();
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#getPermissionLimit
* (org.bukkit.entity.Player, java.lang.String)
*/
@Override
public String getPermissionLimit(final Player p, final String limit) {
if (!isChatEnabled()) {
return super.getPermissionLimit(p, limit);
}
return vaultChat.getPlayerInfoString(p, "admincmd." + limit, "");
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#getPrefix(org.
* bukkit.entity.Player)
*/
@Override
public String getPrefix(final Player player) {
if (!isChatEnabled()) {
return "";
}
return vaultChat.getPlayerPrefix(player);
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#getSuffix(org.
* bukkit.entity.Player)
*/
@Override
public String getSuffix(final Player player) {
if (!isChatEnabled()) {
return "";
}
return vaultChat.getPlayerSuffix(player);
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#getUsers(java.
* lang.String)
*/
@Override
public Set<Player> getUsers(final String groupName)
throws NoPermissionsPlugin {
throw new NoPermissionsPlugin();
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#hasPerm(org.bukkit
* .command.CommandSender, org.bukkit.permissions.Permission, boolean)
*/
@Override
public boolean hasPerm(final CommandSender player, final Permission perm,
final boolean errorMsg) {
return hasPerm(player, perm.getName(), errorMsg);
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#hasPerm(org.bukkit
* .command.CommandSender, java.lang.String, boolean)
*/
@Override
public boolean hasPerm(final CommandSender player, final String perm,
final boolean errorMsg) {
if (vaultPerm.has(player, perm)) {
return true;
} else if (errorMsg) {
LocaleManager.sI18n(player, "errorNotPerm", "p", perm);
}
return false;
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#isInGroup(java
* .lang.String, org.bukkit.entity.Player)
*/
@Override
public boolean isInGroup(final String groupName, final Player player)
throws NoPermissionsPlugin {
return vaultPerm.playerInGroup(player, groupName);
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.Permissions.Plugins.IPermissionPlugin#getGroup(org.bukkit
* .entity.Player)
*/
@Override
public Group getGroup(final Player player) {
final String groupName = vaultPerm.getPrimaryGroup(player);
if (groupName == null) {
return new Group();
} else {
return new Group(groupName, player);
}
}
}
| false | true | public VaultWrapperPermission() {
final RegisteredServiceProvider<Chat> rspChat = ACPluginManager
.getServer().getServicesManager().getRegistration(Chat.class);
if (rspChat != null) {
vaultChat = rspChat.getProvider();
}
final RegisteredServiceProvider<net.milkbowl.vault.permission.Permission> rspPerm = ACPluginManager
.getServer()
.getServicesManager()
.getRegistration(net.milkbowl.vault.permission.Permission.class);
if (rspPerm != null) {
vaultPerm = rspPerm.getProvider();
}
}
| public VaultWrapperPermission() {
final RegisteredServiceProvider<Chat> rspChat = ACPluginManager
.getServer().getServicesManager().getRegistration(Chat.class);
if (rspChat != null && rspChat.getProvider() != null) {
vaultChat = rspChat.getProvider();
}
final RegisteredServiceProvider<net.milkbowl.vault.permission.Permission> rspPerm = ACPluginManager
.getServer()
.getServicesManager()
.getRegistration(net.milkbowl.vault.permission.Permission.class);
if (rspPerm != null && rspPerm.getProvider() != null) {
vaultPerm = rspPerm.getProvider();
}
}
|
diff --git a/Core/src/org/sleuthkit/autopsy/directorytree/NewWindowViewAction.java b/Core/src/org/sleuthkit/autopsy/directorytree/NewWindowViewAction.java
index 01535a00c..f65aaf450 100644
--- a/Core/src/org/sleuthkit/autopsy/directorytree/NewWindowViewAction.java
+++ b/Core/src/org/sleuthkit/autopsy/directorytree/NewWindowViewAction.java
@@ -1,83 +1,85 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 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.directorytree;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import javax.swing.AbstractAction;
import javax.swing.SwingUtilities;
import org.openide.nodes.Node;
import org.openide.windows.Mode;
import org.openide.windows.WindowManager;
import org.sleuthkit.autopsy.corecomponents.DataContentTopComponent;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.TskCoreException;
/**
* Opens new ContentViewer pane in a detached window
*/
public class NewWindowViewAction extends AbstractAction{
private static Logger logger = Logger.getLogger(NewWindowViewAction.class.getName());
private Node contentNode ;
public NewWindowViewAction(String title, Node contentNode){
super(title);
this.contentNode = contentNode;
}
@Override
public void actionPerformed(ActionEvent e) {
Logger.noteAction(this.getClass());
String name = "DataContent";
String s = contentNode.getLookup().lookup(String.class);
if (s != null) {
name = s;
} else {
Content c = contentNode.getLookup().lookup(Content.class);
if (c != null) {
try {
name = c.getUniquePath();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Except while calling Content.getUniquePath() on " + c);
}
}
}
final DataContentTopComponent dctc = DataContentTopComponent.createUndocked(name, null);
Mode m = WindowManager.getDefault().findMode("outputFloat");
m.dockInto(dctc);
dctc.open();
+ // Queue setting the node on the EDT thread to be done later so the dctc
+ // can completely initialize.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
dctc.setNode(contentNode);
}
});
}
}
| true | true | public void actionPerformed(ActionEvent e) {
Logger.noteAction(this.getClass());
String name = "DataContent";
String s = contentNode.getLookup().lookup(String.class);
if (s != null) {
name = s;
} else {
Content c = contentNode.getLookup().lookup(Content.class);
if (c != null) {
try {
name = c.getUniquePath();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Except while calling Content.getUniquePath() on " + c);
}
}
}
final DataContentTopComponent dctc = DataContentTopComponent.createUndocked(name, null);
Mode m = WindowManager.getDefault().findMode("outputFloat");
m.dockInto(dctc);
dctc.open();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
dctc.setNode(contentNode);
}
});
}
| public void actionPerformed(ActionEvent e) {
Logger.noteAction(this.getClass());
String name = "DataContent";
String s = contentNode.getLookup().lookup(String.class);
if (s != null) {
name = s;
} else {
Content c = contentNode.getLookup().lookup(Content.class);
if (c != null) {
try {
name = c.getUniquePath();
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Except while calling Content.getUniquePath() on " + c);
}
}
}
final DataContentTopComponent dctc = DataContentTopComponent.createUndocked(name, null);
Mode m = WindowManager.getDefault().findMode("outputFloat");
m.dockInto(dctc);
dctc.open();
// Queue setting the node on the EDT thread to be done later so the dctc
// can completely initialize.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
dctc.setNode(contentNode);
}
});
}
|
diff --git a/melete-app/src/java/org/etudes/tool/melete/SectionPage.java b/melete-app/src/java/org/etudes/tool/melete/SectionPage.java
index f9174ed1..4138f27c 100644
--- a/melete-app/src/java/org/etudes/tool/melete/SectionPage.java
+++ b/melete-app/src/java/org/etudes/tool/melete/SectionPage.java
@@ -1,1501 +1,1501 @@
/**********************************************************************************
*
* $URL$
* $$
* $Id$
************************************************************************************
*
* Copyright (c) 2008, 2009 Etudes, Inc.
*
* Portions completed before September 1, 2008 Copyright (c) 2004, 2005, 2006, 2007, 2008 Foothill College, ETUDES 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 org.etudes.tool.melete;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIParameter;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import org.etudes.component.app.melete.MeleteResource;
import org.etudes.component.app.melete.Module;
import org.etudes.component.app.melete.Section;
import org.etudes.component.app.melete.SectionResource;
import org.etudes.component.app.melete.MeleteUserPreference;
import org.imsglobal.simplelti.SimpleLTIUtil;
import org.imsglobal.basiclti.BasicLTIUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etudes.api.app.melete.ModuleObjService;
import org.etudes.api.app.melete.ModuleService;
import org.etudes.api.app.melete.SectionObjService;
import org.etudes.api.app.melete.SectionResourceService;
import org.etudes.api.app.melete.MeleteResourceService;
import org.etudes.api.app.melete.SectionService;
import org.etudes.api.app.melete.exception.MeleteException;
import org.etudes.api.app.melete.exception.UserErrorException;
import org.etudes.api.app.melete.MeleteCHService;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.util.ResourceLoader;
import javax.faces.model.SelectItem;
/**
* @author Rashmi
*
* This class is the backing bean for AddModuleSections.jsp and EditModuleSections.jsp page.
*
* Rashmi - 8/14/06 - add license code and show access options
* Rashmi - add section content as a resource using CH and create module collection using CH
* Rashmi - 8/23/06 - use meletelicense instead of modulelicense
* Rashmi - 3/12/07 - configure FCK editor collectionBase and security advisor
* Rashmi - 3/12/07 - show listing in chunks
*/
public abstract class SectionPage implements Serializable {
private StringBuffer author;
protected String contentEditor;
protected String previewContentData;
protected String hiddenUpload;
protected String checkUploadChange;
private boolean success = false;
private boolean renderInstr=false;
private int maxUploadSize;
public String serverLocation;
public String formName;
protected String uploadFileName;
//rendering flags
protected boolean shouldRenderEditor=false;
protected boolean shouldRenderLink=false;
protected boolean shouldRenderLTI=false;
protected boolean shouldRenderUpload=false;
protected boolean shouldRenderNotype = false;
protected boolean shouldLTIDisplayAdvanced = false;
/** Dependency: The logging service. */
protected Log logger = LogFactory.getLog(SectionPage.class);
protected SectionService sectionService;
protected ModuleService moduleService;
protected ServerConfigurationService serverConfigurationService;
protected ModuleObjService module;
protected SectionObjService section;
protected MeleteCHService meleteCHService;
protected ContentHostingService contentservice;
// rashmi - 3.0 added variables
protected String access;
protected SectionResourceService secResource;
private String linkUrl;
private String ltiDescriptor;
private byte[] secContentData;
protected String selResourceIdFromList;
private String nullString = null;
protected String secResourceName;
protected String secResourceDescription;
protected MeleteResource meleteResource;
protected String FCK_CollId;
protected String currLinkUrl;
protected String currLTIDescriptor;
protected String currLTIKey;
protected String currLTIPassword;
protected String currLTIUrl;
protected String displayCurrLink;
protected String newURLTitle;
protected String newLTIDescriptor;
protected ArrayList allContentTypes;
protected String selectedResourceName;
protected String selectedResourceDescription;
protected MeleteResource selectedResource;
protected String oldType;
public SectionPage()
{
module=null;
section=null;
contentEditor=null;
hiddenUpload=null;
checkUploadChange=null;
serverLocation = "http://localhost:8080";
secResourceName=null;
secResourceDescription="";
selResourceIdFromList = null;
secResource = null;
meleteResource = null;
allContentTypes = null;
}
/**
* @return Returns the ModuleService.
*/
public ModuleService getModuleService() {
return moduleService;
}
/**
* @param moduleService The moduleService to set.
*/
public void setModuleService(ModuleService moduleService) {
this.moduleService = moduleService;
}
/**
* @return success
* render sucess message if this flag is true
*/
public boolean getSuccess()
{
return this.success;
}
/**
* @param success
* to set sucess to true if section save is successful.
*/
public void setSuccess(boolean success)
{
this.success = success;
}
// get rendering flags
public boolean getShouldRenderEditor()
{
if(this.section != null && this.section.getContentType() != null)
{
shouldRenderEditor = this.section.getContentType().equals("typeEditor");
}
return shouldRenderEditor;
}
public boolean getShouldRenderLink()
{
shouldRenderLink = false;
if(this.section != null && this.section.getContentType() != null)
{
shouldRenderLink = this.section.getContentType().equals("typeLink");
}
return shouldRenderLink;
}
public boolean getShouldRenderLTI()
{
shouldRenderLTI = false;
if(this.section != null && this.section.getContentType() != null)
{
shouldRenderLTI = this.section.getContentType().equals("typeLTI");
}
return shouldRenderLTI;
}
public boolean getShouldRenderUpload()
{
if(this.section != null && this.section.getContentType() != null)
{
shouldRenderUpload = this.section.getContentType().equals("typeUpload");
}
return shouldRenderUpload;
}
/**
* @return Returns the shouldRenderNotype.
*/
public boolean isShouldRenderNotype() {
if(this.section != null && this.section.getContentType() != null)
{
shouldRenderNotype = this.section.getContentType().equals("notype");
}
return shouldRenderNotype;
}
/**
* @return module
* if module is not set, get the module from session.
* revision -- 12/20 Rashmi -- to refresh module to currModule
*/
public ModuleObjService getModule()
{
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
ModuleObjService nextModule =null;
if(module == null && section != null && section.getModule()!= null )
{
module=(Module)section.getModule();
return module;
}
if(sessionMap.containsKey("currModule"))
{
nextModule= (ModuleObjService)sessionMap.get("currModule");
if (logger.isDebugEnabled()) logger.debug("contains currModule in sessionMap and next curr module and module" + nextModule + module);
}
if(module == null || (nextModule!=null && nextModule.getModuleId() != module.getModuleId()))
{
if (logger.isDebugEnabled()) logger.debug("get module of add section page called and module is null");
module = (ModuleObjService)sessionMap.get("currModule");
}
return module;
}
public void setModule(ModuleObjService module)
{
this.module = module;
}
/**
* @return section.
* create a new instance of section and assign default values.
* set name from user
*
* Revision -- 11/22 user info from session
*/
public SectionObjService getSection()
{
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
if (null == this.section) {
if (logger.isDebugEnabled()) logger.debug("get section is null so creating one");
this.section = new Section();
this.section.setContentType("notype");
// user info from session
this.section.setCreatedByFname((String)sessionMap.get("firstName"));
this.section.setCreatedByLname((String)sessionMap.get("lastName"));
this.section.setTextualContent(true);
}
return this.section;
}
/*
* set section. This method is called to set section for edit
* by breadcrumps hyperlinks in editmodulesections.jsp page and
* also by editmodule.jsp and list_modules_auth.jsp
*
* Revision -- Rashmi 12/20 to set section as null
*/
public void setSection(SectionObjService sec)
{
try
{
this.section = null;
if(sec !=null)
{
if (logger.isDebugEnabled()) logger.debug("setSection called and section is not null");
this.module = (Module)sec.getModule();
this.section = sec;
}
}catch(Exception ex){logger.debug(ex.toString());}
}
/*
* added to set module null. seggregated from the setSection method
*/
public void setModuleNull()
{
this.module = null;
}
/*
* get the max uploads size allowed for the course.
* revision - get course from session 11/22 Rashmi
*
* revision -- Rashmi 2/1/05 in accordance to service etc
*
*/
public int getMaxUploadSize()
{
/*
* get from session
*/
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
int sz = Integer.parseInt((String)sessionMap.get("maxSize"));
if (logger.isDebugEnabled()) logger.debug("Size is "+sz);
return sz;
}
//Mallika - new code beg
public void setMaxUploadSize(int sz)
{
this.maxUploadSize = sz;
}
//Mallika - new code end
/**
* concatenates first name and last name of the creator of this section.
* @return author name
*/
public String getAuthor()
{
if(author == null)
{
author = new StringBuffer();
author.append(this.section.getCreatedByFname() + " ");
author.append(this.section.getCreatedByLname());
}
return author.toString();
}
/**
* not required as the fields are disabled.
*/
public void setAuthor(String author){ }
/**
* @param contentEditor
*
*/
public void setContentEditor(String contentEditor){
this.contentEditor = contentEditor;
}
/**
* @return
*/
public String getHiddenUpload()
{
try{
if(section!=null && hiddenUpload == null && meleteResource != null)
{
ContentResource cr = getMeleteCHService().getResource(meleteResource.getResourceId());
hiddenUpload =cr.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
checkUploadChange = hiddenUpload;
}
else if(hiddenUpload !=null)
{
hiddenUpload = hiddenUpload.substring(hiddenUpload.lastIndexOf(File.separator)+1);
}
}catch(Exception ex){
logger.debug("error accessing hidden upload field");}
return hiddenUpload;
}
/**
* @param hiddenUpload
*/
public void setHiddenUpload(String hiddenUpload)
{
this.hiddenUpload = hiddenUpload;
}
/**
* @param event
* @throws AbortProcessingException
* show hides the input boxes to specify the uploaded file name,
* link or writing new content. based on the user radio button selection.
*/
public void showHideContent(ValueChangeEvent event)throws AbortProcessingException
{
FacesContext context = FacesContext.getCurrentInstance();
UIInput contentTypeRadio = (UIInput)event.getComponent();
shouldRenderEditor = contentTypeRadio.getValue().equals("typeEditor");
shouldRenderLink = contentTypeRadio.getValue().equals("typeLink");
shouldRenderUpload = contentTypeRadio.getValue().equals("typeUpload");
shouldRenderNotype = contentTypeRadio.getValue().equals("notype");
shouldRenderLTI = contentTypeRadio.getValue().equals("typeLTI");
selResourceIdFromList = null;
secResourceName = null;
secResourceDescription = null;
setMeleteResource(null);
oldType = section.getContentType();
if(contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath").setRendered(shouldRenderUpload);
contentTypeRadio.findComponent(getFormName()).findComponent("BrowsePath").setRendered(shouldRenderUpload);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("link") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("link").setRendered(shouldRenderLink);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView").setRendered(shouldRenderLTI);
}
if(shouldRenderEditor)
{
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
String usereditor = preferencePage.getUserEditor();
this.contentEditor = new String("Compose content here");
if(contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor") != null && usereditor.equals(preferencePage.FCKEDITOR))
{
contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor").setRendered(shouldRenderEditor);
setFCKCollectionAttrib();
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView") != null && usereditor.equals(preferencePage.SFERYX))
{
preferencePage.setDisplaySferyx(true);
contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView").setRendered(shouldRenderEditor);
}
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm") != null)
{
section.setContentType((String)contentTypeRadio.getValue());
contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm").setRendered(false);
}
//Upon changing content type, license is set by the selected resource, if there is one,
//or via User preferences
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(context);
lPage.setFormName(this.formName);
lPage.resetValues();
/*if (getMeleteResource().getResourceId() != null)
{
lPage.setInitialValues(this.formName, getMeleteResource());
}
else
{*/
ValueBinding binding2 = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding2.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
lPage.setInitialValues(this.formName, mup);
//}
//The code below is required because the setter for the license code kicks in by default
//and we need to actually set the component with the values determined above.(ME-1071)
UIComponent licComp = (UIComponent)contentTypeRadio.findComponent(getFormName());
if(licComp != null && licComp.findComponent("ResourcePropertiesPanel") != null && licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm") != null
&& licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView") != null)
{
licComp = licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView");
UIInput uiInp = (UIInput)licComp.findComponent("licenseCodes");
uiInp.setValue(lPage.getLicenseCodes());
licComp = (UIComponent)contentTypeRadio.findComponent(getFormName()).findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("CCLicenseForm");
uiInp = (UIInput)licComp.findComponent("allowCmrcl");
uiInp.setValue(lPage.getAllowCmrcl());
uiInp = (UIInput)licComp.findComponent("allowMod");
uiInp.setValue(lPage.getAllowMod());
if (lPage.isShouldRenderCC())
{
uiInp = (UIInput)licComp.findComponent("copy_owner");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year");
uiInp.setValue(lPage.getCopyright_year());
}
if (lPage.isShouldRenderCopyright()||lPage.isShouldRenderPublicDomain()||lPage.isShouldRenderFairUse())
{
uiInp = (UIInput)licComp.findComponent("copy_owner1");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year1");
uiInp.setValue(lPage.getCopyright_year());
}
}
}
/**
* @param event
* @throws AbortProcessingException
* Changes the LTI view from basic to advanced.
*/
public void toggleLTIDisplay(ValueChangeEvent event)throws AbortProcessingException
{
// Nothing to do - because the setter handles it all
}
public String getLTIDisplay()
{
if ( shouldLTIDisplayAdvanced ) return "Advanced";
return "Basic";
}
public void setLTIDisplay(String newDisplay)
{
shouldLTIDisplayAdvanced = "Advanced".equals(newDisplay);
}
public String getLTIUrl()
{
return currLTIUrl;
}
public void setLTIUrl(String LTIUrl)
{
currLTIUrl = LTIUrl;
fixDescriptor();
}
public String getLTIKey()
{
return currLTIKey;
}
public void setLTIKey(String LTIKey)
{
currLTIKey = LTIKey;
fixDescriptor();
}
public String getLTIPassword()
{
return currLTIPassword;
}
public void setLTIPassword(String LTIPassword)
{
currLTIPassword = LTIPassword;
fixDescriptor();
}
// Produce a basic descriptor from the URL and Password
private void fixDescriptor()
{
if ( currLTIUrl == null ) return;
String desc =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<basic_lti_link\n" +
" xmlns=\"http://www.imsglobal.org/xsd/imsbasiclti_v1p0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <melete-basic>true</melete-basic> \n" +
" <launch_url>"+currLTIUrl+"</launch_url> \n" +
" <x-secure>\n" ;
if ( currLTIKey != null && currLTIKey.trim().length() > 0 ) {
desc = desc + " <launch_key>"+currLTIKey+"</launch_key> \n" ;
}
if ( currLTIPassword != null && currLTIPassword.trim().length() > 0 ) {
desc = desc + " <launch_secret>"+currLTIPassword+"</launch_secret> \n" ;
}
desc = desc + " </x-secure>\n";
desc = desc + "</basic_lti_link>\n";
setLTIDescriptor(desc);
}
public boolean getShouldLTIDisplayAdvanced()
{
return shouldLTIDisplayAdvanced;
}
public boolean getShouldLTIDisplayBasic()
{
return ! shouldLTIDisplayAdvanced;
}
/*
* modality is required. check if one is selected or not
*/
protected boolean validateModality()
{
if(!(this.section.isAudioContent()|| this.section.isTextualContent()|| this.section.isVideoContent()))
return false;
return true;
}
/*
* adds resource to specified melete module or uploads collection.
*/
public String addResourceToMeleteCollection(String uploadHomeDir, String addCollId) throws UserErrorException,MeleteException
{
try{
String res_mime_type=getMeleteCHService().MIME_TYPE_EDITOR;
boolean encodingFlag = false;
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
res_mime_type= getMeleteCHService().MIME_TYPE_EDITOR;
secContentData = new byte[contentEditor.length()];
secContentData = contentEditor.getBytes();
encodingFlag = true;
secResourceName = getMeleteCHService().getTypeEditorSectionName(section.getSectionId());
secResourceDescription="compose content";
}
if (section.getContentType().equals("typeLink")) {
res_mime_type = getMeleteCHService().MIME_TYPE_LINK;
Util.validateLink(getLinkUrl());
if ((secResourceName == null)|| (secResourceName.trim().length() == 0))
throw new MeleteException("URL_title_reqd");
secContentData = new byte[linkUrl.length()];
secContentData = linkUrl.getBytes();
}
if (section.getContentType().equals("typeLTI")) {
if(getLTIUrl() != null)
Util.validateLink(getLTIUrl());
String pitch = getLTIDescriptor();
if (ltiDescriptor == null || ltiDescriptor.trim().length() == 0) {
throw new MeleteException("add_section_empty_lti");
}
if (! ( SimpleLTIUtil.validateDescriptor(ltiDescriptor)
|| BasicLTIUtil.validateDescriptor(ltiDescriptor) != null ) ) {
throw new MeleteException("add_section_bad_lti");
}
res_mime_type = getMeleteCHService().MIME_TYPE_LTI;
secContentData = new byte[ltiDescriptor.length()];
secContentData = ltiDescriptor.getBytes();
}
if (section.getContentType().equals("typeUpload")) {
res_mime_type = uploadSectionContent("file1");
if (logger.isDebugEnabled())
logger.debug("new names for upload content is"
+ res_mime_type + "," + secResourceName);
if (res_mime_type == null)
throw new MeleteException("select_or_cancel");
}
ResourcePropertiesEdit res = getMeleteCHService().fillInSectionResourceProperties(encodingFlag,
secResourceName, secResourceDescription);
if (logger.isDebugEnabled())
logger.debug("add resource now " + secResourceName);
String newResourceId = getMeleteCHService().addResourceItem(secResourceName, res_mime_type, addCollId, secContentData,res);
return newResourceId;
}
catch(UserErrorException uex)
{
throw uex;
}
catch(MeleteException me)
{
logger.debug("error in creating resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in creating resource for section content" + e.toString());
//e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
/*
* adds resource to specified melete module or uploads collection.
*/
public void editMeleteCollectionResource(String uploadHomeDir,String resourceId) throws MeleteException
{
if (logger.isDebugEnabled()) logger.debug("edit resource function");
String res_mime_type=null;
boolean encodingFlag = false;
try
{
if (logger.isDebugEnabled()) logger.debug("editing properties for " + resourceId);
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
getMeleteCHService().editResource(resourceId, contentEditor);
}
if(resourceId != null && (section.getContentType().equals("typeLink") || section.getContentType().equals("typeUpload") || section.getContentType().equals("typeLTI")))
{
getMeleteCHService().editResourceProperties(resourceId,secResourceName,secResourceDescription);
}
}
catch(MeleteException me)
{
logger.debug("error in editing resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in editing resource for section content" + e.toString());
e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
public abstract String saveHere();
/*
* listener to set action for save button for setting data from html editor
*/
public void saveListener(ActionEvent event)
{
if (logger.isDebugEnabled()) logger.debug("Hello Rashmi ------saveListener called");
}
/*
* Render instructions on preview page
*/
public boolean getRenderInstr()
{
- if (this.section.getInstr()== null ||this.section.getInstr().length() == 0 )
+ if (this.section == null || this.section.getInstr()== null ||this.section.getInstr().length() == 0 )
renderInstr=false;
else renderInstr=true;
return renderInstr;
}
/*
* Revised Rashmi on 1/21/05
* new var module number set back to 0
*/
public void resetSectionValues()
{
this.section= null;
contentEditor=null;
setSuccess(false);
hiddenUpload=null;
checkUploadChange=null;
uploadFileName = null;
secResource = null;
secResourceName = null;
secResourceDescription=null;
secContentData=null;
selResourceIdFromList = null;
meleteResource = null;
setLicenseCodes(null);
linkUrl = null;
ltiDescriptor = null;
FCK_CollId = null;
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
FacesContext ctx = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{remoteBrowserFile}");
RemoteBrowserFile rbPage = (RemoteBrowserFile)binding.getValue(ctx);
if(rbPage != null)
{
rbPage.setRemoteFiles(null);
rbPage.setRemoteLinkFiles(null);
}
shouldRenderEditor=false;
shouldRenderLink=false;
shouldRenderLTI=false;
shouldRenderUpload=false;
shouldRenderNotype = false;
allContentTypes = null;
oldType = null;
if (logger.isDebugEnabled()) logger.debug("!!!!!!!!!reseting section values done !!!!!!!");
}
/*
* reset resource values and license from java cache when its deleted and associated with current section
*/
public void resetMeleteResourceValues()
{
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
secResourceName = null;
secResourceDescription = null;
uploadFileName = null;
setLicenseCodes(null);
}
protected void processSelectedResource(String selResourceIdFromList)
{
FacesContext ctx = FacesContext.getCurrentInstance();
try{
currLinkUrl = getLinkContent(selResourceIdFromList);
ContentResource cr= getMeleteCHService().getResource(selResourceIdFromList);
this.secResourceName = cr.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.secResourceDescription = cr.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
//get resource object
selectedResource = (MeleteResource)sectionService.getMeleteResource(selResourceIdFromList);
//just take resource properties from this object as its assoc with another section
if(selectedResource != null)
{
meleteResource = selectedResource;
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(ctx);
lPage.setInitialValues(formName, selectedResource);
// render selected file name
selectedResourceName = secResourceName;
if (logger.isDebugEnabled()) logger.debug("values changed in resource action for res name and desc" + secResourceName + secResourceDescription);
}
}
catch(Exception ex)
{
logger.debug("error while accessing content resource" + ex.toString());
}
}
/**
* @return remove values from session before closing
*/
public String cancel()
{
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
if(sessionMap.containsKey("currModule"))
{
sessionMap.remove("currModule");
}
resetSectionValues();
return "list_auth_modules";
}
/**
* @return uploaded file or link name for preview page
*/
public String getContentLink()
{
if (logger.isDebugEnabled()) logger.debug("getContentLink fn is called");
return "#";
}
public String getFormName(){
return formName;
}
/**
* @param formName
*/
public void setFormName(String formName){
this.formName = formName;
}
//melete 3.0 work
/**
* @param access The access to set.
*/
public void setAccess(String access) {
this.access = access;
}
/**
* @return Returns the access.
*/
public String getAccess() {
if(this.access == null)
this.access = "site";
return access;
}
/**
* @return Returns the m_license.
*/
/* public SectionResourceLicenseSelector getM_license() {
if(m_license == null)
{
m_license = new SectionResourceLicenseSelector();
if (getMeleteResource().getResourceId() != null)
{
m_license.setInitialValues(this.formName, sectionService,getMeleteResource());
}
else
{
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
m_license.setInitialValues(this.formName, sectionService, mup);
}
}
return m_license;
}*/
/**
* @param m_license The m_license to set.
*/
/* public void setM_license(SectionResourceLicenseSelector m_license) {
this.m_license = m_license;
}*/
public void setLicenseCodes(String licenseCodes)
{
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(context);
lPage.setFormName(formName);
lPage.setLicenseCodes(licenseCodes);
}
/**
* @return Returns the linkUrl.
*/
public String getLinkUrl() {
if(linkUrl == null)linkUrl ="http://";
return linkUrl;
}
/**
* @param linkUrl The linkUrl to set.
* as from section table we will remove link,contentpath and uploadpath fields.
* This will get stored in resources.
*/
public void setLinkUrl(String linkUrl) {
this.linkUrl = linkUrl;
}
/**
* @return Returns the ltiDescriptor.
*/
public String getLTIDescriptor() {
if(ltiDescriptor == null)ltiDescriptor ="";
return ltiDescriptor;
}
/**
* @param ltiDescriptor The ltiDescriptor to set.
* as from section table we will remove link,contentpath and uploadpath fields.
* This will get stored in resources.
*/
public void setLTIDescriptor(String ltiDescriptor) {
this.ltiDescriptor = ltiDescriptor;
}
/*
* get material from the new provided link
*/
public void createLinkUrl()
{
if (secResourceName == null || secResourceName.length() == 0) secResourceName = linkUrl;
secContentData = new byte[getLinkUrl().length()];
secContentData = getLinkUrl().getBytes();
}
/*
* get material from the new provided Descriptor
*/
public void createLTIDescriptor()
{
if (secResourceName == null || secResourceName.length() == 0) secResourceName = "create name in createLTIDescriptor";
secContentData = new byte[getLTIDescriptor().length()];
secContentData = getLTIDescriptor().getBytes();
}
/*
* code for uploading content
*/
public String uploadSectionContent(String fieldname) throws Exception
{
try{
FacesContext context = FacesContext.getCurrentInstance();
org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context.getExternalContext().getRequestMap().get(fieldname);
if(fi !=null && fi.getName() != null && fi.getName().length() !=0)
{
Util.validateUploadFileName(fi.getName());
// filename on the client
secResourceName = fi.getName();
if (secResourceName.indexOf("/") != -1)
{
secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/")+1);
}
if (secResourceName.indexOf("\\") != -1)
{
secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\")+1);
}
if (logger.isDebugEnabled()) logger.debug("Rsrc name is "+secResourceName);
if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int)fi.getSize());
this.secContentData= new byte[(int)fi.getSize()];
InputStream is = fi.getInputStream();
is.read(this.secContentData);
String secContentMimeType = fi.getContentType();
if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType);
return secContentMimeType;
}
else
{
logger.debug("File being uploaded is NULL");
return null;
}
}
catch(MeleteException me)
{
logger.debug("file upload FAILED" + me.toString());
throw me;
}
catch(Exception e)
{
logger.error("file upload FAILED" + e.toString());
return null;
}
}
// to add spring dependency methods
/**
* @return Returns the SectionService.
*/
public SectionService getSectionService() {
return sectionService;
}
/**
* @param SectionService The SectionService to set.
*/
public void setSectionService(SectionService sectionService) {
this.sectionService = sectionService;
}
/**
* @param serverConfigurationService The ServerConfigurationService to set.
*/
public void setServerConfigurationService(
ServerConfigurationService serverConfigurationService) {
this.serverConfigurationService = serverConfigurationService;
}
/**
* @return Returns the secResource.
*/
public SectionResourceService getSecResource() {
if (null == this.secResource || (this.section != null && this.section.getSectionResource() == null)) {
this.secResource = new SectionResource();
}
else this.secResource = this.section.getSectionResource();
return secResource;
}
/**
* @param secResource The secResource to set.
*/
public void setSecResource(SectionResourceService secResource) {
this.secResource = secResource;
}
/**
* @return Returns the nullString.
*/
public String getNullString() {
return nullString;
}
/**
* @return Returns the secResourceDescription.
*/
public String getSecResourceDescription() {
return secResourceDescription;
}
/**
* @param secResourceDescription The secResourceDescription to set.
*/
public void setSecResourceDescription(String secResourceDescription) {
this.secResourceDescription = secResourceDescription;
}
/**
* @return Returns the secResourceName.
*/
public String getSecResourceName() {
return secResourceName;
}
/**
* @param secResourceName The secResourceName to set.
*/
public void setSecResourceName(String secResourceName) {
this.secResourceName = secResourceName;
}
/**
* @return Returns the secContentData.
*/
public byte[] getSecContentData() {
return secContentData;
}
public String getPreviewContentData() {
return previewContentData;
}
/**
* @return Returns the meleteCHService.
*/
public MeleteCHService getMeleteCHService() {
return meleteCHService;
}
public void setMeleteCHService(MeleteCHService meleteCHService) {
this.meleteCHService = meleteCHService;
}
/**
* @return Returns the contentservice.
*/
public ContentHostingService getContentservice() {
return contentservice;
}
/**
* @param contentservice The contentservice to set.
*/
public void setContentservice(ContentHostingService contentservice) {
this.contentservice = contentservice;
}
/**
* @return Returns the meleteResource.
*/
public MeleteResource getMeleteResource() {
logger.debug("check meleteResource" + meleteResource + secResource);
if(formName.equals("AddSectionForm") && meleteResource == null)
{
this.meleteResource = new MeleteResource();
}
if(formName.equals("EditSectionForm") && meleteResource == null)
{
if(secResource != null) this.meleteResource = (MeleteResource)this.secResource.getResource();
if(meleteResource == null) this.meleteResource = new MeleteResource();
}
return meleteResource;
}
/**
* @param meleteResource The meleteResource to set.
*/
public void setMeleteResource(MeleteResource meleteResource) {
this.meleteResource = meleteResource;
}
public void setFCKCollectionAttrib()
{
FCK_CollId = getMeleteCHService().getUploadCollectionId();
String attrb = "fck.security.advisor." + FCK_CollId;
SessionManager.getCurrentSession().setAttribute(attrb, new SecurityAdvisor()
{
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
try
{
Collection meleteGrpAllow = org.sakaiproject.authz.cover.AuthzGroupService.getAuthzGroupsIsAllowed(userId,"melete.author",null );
String anotherRef = new String(reference);
anotherRef = anotherRef.replace("/content/private/meleteDocs" ,"/site");
org.sakaiproject.entity.api.Reference ref1 = org.sakaiproject.entity.cover.EntityManager.newReference(anotherRef);
if (meleteGrpAllow.contains("/site/"+ref1.getContainer()))
{
return SecurityAdvice.ALLOWED;
}
}
catch (Exception e)
{
logger.warn("exception in setting security advice for FCK collection" + e.toString());
return SecurityAdvice.NOT_ALLOWED;
}
return SecurityAdvice.NOT_ALLOWED;
}
});
}
/**
* @return Returns the fCK_CollId.
*/
public String getFCK_CollId() {
return FCK_CollId;
}
/**
* @return Returns the selResourceIdFromList.
*/
public String getSelResourceIdFromList() {
FacesContext ctx = FacesContext.getCurrentInstance();
ValueBinding binding =Util.getBinding("#{listResourcesPage}");
ListResourcesPage listResPage = (ListResourcesPage) binding.getValue(ctx);
selResourceIdFromList = listResPage.getSelResourceIdFromList();
return selResourceIdFromList;
}
/**
* @return Returns the uploadFileName.
*/
public String getUploadFileName() {
if(secResourceName != null && secResourceName.length() !=0) uploadFileName = secResourceName;
return uploadFileName;
}
/**
* @param uploadFileName The uploadFileName to set.
*/
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getDisplayCurrLink()
{
String retval = currLinkUrl;
if (retval != null && retval.length() > 50)
displayCurrLink = retval.substring(0, 50) + "...";
else
displayCurrLink = retval;
return displayCurrLink;
}
public String getDisplayCurrLTI()
{
String retval = secResourceName;
if (retval != null && retval.length() > 50)
displayCurrLink = retval.substring(0, 50) + "...";
else
displayCurrLink = retval;
return displayCurrLink;
}
/**
* @return Returns the currLinkUrl.
*/
public String getCurrLinkUrl()
{
if (!(getLinkUrl().equals("http://") || getLinkUrl().equals("https://"))) currLinkUrl = getLinkUrl();
return currLinkUrl;
}
public String getCurrLTIUrl()
{
if ( meleteResource != null )
{
try
{
String rUrl = getMeleteCHService().getResourceUrl(meleteResource.getResourceId());
return rUrl;
}
catch (Exception e)
{
return "about:blank";
}
}
return "about:blank";
}
/**
* @param currLinkUrl
* The currLinkUrl to set.
*/
public void setCurrLinkUrl(String currLinkUrl)
{
this.currLinkUrl = currLinkUrl;
}
/**
* @return Returns the currLTIDescriptor.
*/
public String getCurrLTIDescriptor()
{
if (!(getLTIDescriptor().equals("http://") || getLTIDescriptor().equals("https://"))) currLTIDescriptor = getLTIDescriptor();
return currLTIDescriptor;
}
/**
* @param currLTIDescriptor
* The currLTIDescriptor to set.
*/
public void setCurrLTIDescriptor(String currLTIDescriptor)
{
this.currLTIDescriptor = currLTIDescriptor;
}
/**
* @return Returns the selectedResource.
*/
public MeleteResource getSelectedResource()
{
if (selectedResource == null) selectedResource = new MeleteResource();
return selectedResource;
}
/**
* @param selectedResource
* The selectedResource to set.
*/
public void setSelectedResource(MeleteResource selectedResource)
{
this.selectedResource = selectedResource;
}
/**
* @return Returns the selectedResourceDescription.
*/
public String getSelectedResourceDescription()
{
return selectedResourceDescription;
}
/**
* @param selectedResourceDescription
* The selectedResourceDescription to set.
*/
public void setSelectedResourceDescription(String selectedResourceDescription)
{
this.selectedResourceDescription = selectedResourceDescription;
}
/**
* @return Returns the selectedResourceName.
*/
public String getSelectedResourceName()
{
return selectedResourceName;
}
/**
* @param selectedResourceName
* The selectedResourceName to set.
*/
public void setSelectedResourceName(String selectedResourceName)
{
this.selectedResourceName = selectedResourceName;
}
/**
* @return the newURLTitle
*/
public String getNewURLTitle()
{
return this.newURLTitle;
}
/**
* @param newURLTitle the newURLTitle to set
*/
public void setNewURLTitle(String newURLTitle)
{
this.newURLTitle = newURLTitle;
}
/**
* @return the newLTIDescriptor
*/
public String getNewLTIDescriptor()
{
return this.newLTIDescriptor;
}
/**
* @return the newLTIDescriptor to set
*/
public void setNewLTIDescriptor(String newLTIDescriptor)
{
this.newLTIDescriptor = newLTIDescriptor;
}
public List getAllContentTypes() {
FacesContext context = FacesContext.getCurrentInstance();
ResourceLoader bundle = new ResourceLoader(
"org.etudes.tool.melete.bundle.Messages");
if (allContentTypes == null) {
Map sessionMap = context.getExternalContext().getSessionMap();
String userId = (String) sessionMap.get("userId");
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage) binding.getValue(context);
boolean userLTIChoice = preferencePage.getUserLTIChoice(userId);
allContentTypes = new ArrayList<SelectItem>(0);
String notypemsg = bundle.getString("addmodulesections_choose_one");
allContentTypes.add(new SelectItem("notype", notypemsg));
String typeEditormsg = bundle.getString("addmodulesections_compose");
allContentTypes.add(new SelectItem("typeEditor", typeEditormsg));
String typeUploadmsg = bundle.getString("addmodulesections_upload_local");
allContentTypes.add(new SelectItem("typeUpload", typeUploadmsg));
String typeLinkmsg = bundle.getString("addmodulesections_link_url");
allContentTypes.add(new SelectItem("typeLink", typeLinkmsg));
if (userLTIChoice) {
String typeLTImsg = bundle.getString("addmodulesections_lti");
allContentTypes.add(new SelectItem("typeLTI", typeLTImsg));
}
}
return allContentTypes;
}
protected String getDisplayName(String resourceId)
{
return getMeleteCHService().getDisplayName(resourceId);
}
protected String getLinkContent(String resourceId)
{
return getMeleteCHService().getLinkContent(resourceId);
}
}
| true | true | public void showHideContent(ValueChangeEvent event)throws AbortProcessingException
{
FacesContext context = FacesContext.getCurrentInstance();
UIInput contentTypeRadio = (UIInput)event.getComponent();
shouldRenderEditor = contentTypeRadio.getValue().equals("typeEditor");
shouldRenderLink = contentTypeRadio.getValue().equals("typeLink");
shouldRenderUpload = contentTypeRadio.getValue().equals("typeUpload");
shouldRenderNotype = contentTypeRadio.getValue().equals("notype");
shouldRenderLTI = contentTypeRadio.getValue().equals("typeLTI");
selResourceIdFromList = null;
secResourceName = null;
secResourceDescription = null;
setMeleteResource(null);
oldType = section.getContentType();
if(contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath").setRendered(shouldRenderUpload);
contentTypeRadio.findComponent(getFormName()).findComponent("BrowsePath").setRendered(shouldRenderUpload);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("link") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("link").setRendered(shouldRenderLink);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView").setRendered(shouldRenderLTI);
}
if(shouldRenderEditor)
{
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
String usereditor = preferencePage.getUserEditor();
this.contentEditor = new String("Compose content here");
if(contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor") != null && usereditor.equals(preferencePage.FCKEDITOR))
{
contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor").setRendered(shouldRenderEditor);
setFCKCollectionAttrib();
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView") != null && usereditor.equals(preferencePage.SFERYX))
{
preferencePage.setDisplaySferyx(true);
contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView").setRendered(shouldRenderEditor);
}
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm") != null)
{
section.setContentType((String)contentTypeRadio.getValue());
contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm").setRendered(false);
}
//Upon changing content type, license is set by the selected resource, if there is one,
//or via User preferences
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(context);
lPage.setFormName(this.formName);
lPage.resetValues();
/*if (getMeleteResource().getResourceId() != null)
{
lPage.setInitialValues(this.formName, getMeleteResource());
}
else
{*/
ValueBinding binding2 = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding2.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
lPage.setInitialValues(this.formName, mup);
//}
//The code below is required because the setter for the license code kicks in by default
//and we need to actually set the component with the values determined above.(ME-1071)
UIComponent licComp = (UIComponent)contentTypeRadio.findComponent(getFormName());
if(licComp != null && licComp.findComponent("ResourcePropertiesPanel") != null && licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm") != null
&& licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView") != null)
{
licComp = licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView");
UIInput uiInp = (UIInput)licComp.findComponent("licenseCodes");
uiInp.setValue(lPage.getLicenseCodes());
licComp = (UIComponent)contentTypeRadio.findComponent(getFormName()).findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("CCLicenseForm");
uiInp = (UIInput)licComp.findComponent("allowCmrcl");
uiInp.setValue(lPage.getAllowCmrcl());
uiInp = (UIInput)licComp.findComponent("allowMod");
uiInp.setValue(lPage.getAllowMod());
if (lPage.isShouldRenderCC())
{
uiInp = (UIInput)licComp.findComponent("copy_owner");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year");
uiInp.setValue(lPage.getCopyright_year());
}
if (lPage.isShouldRenderCopyright()||lPage.isShouldRenderPublicDomain()||lPage.isShouldRenderFairUse())
{
uiInp = (UIInput)licComp.findComponent("copy_owner1");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year1");
uiInp.setValue(lPage.getCopyright_year());
}
}
}
/**
* @param event
* @throws AbortProcessingException
* Changes the LTI view from basic to advanced.
*/
public void toggleLTIDisplay(ValueChangeEvent event)throws AbortProcessingException
{
// Nothing to do - because the setter handles it all
}
public String getLTIDisplay()
{
if ( shouldLTIDisplayAdvanced ) return "Advanced";
return "Basic";
}
public void setLTIDisplay(String newDisplay)
{
shouldLTIDisplayAdvanced = "Advanced".equals(newDisplay);
}
public String getLTIUrl()
{
return currLTIUrl;
}
public void setLTIUrl(String LTIUrl)
{
currLTIUrl = LTIUrl;
fixDescriptor();
}
public String getLTIKey()
{
return currLTIKey;
}
public void setLTIKey(String LTIKey)
{
currLTIKey = LTIKey;
fixDescriptor();
}
public String getLTIPassword()
{
return currLTIPassword;
}
public void setLTIPassword(String LTIPassword)
{
currLTIPassword = LTIPassword;
fixDescriptor();
}
// Produce a basic descriptor from the URL and Password
private void fixDescriptor()
{
if ( currLTIUrl == null ) return;
String desc =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<basic_lti_link\n" +
" xmlns=\"http://www.imsglobal.org/xsd/imsbasiclti_v1p0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <melete-basic>true</melete-basic> \n" +
" <launch_url>"+currLTIUrl+"</launch_url> \n" +
" <x-secure>\n" ;
if ( currLTIKey != null && currLTIKey.trim().length() > 0 ) {
desc = desc + " <launch_key>"+currLTIKey+"</launch_key> \n" ;
}
if ( currLTIPassword != null && currLTIPassword.trim().length() > 0 ) {
desc = desc + " <launch_secret>"+currLTIPassword+"</launch_secret> \n" ;
}
desc = desc + " </x-secure>\n";
desc = desc + "</basic_lti_link>\n";
setLTIDescriptor(desc);
}
public boolean getShouldLTIDisplayAdvanced()
{
return shouldLTIDisplayAdvanced;
}
public boolean getShouldLTIDisplayBasic()
{
return ! shouldLTIDisplayAdvanced;
}
/*
* modality is required. check if one is selected or not
*/
protected boolean validateModality()
{
if(!(this.section.isAudioContent()|| this.section.isTextualContent()|| this.section.isVideoContent()))
return false;
return true;
}
/*
* adds resource to specified melete module or uploads collection.
*/
public String addResourceToMeleteCollection(String uploadHomeDir, String addCollId) throws UserErrorException,MeleteException
{
try{
String res_mime_type=getMeleteCHService().MIME_TYPE_EDITOR;
boolean encodingFlag = false;
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
res_mime_type= getMeleteCHService().MIME_TYPE_EDITOR;
secContentData = new byte[contentEditor.length()];
secContentData = contentEditor.getBytes();
encodingFlag = true;
secResourceName = getMeleteCHService().getTypeEditorSectionName(section.getSectionId());
secResourceDescription="compose content";
}
if (section.getContentType().equals("typeLink")) {
res_mime_type = getMeleteCHService().MIME_TYPE_LINK;
Util.validateLink(getLinkUrl());
if ((secResourceName == null)|| (secResourceName.trim().length() == 0))
throw new MeleteException("URL_title_reqd");
secContentData = new byte[linkUrl.length()];
secContentData = linkUrl.getBytes();
}
if (section.getContentType().equals("typeLTI")) {
if(getLTIUrl() != null)
Util.validateLink(getLTIUrl());
String pitch = getLTIDescriptor();
if (ltiDescriptor == null || ltiDescriptor.trim().length() == 0) {
throw new MeleteException("add_section_empty_lti");
}
if (! ( SimpleLTIUtil.validateDescriptor(ltiDescriptor)
|| BasicLTIUtil.validateDescriptor(ltiDescriptor) != null ) ) {
throw new MeleteException("add_section_bad_lti");
}
res_mime_type = getMeleteCHService().MIME_TYPE_LTI;
secContentData = new byte[ltiDescriptor.length()];
secContentData = ltiDescriptor.getBytes();
}
if (section.getContentType().equals("typeUpload")) {
res_mime_type = uploadSectionContent("file1");
if (logger.isDebugEnabled())
logger.debug("new names for upload content is"
+ res_mime_type + "," + secResourceName);
if (res_mime_type == null)
throw new MeleteException("select_or_cancel");
}
ResourcePropertiesEdit res = getMeleteCHService().fillInSectionResourceProperties(encodingFlag,
secResourceName, secResourceDescription);
if (logger.isDebugEnabled())
logger.debug("add resource now " + secResourceName);
String newResourceId = getMeleteCHService().addResourceItem(secResourceName, res_mime_type, addCollId, secContentData,res);
return newResourceId;
}
catch(UserErrorException uex)
{
throw uex;
}
catch(MeleteException me)
{
logger.debug("error in creating resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in creating resource for section content" + e.toString());
//e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
/*
* adds resource to specified melete module or uploads collection.
*/
public void editMeleteCollectionResource(String uploadHomeDir,String resourceId) throws MeleteException
{
if (logger.isDebugEnabled()) logger.debug("edit resource function");
String res_mime_type=null;
boolean encodingFlag = false;
try
{
if (logger.isDebugEnabled()) logger.debug("editing properties for " + resourceId);
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
getMeleteCHService().editResource(resourceId, contentEditor);
}
if(resourceId != null && (section.getContentType().equals("typeLink") || section.getContentType().equals("typeUpload") || section.getContentType().equals("typeLTI")))
{
getMeleteCHService().editResourceProperties(resourceId,secResourceName,secResourceDescription);
}
}
catch(MeleteException me)
{
logger.debug("error in editing resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in editing resource for section content" + e.toString());
e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
public abstract String saveHere();
/*
* listener to set action for save button for setting data from html editor
*/
public void saveListener(ActionEvent event)
{
if (logger.isDebugEnabled()) logger.debug("Hello Rashmi ------saveListener called");
}
/*
* Render instructions on preview page
*/
public boolean getRenderInstr()
{
if (this.section.getInstr()== null ||this.section.getInstr().length() == 0 )
renderInstr=false;
else renderInstr=true;
return renderInstr;
}
/*
* Revised Rashmi on 1/21/05
* new var module number set back to 0
*/
public void resetSectionValues()
{
this.section= null;
contentEditor=null;
setSuccess(false);
hiddenUpload=null;
checkUploadChange=null;
uploadFileName = null;
secResource = null;
secResourceName = null;
secResourceDescription=null;
secContentData=null;
selResourceIdFromList = null;
meleteResource = null;
setLicenseCodes(null);
linkUrl = null;
ltiDescriptor = null;
FCK_CollId = null;
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
FacesContext ctx = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{remoteBrowserFile}");
RemoteBrowserFile rbPage = (RemoteBrowserFile)binding.getValue(ctx);
if(rbPage != null)
{
rbPage.setRemoteFiles(null);
rbPage.setRemoteLinkFiles(null);
}
shouldRenderEditor=false;
shouldRenderLink=false;
shouldRenderLTI=false;
shouldRenderUpload=false;
shouldRenderNotype = false;
allContentTypes = null;
oldType = null;
if (logger.isDebugEnabled()) logger.debug("!!!!!!!!!reseting section values done !!!!!!!");
}
/*
* reset resource values and license from java cache when its deleted and associated with current section
*/
public void resetMeleteResourceValues()
{
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
secResourceName = null;
secResourceDescription = null;
uploadFileName = null;
setLicenseCodes(null);
}
protected void processSelectedResource(String selResourceIdFromList)
{
FacesContext ctx = FacesContext.getCurrentInstance();
try{
currLinkUrl = getLinkContent(selResourceIdFromList);
ContentResource cr= getMeleteCHService().getResource(selResourceIdFromList);
this.secResourceName = cr.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.secResourceDescription = cr.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
//get resource object
selectedResource = (MeleteResource)sectionService.getMeleteResource(selResourceIdFromList);
//just take resource properties from this object as its assoc with another section
if(selectedResource != null)
{
meleteResource = selectedResource;
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(ctx);
lPage.setInitialValues(formName, selectedResource);
// render selected file name
selectedResourceName = secResourceName;
if (logger.isDebugEnabled()) logger.debug("values changed in resource action for res name and desc" + secResourceName + secResourceDescription);
}
}
catch(Exception ex)
{
logger.debug("error while accessing content resource" + ex.toString());
}
}
/**
* @return remove values from session before closing
*/
public String cancel()
{
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
if(sessionMap.containsKey("currModule"))
{
sessionMap.remove("currModule");
}
resetSectionValues();
return "list_auth_modules";
}
/**
* @return uploaded file or link name for preview page
*/
public String getContentLink()
{
if (logger.isDebugEnabled()) logger.debug("getContentLink fn is called");
return "#";
}
public String getFormName(){
return formName;
}
/**
* @param formName
*/
public void setFormName(String formName){
this.formName = formName;
}
//melete 3.0 work
/**
* @param access The access to set.
*/
public void setAccess(String access) {
this.access = access;
}
/**
* @return Returns the access.
*/
public String getAccess() {
if(this.access == null)
this.access = "site";
return access;
}
/**
* @return Returns the m_license.
*/
/* public SectionResourceLicenseSelector getM_license() {
if(m_license == null)
{
m_license = new SectionResourceLicenseSelector();
if (getMeleteResource().getResourceId() != null)
{
m_license.setInitialValues(this.formName, sectionService,getMeleteResource());
}
else
{
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
m_license.setInitialValues(this.formName, sectionService, mup);
}
}
return m_license;
}*/
| public void showHideContent(ValueChangeEvent event)throws AbortProcessingException
{
FacesContext context = FacesContext.getCurrentInstance();
UIInput contentTypeRadio = (UIInput)event.getComponent();
shouldRenderEditor = contentTypeRadio.getValue().equals("typeEditor");
shouldRenderLink = contentTypeRadio.getValue().equals("typeLink");
shouldRenderUpload = contentTypeRadio.getValue().equals("typeUpload");
shouldRenderNotype = contentTypeRadio.getValue().equals("notype");
shouldRenderLTI = contentTypeRadio.getValue().equals("typeLTI");
selResourceIdFromList = null;
secResourceName = null;
secResourceDescription = null;
setMeleteResource(null);
oldType = section.getContentType();
if(contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("uploadPath").setRendered(shouldRenderUpload);
contentTypeRadio.findComponent(getFormName()).findComponent("BrowsePath").setRendered(shouldRenderUpload);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("link") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("link").setRendered(shouldRenderLink);
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView") != null)
{
contentTypeRadio.findComponent(getFormName()).findComponent("ContentLTIView").setRendered(shouldRenderLTI);
}
if(shouldRenderEditor)
{
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
String usereditor = preferencePage.getUserEditor();
this.contentEditor = new String("Compose content here");
if(contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor") != null && usereditor.equals(preferencePage.FCKEDITOR))
{
contentTypeRadio.findComponent(getFormName()).findComponent("otherMeletecontentEditor").setRendered(shouldRenderEditor);
setFCKCollectionAttrib();
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView") != null && usereditor.equals(preferencePage.SFERYX))
{
preferencePage.setDisplaySferyx(true);
contentTypeRadio.findComponent(getFormName()).findComponent("contentEditorView").setRendered(shouldRenderEditor);
}
}
if(contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm") != null)
{
section.setContentType((String)contentTypeRadio.getValue());
contentTypeRadio.findComponent(getFormName()).findComponent("ResourceListingForm").setRendered(false);
}
//Upon changing content type, license is set by the selected resource, if there is one,
//or via User preferences
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(context);
lPage.setFormName(this.formName);
lPage.resetValues();
/*if (getMeleteResource().getResourceId() != null)
{
lPage.setInitialValues(this.formName, getMeleteResource());
}
else
{*/
ValueBinding binding2 = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding2.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
lPage.setInitialValues(this.formName, mup);
//}
//The code below is required because the setter for the license code kicks in by default
//and we need to actually set the component with the values determined above.(ME-1071)
UIComponent licComp = (UIComponent)contentTypeRadio.findComponent(getFormName());
if(licComp != null && licComp.findComponent("ResourcePropertiesPanel") != null && licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm") != null
&& licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView") != null)
{
licComp = licComp.findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("SectionView");
UIInput uiInp = (UIInput)licComp.findComponent("licenseCodes");
uiInp.setValue(lPage.getLicenseCodes());
licComp = (UIComponent)contentTypeRadio.findComponent(getFormName()).findComponent("ResourcePropertiesPanel").findComponent("LicenseForm").findComponent("CCLicenseForm");
uiInp = (UIInput)licComp.findComponent("allowCmrcl");
uiInp.setValue(lPage.getAllowCmrcl());
uiInp = (UIInput)licComp.findComponent("allowMod");
uiInp.setValue(lPage.getAllowMod());
if (lPage.isShouldRenderCC())
{
uiInp = (UIInput)licComp.findComponent("copy_owner");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year");
uiInp.setValue(lPage.getCopyright_year());
}
if (lPage.isShouldRenderCopyright()||lPage.isShouldRenderPublicDomain()||lPage.isShouldRenderFairUse())
{
uiInp = (UIInput)licComp.findComponent("copy_owner1");
uiInp.setValue(lPage.getCopyright_owner());
uiInp = (UIInput)licComp.findComponent("copy_year1");
uiInp.setValue(lPage.getCopyright_year());
}
}
}
/**
* @param event
* @throws AbortProcessingException
* Changes the LTI view from basic to advanced.
*/
public void toggleLTIDisplay(ValueChangeEvent event)throws AbortProcessingException
{
// Nothing to do - because the setter handles it all
}
public String getLTIDisplay()
{
if ( shouldLTIDisplayAdvanced ) return "Advanced";
return "Basic";
}
public void setLTIDisplay(String newDisplay)
{
shouldLTIDisplayAdvanced = "Advanced".equals(newDisplay);
}
public String getLTIUrl()
{
return currLTIUrl;
}
public void setLTIUrl(String LTIUrl)
{
currLTIUrl = LTIUrl;
fixDescriptor();
}
public String getLTIKey()
{
return currLTIKey;
}
public void setLTIKey(String LTIKey)
{
currLTIKey = LTIKey;
fixDescriptor();
}
public String getLTIPassword()
{
return currLTIPassword;
}
public void setLTIPassword(String LTIPassword)
{
currLTIPassword = LTIPassword;
fixDescriptor();
}
// Produce a basic descriptor from the URL and Password
private void fixDescriptor()
{
if ( currLTIUrl == null ) return;
String desc =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<basic_lti_link\n" +
" xmlns=\"http://www.imsglobal.org/xsd/imsbasiclti_v1p0\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
" <melete-basic>true</melete-basic> \n" +
" <launch_url>"+currLTIUrl+"</launch_url> \n" +
" <x-secure>\n" ;
if ( currLTIKey != null && currLTIKey.trim().length() > 0 ) {
desc = desc + " <launch_key>"+currLTIKey+"</launch_key> \n" ;
}
if ( currLTIPassword != null && currLTIPassword.trim().length() > 0 ) {
desc = desc + " <launch_secret>"+currLTIPassword+"</launch_secret> \n" ;
}
desc = desc + " </x-secure>\n";
desc = desc + "</basic_lti_link>\n";
setLTIDescriptor(desc);
}
public boolean getShouldLTIDisplayAdvanced()
{
return shouldLTIDisplayAdvanced;
}
public boolean getShouldLTIDisplayBasic()
{
return ! shouldLTIDisplayAdvanced;
}
/*
* modality is required. check if one is selected or not
*/
protected boolean validateModality()
{
if(!(this.section.isAudioContent()|| this.section.isTextualContent()|| this.section.isVideoContent()))
return false;
return true;
}
/*
* adds resource to specified melete module or uploads collection.
*/
public String addResourceToMeleteCollection(String uploadHomeDir, String addCollId) throws UserErrorException,MeleteException
{
try{
String res_mime_type=getMeleteCHService().MIME_TYPE_EDITOR;
boolean encodingFlag = false;
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
res_mime_type= getMeleteCHService().MIME_TYPE_EDITOR;
secContentData = new byte[contentEditor.length()];
secContentData = contentEditor.getBytes();
encodingFlag = true;
secResourceName = getMeleteCHService().getTypeEditorSectionName(section.getSectionId());
secResourceDescription="compose content";
}
if (section.getContentType().equals("typeLink")) {
res_mime_type = getMeleteCHService().MIME_TYPE_LINK;
Util.validateLink(getLinkUrl());
if ((secResourceName == null)|| (secResourceName.trim().length() == 0))
throw new MeleteException("URL_title_reqd");
secContentData = new byte[linkUrl.length()];
secContentData = linkUrl.getBytes();
}
if (section.getContentType().equals("typeLTI")) {
if(getLTIUrl() != null)
Util.validateLink(getLTIUrl());
String pitch = getLTIDescriptor();
if (ltiDescriptor == null || ltiDescriptor.trim().length() == 0) {
throw new MeleteException("add_section_empty_lti");
}
if (! ( SimpleLTIUtil.validateDescriptor(ltiDescriptor)
|| BasicLTIUtil.validateDescriptor(ltiDescriptor) != null ) ) {
throw new MeleteException("add_section_bad_lti");
}
res_mime_type = getMeleteCHService().MIME_TYPE_LTI;
secContentData = new byte[ltiDescriptor.length()];
secContentData = ltiDescriptor.getBytes();
}
if (section.getContentType().equals("typeUpload")) {
res_mime_type = uploadSectionContent("file1");
if (logger.isDebugEnabled())
logger.debug("new names for upload content is"
+ res_mime_type + "," + secResourceName);
if (res_mime_type == null)
throw new MeleteException("select_or_cancel");
}
ResourcePropertiesEdit res = getMeleteCHService().fillInSectionResourceProperties(encodingFlag,
secResourceName, secResourceDescription);
if (logger.isDebugEnabled())
logger.debug("add resource now " + secResourceName);
String newResourceId = getMeleteCHService().addResourceItem(secResourceName, res_mime_type, addCollId, secContentData,res);
return newResourceId;
}
catch(UserErrorException uex)
{
throw uex;
}
catch(MeleteException me)
{
logger.debug("error in creating resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in creating resource for section content" + e.toString());
//e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
/*
* adds resource to specified melete module or uploads collection.
*/
public void editMeleteCollectionResource(String uploadHomeDir,String resourceId) throws MeleteException
{
if (logger.isDebugEnabled()) logger.debug("edit resource function");
String res_mime_type=null;
boolean encodingFlag = false;
try
{
if (logger.isDebugEnabled()) logger.debug("editing properties for " + resourceId);
if(section.getContentType().equals("typeEditor"))
{
contentEditor = getMeleteCHService().findLocalImagesEmbeddedInEditor(uploadHomeDir,contentEditor);
getMeleteCHService().editResource(resourceId, contentEditor);
}
if(resourceId != null && (section.getContentType().equals("typeLink") || section.getContentType().equals("typeUpload") || section.getContentType().equals("typeLTI")))
{
getMeleteCHService().editResourceProperties(resourceId,secResourceName,secResourceDescription);
}
}
catch(MeleteException me)
{
logger.debug("error in editing resource for section content" + me.toString());
throw me;
}
catch(Exception e)
{
if (logger.isDebugEnabled()) {
logger.debug("error in editing resource for section content" + e.toString());
e.printStackTrace();
}
throw new MeleteException("add_section_fail");
}
}
public abstract String saveHere();
/*
* listener to set action for save button for setting data from html editor
*/
public void saveListener(ActionEvent event)
{
if (logger.isDebugEnabled()) logger.debug("Hello Rashmi ------saveListener called");
}
/*
* Render instructions on preview page
*/
public boolean getRenderInstr()
{
if (this.section == null || this.section.getInstr()== null ||this.section.getInstr().length() == 0 )
renderInstr=false;
else renderInstr=true;
return renderInstr;
}
/*
* Revised Rashmi on 1/21/05
* new var module number set back to 0
*/
public void resetSectionValues()
{
this.section= null;
contentEditor=null;
setSuccess(false);
hiddenUpload=null;
checkUploadChange=null;
uploadFileName = null;
secResource = null;
secResourceName = null;
secResourceDescription=null;
secContentData=null;
selResourceIdFromList = null;
meleteResource = null;
setLicenseCodes(null);
linkUrl = null;
ltiDescriptor = null;
FCK_CollId = null;
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
FacesContext ctx = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{remoteBrowserFile}");
RemoteBrowserFile rbPage = (RemoteBrowserFile)binding.getValue(ctx);
if(rbPage != null)
{
rbPage.setRemoteFiles(null);
rbPage.setRemoteLinkFiles(null);
}
shouldRenderEditor=false;
shouldRenderLink=false;
shouldRenderLTI=false;
shouldRenderUpload=false;
shouldRenderNotype = false;
allContentTypes = null;
oldType = null;
if (logger.isDebugEnabled()) logger.debug("!!!!!!!!!reseting section values done !!!!!!!");
}
/*
* reset resource values and license from java cache when its deleted and associated with current section
*/
public void resetMeleteResourceValues()
{
currLinkUrl = null;
currLTIDescriptor = null;
currLTIUrl = null;
currLTIKey = null;
currLTIPassword = null;
displayCurrLink = null;
secResourceName = null;
secResourceDescription = null;
uploadFileName = null;
setLicenseCodes(null);
}
protected void processSelectedResource(String selResourceIdFromList)
{
FacesContext ctx = FacesContext.getCurrentInstance();
try{
currLinkUrl = getLinkContent(selResourceIdFromList);
ContentResource cr= getMeleteCHService().getResource(selResourceIdFromList);
this.secResourceName = cr.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
this.secResourceDescription = cr.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
//get resource object
selectedResource = (MeleteResource)sectionService.getMeleteResource(selResourceIdFromList);
//just take resource properties from this object as its assoc with another section
if(selectedResource != null)
{
meleteResource = selectedResource;
ValueBinding binding = Util.getBinding("#{licensePage}");
LicensePage lPage = (LicensePage)binding.getValue(ctx);
lPage.setInitialValues(formName, selectedResource);
// render selected file name
selectedResourceName = secResourceName;
if (logger.isDebugEnabled()) logger.debug("values changed in resource action for res name and desc" + secResourceName + secResourceDescription);
}
}
catch(Exception ex)
{
logger.debug("error while accessing content resource" + ex.toString());
}
}
/**
* @return remove values from session before closing
*/
public String cancel()
{
FacesContext context = FacesContext.getCurrentInstance();
Map sessionMap = context.getExternalContext().getSessionMap();
if(sessionMap.containsKey("currModule"))
{
sessionMap.remove("currModule");
}
resetSectionValues();
return "list_auth_modules";
}
/**
* @return uploaded file or link name for preview page
*/
public String getContentLink()
{
if (logger.isDebugEnabled()) logger.debug("getContentLink fn is called");
return "#";
}
public String getFormName(){
return formName;
}
/**
* @param formName
*/
public void setFormName(String formName){
this.formName = formName;
}
//melete 3.0 work
/**
* @param access The access to set.
*/
public void setAccess(String access) {
this.access = access;
}
/**
* @return Returns the access.
*/
public String getAccess() {
if(this.access == null)
this.access = "site";
return access;
}
/**
* @return Returns the m_license.
*/
/* public SectionResourceLicenseSelector getM_license() {
if(m_license == null)
{
m_license = new SectionResourceLicenseSelector();
if (getMeleteResource().getResourceId() != null)
{
m_license.setInitialValues(this.formName, sectionService,getMeleteResource());
}
else
{
FacesContext context = FacesContext.getCurrentInstance();
ValueBinding binding = Util.getBinding("#{authorPreferences}");
AuthorPreferencePage preferencePage = (AuthorPreferencePage)binding.getValue(context);
MeleteUserPreference mup = preferencePage.getMup();
m_license.setInitialValues(this.formName, sectionService, mup);
}
}
return m_license;
}*/
|
diff --git a/src/icm/gui/employee/EmployeeRequestDetailsComponent.java b/src/icm/gui/employee/EmployeeRequestDetailsComponent.java
index f1388dd..a1a178a 100644
--- a/src/icm/gui/employee/EmployeeRequestDetailsComponent.java
+++ b/src/icm/gui/employee/EmployeeRequestDetailsComponent.java
@@ -1,290 +1,290 @@
package icm.gui.employee;
import icm.client.ICMClient;
import icm.dao.Employee;
import icm.dao.EmployeeType;
import icm.dao.Request;
import icm.dao.RequestStatus;
import icm.gui.StageListingComponent;
import icm.intent.AssignSupervisorIntent;
import icm.intent.BrowseEmployeesIntent;
import icm.intent.ResumeIntent;
import icm.intent.SuspendIntent;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
@SuppressWarnings("serial")
public class EmployeeRequestDetailsComponent extends JComponent implements Observer
{
private JList<Request> rqst;
public EmployeeRequestDetailsComponent(final Employee employee, final JList<Request> requests, final ICMClient client)
{
rqst=requests;
JLabel lblNewLabel = new JLabel("RequestID:");
lblNewLabel.setBounds(10, 11, 94, 20);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblSubmitted = new JLabel("Submitted:");
lblSubmitted.setBounds(10, 39, 94, 20);
lblSubmitted.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblCurrentState = new JLabel("Current State:");
lblCurrentState.setBounds(10, 79, 94, 16);
lblCurrentState.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblRequest = new JLabel("Request:");
lblRequest.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblRequest.setBounds(10, 194, 94, 17);
JLabel lblComments = new JLabel("Comments:");
lblComments.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblComments.setBounds(10, 323, 94, 17);
JLabel lblSupervisor = new JLabel("Supervisor:");
lblSupervisor.setBounds(279, 17, 79, 16);
lblSupervisor.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblStatus = new JLabel("Status:");
lblStatus.setBounds(287, 45, 71, 16);
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 13));
final JTextPane reqIDtext = new JTextPane();
reqIDtext.setBounds(108, 11, 80, 22);
reqIDtext.setFont(new Font("Tahoma", Font.PLAIN, 13));
reqIDtext.setEditable(false);
final JTextPane submitText = new JTextPane();
submitText.setBounds(108, 39, 161, 22);
submitText.setFont(new Font("Tahoma", Font.PLAIN, 13));
submitText.setEditable(false);
final JTextArea curr_stateText = new JTextArea();
curr_stateText.setFont(new Font("Courier New", Font.PLAIN, 13));
curr_stateText.setLineWrap(true);
curr_stateText.setEditable(false);
JScrollPane currTextScrollpane=new JScrollPane(curr_stateText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
currTextScrollpane.setBounds(108, 79, 263, 89);
final JTextArea requestText = new JTextArea();
requestText.setFont(new Font("Courier New", Font.PLAIN, 13));
requestText.setLineWrap(true);
requestText.setEditable(false);
JScrollPane reqTextScrollpane=new JScrollPane(requestText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
reqTextScrollpane.setBounds(108, 194, 263, 103);
final JTextArea commentText = new JTextArea();
commentText.setFont(new Font("Courier New", Font.PLAIN, 13));
commentText.setLineWrap(true);
commentText.setEditable(false);
JScrollPane commentTextScrollpane=new JScrollPane(commentText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
commentTextScrollpane.setBounds(108, 323, 263, 70);
final JTextPane supervisorText = new JTextPane();
supervisorText.setBounds(368, 11, 106, 22);
supervisorText.setFont(new Font("Tahoma", Font.PLAIN, 13));
supervisorText.setEditable(false);
final JTextPane statusText = new JTextPane();
statusText.setBounds(368, 39, 106, 22);
statusText.setFont(new Font("Tahoma", Font.PLAIN, 13));
statusText.setEditable(false);
final JButton assignButton = new JButton("Assign");
assignButton.setBounds(480, 11, 90, 20);
assignButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
assignButton.setEnabled(false);
assignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AssignEmployeeDialog dialog = new AssignEmployeeDialog(SwingUtilities.windowForComponent(EmployeeRequestDetailsComponent.this));
try
{
BrowseEmployeesIntent browse = new BrowseEmployeesIntent();
EmployeeType filter[] = {EmployeeType.ENGINEER};
browse.setFilter(filter);
client.registerAndSend(browse, dialog);
dialog.setVisible(true);
if( dialog.getConfirmed() && dialog.getValue()!=null && requests.getSelectedValue()!=null)
{
AssignSupervisorIntent intent = new AssignSupervisorIntent();
intent.setCandidateid(dialog.getValue().getEmployeeId());
intent.setRequestid(requests.getSelectedValue().getRequestID());
try
{
client.registerAndSend(intent,EmployeeRequestDetailsComponent.this);
}
catch (IOException e1) {e1.printStackTrace();}
}
}
catch (IOException e2){e2.printStackTrace();}
}
});
final JButton suspendButton = new JButton("Suspend");
suspendButton.setBounds(480, 39, 90, 20);
suspendButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
suspendButton.setEnabled(false);
suspendButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
SuspendIntent intent = new SuspendIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
- suspendButton.setVisible(false);
+ suspendButton.setEnabled(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
final JButton resumeButton = new JButton("Resume");
resumeButton.setBounds(480, 67, 90, 20);
resumeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
resumeButton.setEnabled(false);
resumeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
ResumeIntent intent = new ResumeIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
- resumeButton.setVisible(false);
+ resumeButton.setEnabled(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
StageListingComponent stageListComp = new StageListingComponent(client,requests,employee);
stageListComp.setBounds(580, 11, 631, 396);
setLayout(null);
add(lblCurrentState);
add(currTextScrollpane);
add(lblRequest);
add(reqTextScrollpane);
add(resumeButton);
add(lblNewLabel);
add(reqIDtext);
add(lblSupervisor);
add(lblSubmitted);
add(submitText);
add(lblStatus);
add(statusText);
add(suspendButton);
add(supervisorText);
add(assignButton);
add(lblComments);
add(commentTextScrollpane);
add(stageListComp);
ListSelectionListener listener = new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent listSelectionEvent)
{
if(requests.getSelectedValue()!=null)
{
assignButton.setEnabled(false);
resumeButton.setEnabled(false);
suspendButton.setEnabled(false);
Request request = requests.getSelectedValue();
if(listSelectionEvent.getValueIsAdjusting()==false)//fired twice,still need fix
{
submitText.setText((new java.util.Date(request.getRecievedAt()).toString()));
statusText.setText(request.getStatus().toString());
if( request.getSupervisor()!=null )
supervisorText.setText(request.getSupervisor().getName()+" "+request.getSupervisor().getSurname());
else
supervisorText.setText("");
if(employee.getType()==EmployeeType.DIRECTOR)
{
assignButton.setEnabled(true);
if(request.getStatus()==RequestStatus.SUSPENDED)
{
resumeButton.setEnabled(true);
}
}
if( request.getSupervisor()!=null)
if( request.getSupervisor().getEmployeeId()==employee.getEmployeeId() && request.getStatus()!=RequestStatus.SUSPENDED)
suspendButton.setEnabled(true);
reqIDtext.setText(Integer.toString(request.getRequestID()));
curr_stateText.setText(request.getCurrentState());
requestText.setText(request.getRequest());
commentText.setText(request.getComments());
}
}
}
};
requests.addListSelectionListener(listener);
}
/**internal use*/
private boolean opSuccess=false;
@Override
public void update(Observable arg0, Object arg1 )
{
if( arg1 instanceof Boolean )
{
opSuccess=(Boolean)arg1;
}
if( arg1 instanceof String )
{
if( opSuccess )
JOptionPane.showMessageDialog(this,(String)arg1, "Operation completed", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(this,(String)arg1, "Operation failed", JOptionPane.ERROR_MESSAGE);
}
else if( arg1 instanceof Request )
{
DefaultListModel<Request> model = (DefaultListModel<Request>) rqst.getModel();
model.addElement((Request)arg1);
rqst.setSelectedValue((Request)arg1, true);
}
}
}
| false | true | public EmployeeRequestDetailsComponent(final Employee employee, final JList<Request> requests, final ICMClient client)
{
rqst=requests;
JLabel lblNewLabel = new JLabel("RequestID:");
lblNewLabel.setBounds(10, 11, 94, 20);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblSubmitted = new JLabel("Submitted:");
lblSubmitted.setBounds(10, 39, 94, 20);
lblSubmitted.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblCurrentState = new JLabel("Current State:");
lblCurrentState.setBounds(10, 79, 94, 16);
lblCurrentState.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblRequest = new JLabel("Request:");
lblRequest.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblRequest.setBounds(10, 194, 94, 17);
JLabel lblComments = new JLabel("Comments:");
lblComments.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblComments.setBounds(10, 323, 94, 17);
JLabel lblSupervisor = new JLabel("Supervisor:");
lblSupervisor.setBounds(279, 17, 79, 16);
lblSupervisor.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblStatus = new JLabel("Status:");
lblStatus.setBounds(287, 45, 71, 16);
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 13));
final JTextPane reqIDtext = new JTextPane();
reqIDtext.setBounds(108, 11, 80, 22);
reqIDtext.setFont(new Font("Tahoma", Font.PLAIN, 13));
reqIDtext.setEditable(false);
final JTextPane submitText = new JTextPane();
submitText.setBounds(108, 39, 161, 22);
submitText.setFont(new Font("Tahoma", Font.PLAIN, 13));
submitText.setEditable(false);
final JTextArea curr_stateText = new JTextArea();
curr_stateText.setFont(new Font("Courier New", Font.PLAIN, 13));
curr_stateText.setLineWrap(true);
curr_stateText.setEditable(false);
JScrollPane currTextScrollpane=new JScrollPane(curr_stateText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
currTextScrollpane.setBounds(108, 79, 263, 89);
final JTextArea requestText = new JTextArea();
requestText.setFont(new Font("Courier New", Font.PLAIN, 13));
requestText.setLineWrap(true);
requestText.setEditable(false);
JScrollPane reqTextScrollpane=new JScrollPane(requestText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
reqTextScrollpane.setBounds(108, 194, 263, 103);
final JTextArea commentText = new JTextArea();
commentText.setFont(new Font("Courier New", Font.PLAIN, 13));
commentText.setLineWrap(true);
commentText.setEditable(false);
JScrollPane commentTextScrollpane=new JScrollPane(commentText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
commentTextScrollpane.setBounds(108, 323, 263, 70);
final JTextPane supervisorText = new JTextPane();
supervisorText.setBounds(368, 11, 106, 22);
supervisorText.setFont(new Font("Tahoma", Font.PLAIN, 13));
supervisorText.setEditable(false);
final JTextPane statusText = new JTextPane();
statusText.setBounds(368, 39, 106, 22);
statusText.setFont(new Font("Tahoma", Font.PLAIN, 13));
statusText.setEditable(false);
final JButton assignButton = new JButton("Assign");
assignButton.setBounds(480, 11, 90, 20);
assignButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
assignButton.setEnabled(false);
assignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AssignEmployeeDialog dialog = new AssignEmployeeDialog(SwingUtilities.windowForComponent(EmployeeRequestDetailsComponent.this));
try
{
BrowseEmployeesIntent browse = new BrowseEmployeesIntent();
EmployeeType filter[] = {EmployeeType.ENGINEER};
browse.setFilter(filter);
client.registerAndSend(browse, dialog);
dialog.setVisible(true);
if( dialog.getConfirmed() && dialog.getValue()!=null && requests.getSelectedValue()!=null)
{
AssignSupervisorIntent intent = new AssignSupervisorIntent();
intent.setCandidateid(dialog.getValue().getEmployeeId());
intent.setRequestid(requests.getSelectedValue().getRequestID());
try
{
client.registerAndSend(intent,EmployeeRequestDetailsComponent.this);
}
catch (IOException e1) {e1.printStackTrace();}
}
}
catch (IOException e2){e2.printStackTrace();}
}
});
final JButton suspendButton = new JButton("Suspend");
suspendButton.setBounds(480, 39, 90, 20);
suspendButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
suspendButton.setEnabled(false);
suspendButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
SuspendIntent intent = new SuspendIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
suspendButton.setVisible(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
final JButton resumeButton = new JButton("Resume");
resumeButton.setBounds(480, 67, 90, 20);
resumeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
resumeButton.setEnabled(false);
resumeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
ResumeIntent intent = new ResumeIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
resumeButton.setVisible(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
StageListingComponent stageListComp = new StageListingComponent(client,requests,employee);
stageListComp.setBounds(580, 11, 631, 396);
setLayout(null);
add(lblCurrentState);
add(currTextScrollpane);
add(lblRequest);
add(reqTextScrollpane);
add(resumeButton);
add(lblNewLabel);
add(reqIDtext);
add(lblSupervisor);
add(lblSubmitted);
add(submitText);
add(lblStatus);
add(statusText);
add(suspendButton);
add(supervisorText);
add(assignButton);
add(lblComments);
add(commentTextScrollpane);
add(stageListComp);
ListSelectionListener listener = new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent listSelectionEvent)
{
if(requests.getSelectedValue()!=null)
{
assignButton.setEnabled(false);
resumeButton.setEnabled(false);
suspendButton.setEnabled(false);
Request request = requests.getSelectedValue();
if(listSelectionEvent.getValueIsAdjusting()==false)//fired twice,still need fix
{
submitText.setText((new java.util.Date(request.getRecievedAt()).toString()));
statusText.setText(request.getStatus().toString());
if( request.getSupervisor()!=null )
supervisorText.setText(request.getSupervisor().getName()+" "+request.getSupervisor().getSurname());
else
supervisorText.setText("");
if(employee.getType()==EmployeeType.DIRECTOR)
{
assignButton.setEnabled(true);
if(request.getStatus()==RequestStatus.SUSPENDED)
{
resumeButton.setEnabled(true);
}
}
if( request.getSupervisor()!=null)
if( request.getSupervisor().getEmployeeId()==employee.getEmployeeId() && request.getStatus()!=RequestStatus.SUSPENDED)
suspendButton.setEnabled(true);
reqIDtext.setText(Integer.toString(request.getRequestID()));
curr_stateText.setText(request.getCurrentState());
requestText.setText(request.getRequest());
commentText.setText(request.getComments());
}
}
}
};
requests.addListSelectionListener(listener);
}
| public EmployeeRequestDetailsComponent(final Employee employee, final JList<Request> requests, final ICMClient client)
{
rqst=requests;
JLabel lblNewLabel = new JLabel("RequestID:");
lblNewLabel.setBounds(10, 11, 94, 20);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblSubmitted = new JLabel("Submitted:");
lblSubmitted.setBounds(10, 39, 94, 20);
lblSubmitted.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblCurrentState = new JLabel("Current State:");
lblCurrentState.setBounds(10, 79, 94, 16);
lblCurrentState.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblRequest = new JLabel("Request:");
lblRequest.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblRequest.setBounds(10, 194, 94, 17);
JLabel lblComments = new JLabel("Comments:");
lblComments.setFont(new Font("Tahoma", Font.PLAIN, 13));
lblComments.setBounds(10, 323, 94, 17);
JLabel lblSupervisor = new JLabel("Supervisor:");
lblSupervisor.setBounds(279, 17, 79, 16);
lblSupervisor.setFont(new Font("Tahoma", Font.PLAIN, 13));
JLabel lblStatus = new JLabel("Status:");
lblStatus.setBounds(287, 45, 71, 16);
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 13));
final JTextPane reqIDtext = new JTextPane();
reqIDtext.setBounds(108, 11, 80, 22);
reqIDtext.setFont(new Font("Tahoma", Font.PLAIN, 13));
reqIDtext.setEditable(false);
final JTextPane submitText = new JTextPane();
submitText.setBounds(108, 39, 161, 22);
submitText.setFont(new Font("Tahoma", Font.PLAIN, 13));
submitText.setEditable(false);
final JTextArea curr_stateText = new JTextArea();
curr_stateText.setFont(new Font("Courier New", Font.PLAIN, 13));
curr_stateText.setLineWrap(true);
curr_stateText.setEditable(false);
JScrollPane currTextScrollpane=new JScrollPane(curr_stateText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
currTextScrollpane.setBounds(108, 79, 263, 89);
final JTextArea requestText = new JTextArea();
requestText.setFont(new Font("Courier New", Font.PLAIN, 13));
requestText.setLineWrap(true);
requestText.setEditable(false);
JScrollPane reqTextScrollpane=new JScrollPane(requestText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
reqTextScrollpane.setBounds(108, 194, 263, 103);
final JTextArea commentText = new JTextArea();
commentText.setFont(new Font("Courier New", Font.PLAIN, 13));
commentText.setLineWrap(true);
commentText.setEditable(false);
JScrollPane commentTextScrollpane=new JScrollPane(commentText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
commentTextScrollpane.setBounds(108, 323, 263, 70);
final JTextPane supervisorText = new JTextPane();
supervisorText.setBounds(368, 11, 106, 22);
supervisorText.setFont(new Font("Tahoma", Font.PLAIN, 13));
supervisorText.setEditable(false);
final JTextPane statusText = new JTextPane();
statusText.setBounds(368, 39, 106, 22);
statusText.setFont(new Font("Tahoma", Font.PLAIN, 13));
statusText.setEditable(false);
final JButton assignButton = new JButton("Assign");
assignButton.setBounds(480, 11, 90, 20);
assignButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
assignButton.setEnabled(false);
assignButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AssignEmployeeDialog dialog = new AssignEmployeeDialog(SwingUtilities.windowForComponent(EmployeeRequestDetailsComponent.this));
try
{
BrowseEmployeesIntent browse = new BrowseEmployeesIntent();
EmployeeType filter[] = {EmployeeType.ENGINEER};
browse.setFilter(filter);
client.registerAndSend(browse, dialog);
dialog.setVisible(true);
if( dialog.getConfirmed() && dialog.getValue()!=null && requests.getSelectedValue()!=null)
{
AssignSupervisorIntent intent = new AssignSupervisorIntent();
intent.setCandidateid(dialog.getValue().getEmployeeId());
intent.setRequestid(requests.getSelectedValue().getRequestID());
try
{
client.registerAndSend(intent,EmployeeRequestDetailsComponent.this);
}
catch (IOException e1) {e1.printStackTrace();}
}
}
catch (IOException e2){e2.printStackTrace();}
}
});
final JButton suspendButton = new JButton("Suspend");
suspendButton.setBounds(480, 39, 90, 20);
suspendButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
suspendButton.setEnabled(false);
suspendButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
SuspendIntent intent = new SuspendIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
suspendButton.setEnabled(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
final JButton resumeButton = new JButton("Resume");
resumeButton.setBounds(480, 67, 90, 20);
resumeButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
resumeButton.setEnabled(false);
resumeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
ResumeIntent intent = new ResumeIntent();
intent.setRequestID(requests.getSelectedValue().getRequestID());
client.registerAndSend(intent, EmployeeRequestDetailsComponent.this);
resumeButton.setEnabled(false);
}
catch (IOException e1) {e1.printStackTrace();}
}
});
StageListingComponent stageListComp = new StageListingComponent(client,requests,employee);
stageListComp.setBounds(580, 11, 631, 396);
setLayout(null);
add(lblCurrentState);
add(currTextScrollpane);
add(lblRequest);
add(reqTextScrollpane);
add(resumeButton);
add(lblNewLabel);
add(reqIDtext);
add(lblSupervisor);
add(lblSubmitted);
add(submitText);
add(lblStatus);
add(statusText);
add(suspendButton);
add(supervisorText);
add(assignButton);
add(lblComments);
add(commentTextScrollpane);
add(stageListComp);
ListSelectionListener listener = new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent listSelectionEvent)
{
if(requests.getSelectedValue()!=null)
{
assignButton.setEnabled(false);
resumeButton.setEnabled(false);
suspendButton.setEnabled(false);
Request request = requests.getSelectedValue();
if(listSelectionEvent.getValueIsAdjusting()==false)//fired twice,still need fix
{
submitText.setText((new java.util.Date(request.getRecievedAt()).toString()));
statusText.setText(request.getStatus().toString());
if( request.getSupervisor()!=null )
supervisorText.setText(request.getSupervisor().getName()+" "+request.getSupervisor().getSurname());
else
supervisorText.setText("");
if(employee.getType()==EmployeeType.DIRECTOR)
{
assignButton.setEnabled(true);
if(request.getStatus()==RequestStatus.SUSPENDED)
{
resumeButton.setEnabled(true);
}
}
if( request.getSupervisor()!=null)
if( request.getSupervisor().getEmployeeId()==employee.getEmployeeId() && request.getStatus()!=RequestStatus.SUSPENDED)
suspendButton.setEnabled(true);
reqIDtext.setText(Integer.toString(request.getRequestID()));
curr_stateText.setText(request.getCurrentState());
requestText.setText(request.getRequest());
commentText.setText(request.getComments());
}
}
}
};
requests.addListSelectionListener(listener);
}
|
diff --git a/src/serverTCP/Connection.java b/src/serverTCP/Connection.java
index 784b461..62ffa7e 100644
--- a/src/serverTCP/Connection.java
+++ b/src/serverTCP/Connection.java
@@ -1,38 +1,38 @@
package serverTCP;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
* Created with IntelliJ IDEA.
* User: joaosimoes
* Date: 10/15/13
* Time: 4:44 PM
* To change this template use File | Settings | File Templates.
*/
public class Connection extends Thread {
private boolean shutDown;
private Socket clientSocket;
private ObjectInputStream inStream;
private ObjectOutputStream outStream;
public Connection(Socket cSocket) {
clientSocket = cSocket;
shutDown = false;
try {
+ outStream = new ObjectOutputStream(cSocket.getOutputStream());
inStream = new ObjectInputStream(cSocket.getInputStream());
- outStream = new ObjectOutputStream(cSocket.getOutputStream());
} catch (IOException ie) {
}
}
@Override
public void run() {
}
}
| false | true | public Connection(Socket cSocket) {
clientSocket = cSocket;
shutDown = false;
try {
inStream = new ObjectInputStream(cSocket.getInputStream());
outStream = new ObjectOutputStream(cSocket.getOutputStream());
} catch (IOException ie) {
}
}
| public Connection(Socket cSocket) {
clientSocket = cSocket;
shutDown = false;
try {
outStream = new ObjectOutputStream(cSocket.getOutputStream());
inStream = new ObjectInputStream(cSocket.getInputStream());
} catch (IOException ie) {
}
}
|
diff --git a/src/test/java/org/seleniumhq/selenium/fluent/ops/url.java b/src/test/java/org/seleniumhq/selenium/fluent/ops/url.java
index 4aad312..ceabc9b 100644
--- a/src/test/java/org/seleniumhq/selenium/fluent/ops/url.java
+++ b/src/test/java/org/seleniumhq/selenium/fluent/ops/url.java
@@ -1,40 +1,40 @@
package org.seleniumhq.selenium.fluent.ops;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.seleniumhq.selenium.fluent.BaseTest;
import org.seleniumhq.selenium.fluent.FluentWebDriverImpl;
import org.seleniumhq.selenium.fluent.TestableString;
import org.seleniumhq.selenium.fluent.WebDriverJournal;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
public class url extends BaseTest {
private StringBuilder sb;
private WebDriver wd;
private FluentWebDriverImpl fwd;
@Before
public void setup() {
sb = new StringBuilder();
wd = new WebDriverJournal(sb);
fwd = new FluentWebDriverImpl(wd);
FAIL_ON_NEXT.set(null);
}
@Test
- public void button_functionality() {
+ public void url_functionality() {
TestableString url = fwd.url();
assertThat(url, notNullValue());
assertThat(sb.toString(), equalTo("getCurrentUrl():STR#1\n"));
assertThat("" + url, equalTo("STR#1"));
assertThat(url.toString(), equalTo("STR#1"));
}
}
| true | true | public void button_functionality() {
TestableString url = fwd.url();
assertThat(url, notNullValue());
assertThat(sb.toString(), equalTo("getCurrentUrl():STR#1\n"));
assertThat("" + url, equalTo("STR#1"));
assertThat(url.toString(), equalTo("STR#1"));
}
| public void url_functionality() {
TestableString url = fwd.url();
assertThat(url, notNullValue());
assertThat(sb.toString(), equalTo("getCurrentUrl():STR#1\n"));
assertThat("" + url, equalTo("STR#1"));
assertThat(url.toString(), equalTo("STR#1"));
}
|
diff --git a/src/main/java/com/epita/mti/plic/opensource/controlibutility/serialization/ObjectReceiver.java b/src/main/java/com/epita/mti/plic/opensource/controlibutility/serialization/ObjectReceiver.java
index 4d5eaf3..7d36a82 100644
--- a/src/main/java/com/epita/mti/plic/opensource/controlibutility/serialization/ObjectReceiver.java
+++ b/src/main/java/com/epita/mti/plic/opensource/controlibutility/serialization/ObjectReceiver.java
@@ -1,243 +1,239 @@
package com.epita.mti.plic.opensource.controlibutility.serialization;
import com.epita.mti.plic.opensource.controlibutility.beans.*;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.codehaus.jackson.type.TypeReference;
/**
* The ObjectReceiver class is part of a Observable/Observer pattern. It listens
* the socket in a thread and notifies its observers when an object is received
* and deserialized. A list of the user's observers is necessary while
* instantiating that class in order to notify them.
*
* @author Julien "Roulyo" Fraisse
*/
public class ObjectReceiver extends Observable implements Runnable
{
private InputStream inputStream = null;
private HashMap<String, Class<?>> beansMap;
private ObjectReader reader = null;
private ArrayList<Observer> currentObservers = new ArrayList<Observer>();
/**
* Ctor instantiate the IntputStream used by the ObjectReceiver to deserialize
* data from a socket's input stream.
*
* @param inputStream Socket's input stream.
* @param observersList List of user's observers.
*/
public ObjectReceiver(Socket socket,
List<Observer> observersList) throws IOException
{
this.inputStream = socket.getInputStream();
for (Observer observer : observersList)
{
currentObservers.add(observer);
super.addObserver(observer);
}
ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
reader = mapper.reader(new TypeReference<Map<String, Object>>()
{
});
initMap();
}
/**
* Ctor alternate version with only one observer.
*
* @param inputStream Socket's input stream.
* @param observer User's observer.
*/
public ObjectReceiver(Socket socket,
Observer observer) throws IOException
{
this.inputStream = socket.getInputStream();
currentObservers.add(observer);
super.addObserver(observer);
ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
reader = mapper.reader(new TypeReference<Map<String, Object>>()
{
});
initMap();
}
/**
* Ctor alternate version with no observer.
*
* @param inputStream Socket's input stream.
* @param observer User's observer.
*/
public ObjectReceiver(Socket socket) throws IOException
{
this.inputStream = socket.getInputStream();
ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
reader = mapper.reader(new TypeReference<Map<String, Object>>()
{
});
initMap();
}
/**
* Initialize the map with defaults value;
*/
private void initMap()
{
beansMap = new HashMap<String, Class<?>>();
beansMap.put("accel", CLAccel.class);
beansMap.put("button-pressure", CLButtonPressure.class);
beansMap.put("image", CLButtonPressure.class);
beansMap.put("pressure", CLPressure.class);
beansMap.put("vector", CLVector.class);
beansMap.put("jarFile", CLJarFile.class);
}
/**
* This method allows users to close the stream properly.
*/
public void disposeStream()
{
try
{
this.inputStream.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
/**
* Set a new IntputStream from another socket's input stream. Close the one
* used previously.
*
* @param inputStream
*/
public void setInputStream(InputStream inputStream)
{
try
{
this.inputStream.close();
System.out.println("OK");
}
catch (IOException ex)
{
ex.printStackTrace();
}
this.inputStream = inputStream;
}
@Override
public void run()
{
try
{
this.read();
}
catch (NoSuchMethodException ex)
{
ex.printStackTrace();
}
catch (IllegalArgumentException ex)
{
ex.printStackTrace();
}
catch (InvocationTargetException ex)
{
ex.printStackTrace();
}
catch (InstantiationException ex)
{
ex.printStackTrace();
}
catch (IllegalAccessException ex)
{
ex.printStackTrace();
}
}
/**
* This method deserialize data from the socket while it is openned, and
* notifies its observers when a CLSerializable can be restitute.
*/
public synchronized void read() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException
{
CLSerializable bean;
Map<String, Object> map;
try
{
map = reader.readValue(inputStream);
while (map != null)
{
Object mapType = map.get("type");
Class<?> beanClass;
if (mapType != null)
{
beanClass = beansMap.get(mapType.toString());
Constructor<?> constructor = beanClass.getConstructor(HashMap.class);
bean = (CLSerializable) constructor.newInstance(map);
setChanged();
notifyObservers(bean);
- try
- {
- map = reader.readValue(inputStream);
- }
- catch (IOException ex) {}
+ map = reader.readValue(inputStream);
}
else
{
map = null;
}
}
}
catch (EOFException ex)
{
System.out.println("Client disconnected.");
}
catch (IOException ex)
{
- Logger.getLogger(ObjectReceiver.class.getName()).log(Level.SEVERE, null, ex);
+ //ex.printStackTrace();
}
}
public void clearPlugins()
{
for (Observer o : currentObservers)
{
deleteObserver(o);
}
currentObservers.clear();
}
public HashMap<String, Class<?>> getBeansMap()
{
return beansMap;
}
public void setBeansMap(HashMap<String, Class<?>> beansMap)
{
this.beansMap = beansMap;
}
@Override
public void addObserver(Observer o)
{
currentObservers.add(o);
super.addObserver(o);
}
}
| false | true | public synchronized void read() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException
{
CLSerializable bean;
Map<String, Object> map;
try
{
map = reader.readValue(inputStream);
while (map != null)
{
Object mapType = map.get("type");
Class<?> beanClass;
if (mapType != null)
{
beanClass = beansMap.get(mapType.toString());
Constructor<?> constructor = beanClass.getConstructor(HashMap.class);
bean = (CLSerializable) constructor.newInstance(map);
setChanged();
notifyObservers(bean);
try
{
map = reader.readValue(inputStream);
}
catch (IOException ex) {}
}
else
{
map = null;
}
}
}
catch (EOFException ex)
{
System.out.println("Client disconnected.");
}
catch (IOException ex)
{
Logger.getLogger(ObjectReceiver.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public synchronized void read() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException
{
CLSerializable bean;
Map<String, Object> map;
try
{
map = reader.readValue(inputStream);
while (map != null)
{
Object mapType = map.get("type");
Class<?> beanClass;
if (mapType != null)
{
beanClass = beansMap.get(mapType.toString());
Constructor<?> constructor = beanClass.getConstructor(HashMap.class);
bean = (CLSerializable) constructor.newInstance(map);
setChanged();
notifyObservers(bean);
map = reader.readValue(inputStream);
}
else
{
map = null;
}
}
}
catch (EOFException ex)
{
System.out.println("Client disconnected.");
}
catch (IOException ex)
{
//ex.printStackTrace();
}
}
|
diff --git a/src/main/java/net/praqma/hudson/scm/PucmState.java b/src/main/java/net/praqma/hudson/scm/PucmState.java
index 9843b2b..352be23 100644
--- a/src/main/java/net/praqma/hudson/scm/PucmState.java
+++ b/src/main/java/net/praqma/hudson/scm/PucmState.java
@@ -1,254 +1,254 @@
package net.praqma.hudson.scm;
import hudson.model.AbstractProject;
import hudson.model.Build;
import java.util.ArrayList;
import java.util.List;
import net.praqma.clearcase.ucm.entities.Baseline;
import net.praqma.clearcase.ucm.entities.Component;
import net.praqma.clearcase.ucm.entities.Project;
import net.praqma.clearcase.ucm.entities.Stream;
/**
*
* @author wolfgang
*
*/
public class PucmState
{
private List<State> states = new ArrayList<State>();
private static final String linesep = System.getProperty( "line.separator" );
/**
* Get a state given job name and job number
* @param jobName the hudson job name
* @param jobNumber the hudson job number
* @return
*/
public State getState( String jobName, Integer jobNumber )
{
for( State s : states )
{
if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber )
{
return s;
}
}
State s = new State( jobName, jobNumber );
states.add( s );
return s;
}
public boolean removeState( String jobName, Integer jobNumber )
{
for( State s : states )
{
if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber )
{
states.remove( s );
return true;
}
}
return false;
}
public State getStateByBaseline( String jobName, String baseline )
{
for( State s : states )
{
if( s.getJobName().equals( jobName ) && s.getBaseline() != null && s.getBaseline().GetFQName().equals( baseline ) )
{
return s;
}
}
return null;
}
public void addState( State state )
{
this.states.add( state );
}
public boolean stateExists( State state )
{
return stateExists( state.jobName, state.jobNumber );
}
public boolean stateExists( String jobName, Integer jobNumber )
{
for( State s : states )
{
if( s.getJobName().equals( jobName ) && s.getJobNumber() == jobNumber )
{
return true;
}
}
return false;
}
public boolean removeState( State state )
{
return states.remove( state );
}
- public int recalculate( AbstractProject<?, ?> project )
+ public synchronized int recalculate( AbstractProject<?, ?> project )
{
int count = 0;
for( State s : states )
{
Integer bnum = s.getJobNumber();
Object o = project.getBuildByNumber( bnum );
Build bld = (Build)o;
/* The job is not running */
if( !bld.isLogUpdated() )
{
s.remove();
count++;
}
}
return count;
}
public int size()
{
return states.size();
}
public String stringify()
{
return net.praqma.util.structure.Printer.listPrinterToString( states );
}
public class State
{
private Baseline baseline;
private Stream stream;
private Component component;
private boolean doPostBuild = true;
private Project.Plevel plevel;
private String jobName;
private Integer jobNumber;
public State(){}
public State( String jobName, Integer jobNumber )
{
this.jobName = jobName;
this.jobNumber = jobNumber;
}
public State( String jobName, Integer jobNumber, Baseline baseline, Stream stream, Component component, boolean doPostBuild )
{
this.jobName = jobName;
this.jobNumber = jobNumber;
this.baseline = baseline;
this.stream = stream;
this.component = component;
this.doPostBuild = doPostBuild;
}
@Deprecated
public void save()
{
PucmState.this.addState( this );
}
public boolean remove()
{
return PucmState.this.removeState( this );
}
public Baseline getBaseline()
{
return baseline;
}
public void setBaseline( Baseline baseline )
{
this.baseline = baseline;
}
public Stream getStream()
{
return stream;
}
public void setStream( Stream stream )
{
this.stream = stream;
}
public Component getComponent()
{
return component;
}
public void setComponent( Component component )
{
this.component = component;
}
public boolean doPostBuild()
{
return doPostBuild;
}
public void setPostBuild( boolean doPostBuild )
{
this.doPostBuild = doPostBuild;
}
public String getJobName()
{
return jobName;
}
public void setJobName( String jobName )
{
this.jobName = jobName;
}
public Integer getJobNumber()
{
return jobNumber;
}
public void setJobNumber( Integer jobNumber )
{
this.jobNumber = jobNumber;
}
public void setPlevel( Project.Plevel plevel )
{
this.plevel = plevel;
}
public Project.Plevel getPlevel()
{
return plevel;
}
public String stringify()
{
StringBuffer sb = new StringBuffer();
sb.append( "Job name : " + this.jobName + linesep );
sb.append( "Job number: " + this.jobNumber + linesep );
sb.append( "Component : " + this.component + linesep );
sb.append( "Stream : " + this.stream + linesep );
sb.append( "Baseline : " + this.baseline + linesep );
sb.append( "Plevel : " + ( this.plevel != null ? this.plevel.toString() : "Missing" ) + linesep );
sb.append( "postBuild : " + this.doPostBuild + linesep );
return sb.toString();
}
public String toString()
{
return "(" + jobName + ", " + jobNumber + ")";
}
}
}
| true | true | public int recalculate( AbstractProject<?, ?> project )
{
int count = 0;
for( State s : states )
{
Integer bnum = s.getJobNumber();
Object o = project.getBuildByNumber( bnum );
Build bld = (Build)o;
/* The job is not running */
if( !bld.isLogUpdated() )
{
s.remove();
count++;
}
}
return count;
}
| public synchronized int recalculate( AbstractProject<?, ?> project )
{
int count = 0;
for( State s : states )
{
Integer bnum = s.getJobNumber();
Object o = project.getBuildByNumber( bnum );
Build bld = (Build)o;
/* The job is not running */
if( !bld.isLogUpdated() )
{
s.remove();
count++;
}
}
return count;
}
|
diff --git a/src/com/dmdirc/updater/components/LauncherComponent.java b/src/com/dmdirc/updater/components/LauncherComponent.java
index b35c46684..94d7c2f0d 100644
--- a/src/com/dmdirc/updater/components/LauncherComponent.java
+++ b/src/com/dmdirc/updater/components/LauncherComponent.java
@@ -1,138 +1,138 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.updater.components;
import com.dmdirc.updater.UpdateChecker;
import com.dmdirc.updater.UpdateComponent;
import com.dmdirc.updater.OptionsComponent;
import com.dmdirc.updater.Version;
import com.dmdirc.util.resourcemanager.ZipResourceManager;
import java.io.File;
/**
* Component for updates of DMDirc's launcher.
*
* @author chris
*/
public class LauncherComponent implements UpdateComponent, OptionsComponent {
/** The platform of our current launcher. */
private static String platform = "";
/** The version of our current launcher. */
private static int version = -1;
/** The options of our current launcher. */
private static String[] options = new String[]{};
/**
* Parses the specified launcher information.
*
* @param info The platform and version of the launcher, separated by '-'.
*/
public static void setLauncherInfo(final String info) {
final int hpos = info.indexOf('-');
final int cpos = info.indexOf(',');
if (hpos == -1) {
return;
}
try {
platform = info.substring(0, hpos);
if (cpos == -1) {
version = Integer.parseInt(info.substring(hpos + 1));
} else {
- version = Integer.parseInt(info.substring(hpos + 1), cpos);
+ version = Integer.parseInt(info.substring(hpos + 1, cpos));
options = info.substring(cpos + 1).split(",");
}
} catch (NumberFormatException ex) {
return;
}
UpdateChecker.registerComponent(new LauncherComponent());
}
/**
* Determines if the client has been run using the launcher.
*
* @return True if the launcher has been used, false otherwise
*/
public static boolean isUsingLauncher() {
return version != -1;
}
/** {@inheritDoc} */
@Override
public String getName() {
return "launcher-" + platform;
}
/** {@inheritDoc} */
@Override
public String getFriendlyName() {
return "Launcher";
}
/** {@inheritDoc} */
@Override
public String getFriendlyVersion() {
return String.valueOf(getVersion());
}
/** {@inheritDoc} */
@Override
public Version getVersion() {
return new Version(version);
}
/** {@inheritDoc} */
@Override
public String[] getOptions() {
return options;
}
/** {@inheritDoc} */
@Override
public boolean doInstall(final String path) throws Exception {
final File tmpFile = new File(path);
if (platform.equalsIgnoreCase("Linux") || platform.equalsIgnoreCase("unix")) {
final File targetFile = new File(tmpFile.getParent() + File.separator + ".launcher.sh");
if (targetFile.exists()) {
targetFile.delete();
}
tmpFile.renameTo(targetFile);
targetFile.setExecutable(true);
return true;
} else {
final ZipResourceManager ziprm = ZipResourceManager.getInstance(path);
ziprm.extractResources("", tmpFile.getParent()+ File.separator);
new File(path).delete();
return true;
}
}
}
| true | true | public static void setLauncherInfo(final String info) {
final int hpos = info.indexOf('-');
final int cpos = info.indexOf(',');
if (hpos == -1) {
return;
}
try {
platform = info.substring(0, hpos);
if (cpos == -1) {
version = Integer.parseInt(info.substring(hpos + 1));
} else {
version = Integer.parseInt(info.substring(hpos + 1), cpos);
options = info.substring(cpos + 1).split(",");
}
} catch (NumberFormatException ex) {
return;
}
UpdateChecker.registerComponent(new LauncherComponent());
}
| public static void setLauncherInfo(final String info) {
final int hpos = info.indexOf('-');
final int cpos = info.indexOf(',');
if (hpos == -1) {
return;
}
try {
platform = info.substring(0, hpos);
if (cpos == -1) {
version = Integer.parseInt(info.substring(hpos + 1));
} else {
version = Integer.parseInt(info.substring(hpos + 1, cpos));
options = info.substring(cpos + 1).split(",");
}
} catch (NumberFormatException ex) {
return;
}
UpdateChecker.registerComponent(new LauncherComponent());
}
|
diff --git a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/EntityTagDelegate.java b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/EntityTagDelegate.java
index c6e56e7f1..abb00f7c0 100644
--- a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/EntityTagDelegate.java
+++ b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/EntityTagDelegate.java
@@ -1,36 +1,38 @@
package org.jboss.resteasy.plugins.delegates;
import javax.ws.rs.core.EntityTag;
import javax.ws.rs.ext.RuntimeDelegate;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class EntityTagDelegate implements RuntimeDelegate.HeaderDelegate<EntityTag>
{
public EntityTag fromString(String value) throws IllegalArgumentException
{
if (value == null) throw new IllegalArgumentException("value of EntityTag is null");
+ boolean weakTag = false;
+ if (value.startsWith("W/"))
+ {
+ weakTag = true;
+ value = value.substring(2);
+ }
if (value.startsWith("\""))
{
value = value.substring(1);
}
if (value.endsWith("\""))
{
value = value.substring(0, value.length() - 1);
}
- if (value.startsWith("W/"))
- {
- return new EntityTag(value.substring(2), true);
- }
- return new EntityTag(value);
+ return new EntityTag(value, weakTag);
}
public String toString(EntityTag value)
{
String weak = value.isWeak() ? "W/" : "";
return weak + '"' + value.getValue() + '"';
}
}
| false | true | public EntityTag fromString(String value) throws IllegalArgumentException
{
if (value == null) throw new IllegalArgumentException("value of EntityTag is null");
if (value.startsWith("\""))
{
value = value.substring(1);
}
if (value.endsWith("\""))
{
value = value.substring(0, value.length() - 1);
}
if (value.startsWith("W/"))
{
return new EntityTag(value.substring(2), true);
}
return new EntityTag(value);
}
| public EntityTag fromString(String value) throws IllegalArgumentException
{
if (value == null) throw new IllegalArgumentException("value of EntityTag is null");
boolean weakTag = false;
if (value.startsWith("W/"))
{
weakTag = true;
value = value.substring(2);
}
if (value.startsWith("\""))
{
value = value.substring(1);
}
if (value.endsWith("\""))
{
value = value.substring(0, value.length() - 1);
}
return new EntityTag(value, weakTag);
}
|
diff --git a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java b/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java
index eceb69f392..aeb4755d94 100644
--- a/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java
+++ b/plugins/sonar-email-notifications-plugin/src/test/java/org/sonar/plugins/emailnotifications/EmailNotificationsPluginTest.java
@@ -1,31 +1,31 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.emailnotifications;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class EmailNotificationsPluginTest {
@Test
public void should_get_extensions() {
- assertThat(new EmailNotificationsPlugin().getExtensions()).hasSize(5);
+ assertThat(new EmailNotificationsPlugin().getExtensions()).hasSize(7);
}
}
| true | true | public void should_get_extensions() {
assertThat(new EmailNotificationsPlugin().getExtensions()).hasSize(5);
}
| public void should_get_extensions() {
assertThat(new EmailNotificationsPlugin().getExtensions()).hasSize(7);
}
|
diff --git a/src/main/java/de/cubeisland/antiguest/AntiGuest.java b/src/main/java/de/cubeisland/antiguest/AntiGuest.java
index 7eaff1a..f81d14d 100644
--- a/src/main/java/de/cubeisland/antiguest/AntiGuest.java
+++ b/src/main/java/de/cubeisland/antiguest/AntiGuest.java
@@ -1,218 +1,218 @@
package de.cubeisland.antiguest;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.logging.Logger;
import org.bukkit.configuration.Configuration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.plugin.java.JavaPlugin;
import de.cubeisland.antiguest.commands.BasicCommands;
import de.cubeisland.antiguest.commands.PreventionManagementCommands;
import de.cubeisland.antiguest.prevention.Prevention;
import de.cubeisland.antiguest.prevention.PreventionConfiguration;
import de.cubeisland.antiguest.prevention.PreventionManager;
import de.cubeisland.antiguest.prevention.PreventionPlugin;
import de.cubeisland.antiguest.prevention.Punishment;
import de.cubeisland.libMinecraft.command.BaseCommand;
import de.cubeisland.libMinecraft.translation.Translation;
import org.reflections.Reflections;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.SEVERE;
public class AntiGuest extends JavaPlugin implements Listener, PreventionPlugin
{
private static Logger logger = null;
private File preventionConfigFolder;
private static Translation translation;
private BaseCommand baseCommand;
private boolean punishments;
private boolean logViolations;
@Override
public void onEnable()
{
logger = this.getLogger();
File dataFolder = this.getDataFolder();
if (!dataFolder.exists() && !dataFolder.mkdirs())
{
logger.log(SEVERE, "Failed to create the data folder!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.preventionConfigFolder = new File(dataFolder, "preventions");
reloadConfig();
Configuration config = getConfig();
config.addDefault("language", System.getProperty("user.language", "en"));
config.options().copyDefaults(true);
translation = Translation.get(this.getClass(), getConfig().getString("language"));
if (translation == null)
{
translation = Translation.get(this.getClass(), "en");
config.set("language", "en");
}
saveConfig();
this.punishments = config.getBoolean("punishments");
this.logViolations = config.getBoolean("log-violations");
this.baseCommand = new BaseCommand(this, "antiguest.commands.");
this.baseCommand.registerCommands(new BasicCommands(this)).registerCommands(new PreventionManagementCommands());
getCommand("antiguest").setExecutor(this.baseCommand);
PreventionManager manager = PreventionManager.getInstance();
Reflections reflections = new Reflections(this.getClass().getPackage().getName());
for (Class<? extends Punishment> punishmentClass : reflections.getSubTypesOf(Punishment.class))
{
try
{
manager.registerPunishment(punishmentClass.newInstance());
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (access failed)!", e);
}
}
for (Class<? extends Prevention> preventionClass : reflections.getSubTypesOf(Prevention.class))
{
if (preventionClass.isInterface() || Modifier.isAbstract(preventionClass.getModifiers()))
{
continue;
}
try
{
- Constructor<? extends Prevention> constructor = preventionClass.getConstructor(this.getClass());
+ Constructor<? extends Prevention> constructor = preventionClass.getConstructor(PreventionPlugin.class);
constructor.setAccessible(true);
manager.registerPrevention(constructor.newInstance(this));
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (access failed)!", e);
}
catch (NoSuchMethodException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (missing/invalid constructor)!", e);
}
catch (InvocationTargetException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (error in constructor)!", e);
}
}
manager.enablePreventions();
logger.info(PreventionManager.getInstance().getPreventions().size() + " Prevention(s) have been registered!");
this.convertPreventionConfigs();
}
@Override
public void onDisable()
{
translation = null;
PreventionManager.getInstance().disablePreventions();
}
private void convertPreventionConfigs()
{
final String messageDelayKey = "messageDelay";
PreventionConfiguration prevConfig;
for (Prevention prevention : PreventionManager.getInstance().getPreventions())
{
prevConfig = prevention.getConfig();
if (prevConfig.contains(messageDelayKey))
{
prevConfig.set("throttleDelay", prevConfig.get(messageDelayKey));
prevConfig.set(messageDelayKey, null);
prevention.saveConfig();
}
}
}
public File getConfigurationFolder()
{
return this.preventionConfigFolder;
}
public static void log(String msg)
{
logger.log(INFO, msg);
}
public static void error(String msg)
{
logger.log(SEVERE, msg);
}
public static void error(String msg, Throwable t)
{
logger.log(SEVERE, msg, t);
}
public static String _(String message, Object... params)
{
return translation.translate(message, params);
}
public Translation getTranslation()
{
return translation;
}
public void setTranslation(Translation newTranslation)
{
translation = newTranslation;
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPluginDisable(PluginDisableEvent event)
{
PreventionManager.getInstance().disablePreventions(event.getPlugin());
}
public BaseCommand getBaseCommand()
{
return this.baseCommand;
}
public String getPermissionBase()
{
return "antiguest.preventions.";
}
public boolean allowPunishments()
{
return this.punishments;
}
public boolean logViolations()
{
return this.logViolations;
}
}
| true | true | public void onEnable()
{
logger = this.getLogger();
File dataFolder = this.getDataFolder();
if (!dataFolder.exists() && !dataFolder.mkdirs())
{
logger.log(SEVERE, "Failed to create the data folder!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.preventionConfigFolder = new File(dataFolder, "preventions");
reloadConfig();
Configuration config = getConfig();
config.addDefault("language", System.getProperty("user.language", "en"));
config.options().copyDefaults(true);
translation = Translation.get(this.getClass(), getConfig().getString("language"));
if (translation == null)
{
translation = Translation.get(this.getClass(), "en");
config.set("language", "en");
}
saveConfig();
this.punishments = config.getBoolean("punishments");
this.logViolations = config.getBoolean("log-violations");
this.baseCommand = new BaseCommand(this, "antiguest.commands.");
this.baseCommand.registerCommands(new BasicCommands(this)).registerCommands(new PreventionManagementCommands());
getCommand("antiguest").setExecutor(this.baseCommand);
PreventionManager manager = PreventionManager.getInstance();
Reflections reflections = new Reflections(this.getClass().getPackage().getName());
for (Class<? extends Punishment> punishmentClass : reflections.getSubTypesOf(Punishment.class))
{
try
{
manager.registerPunishment(punishmentClass.newInstance());
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (access failed)!", e);
}
}
for (Class<? extends Prevention> preventionClass : reflections.getSubTypesOf(Prevention.class))
{
if (preventionClass.isInterface() || Modifier.isAbstract(preventionClass.getModifiers()))
{
continue;
}
try
{
Constructor<? extends Prevention> constructor = preventionClass.getConstructor(this.getClass());
constructor.setAccessible(true);
manager.registerPrevention(constructor.newInstance(this));
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (access failed)!", e);
}
catch (NoSuchMethodException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (missing/invalid constructor)!", e);
}
catch (InvocationTargetException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (error in constructor)!", e);
}
}
manager.enablePreventions();
logger.info(PreventionManager.getInstance().getPreventions().size() + " Prevention(s) have been registered!");
this.convertPreventionConfigs();
}
| public void onEnable()
{
logger = this.getLogger();
File dataFolder = this.getDataFolder();
if (!dataFolder.exists() && !dataFolder.mkdirs())
{
logger.log(SEVERE, "Failed to create the data folder!");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
this.preventionConfigFolder = new File(dataFolder, "preventions");
reloadConfig();
Configuration config = getConfig();
config.addDefault("language", System.getProperty("user.language", "en"));
config.options().copyDefaults(true);
translation = Translation.get(this.getClass(), getConfig().getString("language"));
if (translation == null)
{
translation = Translation.get(this.getClass(), "en");
config.set("language", "en");
}
saveConfig();
this.punishments = config.getBoolean("punishments");
this.logViolations = config.getBoolean("log-violations");
this.baseCommand = new BaseCommand(this, "antiguest.commands.");
this.baseCommand.registerCommands(new BasicCommands(this)).registerCommands(new PreventionManagementCommands());
getCommand("antiguest").setExecutor(this.baseCommand);
PreventionManager manager = PreventionManager.getInstance();
Reflections reflections = new Reflections(this.getClass().getPackage().getName());
for (Class<? extends Punishment> punishmentClass : reflections.getSubTypesOf(Punishment.class))
{
try
{
manager.registerPunishment(punishmentClass.newInstance());
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + punishmentClass
.getSimpleName() + " (access failed)!", e);
}
}
for (Class<? extends Prevention> preventionClass : reflections.getSubTypesOf(Prevention.class))
{
if (preventionClass.isInterface() || Modifier.isAbstract(preventionClass.getModifiers()))
{
continue;
}
try
{
Constructor<? extends Prevention> constructor = preventionClass.getConstructor(PreventionPlugin.class);
constructor.setAccessible(true);
manager.registerPrevention(constructor.newInstance(this));
}
catch (InstantiationException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (instantiation failed)!", e);
}
catch (IllegalAccessException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (access failed)!", e);
}
catch (NoSuchMethodException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (missing/invalid constructor)!", e);
}
catch (InvocationTargetException e)
{
error("Failed to create the instance of the " + preventionClass
.getSimpleName() + " (error in constructor)!", e);
}
}
manager.enablePreventions();
logger.info(PreventionManager.getInstance().getPreventions().size() + " Prevention(s) have been registered!");
this.convertPreventionConfigs();
}
|
diff --git a/vlc-android/src/org/videolan/vlc/android/BrowserAdapter.java b/vlc-android/src/org/videolan/vlc/android/BrowserAdapter.java
index a4eca150..ba91c5f0 100644
--- a/vlc-android/src/org/videolan/vlc/android/BrowserAdapter.java
+++ b/vlc-android/src/org/videolan/vlc/android/BrowserAdapter.java
@@ -1,112 +1,112 @@
package org.videolan.vlc.android;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class BrowserAdapter extends ArrayAdapter<File>
implements Comparator<File> {
public final static String TAG = "VLC/BrowserAdapter";
public BrowserAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public synchronized void add(File object) {
super.add(object);
}
/**
* Display the view of a file browser item.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.browser_item,
parent, false);
}
final File item = getItem(position);
final DatabaseManager dbManager = DatabaseManager.getInstance();
- if ( item != null ) {
+ if ( item != null && item.getName() != null ) {
TextView dirTextView =
(TextView)view.findViewById(R.id.browser_item_dir);
dirTextView.setText(item.getName());
final CheckBox dirCheckBox =
(CheckBox)view.findViewById(R.id.browser_item_selected);
dirCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (dirCheckBox.isEnabled() && isChecked) {
dbManager.addDir(item.getPath());
File tmpFile = item;
while(!tmpFile.getPath().equals("/")) {
tmpFile = tmpFile.getParentFile();
dbManager.removeDir(tmpFile.getPath());
}
} else {
dbManager.removeDir(item.getPath());
}
}
});
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(false);
List<File> dirs = dbManager.getMediaDirs();
for (File dir : dirs) {
if (dir.getPath().equals(item.getPath())) {
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(true);
break;
} else if (dir.getPath().startsWith(item.getPath())) {
Log.i(TAG, item.getPath() + " startWith " + dir.getPath());
dirCheckBox.setEnabled(false);
dirCheckBox.setChecked(true);
break;
}
}
}
return view;
}
public void sort() {
super.sort(this);
}
public int compare(File file1, File file2) {
return file1.getName().toUpperCase().compareTo(
file2.getName().toUpperCase());
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.browser_item,
parent, false);
}
final File item = getItem(position);
final DatabaseManager dbManager = DatabaseManager.getInstance();
if ( item != null ) {
TextView dirTextView =
(TextView)view.findViewById(R.id.browser_item_dir);
dirTextView.setText(item.getName());
final CheckBox dirCheckBox =
(CheckBox)view.findViewById(R.id.browser_item_selected);
dirCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (dirCheckBox.isEnabled() && isChecked) {
dbManager.addDir(item.getPath());
File tmpFile = item;
while(!tmpFile.getPath().equals("/")) {
tmpFile = tmpFile.getParentFile();
dbManager.removeDir(tmpFile.getPath());
}
} else {
dbManager.removeDir(item.getPath());
}
}
});
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(false);
List<File> dirs = dbManager.getMediaDirs();
for (File dir : dirs) {
if (dir.getPath().equals(item.getPath())) {
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(true);
break;
} else if (dir.getPath().startsWith(item.getPath())) {
Log.i(TAG, item.getPath() + " startWith " + dir.getPath());
dirCheckBox.setEnabled(false);
dirCheckBox.setChecked(true);
break;
}
}
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.browser_item,
parent, false);
}
final File item = getItem(position);
final DatabaseManager dbManager = DatabaseManager.getInstance();
if ( item != null && item.getName() != null ) {
TextView dirTextView =
(TextView)view.findViewById(R.id.browser_item_dir);
dirTextView.setText(item.getName());
final CheckBox dirCheckBox =
(CheckBox)view.findViewById(R.id.browser_item_selected);
dirCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (dirCheckBox.isEnabled() && isChecked) {
dbManager.addDir(item.getPath());
File tmpFile = item;
while(!tmpFile.getPath().equals("/")) {
tmpFile = tmpFile.getParentFile();
dbManager.removeDir(tmpFile.getPath());
}
} else {
dbManager.removeDir(item.getPath());
}
}
});
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(false);
List<File> dirs = dbManager.getMediaDirs();
for (File dir : dirs) {
if (dir.getPath().equals(item.getPath())) {
dirCheckBox.setEnabled(true);
dirCheckBox.setChecked(true);
break;
} else if (dir.getPath().startsWith(item.getPath())) {
Log.i(TAG, item.getPath() + " startWith " + dir.getPath());
dirCheckBox.setEnabled(false);
dirCheckBox.setChecked(true);
break;
}
}
}
return view;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.