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/common/logisticspipes/asm/LogisticsClassTransformer.java b/common/logisticspipes/asm/LogisticsClassTransformer.java
index 39ac4b31..784ea0ba 100644
--- a/common/logisticspipes/asm/LogisticsClassTransformer.java
+++ b/common/logisticspipes/asm/LogisticsClassTransformer.java
@@ -1,201 +1,215 @@
package logisticspipes.asm;
import java.util.ArrayList;
import java.util.List;
import logisticspipes.LogisticsPipes;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.relauncher.IClassTransformer;
import cpw.mods.fml.relauncher.Side;
public class LogisticsClassTransformer implements IClassTransformer {
private abstract class LocalMethodVisitor extends MethodNode {
public LocalMethodVisitor(final int access, final String name, final String desc, final String signature, final String[] exceptions) {
super(access, name, desc, signature, exceptions);
}
@Override
public void visitCode() {
super.visitCode();
addCode(this);
}
protected abstract void addCode(MethodNode node);
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes) {
try {
if(name.equals("buildcraft.transport.PipeTransportItems")) {
return handlePipeTransportItems(bytes);
}
if(!name.startsWith("logisticspipes.")) {
return bytes;
}
if(name.equals("logisticspipes.asm.LogisticsASMHelperClass")) { //Don't check the helper class
return bytes;
}
return handleLPTransformation(bytes);
} catch(Exception e) {
if(LogisticsPipes.DEBUG) { //For better Debugging
e.printStackTrace();
return bytes;
}
throw new RuntimeException(e);
}
}
private byte[] handlePipeTransportItems(byte[] bytes) {
ClassNode node = new ClassNode();
ClassReader reader = new ClassReader(bytes);
reader.accept(node, 0);
boolean handled = false;
for(MethodNode m:node.methods) {
if(m.name.equals("canReceivePipeObjects")) {
MethodNode newM = new LocalMethodVisitor(m.access, m.name, m.desc, m.signature, m.exceptions.toArray(new String[0])) {
@Override
protected void addCode(MethodNode node) {
LogisticsASMHelperClass.visitCanRecivePipeObject(node);
}
};
m.accept(newM);
node.methods.set(node.methods.indexOf(m), newM);
handled = true;
break;
}
}
if(!handled) {
throw new RuntimeException("Method 'canReceivePipeObjects' from 'buildcraft.transport.PipeTransportItems' could not be found.");
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
node.accept(writer);
return writer.toByteArray();
}
@SuppressWarnings("unchecked")
private byte[] handleLPTransformation(byte[] bytes) {
- ClassNode node = new ClassNode();
+ final ClassNode node = new ClassNode();
ClassReader reader = new ClassReader(bytes);
reader.accept(node, 0);
boolean changed = false;
if(node.visibleAnnotations != null) {
for(AnnotationNode a:node.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentInterface;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("interfacePath")) {
List<String> modId = (List<String>) a.values.get(1);
List<String> interfacePath = (List<String>) a.values.get(3);
if(modId.size() != interfacePath.size()) {
throw new RuntimeException("The Arrays have to be of the same size.");
}
for(int i=0;i<modId.size();i++) {
if(!Loader.isModLoaded(modId.get(i))) {
for(String inter:node.interfaces) {
if(inter.replace("/", ".").equals(interfacePath.get(i))) {
node.interfaces.remove(inter);
changed = true;
break;
}
}
}
}
} else {
throw new UnsupportedOperationException("Can't parse the annotations correctly");
}
}
}
}
List<MethodNode> methodsToRemove = new ArrayList<MethodNode>();
for(MethodNode m:node.methods) {
if(m.visibleAnnotations != null) {
for(AnnotationNode a:m.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentMethod;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
methodsToRemove.add(m);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
} else if(a.desc.equals("Llogisticspipes/asm/ClientSideOnlyMethodContent;")) {
if(FMLCommonHandler.instance().getSide().equals(Side.SERVER)) {
m.instructions.clear();
m.localVariables.clear();
m.tryCatchBlocks.clear();
m.visitCode();
Label l0 = new Label();
m.visitLabel(l0);
m.visitMethodInsn(Opcodes.INVOKESTATIC, "logisticspipes/asm/LogisitcsASMHookClass", "callingClearedMethod", "()V");
Label l1 = new Label();
m.visitLabel(l1);
m.visitInsn(Opcodes.RETURN);
Label l2 = new Label();
m.visitLabel(l2);
m.visitLocalVariable("this", "Llogisticspipes/network/packets/DummyPacket;", null, l0, l2, 0);
m.visitLocalVariable("player", "Lnet/minecraft/entity/player/EntityPlayer;", null, l0, l2, 1);
m.visitMaxs(0, 2);
m.visitEnd();
changed = true;
break;
}
} else if(a.desc.equals("Llogisticspipes/asm/ModDependentMethodName;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("newName")) {
String modId = a.values.get(1).toString();
- String newName = a.values.get(3).toString();
+ final String newName = a.values.get(3).toString();
if(Loader.isModLoaded(modId)) {
+ final String oldName = m.name;
m.name = newName;
+ MethodNode newM = new MethodNode(m.access, m.name, m.desc, m.signature, m.exceptions.toArray(new String[0])) {
+ @Override
+ public void visitMethodInsn(int opcode, String owner, String name, String desc) {
+ if(name.equals(oldName) && owner.equals(node.superName)) {
+ super.visitMethodInsn(opcode, owner, newName, desc);
+ } else {
+ super.visitMethodInsn(opcode, owner, name, desc);
+ }
+ }
+ };
+ m.accept(newM);
+ node.methods.set(node.methods.indexOf(m), newM);
+ changed = true;
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(MethodNode m:methodsToRemove) {
node.methods.remove(m);
}
List<FieldNode> fieldsToRemove = new ArrayList<FieldNode>();
for(FieldNode f:node.fields) {
if(f.visibleAnnotations != null) {
for(AnnotationNode a:f.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentField;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
fieldsToRemove.add(f);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(FieldNode f:fieldsToRemove) {
node.fields.remove(f);
}
if(!changed && methodsToRemove.isEmpty() && fieldsToRemove.isEmpty()) {
return bytes;
}
ClassWriter writer = new ClassWriter(0);
node.accept(writer);
return writer.toByteArray();
}
}
| false | true | private byte[] handleLPTransformation(byte[] bytes) {
ClassNode node = new ClassNode();
ClassReader reader = new ClassReader(bytes);
reader.accept(node, 0);
boolean changed = false;
if(node.visibleAnnotations != null) {
for(AnnotationNode a:node.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentInterface;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("interfacePath")) {
List<String> modId = (List<String>) a.values.get(1);
List<String> interfacePath = (List<String>) a.values.get(3);
if(modId.size() != interfacePath.size()) {
throw new RuntimeException("The Arrays have to be of the same size.");
}
for(int i=0;i<modId.size();i++) {
if(!Loader.isModLoaded(modId.get(i))) {
for(String inter:node.interfaces) {
if(inter.replace("/", ".").equals(interfacePath.get(i))) {
node.interfaces.remove(inter);
changed = true;
break;
}
}
}
}
} else {
throw new UnsupportedOperationException("Can't parse the annotations correctly");
}
}
}
}
List<MethodNode> methodsToRemove = new ArrayList<MethodNode>();
for(MethodNode m:node.methods) {
if(m.visibleAnnotations != null) {
for(AnnotationNode a:m.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentMethod;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
methodsToRemove.add(m);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
} else if(a.desc.equals("Llogisticspipes/asm/ClientSideOnlyMethodContent;")) {
if(FMLCommonHandler.instance().getSide().equals(Side.SERVER)) {
m.instructions.clear();
m.localVariables.clear();
m.tryCatchBlocks.clear();
m.visitCode();
Label l0 = new Label();
m.visitLabel(l0);
m.visitMethodInsn(Opcodes.INVOKESTATIC, "logisticspipes/asm/LogisitcsASMHookClass", "callingClearedMethod", "()V");
Label l1 = new Label();
m.visitLabel(l1);
m.visitInsn(Opcodes.RETURN);
Label l2 = new Label();
m.visitLabel(l2);
m.visitLocalVariable("this", "Llogisticspipes/network/packets/DummyPacket;", null, l0, l2, 0);
m.visitLocalVariable("player", "Lnet/minecraft/entity/player/EntityPlayer;", null, l0, l2, 1);
m.visitMaxs(0, 2);
m.visitEnd();
changed = true;
break;
}
} else if(a.desc.equals("Llogisticspipes/asm/ModDependentMethodName;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("newName")) {
String modId = a.values.get(1).toString();
String newName = a.values.get(3).toString();
if(Loader.isModLoaded(modId)) {
m.name = newName;
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(MethodNode m:methodsToRemove) {
node.methods.remove(m);
}
List<FieldNode> fieldsToRemove = new ArrayList<FieldNode>();
for(FieldNode f:node.fields) {
if(f.visibleAnnotations != null) {
for(AnnotationNode a:f.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentField;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
fieldsToRemove.add(f);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(FieldNode f:fieldsToRemove) {
node.fields.remove(f);
}
if(!changed && methodsToRemove.isEmpty() && fieldsToRemove.isEmpty()) {
return bytes;
}
ClassWriter writer = new ClassWriter(0);
node.accept(writer);
return writer.toByteArray();
}
| private byte[] handleLPTransformation(byte[] bytes) {
final ClassNode node = new ClassNode();
ClassReader reader = new ClassReader(bytes);
reader.accept(node, 0);
boolean changed = false;
if(node.visibleAnnotations != null) {
for(AnnotationNode a:node.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentInterface;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("interfacePath")) {
List<String> modId = (List<String>) a.values.get(1);
List<String> interfacePath = (List<String>) a.values.get(3);
if(modId.size() != interfacePath.size()) {
throw new RuntimeException("The Arrays have to be of the same size.");
}
for(int i=0;i<modId.size();i++) {
if(!Loader.isModLoaded(modId.get(i))) {
for(String inter:node.interfaces) {
if(inter.replace("/", ".").equals(interfacePath.get(i))) {
node.interfaces.remove(inter);
changed = true;
break;
}
}
}
}
} else {
throw new UnsupportedOperationException("Can't parse the annotations correctly");
}
}
}
}
List<MethodNode> methodsToRemove = new ArrayList<MethodNode>();
for(MethodNode m:node.methods) {
if(m.visibleAnnotations != null) {
for(AnnotationNode a:m.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentMethod;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
methodsToRemove.add(m);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
} else if(a.desc.equals("Llogisticspipes/asm/ClientSideOnlyMethodContent;")) {
if(FMLCommonHandler.instance().getSide().equals(Side.SERVER)) {
m.instructions.clear();
m.localVariables.clear();
m.tryCatchBlocks.clear();
m.visitCode();
Label l0 = new Label();
m.visitLabel(l0);
m.visitMethodInsn(Opcodes.INVOKESTATIC, "logisticspipes/asm/LogisitcsASMHookClass", "callingClearedMethod", "()V");
Label l1 = new Label();
m.visitLabel(l1);
m.visitInsn(Opcodes.RETURN);
Label l2 = new Label();
m.visitLabel(l2);
m.visitLocalVariable("this", "Llogisticspipes/network/packets/DummyPacket;", null, l0, l2, 0);
m.visitLocalVariable("player", "Lnet/minecraft/entity/player/EntityPlayer;", null, l0, l2, 1);
m.visitMaxs(0, 2);
m.visitEnd();
changed = true;
break;
}
} else if(a.desc.equals("Llogisticspipes/asm/ModDependentMethodName;")) {
if(a.values.size() == 4 && a.values.get(0).equals("modId") && a.values.get(2).equals("newName")) {
String modId = a.values.get(1).toString();
final String newName = a.values.get(3).toString();
if(Loader.isModLoaded(modId)) {
final String oldName = m.name;
m.name = newName;
MethodNode newM = new MethodNode(m.access, m.name, m.desc, m.signature, m.exceptions.toArray(new String[0])) {
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc) {
if(name.equals(oldName) && owner.equals(node.superName)) {
super.visitMethodInsn(opcode, owner, newName, desc);
} else {
super.visitMethodInsn(opcode, owner, name, desc);
}
}
};
m.accept(newM);
node.methods.set(node.methods.indexOf(m), newM);
changed = true;
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(MethodNode m:methodsToRemove) {
node.methods.remove(m);
}
List<FieldNode> fieldsToRemove = new ArrayList<FieldNode>();
for(FieldNode f:node.fields) {
if(f.visibleAnnotations != null) {
for(AnnotationNode a:f.visibleAnnotations) {
if(a.desc.equals("Llogisticspipes/asm/ModDependentField;")) {
if(a.values.size() == 2 && a.values.get(0).equals("modId")) {
String modId = a.values.get(1).toString();
if(!Loader.isModLoaded(modId)) {
fieldsToRemove.add(f);
break;
}
} else {
throw new UnsupportedOperationException("Can't parse the annotation correctly");
}
}
}
}
}
for(FieldNode f:fieldsToRemove) {
node.fields.remove(f);
}
if(!changed && methodsToRemove.isEmpty() && fieldsToRemove.isEmpty()) {
return bytes;
}
ClassWriter writer = new ClassWriter(0);
node.accept(writer);
return writer.toByteArray();
}
|
diff --git a/jsf-ri/src/com/sun/faces/facelets/impl/PageDeclarationLanguageImpl.java b/jsf-ri/src/com/sun/faces/facelets/impl/PageDeclarationLanguageImpl.java
index 814c515c3..8533d7f03 100644
--- a/jsf-ri/src/com/sun/faces/facelets/impl/PageDeclarationLanguageImpl.java
+++ b/jsf-ri/src/com/sun/faces/facelets/impl/PageDeclarationLanguageImpl.java
@@ -1,156 +1,154 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* 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.sun.faces.facelets.impl;
import com.sun.faces.facelets.Facelet;
import com.sun.faces.facelets.FaceletContext;
import com.sun.faces.facelets.FaceletException;
import com.sun.faces.facelets.FaceletFactory;
import com.sun.faces.facelets.el.VariableMapperWrapper;
import com.sun.faces.facelets.tag.composite.CompositeComponentBeanInfo;
import com.sun.faces.facelets.tag.jsf.CompositeComponentTagHandler;
import com.sun.faces.util.RequestStateManager;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.ELException;
import javax.el.ValueExpression;
import javax.el.VariableMapper;
import javax.faces.FacesException;
import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.component.UIComponent;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
import javax.faces.webapp.pdl.PageDeclarationLanguage;
/**
* RELEASE_PENDING (rlubke,driscoll) document
*/
public class PageDeclarationLanguageImpl extends PageDeclarationLanguage {
@Override
public BeanInfo getComponentMetadata(FacesContext context,
Resource compositeComponentResource) {
// PENDING this implementation is terribly wasteful.
// Must find a better way.
CompositeComponentBeanInfo result = null;
FaceletContext ctx = (FaceletContext)
context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
FaceletFactory factory = (FaceletFactory)
RequestStateManager.get(context, RequestStateManager.FACELET_FACTORY);
VariableMapper orig = ctx.getVariableMapper();
UIComponent tmp = context.getApplication().createComponent("javax.faces.NamingContainer");
UIPanel facetComponent = (UIPanel)
context.getApplication().createComponent("javax.faces.Panel");
facetComponent.setRendererType("javax.faces.Group");
tmp.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, facetComponent);
// We have to put the resource in here just so the classes that eventually
// get called by facelets have access to it.
tmp.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY,
compositeComponentResource);
Facelet f;
try {
f = factory.getFacelet(compositeComponentResource.getURL());
VariableMapper wrapper = new VariableMapperWrapper(orig) {
@Override
public ValueExpression resolveVariable(String variable) {
return super.resolveVariable(variable);
}
};
ctx.setVariableMapper(wrapper);
f.apply(context, facetComponent);
- } catch (IOException ex) {
- Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
- } catch (FaceletException ex) {
- Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
- } catch (FacesException ex) {
- Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
- } catch (ELException ex) {
- Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
+ } catch (Exception e) {
+ if (e instanceof FacesException) {
+ throw (FacesException) e;
+ } else {
+ throw new FacesException(e);
+ }
}
finally {
ctx.setVariableMapper(orig);
}
result = (CompositeComponentBeanInfo)
tmp.getAttributes().get(UIComponent.BEANINFO_KEY);
return result;
}
public Resource getScriptComponentResource(FacesContext context,
Resource componentResource) {
Resource result = null;
String resourceName = componentResource.getResourceName();
if (resourceName.endsWith(".xhtml")) {
resourceName = resourceName.substring(0,
resourceName.length() - 6) + ".groovy";
ResourceHandler resourceHandler = context.getApplication().getResourceHandler();
result = resourceHandler.createResource(resourceName,
componentResource.getLibraryName());
}
return result;
}
}
| true | true | public BeanInfo getComponentMetadata(FacesContext context,
Resource compositeComponentResource) {
// PENDING this implementation is terribly wasteful.
// Must find a better way.
CompositeComponentBeanInfo result = null;
FaceletContext ctx = (FaceletContext)
context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
FaceletFactory factory = (FaceletFactory)
RequestStateManager.get(context, RequestStateManager.FACELET_FACTORY);
VariableMapper orig = ctx.getVariableMapper();
UIComponent tmp = context.getApplication().createComponent("javax.faces.NamingContainer");
UIPanel facetComponent = (UIPanel)
context.getApplication().createComponent("javax.faces.Panel");
facetComponent.setRendererType("javax.faces.Group");
tmp.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, facetComponent);
// We have to put the resource in here just so the classes that eventually
// get called by facelets have access to it.
tmp.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY,
compositeComponentResource);
Facelet f;
try {
f = factory.getFacelet(compositeComponentResource.getURL());
VariableMapper wrapper = new VariableMapperWrapper(orig) {
@Override
public ValueExpression resolveVariable(String variable) {
return super.resolveVariable(variable);
}
};
ctx.setVariableMapper(wrapper);
f.apply(context, facetComponent);
} catch (IOException ex) {
Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (FaceletException ex) {
Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (FacesException ex) {
Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
} catch (ELException ex) {
Logger.getLogger(CompositeComponentTagHandler.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
ctx.setVariableMapper(orig);
}
result = (CompositeComponentBeanInfo)
tmp.getAttributes().get(UIComponent.BEANINFO_KEY);
return result;
}
| public BeanInfo getComponentMetadata(FacesContext context,
Resource compositeComponentResource) {
// PENDING this implementation is terribly wasteful.
// Must find a better way.
CompositeComponentBeanInfo result = null;
FaceletContext ctx = (FaceletContext)
context.getAttributes().get(FaceletContext.FACELET_CONTEXT_KEY);
FaceletFactory factory = (FaceletFactory)
RequestStateManager.get(context, RequestStateManager.FACELET_FACTORY);
VariableMapper orig = ctx.getVariableMapper();
UIComponent tmp = context.getApplication().createComponent("javax.faces.NamingContainer");
UIPanel facetComponent = (UIPanel)
context.getApplication().createComponent("javax.faces.Panel");
facetComponent.setRendererType("javax.faces.Group");
tmp.getFacets().put(UIComponent.COMPOSITE_FACET_NAME, facetComponent);
// We have to put the resource in here just so the classes that eventually
// get called by facelets have access to it.
tmp.getAttributes().put(Resource.COMPONENT_RESOURCE_KEY,
compositeComponentResource);
Facelet f;
try {
f = factory.getFacelet(compositeComponentResource.getURL());
VariableMapper wrapper = new VariableMapperWrapper(orig) {
@Override
public ValueExpression resolveVariable(String variable) {
return super.resolveVariable(variable);
}
};
ctx.setVariableMapper(wrapper);
f.apply(context, facetComponent);
} catch (Exception e) {
if (e instanceof FacesException) {
throw (FacesException) e;
} else {
throw new FacesException(e);
}
}
finally {
ctx.setVariableMapper(orig);
}
result = (CompositeComponentBeanInfo)
tmp.getAttributes().get(UIComponent.BEANINFO_KEY);
return result;
}
|
diff --git a/src/org/oscim/renderer/overlays/ExtrusionOverlay.java b/src/org/oscim/renderer/overlays/ExtrusionOverlay.java
index f4611148..2770b903 100644
--- a/src/org/oscim/renderer/overlays/ExtrusionOverlay.java
+++ b/src/org/oscim/renderer/overlays/ExtrusionOverlay.java
@@ -1,458 +1,458 @@
/*
* Copyright 2012 OpenScienceMap
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.renderer.overlays;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import org.oscim.core.MapPosition;
import org.oscim.generator.JobTile;
import org.oscim.renderer.GLRenderer;
import org.oscim.renderer.GLState;
import org.oscim.renderer.MapTile;
import org.oscim.renderer.TileManager;
import org.oscim.renderer.TileSet;
import org.oscim.renderer.layer.ExtrusionLayer;
import org.oscim.utils.FastMath;
import org.oscim.utils.GlUtils;
import org.oscim.view.MapView;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
/**
* @author Hannes Janetzek
*/
public class ExtrusionOverlay extends RenderOverlay {
private final static String TAG = ExtrusionOverlay.class.getName();
public ExtrusionOverlay(MapView mapView) {
super(mapView);
}
private static int[] extrusionProgram = new int[2];
private static int[] hExtrusionVertexPosition = new int[2];
private static int[] hExtrusionLightPosition = new int[2];
private static int[] hExtrusionMatrix = new int[2];
private static int[] hExtrusionColor = new int[2];
private static int[] hExtrusionAlpha = new int[2];
private static int[] hExtrusionMode = new int[2];
private boolean initialized = false;
// FIXME sum up size used while filling layer only up to:
private int BUFFERSIZE = 65536 * 2;
private TileSet mTileSet;
private ShortBuffer mShortBuffer;
private MapTile[] mTiles;
private int mTileCnt;
@Override
public synchronized void update(MapPosition curPos, boolean positionChanged,
boolean tilesChanged) {
mMapView.getMapViewPosition().getMapPosition(mMapPosition, null);
if (!initialized) {
initialized = true;
for (int i = 1; i < 2; i++) {
// Set up the program for rendering extrusions
extrusionProgram[i] = GlUtils.createProgram(extrusionVertexShader[i],
extrusionFragmentShader);
if (extrusionProgram[i] == 0) {
Log.e(TAG, "Could not create extrusion shader program. " + i);
return;
}
hExtrusionMatrix[i] = GLES20.glGetUniformLocation(extrusionProgram[i], "u_mvp");
hExtrusionColor[i] = GLES20.glGetUniformLocation(extrusionProgram[i], "u_color");
hExtrusionAlpha[i] = GLES20.glGetUniformLocation(extrusionProgram[i], "u_alpha");
hExtrusionMode[i] = GLES20.glGetUniformLocation(extrusionProgram[i], "u_mode");
hExtrusionVertexPosition[i] = GLES20.glGetAttribLocation(extrusionProgram[i],
"a_pos");
hExtrusionLightPosition[i] = GLES20.glGetAttribLocation(extrusionProgram[i],
"a_light");
}
ByteBuffer buf = ByteBuffer.allocateDirect(BUFFERSIZE)
.order(ByteOrder.nativeOrder());
mShortBuffer = buf.asShortBuffer();
}
int ready = 0;
mTileSet = TileManager.getActiveTiles(mTileSet);
MapTile[] tiles = mTileSet.tiles;
// FIXME just release tiles in this case
if (mAlpha == 0 || curPos.zoomLevel < 16) {
isReady = false;
return;
}
// keep a list of tiles available for rendering
if (mTiles == null || mTiles.length < mTileSet.cnt * 4)
mTiles = new MapTile[mTileSet.cnt * 4];
ExtrusionLayer el;
if (curPos.zoomLevel >= 17) {
for (int i = 0; i < mTileSet.cnt; i++) {
if (!tiles[i].isVisible)
continue;
el = getLayer(tiles[i]);
if (el == null)
continue;
if (!el.compiled) {
el.compile(mShortBuffer);
GlUtils.checkGlError("...");
}
if (el.compiled)
mTiles[ready++] = tiles[i];
}
} else if (curPos.zoomLevel == 16) {
for (int i = 0; i < mTileSet.cnt; i++) {
if (!tiles[i].isVisible)
continue;
MapTile t = tiles[i];
for (byte j = 0; j < 4; j++) {
if ((t.proxies & (1 << j)) != 0) {
MapTile c = t.rel.child[j].tile;
el = getLayer(c);
if (el == null || !el.compiled)
continue;
mTiles[ready++] = c;
}
}
}
}
mTileCnt = ready;
isReady = ready > 0;
}
private static ExtrusionLayer getLayer(MapTile t) {
if (t.layers != null && t.layers.extrusionLayers != null
&& t.state == JobTile.STATE_READY)
return (ExtrusionLayer) t.layers.extrusionLayers;
return null;
}
private boolean debug = false;
private final float[] mVPMatrix = new float[16];
@Override
public synchronized void render(MapPosition pos, float[] mv, float[] proj) {
// TODO one could render in one pass to texture and then draw the texture
// with alpha... might be faster.
Matrix.multiplyMM(mVPMatrix, 0, proj, 0, pos.viewMatrix, 0);
proj = mVPMatrix;
MapTile[] tiles = mTiles;
float div = FastMath.pow(tiles[0].zoomLevel - pos.zoomLevel);
int shaderMode = 1;
int uExtAlpha = hExtrusionAlpha[shaderMode];
int uExtColor = hExtrusionColor[shaderMode];
int uExtVertexPosition = hExtrusionVertexPosition[shaderMode];
int uExtLightPosition = hExtrusionLightPosition[shaderMode];
int uExtMatrix = hExtrusionMatrix[shaderMode];
int uExtMode = hExtrusionMode[shaderMode];
if (debug) {
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLState.test(false, false);
for (int i = 0; i < mTileCnt; i++) {
ExtrusionLayer el = (ExtrusionLayer) tiles[i].layers.extrusionLayers;
setMatrix(pos, mv, proj, tiles[i], div, 0);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
return;
}
GLES20.glDepthMask(true);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT);
GLState.test(true, false);
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, -1);
if (pos.scale < 2) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_FRONT);
}
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glColorMask(false, false, false, false);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLES20.glUniform1f(uExtAlpha, mAlpha);
// draw to depth buffer
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
}
// enable color buffer, use depth mask
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthMask(false);
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
GLES20.glDepthFunc(GLES20.GL_EQUAL);
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
// draw roof
GLES20.glUniform1i(uExtMode, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[2],
GLES20.GL_UNSIGNED_SHORT, (el.mIndiceCnt[0] + el.mIndiceCnt[1]) * 2);
// draw sides 1
GLES20.glUniform1i(uExtMode, 1);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[0],
GLES20.GL_UNSIGNED_SHORT, 0);
// draw sides 2
GLES20.glUniform1i(uExtMode, 2);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[1],
GLES20.GL_UNSIGNED_SHORT, el.mIndiceCnt[0] * 2);
// drawing gl_lines with the same coordinates does not result in
// same depth values as polygons, so add offset and draw gl_lequal:
GLES20.glDepthFunc(GLES20.GL_LEQUAL);
- GlUtils.addOffsetM(mv, 1000);
+ GlUtils.addOffsetM(mv, 100);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glUniform1i(uExtMode, 3);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
if (pos.scale < 2)
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
}
private static void setMatrix(MapPosition mapPosition, float[] matrix, float[] proj,
MapTile tile, float div, int delta) {
float x = (float) (tile.pixelX - mapPosition.x * div);
float y = (float) (tile.pixelY - mapPosition.y * div);
float scale = mapPosition.scale / div;
GlUtils.setTileMatrix(matrix, x, y, scale);
// scale height
matrix[10] = scale / (1000f * GLRenderer.COORD_MULTIPLIER);
Matrix.multiplyMM(matrix, 0, proj, 0, matrix, 0);
GlUtils.addOffsetM(matrix, delta);
}
private final float _a = 0.8f;
private final float _r = 0xe9;
private final float _g = 0xe8;
private final float _b = 0xe6;
private final float _o = 55;
private final float _s = 20;
private final float _l = 16;
private float mAlpha = 1;
private final float[] mColor = {
// roof color
_a * ((_r + _l) / 255),
_a * ((_g + _l) / 255),
_a * ((_b + _l) / 255),
_a,
// sligthly differ adjacent side
// faces to improve contrast
_a * ((_r - _s + 1) / 255),
_a * ((_g - _s) / 255),
_a * ((_b - _s) / 255),
_a,
_a * ((_r - _s) / 255),
_a * ((_g - _s) / 255),
_a * ((_b - _s - 2) / 255),
_a,
// roof outline
(_r - _o) / 255,
(_g - _o) / 255,
(_b - _o) / 255,
// 1, 0, 0,
1.0f,
};
final static String[] extrusionVertexShader = {
"precision mediump float;"
+ "uniform mat4 u_mvp;"
+ "uniform vec4 u_color[4];"
+ "uniform int u_mode;"
+ "uniform float u_alpha;"
+ "attribute vec4 a_pos;"
+ "attribute vec2 a_light;"
+ "varying vec4 color;"
+ "const float ff = 255.0;"
+ "float c_alpha = 0.8;"
+ "void main() {"
+ " gl_Position = u_mvp * a_pos;"
+ " if (u_mode == 0)"
// roof / depth pass
+ " color = u_color[0];"
+ " else {"
// decrease contrast with distance
+ " float z = (0.96 + gl_Position.z * 0.04);"
+ " if (u_mode == 1){"
// sides 1 - use 0xff00
// scale direction to -0.5<>0.5
+ " float dir = abs(a_light.y / ff - 0.5);"
+ " color = u_color[1] * z;"
+ " color.rgb *= (0.7 + dir * 0.4);"
+ " } else if (u_mode == 2){"
// sides 2 - use 0x00ff
+ " float dir = abs(a_light.x / ff - 0.5);"
+ " color = u_color[2] * z;"
+ " color.rgb *= (0.7 + dir * 0.4);"
+ " } else"
// outline
+ " color = u_color[3] * z;"
+ "}}",
"precision mediump float;"
+ "uniform mat4 u_mvp;"
+ "uniform vec4 u_color[4];"
+ "uniform int u_mode;"
+ "uniform float u_alpha;"
+ "attribute vec4 a_pos;"
+ "attribute vec2 a_light;"
+ "varying vec4 color;"
//+ "varying float z;"
+ "const float ff = 255.0;"
+ "void main() {"
// change height by u_alpha
+ " gl_Position = u_mvp * vec4(a_pos.xy, a_pos.z * u_alpha, 1.0);"
//+ " z = gl_Position.z;"
+ " if (u_mode == 0)"
// roof / depth pass
+ " color = u_color[0];"
+ " else {"
// decrease contrast with distance
+ " if (u_mode == 1){"
// sides 1 - use 0xff00
// scale direction to -0.5<>0.5
//+ " float dir = abs(a_light.y / ff - 0.5);"
+ " float dir = a_light.y / ff;"
+ " float z = (0.98 + gl_Position.z * 0.02);"
+ " color = u_color[1];"
+ " color.rgb *= (0.8 + dir * 0.2) * z;"
+ " } else if (u_mode == 2){"
// sides 2 - use 0x00ff
//+ " float dir = abs(a_light.x / ff - 0.5);"
+ " float dir = a_light.x / ff;"
+ " float z = (0.95 + gl_Position.z * 0.05);"
+ " color = u_color[2] * z;"
+ " color.rgb *= (0.8 + dir * 0.2) * z;"
+ " } else {"
// outline
+ " float z = (0.8 - gl_Position.z * 0.2);"
+ " color = u_color[3] * z;"
+ "}}}"
};
final static String extrusionFragmentShader = ""
+ "precision mediump float;"
+ "varying vec4 color;"
+ "void main() {"
+ " gl_FragColor = color;"
+ "}";
final static String extrusionFragmentShaderZ = ""
+ "precision highp float;"
+ "uniform vec4 u_color;"
+ "varying float z;"
+ "void main() {"
+ "if (z < 0.0)"
+ " gl_FragColor = vec4(z * -1.0, 0.0, 0.0, 1.0);"
+ "else"
+ " gl_FragColor = vec4(0.0, 0.0, z, 1.0);"
+ "}";
public void setAlpha(float a) {
mAlpha = a;
}
}
| true | true | public synchronized void render(MapPosition pos, float[] mv, float[] proj) {
// TODO one could render in one pass to texture and then draw the texture
// with alpha... might be faster.
Matrix.multiplyMM(mVPMatrix, 0, proj, 0, pos.viewMatrix, 0);
proj = mVPMatrix;
MapTile[] tiles = mTiles;
float div = FastMath.pow(tiles[0].zoomLevel - pos.zoomLevel);
int shaderMode = 1;
int uExtAlpha = hExtrusionAlpha[shaderMode];
int uExtColor = hExtrusionColor[shaderMode];
int uExtVertexPosition = hExtrusionVertexPosition[shaderMode];
int uExtLightPosition = hExtrusionLightPosition[shaderMode];
int uExtMatrix = hExtrusionMatrix[shaderMode];
int uExtMode = hExtrusionMode[shaderMode];
if (debug) {
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLState.test(false, false);
for (int i = 0; i < mTileCnt; i++) {
ExtrusionLayer el = (ExtrusionLayer) tiles[i].layers.extrusionLayers;
setMatrix(pos, mv, proj, tiles[i], div, 0);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
return;
}
GLES20.glDepthMask(true);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT);
GLState.test(true, false);
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, -1);
if (pos.scale < 2) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_FRONT);
}
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glColorMask(false, false, false, false);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLES20.glUniform1f(uExtAlpha, mAlpha);
// draw to depth buffer
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
}
// enable color buffer, use depth mask
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthMask(false);
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
GLES20.glDepthFunc(GLES20.GL_EQUAL);
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
// draw roof
GLES20.glUniform1i(uExtMode, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[2],
GLES20.GL_UNSIGNED_SHORT, (el.mIndiceCnt[0] + el.mIndiceCnt[1]) * 2);
// draw sides 1
GLES20.glUniform1i(uExtMode, 1);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[0],
GLES20.GL_UNSIGNED_SHORT, 0);
// draw sides 2
GLES20.glUniform1i(uExtMode, 2);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[1],
GLES20.GL_UNSIGNED_SHORT, el.mIndiceCnt[0] * 2);
// drawing gl_lines with the same coordinates does not result in
// same depth values as polygons, so add offset and draw gl_lequal:
GLES20.glDepthFunc(GLES20.GL_LEQUAL);
GlUtils.addOffsetM(mv, 1000);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glUniform1i(uExtMode, 3);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
if (pos.scale < 2)
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
}
| public synchronized void render(MapPosition pos, float[] mv, float[] proj) {
// TODO one could render in one pass to texture and then draw the texture
// with alpha... might be faster.
Matrix.multiplyMM(mVPMatrix, 0, proj, 0, pos.viewMatrix, 0);
proj = mVPMatrix;
MapTile[] tiles = mTiles;
float div = FastMath.pow(tiles[0].zoomLevel - pos.zoomLevel);
int shaderMode = 1;
int uExtAlpha = hExtrusionAlpha[shaderMode];
int uExtColor = hExtrusionColor[shaderMode];
int uExtVertexPosition = hExtrusionVertexPosition[shaderMode];
int uExtLightPosition = hExtrusionLightPosition[shaderMode];
int uExtMatrix = hExtrusionMatrix[shaderMode];
int uExtMode = hExtrusionMode[shaderMode];
if (debug) {
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLState.test(false, false);
for (int i = 0; i < mTileCnt; i++) {
ExtrusionLayer el = (ExtrusionLayer) tiles[i].layers.extrusionLayers;
setMatrix(pos, mv, proj, tiles[i], div, 0);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
return;
}
GLES20.glDepthMask(true);
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT);
GLState.test(true, false);
GLES20.glUseProgram(extrusionProgram[shaderMode]);
GLState.enableVertexArrays(uExtVertexPosition, -1);
if (pos.scale < 2) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
GLES20.glCullFace(GLES20.GL_FRONT);
}
GLES20.glDepthFunc(GLES20.GL_LESS);
GLES20.glColorMask(false, false, false, false);
GLES20.glUniform1i(uExtMode, 0);
GLES20.glUniform4fv(uExtColor, 4, mColor, 0);
GLES20.glUniform1f(uExtAlpha, mAlpha);
// draw to depth buffer
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]),
GLES20.GL_UNSIGNED_SHORT, 0);
}
// enable color buffer, use depth mask
GLState.enableVertexArrays(uExtVertexPosition, uExtLightPosition);
GLES20.glColorMask(true, true, true, true);
GLES20.glDepthMask(false);
for (int i = 0; i < mTileCnt; i++) {
MapTile t = tiles[i];
ExtrusionLayer el = (ExtrusionLayer) t.layers.extrusionLayers;
GLES20.glDepthFunc(GLES20.GL_EQUAL);
int d = GLRenderer.depthOffset(t) * 10;
setMatrix(pos, mv, proj, t, div, d);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, el.mIndicesBufferID);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, el.mVertexBufferID);
GLES20.glVertexAttribPointer(uExtVertexPosition, 3,
GLES20.GL_SHORT, false, 8, 0);
GLES20.glVertexAttribPointer(uExtLightPosition, 2,
GLES20.GL_UNSIGNED_BYTE, false, 8, 6);
// draw roof
GLES20.glUniform1i(uExtMode, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[2],
GLES20.GL_UNSIGNED_SHORT, (el.mIndiceCnt[0] + el.mIndiceCnt[1]) * 2);
// draw sides 1
GLES20.glUniform1i(uExtMode, 1);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[0],
GLES20.GL_UNSIGNED_SHORT, 0);
// draw sides 2
GLES20.glUniform1i(uExtMode, 2);
GLES20.glDrawElements(GLES20.GL_TRIANGLES, el.mIndiceCnt[1],
GLES20.GL_UNSIGNED_SHORT, el.mIndiceCnt[0] * 2);
// drawing gl_lines with the same coordinates does not result in
// same depth values as polygons, so add offset and draw gl_lequal:
GLES20.glDepthFunc(GLES20.GL_LEQUAL);
GlUtils.addOffsetM(mv, 100);
GLES20.glUniformMatrix4fv(uExtMatrix, 1, false, mv, 0);
GLES20.glUniform1i(uExtMode, 3);
GLES20.glDrawElements(GLES20.GL_LINES, el.mIndiceCnt[3],
GLES20.GL_UNSIGNED_SHORT,
(el.mIndiceCnt[0] + el.mIndiceCnt[1] + el.mIndiceCnt[2]) * 2);
// just a temporary reference!
tiles[i] = null;
}
if (pos.scale < 2)
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
}
|
diff --git a/src/eu/bryants/anthony/toylanguage/compiler/passes/TypeChecker.java b/src/eu/bryants/anthony/toylanguage/compiler/passes/TypeChecker.java
index 6117584..ebff66a 100644
--- a/src/eu/bryants/anthony/toylanguage/compiler/passes/TypeChecker.java
+++ b/src/eu/bryants/anthony/toylanguage/compiler/passes/TypeChecker.java
@@ -1,1148 +1,1147 @@
package eu.bryants.anthony.toylanguage.compiler.passes;
import java.math.BigInteger;
import java.util.Set;
import eu.bryants.anthony.toylanguage.ast.CompilationUnit;
import eu.bryants.anthony.toylanguage.ast.CompoundDefinition;
import eu.bryants.anthony.toylanguage.ast.expression.ArithmeticExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayCreationExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BitwiseNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BracketedExpression;
import eu.bryants.anthony.toylanguage.ast.expression.CastExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression.ComparisonOperator;
import eu.bryants.anthony.toylanguage.ast.expression.Expression;
import eu.bryants.anthony.toylanguage.ast.expression.FieldAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.toylanguage.ast.expression.InlineIfExpression;
import eu.bryants.anthony.toylanguage.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression.LogicalOperator;
import eu.bryants.anthony.toylanguage.ast.expression.MinusExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ShiftExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ThisExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleIndexExpression;
import eu.bryants.anthony.toylanguage.ast.expression.VariableExpression;
import eu.bryants.anthony.toylanguage.ast.member.ArrayLengthMember;
import eu.bryants.anthony.toylanguage.ast.member.Constructor;
import eu.bryants.anthony.toylanguage.ast.member.Field;
import eu.bryants.anthony.toylanguage.ast.member.Member;
import eu.bryants.anthony.toylanguage.ast.member.Method;
import eu.bryants.anthony.toylanguage.ast.misc.ArrayElementAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Assignee;
import eu.bryants.anthony.toylanguage.ast.misc.BlankAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.FieldAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Parameter;
import eu.bryants.anthony.toylanguage.ast.misc.VariableAssignee;
import eu.bryants.anthony.toylanguage.ast.statement.AssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Block;
import eu.bryants.anthony.toylanguage.ast.statement.BreakStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ContinueStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ExpressionStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ForStatement;
import eu.bryants.anthony.toylanguage.ast.statement.IfStatement;
import eu.bryants.anthony.toylanguage.ast.statement.PrefixIncDecStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ReturnStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ShorthandAssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ShorthandAssignStatement.ShorthandAssignmentOperator;
import eu.bryants.anthony.toylanguage.ast.statement.Statement;
import eu.bryants.anthony.toylanguage.ast.statement.WhileStatement;
import eu.bryants.anthony.toylanguage.ast.terminal.IntegerLiteral;
import eu.bryants.anthony.toylanguage.ast.type.ArrayType;
import eu.bryants.anthony.toylanguage.ast.type.FunctionType;
import eu.bryants.anthony.toylanguage.ast.type.NamedType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType.PrimitiveTypeType;
import eu.bryants.anthony.toylanguage.ast.type.TupleType;
import eu.bryants.anthony.toylanguage.ast.type.Type;
import eu.bryants.anthony.toylanguage.ast.type.VoidType;
import eu.bryants.anthony.toylanguage.compiler.ConceptualException;
/*
* Created on 8 Apr 2012
*/
/**
* @author Anthony Bryant
*/
public class TypeChecker
{
public static void checkTypes(CompilationUnit compilationUnit) throws ConceptualException
{
for (CompoundDefinition compoundDefinition : compilationUnit.getCompoundDefinitions())
{
for (Constructor constructor : compoundDefinition.getConstructors())
{
checkTypes(constructor.getBlock(), VoidType.VOID_TYPE, compilationUnit);
}
for (Field field : compoundDefinition.getFields())
{
checkTypes(field);
}
for (Method method : compoundDefinition.getAllMethods())
{
checkTypes(method.getBlock(), method.getReturnType(), compilationUnit);
}
}
}
private static void checkTypes(Field field) throws ConceptualException
{
if (!field.isStatic())
{
// allow any types on a non-static field
return;
}
Type type = field.getType();
if (!type.isNullable())
{
throw new ConceptualException("Static fields must always have a type which has a language-defined default value (e.g. 0 for uint). Consider making this field nullable.", type.getLexicalPhrase());
}
}
private static void checkTypes(Statement statement, Type returnType, CompilationUnit compilationUnit) throws ConceptualException
{
if (statement instanceof AssignStatement)
{
AssignStatement assignStatement = (AssignStatement) statement;
Type declaredType = assignStatement.getType();
Assignee[] assignees = assignStatement.getAssignees();
boolean distributedTupleType = declaredType != null && declaredType instanceof TupleType && !declaredType.isNullable() && ((TupleType) declaredType).getSubTypes().length == assignees.length;
Type[] tupledSubTypes;
if (distributedTupleType)
{
// the type is distributed, so in the following statement:
// (int, long) a, b;
// a has type int, and b has type long
// so set the tupledSubTypes array to the declared subTypes array
tupledSubTypes = ((TupleType) declaredType).getSubTypes();
}
else
{
tupledSubTypes = new Type[assignees.length];
}
for (int i = 0; i < assignees.length; i++)
{
if (assignees[i] instanceof VariableAssignee)
{
VariableAssignee variableAssignee = (VariableAssignee) assignees[i];
if (declaredType != null)
{
// we have a declared type, so check that the variable matches it
if (!variableAssignee.getResolvedVariable().getType().isEquivalent(distributedTupleType ? tupledSubTypes[i] : declaredType))
{
throw new ConceptualException("The variable type '" + variableAssignee.getResolvedVariable().getType() + "' does not match the declared type '" + (distributedTupleType ? tupledSubTypes[i] : declaredType) + "'", assignees[i].getLexicalPhrase());
}
}
if (!distributedTupleType)
{
tupledSubTypes[i] = variableAssignee.getResolvedVariable().getType();
}
variableAssignee.setResolvedType(distributedTupleType ? tupledSubTypes[i] : declaredType);
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
Type arrayType = checkTypes(arrayElementAssignee.getArrayExpression(), compilationUnit);
if (!(arrayType instanceof ArrayType))
{
throw new ConceptualException("Array assignments are not defined for the type " + arrayType, arrayElementAssignee.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayElementAssignee.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, arrayElementAssignee.getDimensionExpression().getLexicalPhrase());
}
Type baseType = ((ArrayType) arrayType).getBaseType();
if (declaredType != null)
{
// we have a declared type, so check that the array base type matches it
if (!baseType.isEquivalent(distributedTupleType ? tupledSubTypes[i] : declaredType))
{
throw new ConceptualException("The array element type '" + baseType + "' does not match the declared type '" + (distributedTupleType ? tupledSubTypes[i] : declaredType) + "'", assignees[i].getLexicalPhrase());
}
}
if (!distributedTupleType)
{
tupledSubTypes[i] = baseType;
}
arrayElementAssignee.setResolvedType(distributedTupleType ? tupledSubTypes[i] : declaredType);
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
// no need to do the following type checking here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
// Type type = checkTypes(fieldAccessExpression.getBaseExpression(), compilationUnit);
Member member = fieldAccessExpression.getResolvedMember();
Type type;
if (member instanceof ArrayLengthMember)
{
throw new ConceptualException("Cannot assign to an array's length", fieldAssignee.getLexicalPhrase());
}
else if (member instanceof Field)
{
type = ((Field) member).getType();
}
else if (member instanceof Method)
{
throw new ConceptualException("Cannot assign to a method", fieldAssignee.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
if (declaredType != null)
{
if (!type.isEquivalent(distributedTupleType ? tupledSubTypes[i] : declaredType))
{
throw new ConceptualException("The field type '" + type + "' does not match the declared type '" + (distributedTupleType ? tupledSubTypes[i] : declaredType) + "'", fieldAssignee.getLexicalPhrase());
}
}
if (!distributedTupleType)
{
tupledSubTypes[i] = type;
}
fieldAssignee.setResolvedType(distributedTupleType ? tupledSubTypes[i] : declaredType);
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to,
// but we need to make sure tupledSubTypes[i] has its type now, if possible
if (!distributedTupleType && declaredType != null)
{
tupledSubTypes[i] = declaredType;
}
// if there is no declared type, then there must be an expression, so we leave tupledSubTypes[i] as null, so that we can fill it in later
assignees[i].setResolvedType(distributedTupleType ? tupledSubTypes[i] : declaredType);
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
if (assignStatement.getExpression() == null)
{
// we definitely have a declared type here, so the assignees definitely all have their types set
// so we don't need to do anything
}
else
{
Type exprType = checkTypes(assignStatement.getExpression(), compilationUnit);
if (tupledSubTypes.length == 1)
{
if (tupledSubTypes[0] == null)
{
tupledSubTypes[0] = exprType;
}
else if (!tupledSubTypes[0].canAssign(exprType))
{
throw new ConceptualException("Cannot assign an expression of type " + exprType + " to a variable of type " + tupledSubTypes[0], assignStatement.getLexicalPhrase());
}
assignees[0].setResolvedType(tupledSubTypes[0]);
}
else
{
boolean assignable = exprType instanceof TupleType && ((TupleType) exprType).getSubTypes().length == tupledSubTypes.length;
if (assignable)
{
TupleType exprTupleType = (TupleType) exprType;
Type[] exprSubTypes = exprTupleType.getSubTypes();
for (int i = 0; i < exprSubTypes.length; i++)
{
if (tupledSubTypes[i] == null)
{
tupledSubTypes[i] = exprSubTypes[i];
}
else if (!tupledSubTypes[i].canAssign(exprSubTypes[i]))
{
assignable = false;
break;
}
assignees[i].setResolvedType(tupledSubTypes[i]);
}
}
if (!assignable)
{
StringBuffer buffer = new StringBuffer("(");
for (int i = 0; i < tupledSubTypes.length; i++)
{
buffer.append(tupledSubTypes[i] == null ? "_" : tupledSubTypes[i]);
if (i != tupledSubTypes.length - 1)
{
buffer.append(", ");
}
}
buffer.append(")");
throw new ConceptualException("Cannot assign an expression of type " + exprType + " to a tuple of type " + buffer, assignStatement.getLexicalPhrase());
}
}
}
}
else if (statement instanceof Block)
{
for (Statement s : ((Block) statement).getStatements())
{
checkTypes(s, returnType, compilationUnit);
}
}
else if (statement instanceof BreakStatement)
{
// do nothing
}
else if (statement instanceof ContinueStatement)
{
// do nothing
}
else if (statement instanceof ExpressionStatement)
{
checkTypes(((ExpressionStatement) statement).getExpression(), compilationUnit);
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
Statement init = forStatement.getInitStatement();
if (init != null)
{
checkTypes(init, returnType, compilationUnit);
}
Expression condition = forStatement.getConditional();
if (condition != null)
{
Type conditionType = checkTypes(condition, compilationUnit);
if (conditionType.isNullable() || !(conditionType instanceof PrimitiveType) || ((PrimitiveType) conditionType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + conditionType + "'", condition.getLexicalPhrase());
}
}
Statement update = forStatement.getUpdateStatement();
if (update != null)
{
checkTypes(update, returnType, compilationUnit);
}
checkTypes(forStatement.getBlock(), returnType, compilationUnit);
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
Type exprType = checkTypes(ifStatement.getExpression(), compilationUnit);
if (exprType.isNullable() || !(exprType instanceof PrimitiveType) || ((PrimitiveType) exprType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + exprType + "'", ifStatement.getExpression().getLexicalPhrase());
}
checkTypes(ifStatement.getThenClause(), returnType, compilationUnit);
if (ifStatement.getElseClause() != null)
{
checkTypes(ifStatement.getElseClause(), returnType, compilationUnit);
}
}
else if (statement instanceof PrefixIncDecStatement)
{
PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement;
Assignee assignee = prefixIncDecStatement.getAssignee();
Type assigneeType;
if (assignee instanceof VariableAssignee)
{
assigneeType = ((VariableAssignee) assignee).getResolvedVariable().getType();
assignee.setResolvedType(assigneeType);
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
Type arrayType = checkTypes(arrayElementAssignee.getArrayExpression(), compilationUnit);
if (!(arrayType instanceof ArrayType))
{
throw new ConceptualException("Array accesses are not defined for the type " + arrayType, arrayElementAssignee.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayElementAssignee.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, arrayElementAssignee.getDimensionExpression().getLexicalPhrase());
}
assigneeType = ((ArrayType) arrayType).getBaseType();
assignee.setResolvedType(assigneeType);
}
else if (assignee instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignee;
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
// no need to do the following type checking here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
// Type type = checkTypes(fieldAccessExpression.getExpression(), compilationUnit);
Member member = fieldAccessExpression.getResolvedMember();
if (member instanceof ArrayLengthMember)
{
throw new ConceptualException("Cannot increment or decrement an array's length", fieldAssignee.getLexicalPhrase());
}
else if (member instanceof Field)
{
assigneeType = ((Field) member).getType();
}
else if (member instanceof Method)
{
throw new ConceptualException("Cannot increment or decrement a method", fieldAssignee.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
fieldAssignee.setResolvedType(assigneeType);
}
else
{
// ignore blank assignees, they shouldn't be able to get through variable resolution
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
if (assigneeType.isNullable() || !(assigneeType instanceof PrimitiveType) || ((PrimitiveType) assigneeType).getPrimitiveTypeType() == PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("Cannot " + (prefixIncDecStatement.isIncrement() ? "inc" : "dec") + "rement an assignee of type " + assigneeType, assignee.getLexicalPhrase());
}
}
else if (statement instanceof ReturnStatement)
{
Expression returnExpression = ((ReturnStatement) statement).getExpression();
if (returnExpression == null)
{
if (!(returnType instanceof VoidType))
{
throw new ConceptualException("A non-void function cannot return with no value", statement.getLexicalPhrase());
}
}
else
{
if (returnType instanceof VoidType)
{
throw new ConceptualException("A void function cannot return a value", statement.getLexicalPhrase());
}
Type exprType = checkTypes(returnExpression, compilationUnit);
if (!returnType.canAssign(exprType))
{
throw new ConceptualException("Cannot return an expression of type '" + exprType + "' from a function with return type '" + returnType + "'", statement.getLexicalPhrase());
}
}
}
else if (statement instanceof ShorthandAssignStatement)
{
ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement;
Assignee[] assignees = shorthandAssignStatement.getAssignees();
Type[] types = new Type[assignees.length];
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof VariableAssignee)
{
VariableAssignee variableAssignee = (VariableAssignee) assignees[i];
types[i] = variableAssignee.getResolvedVariable().getType();
variableAssignee.setResolvedType(types[i]);
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
Type arrayType = checkTypes(arrayElementAssignee.getArrayExpression(), compilationUnit);
if (!(arrayType instanceof ArrayType))
{
throw new ConceptualException("Array assignments are not defined for the type " + arrayType, arrayElementAssignee.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayElementAssignee.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, arrayElementAssignee.getDimensionExpression().getLexicalPhrase());
}
types[i] = ((ArrayType) arrayType).getBaseType();
arrayElementAssignee.setResolvedType(types[i]);
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
// no need to do the following type checking here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
// Type type = checkTypes(fieldAccessExpression.getExpression(), compilationUnit);
Member member = fieldAccessExpression.getResolvedMember();
if (member instanceof ArrayLengthMember)
{
throw new ConceptualException("Cannot assign to an array's length", fieldAssignee.getLexicalPhrase());
}
else if (member instanceof Field)
{
types[i] = ((Field) member).getType();
}
else if (member instanceof Method)
{
throw new ConceptualException("Cannot assign to a method", fieldAssignee.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
fieldAssignee.setResolvedType(types[i]);
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to, so leave its type as null
types[i] = null;
assignees[i].setResolvedType(null);
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
Type expressionType = checkTypes(shorthandAssignStatement.getExpression(), compilationUnit);
Type[] rightTypes;
if (expressionType instanceof TupleType && !expressionType.isNullable() && ((TupleType) expressionType).getSubTypes().length == assignees.length)
{
TupleType expressionTupleType = (TupleType) expressionType;
rightTypes = expressionTupleType.getSubTypes();
}
else
{
rightTypes = new Type[assignees.length];
for (int i = 0; i < rightTypes.length; ++i)
{
rightTypes[i] = expressionType;
}
}
ShorthandAssignmentOperator operator = shorthandAssignStatement.getOperator();
for (int i = 0; i < assignees.length; ++i)
{
Type left = types[i];
Type right = rightTypes[i];
if (left == null)
{
// the left hand side is a blank assignee, so pretend it is the same type as the right hand side
left = right;
types[i] = left;
assignees[i].setResolvedType(left);
}
if (!(left instanceof PrimitiveType) || !(right instanceof PrimitiveType) || left.isNullable() || right.isNullable())
{
throw new ConceptualException("The operator '" + operator + "' is not defined for types " + left + " and " + right, shorthandAssignStatement.getLexicalPhrase());
}
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) left).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) right).getPrimitiveTypeType();
if (operator == ShorthandAssignmentOperator.AND || operator == ShorthandAssignmentOperator.OR || operator == ShorthandAssignmentOperator.XOR)
{
if (leftPrimitiveType.isFloating() || rightPrimitiveType.isFloating() || !left.canAssign(right))
{
throw new ConceptualException("The operator '" + operator + "' is not defined for types " + left + " and " + right, shorthandAssignStatement.getLexicalPhrase());
}
}
else if (operator == ShorthandAssignmentOperator.ADD || operator == ShorthandAssignmentOperator.SUBTRACT ||
operator == ShorthandAssignmentOperator.MULTIPLY || operator == ShorthandAssignmentOperator.DIVIDE ||
operator == ShorthandAssignmentOperator.REMAINDER || operator == ShorthandAssignmentOperator.MODULO)
{
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN || rightPrimitiveType == PrimitiveTypeType.BOOLEAN || !left.canAssign(right))
{
throw new ConceptualException("The operator '" + operator + "' is not defined for types " + left + " and " + right, shorthandAssignStatement.getLexicalPhrase());
}
}
else if (operator == ShorthandAssignmentOperator.LEFT_SHIFT || operator == ShorthandAssignmentOperator.RIGHT_SHIFT)
{
if (leftPrimitiveType.isFloating() || rightPrimitiveType.isFloating() ||
leftPrimitiveType == PrimitiveTypeType.BOOLEAN || rightPrimitiveType == PrimitiveTypeType.BOOLEAN ||
rightPrimitiveType.isSigned())
{
throw new ConceptualException("The operator '" + operator + "' is not defined for types " + left + " and " + right, shorthandAssignStatement.getLexicalPhrase());
}
}
else
{
throw new IllegalStateException("Unknown shorthand assignment operator: " + operator);
}
}
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
Type exprType = checkTypes(whileStatement.getExpression(), compilationUnit);
if (exprType.isNullable() || !(exprType instanceof PrimitiveType) || ((PrimitiveType) exprType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + exprType + "'", whileStatement.getExpression().getLexicalPhrase());
}
checkTypes(whileStatement.getStatement(), returnType, compilationUnit);
}
else
{
throw new ConceptualException("Internal type checking error: Unknown statement type", statement.getLexicalPhrase());
}
}
/**
* Checks the types on an Expression recursively.
* This method should only be called on an Expression after the resolver has been run over that Expression
* @param expression - the Expression to check the types on
* @param compilationUnit - the compilation unit containing the expression
* @return the Type of the Expression
* @throws ConceptualException - if a conceptual problem is encountered while checking the types
*/
public static Type checkTypes(Expression expression, CompilationUnit compilationUnit) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
Type leftType = checkTypes(arithmeticExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(arithmeticExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
arithmeticExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
arithmeticExpression.setType(rightType);
return rightType;
}
// the type will now only be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
}
}
throw new ConceptualException("The operator '" + arithmeticExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", arithmeticExpression.getLexicalPhrase());
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
Type type = checkTypes(arrayAccessExpression.getArrayExpression(), compilationUnit);
if (!(type instanceof ArrayType) || type.isNullable())
{
throw new ConceptualException("Array accesses are not defined for type " + type, arrayAccessExpression.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayAccessExpression.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, dimensionType.getLexicalPhrase());
}
Type baseType = ((ArrayType) type).getBaseType();
arrayAccessExpression.setType(baseType);
return baseType;
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression e : creationExpression.getDimensionExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(type))
{
throw new ConceptualException("Cannot use an expression of type " + type + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, e.getLexicalPhrase());
}
}
}
Type baseType = creationExpression.getType().getBaseType();
if (creationExpression.getValueExpressions() == null)
{
if (!baseType.isNullable())
{
throw new ConceptualException("Cannot create an array of '" + baseType + "' without an initialiser.", creationExpression.getLexicalPhrase());
}
}
else
{
for (Expression e : creationExpression.getValueExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!baseType.canAssign(type))
{
throw new ConceptualException("Cannot add an expression of type " + type + " to an array of type " + baseType, e.getLexicalPhrase());
}
}
}
return creationExpression.getType();
}
else if (expression instanceof BitwiseNotExpression)
{
Type type = checkTypes(((BitwiseNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
if (!primitiveTypeType.isFloating())
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The operator '~' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BooleanLiteralExpression)
{
Type type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
expression.setType(type);
return type;
}
else if (expression instanceof BooleanNotExpression)
{
Type type = checkTypes(((BooleanNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable() && ((PrimitiveType) type).getPrimitiveTypeType() == PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
throw new ConceptualException("The operator '!' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BracketedExpression)
{
Type type = checkTypes(((BracketedExpression) expression).getExpression(), compilationUnit);
expression.setType(type);
return type;
}
else if (expression instanceof CastExpression)
{
Type exprType = checkTypes(((CastExpression) expression).getExpression(), compilationUnit);
Type castedType = expression.getType();
if (exprType.canAssign(castedType) || castedType.canAssign(exprType))
{
// if the assignment works in reverse (i.e. the casted type can be assigned to the expression) then it can be casted back
// (also allow it if the assignment works forwards, although really that should be a warning about an unnecessary cast)
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
if (exprType instanceof PrimitiveType && castedType instanceof PrimitiveType && !exprType.isNullable() && !castedType.isNullable())
{
// allow non-floating primitive types with the same bit count to be casted to each other
PrimitiveTypeType exprPrimitiveTypeType = ((PrimitiveType) exprType).getPrimitiveTypeType();
PrimitiveTypeType castedPrimitiveTypeType = ((PrimitiveType) castedType).getPrimitiveTypeType();
if (!exprPrimitiveTypeType.isFloating() && !castedPrimitiveTypeType.isFloating() &&
exprPrimitiveTypeType.getBitCount() == castedPrimitiveTypeType.getBitCount())
{
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
}
throw new ConceptualException("Cannot cast from '" + exprType + "' to '" + castedType + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
ComparisonOperator operator = comparisonExpression.getOperator();
Type leftType = checkTypes(comparisonExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(comparisonExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN &&
(comparisonExpression.getOperator() == ComparisonOperator.EQUAL || comparisonExpression.getOperator() == ComparisonOperator.NOT_EQUAL))
{
// comparing booleans is only valid when using '==' or '!='
comparisonExpression.setComparisonType((PrimitiveType) leftType);
PrimitiveType type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(type);
return type;
}
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
comparisonExpression.setComparisonType((PrimitiveType) leftType);
}
else if (rightType.canAssign(leftType))
{
comparisonExpression.setComparisonType((PrimitiveType) rightType);
}
else
{
// comparisonType will be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
// but since comparing numeric types should always be valid, we just set the comparisonType to null anyway
// and let the code generator handle it by converting to larger signed types first
comparisonExpression.setComparisonType(null);
}
// comparing any numeric types is always valid
Type resultType = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(resultType);
return resultType;
}
}
throw new ConceptualException("The '" + operator + "' operator is not defined for types '" + leftType + "' and '" + rightType + "'", comparisonExpression.getLexicalPhrase());
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
// no need to do the following type check here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
- // Type type = checkTypes(fieldAccessExpression.getExpression(), compilationUnit);
+ // Type type = checkTypes(fieldAccessExpression.getBaseExpression(), compilationUnit);
if (fieldAccessExpression.getBaseExpression() != null)
{
Type baseExpressionType = fieldAccessExpression.getBaseExpression().getType();
if (baseExpressionType.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the field '" + fieldAccessExpression.getFieldName() + "' on something which is nullable. Consider using the '?.' operator.", fieldAccessExpression.getLexicalPhrase());
}
}
Member member = fieldAccessExpression.getResolvedMember();
Type type;
if (member instanceof Field)
{
type = ((Field) member).getType();
}
else if (member instanceof ArrayLengthMember)
{
type = ArrayLengthMember.ARRAY_LENGTH_TYPE;
}
else if (member instanceof Method)
{
// TODO: add function types properly and remove this restriction
throw new ConceptualException("Cannot yet access a method as a field", fieldAccessExpression.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
fieldAccessExpression.setType(type);
return type;
}
else if (expression instanceof FloatingLiteralExpression)
{
String floatingString = ((FloatingLiteralExpression) expression).getLiteral().toString();
if (Float.parseFloat(floatingString) == Double.parseDouble(floatingString))
{
// the value fits in a float, so that is its initial type (which will automatically be casted to double if necessary)
Type type = new PrimitiveType(false, PrimitiveTypeType.FLOAT, null);
expression.setType(type);
return type;
}
Type type = new PrimitiveType(false, PrimitiveTypeType.DOUBLE, null);
expression.setType(type);
return type;
}
else if (expression instanceof FunctionCallExpression)
{
- // TODO: finish the type-checking for nullability
FunctionCallExpression functionCallExpression = (FunctionCallExpression) expression;
Expression[] arguments = functionCallExpression.getArguments();
Parameter[] parameters = null;
Type[] parameterTypes = null;
String name = null;
Type returnType;
if (functionCallExpression.getResolvedMethod() != null)
{
if (functionCallExpression.getResolvedBaseExpression() != null)
{
Type type = checkTypes(functionCallExpression.getResolvedBaseExpression(), compilationUnit);
if (type.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the method '" + functionCallExpression.getResolvedMethod().getName() + "' on something which is nullable. Consider using the '?.' operator.", functionCallExpression.getLexicalPhrase());
}
Set<Member> memberSet = type.getMembers(functionCallExpression.getResolvedMethod().getName());
if (!memberSet.contains(functionCallExpression.getResolvedMethod()))
{
throw new ConceptualException("The method '" + functionCallExpression.getResolvedMethod().getName() + "' does not exist for type '" + type + "'", functionCallExpression.getLexicalPhrase());
}
}
parameters = functionCallExpression.getResolvedMethod().getParameters();
returnType = functionCallExpression.getResolvedMethod().getReturnType();
name = functionCallExpression.getResolvedMethod().getName();
}
else if (functionCallExpression.getResolvedConstructor() != null)
{
parameters = functionCallExpression.getResolvedConstructor().getParameters();
returnType = new NamedType(false, functionCallExpression.getResolvedConstructor().getContainingDefinition());
name = functionCallExpression.getResolvedConstructor().getName();
}
else if (functionCallExpression.getResolvedBaseExpression() != null)
{
Expression baseExpression = functionCallExpression.getResolvedBaseExpression();
Type baseType = checkTypes(baseExpression, compilationUnit);
if (baseType.isNullable())
{
throw new ConceptualException("Cannot call a nullable function.", functionCallExpression.getLexicalPhrase());
}
if (!(baseType instanceof FunctionType))
{
throw new ConceptualException("Cannot call something which is not a method or a constructor", functionCallExpression.getLexicalPhrase());
}
parameterTypes = ((FunctionType) baseType).getParameterTypes();
returnType = ((FunctionType) baseType).getReturnType();
}
else
{
throw new IllegalArgumentException("Unresolved function call: " + functionCallExpression);
}
if (parameterTypes == null)
{
parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
parameterTypes[i] = parameters[i].getType();
}
}
if (arguments.length != parameterTypes.length)
{
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < parameterTypes.length; i++)
{
buffer.append(parameterTypes[i]);
if (i != parameterTypes.length - 1)
{
buffer.append(", ");
}
}
throw new ConceptualException("The function '" + (name == null ? "" : name) + "(" + buffer + ")' is not defined to take " + arguments.length + " arguments", functionCallExpression.getLexicalPhrase());
}
for (int i = 0; i < arguments.length; i++)
{
Type type = checkTypes(arguments[i], compilationUnit);
if (!parameterTypes[i].canAssign(type))
{
throw new ConceptualException("Cannot pass an argument of type '" + type + "' as a parameter of type '" + parameterTypes[i] + "'", arguments[i].getLexicalPhrase());
}
}
functionCallExpression.setType(returnType);
return returnType;
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
Type conditionType = checkTypes(inlineIf.getCondition(), compilationUnit);
if (!(conditionType instanceof PrimitiveType) || conditionType.isNullable() || ((PrimitiveType) conditionType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + conditionType + "'", inlineIf.getCondition().getLexicalPhrase());
}
Type thenType = checkTypes(inlineIf.getThenExpression(), compilationUnit);
Type elseType = checkTypes(inlineIf.getElseExpression(), compilationUnit);
if (thenType.canAssign(elseType))
{
inlineIf.setType(thenType);
return thenType;
}
if (elseType.canAssign(thenType))
{
inlineIf.setType(elseType);
return elseType;
}
throw new ConceptualException("The types of the then and else clauses of this inline if expression are incompatible, they are: " + thenType + " and " + elseType, inlineIf.getLexicalPhrase());
}
else if (expression instanceof IntegerLiteralExpression)
{
BigInteger value = ((IntegerLiteralExpression) expression).getLiteral().getValue();
PrimitiveTypeType primitiveTypeType;
if (value.signum() < 0)
{
// the number must be signed
// check that bitLength() < SIZE to find out which signed type to use
// use strictly less than because bitLength() excludes the sign bit
if (value.bitLength() < Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.BYTE;
}
else if (value.bitLength() < Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.SHORT;
}
else if (value.bitLength() < Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.INT;
}
else if (value.bitLength() < Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.LONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a long", expression.getLexicalPhrase());
}
}
else
{
// the number is assumed to be unsigned
// use a '<=' check against the size this time, because we don't need to store a sign bit
if (value.bitLength() <= Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UBYTE;
}
else if (value.bitLength() <= Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.USHORT;
}
else if (value.bitLength() <= Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UINT;
}
else if (value.bitLength() <= Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.ULONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a ulong", expression.getLexicalPhrase());
}
}
Type type = new PrimitiveType(false, primitiveTypeType, null);
expression.setType(type);
return type;
}
else if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
Type leftType = checkTypes(logicalExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(logicalExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow all floating types
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating())
{
// disallow short-circuit operators for any types but boolean
if (logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_AND || logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_OR)
{
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN)
{
logicalExpression.setType(leftType);
return leftType;
}
throw new ConceptualException("The short-circuit operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
// allow all (non-short-circuit) boolean/integer operations if the types match
if (leftPrimitiveType == rightPrimitiveType)
{
logicalExpression.setType(leftType);
return leftType;
}
// both types are now integers or booleans
// if one can be converted to the other (left -> right or right -> left), then do the conversion
if (leftType.canAssign(rightType))
{
logicalExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
logicalExpression.setType(rightType);
return rightType;
}
}
}
throw new ConceptualException("The operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
else if (expression instanceof MinusExpression)
{
Type type = checkTypes(((MinusExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
// allow the unary minus operator to automatically convert from unsigned to signed integer values
if (primitiveTypeType == PrimitiveTypeType.UBYTE)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.BYTE, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.USHORT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.SHORT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.UINT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.INT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.ULONG)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.LONG, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType != PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The unary operator '-' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
Type leftType = checkTypes(shiftExpression.getLeftExpression(), compilationUnit);
Type rightType = checkTypes(shiftExpression.getRightExpression(), compilationUnit);
if (leftType instanceof PrimitiveType && rightType instanceof PrimitiveType && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow floating point types and booleans
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating() &&
leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN &&
!rightPrimitiveType.isSigned())
{
// we know that both types are integers here, and the shift operator should always take the type of the left argument,
// so we will later convert the right type to the left type, whatever it is
shiftExpression.setType(leftType);
return leftType;
}
}
throw new ConceptualException("The operator '" + shiftExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", shiftExpression.getLexicalPhrase());
}
else if (expression instanceof ThisExpression)
{
// the type has already been resolved by the Resolver
return expression.getType();
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Expression[] subExpressions = tupleExpression.getSubExpressions();
Type[] subTypes = new Type[subExpressions.length];
for (int i = 0; i < subTypes.length; i++)
{
subTypes[i] = checkTypes(subExpressions[i], compilationUnit);
}
TupleType type = new TupleType(false, subTypes, null);
tupleExpression.setType(type);
return type;
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
Type type = checkTypes(indexExpression.getExpression(), compilationUnit);
if (!(type instanceof TupleType))
{
throw new ConceptualException("Cannot index into the non-tuple type: " + type, indexExpression.getLexicalPhrase());
}
if (type.isNullable())
{
throw new ConceptualException("Cannot index into a nullable tuple type: " + type, indexExpression.getLexicalPhrase());
}
TupleType tupleType = (TupleType) type;
IntegerLiteral indexLiteral = indexExpression.getIndexLiteral();
BigInteger value = indexLiteral.getValue();
Type[] subTypes = tupleType.getSubTypes();
// using 1 based indexing, do a bounds check and find the result type
if (value.compareTo(BigInteger.valueOf(1)) < 0 || value.compareTo(BigInteger.valueOf(subTypes.length)) > 0)
{
throw new ConceptualException("Index " + value + " does not exist in a tuple of type " + tupleType, indexExpression.getLexicalPhrase());
}
Type indexType = subTypes[value.intValue() - 1];
indexExpression.setType(indexType);
return indexType;
}
else if (expression instanceof VariableExpression)
{
Type type = ((VariableExpression) expression).getResolvedVariable().getType();
expression.setType(type);
return type;
}
throw new ConceptualException("Internal type checking error: Unknown expression type", expression.getLexicalPhrase());
}
}
| false | true | public static Type checkTypes(Expression expression, CompilationUnit compilationUnit) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
Type leftType = checkTypes(arithmeticExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(arithmeticExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
arithmeticExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
arithmeticExpression.setType(rightType);
return rightType;
}
// the type will now only be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
}
}
throw new ConceptualException("The operator '" + arithmeticExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", arithmeticExpression.getLexicalPhrase());
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
Type type = checkTypes(arrayAccessExpression.getArrayExpression(), compilationUnit);
if (!(type instanceof ArrayType) || type.isNullable())
{
throw new ConceptualException("Array accesses are not defined for type " + type, arrayAccessExpression.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayAccessExpression.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, dimensionType.getLexicalPhrase());
}
Type baseType = ((ArrayType) type).getBaseType();
arrayAccessExpression.setType(baseType);
return baseType;
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression e : creationExpression.getDimensionExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(type))
{
throw new ConceptualException("Cannot use an expression of type " + type + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, e.getLexicalPhrase());
}
}
}
Type baseType = creationExpression.getType().getBaseType();
if (creationExpression.getValueExpressions() == null)
{
if (!baseType.isNullable())
{
throw new ConceptualException("Cannot create an array of '" + baseType + "' without an initialiser.", creationExpression.getLexicalPhrase());
}
}
else
{
for (Expression e : creationExpression.getValueExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!baseType.canAssign(type))
{
throw new ConceptualException("Cannot add an expression of type " + type + " to an array of type " + baseType, e.getLexicalPhrase());
}
}
}
return creationExpression.getType();
}
else if (expression instanceof BitwiseNotExpression)
{
Type type = checkTypes(((BitwiseNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
if (!primitiveTypeType.isFloating())
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The operator '~' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BooleanLiteralExpression)
{
Type type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
expression.setType(type);
return type;
}
else if (expression instanceof BooleanNotExpression)
{
Type type = checkTypes(((BooleanNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable() && ((PrimitiveType) type).getPrimitiveTypeType() == PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
throw new ConceptualException("The operator '!' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BracketedExpression)
{
Type type = checkTypes(((BracketedExpression) expression).getExpression(), compilationUnit);
expression.setType(type);
return type;
}
else if (expression instanceof CastExpression)
{
Type exprType = checkTypes(((CastExpression) expression).getExpression(), compilationUnit);
Type castedType = expression.getType();
if (exprType.canAssign(castedType) || castedType.canAssign(exprType))
{
// if the assignment works in reverse (i.e. the casted type can be assigned to the expression) then it can be casted back
// (also allow it if the assignment works forwards, although really that should be a warning about an unnecessary cast)
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
if (exprType instanceof PrimitiveType && castedType instanceof PrimitiveType && !exprType.isNullable() && !castedType.isNullable())
{
// allow non-floating primitive types with the same bit count to be casted to each other
PrimitiveTypeType exprPrimitiveTypeType = ((PrimitiveType) exprType).getPrimitiveTypeType();
PrimitiveTypeType castedPrimitiveTypeType = ((PrimitiveType) castedType).getPrimitiveTypeType();
if (!exprPrimitiveTypeType.isFloating() && !castedPrimitiveTypeType.isFloating() &&
exprPrimitiveTypeType.getBitCount() == castedPrimitiveTypeType.getBitCount())
{
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
}
throw new ConceptualException("Cannot cast from '" + exprType + "' to '" + castedType + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
ComparisonOperator operator = comparisonExpression.getOperator();
Type leftType = checkTypes(comparisonExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(comparisonExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN &&
(comparisonExpression.getOperator() == ComparisonOperator.EQUAL || comparisonExpression.getOperator() == ComparisonOperator.NOT_EQUAL))
{
// comparing booleans is only valid when using '==' or '!='
comparisonExpression.setComparisonType((PrimitiveType) leftType);
PrimitiveType type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(type);
return type;
}
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
comparisonExpression.setComparisonType((PrimitiveType) leftType);
}
else if (rightType.canAssign(leftType))
{
comparisonExpression.setComparisonType((PrimitiveType) rightType);
}
else
{
// comparisonType will be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
// but since comparing numeric types should always be valid, we just set the comparisonType to null anyway
// and let the code generator handle it by converting to larger signed types first
comparisonExpression.setComparisonType(null);
}
// comparing any numeric types is always valid
Type resultType = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(resultType);
return resultType;
}
}
throw new ConceptualException("The '" + operator + "' operator is not defined for types '" + leftType + "' and '" + rightType + "'", comparisonExpression.getLexicalPhrase());
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
// no need to do the following type check here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
// Type type = checkTypes(fieldAccessExpression.getExpression(), compilationUnit);
if (fieldAccessExpression.getBaseExpression() != null)
{
Type baseExpressionType = fieldAccessExpression.getBaseExpression().getType();
if (baseExpressionType.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the field '" + fieldAccessExpression.getFieldName() + "' on something which is nullable. Consider using the '?.' operator.", fieldAccessExpression.getLexicalPhrase());
}
}
Member member = fieldAccessExpression.getResolvedMember();
Type type;
if (member instanceof Field)
{
type = ((Field) member).getType();
}
else if (member instanceof ArrayLengthMember)
{
type = ArrayLengthMember.ARRAY_LENGTH_TYPE;
}
else if (member instanceof Method)
{
// TODO: add function types properly and remove this restriction
throw new ConceptualException("Cannot yet access a method as a field", fieldAccessExpression.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
fieldAccessExpression.setType(type);
return type;
}
else if (expression instanceof FloatingLiteralExpression)
{
String floatingString = ((FloatingLiteralExpression) expression).getLiteral().toString();
if (Float.parseFloat(floatingString) == Double.parseDouble(floatingString))
{
// the value fits in a float, so that is its initial type (which will automatically be casted to double if necessary)
Type type = new PrimitiveType(false, PrimitiveTypeType.FLOAT, null);
expression.setType(type);
return type;
}
Type type = new PrimitiveType(false, PrimitiveTypeType.DOUBLE, null);
expression.setType(type);
return type;
}
else if (expression instanceof FunctionCallExpression)
{
// TODO: finish the type-checking for nullability
FunctionCallExpression functionCallExpression = (FunctionCallExpression) expression;
Expression[] arguments = functionCallExpression.getArguments();
Parameter[] parameters = null;
Type[] parameterTypes = null;
String name = null;
Type returnType;
if (functionCallExpression.getResolvedMethod() != null)
{
if (functionCallExpression.getResolvedBaseExpression() != null)
{
Type type = checkTypes(functionCallExpression.getResolvedBaseExpression(), compilationUnit);
if (type.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the method '" + functionCallExpression.getResolvedMethod().getName() + "' on something which is nullable. Consider using the '?.' operator.", functionCallExpression.getLexicalPhrase());
}
Set<Member> memberSet = type.getMembers(functionCallExpression.getResolvedMethod().getName());
if (!memberSet.contains(functionCallExpression.getResolvedMethod()))
{
throw new ConceptualException("The method '" + functionCallExpression.getResolvedMethod().getName() + "' does not exist for type '" + type + "'", functionCallExpression.getLexicalPhrase());
}
}
parameters = functionCallExpression.getResolvedMethod().getParameters();
returnType = functionCallExpression.getResolvedMethod().getReturnType();
name = functionCallExpression.getResolvedMethod().getName();
}
else if (functionCallExpression.getResolvedConstructor() != null)
{
parameters = functionCallExpression.getResolvedConstructor().getParameters();
returnType = new NamedType(false, functionCallExpression.getResolvedConstructor().getContainingDefinition());
name = functionCallExpression.getResolvedConstructor().getName();
}
else if (functionCallExpression.getResolvedBaseExpression() != null)
{
Expression baseExpression = functionCallExpression.getResolvedBaseExpression();
Type baseType = checkTypes(baseExpression, compilationUnit);
if (baseType.isNullable())
{
throw new ConceptualException("Cannot call a nullable function.", functionCallExpression.getLexicalPhrase());
}
if (!(baseType instanceof FunctionType))
{
throw new ConceptualException("Cannot call something which is not a method or a constructor", functionCallExpression.getLexicalPhrase());
}
parameterTypes = ((FunctionType) baseType).getParameterTypes();
returnType = ((FunctionType) baseType).getReturnType();
}
else
{
throw new IllegalArgumentException("Unresolved function call: " + functionCallExpression);
}
if (parameterTypes == null)
{
parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
parameterTypes[i] = parameters[i].getType();
}
}
if (arguments.length != parameterTypes.length)
{
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < parameterTypes.length; i++)
{
buffer.append(parameterTypes[i]);
if (i != parameterTypes.length - 1)
{
buffer.append(", ");
}
}
throw new ConceptualException("The function '" + (name == null ? "" : name) + "(" + buffer + ")' is not defined to take " + arguments.length + " arguments", functionCallExpression.getLexicalPhrase());
}
for (int i = 0; i < arguments.length; i++)
{
Type type = checkTypes(arguments[i], compilationUnit);
if (!parameterTypes[i].canAssign(type))
{
throw new ConceptualException("Cannot pass an argument of type '" + type + "' as a parameter of type '" + parameterTypes[i] + "'", arguments[i].getLexicalPhrase());
}
}
functionCallExpression.setType(returnType);
return returnType;
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
Type conditionType = checkTypes(inlineIf.getCondition(), compilationUnit);
if (!(conditionType instanceof PrimitiveType) || conditionType.isNullable() || ((PrimitiveType) conditionType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + conditionType + "'", inlineIf.getCondition().getLexicalPhrase());
}
Type thenType = checkTypes(inlineIf.getThenExpression(), compilationUnit);
Type elseType = checkTypes(inlineIf.getElseExpression(), compilationUnit);
if (thenType.canAssign(elseType))
{
inlineIf.setType(thenType);
return thenType;
}
if (elseType.canAssign(thenType))
{
inlineIf.setType(elseType);
return elseType;
}
throw new ConceptualException("The types of the then and else clauses of this inline if expression are incompatible, they are: " + thenType + " and " + elseType, inlineIf.getLexicalPhrase());
}
else if (expression instanceof IntegerLiteralExpression)
{
BigInteger value = ((IntegerLiteralExpression) expression).getLiteral().getValue();
PrimitiveTypeType primitiveTypeType;
if (value.signum() < 0)
{
// the number must be signed
// check that bitLength() < SIZE to find out which signed type to use
// use strictly less than because bitLength() excludes the sign bit
if (value.bitLength() < Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.BYTE;
}
else if (value.bitLength() < Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.SHORT;
}
else if (value.bitLength() < Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.INT;
}
else if (value.bitLength() < Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.LONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a long", expression.getLexicalPhrase());
}
}
else
{
// the number is assumed to be unsigned
// use a '<=' check against the size this time, because we don't need to store a sign bit
if (value.bitLength() <= Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UBYTE;
}
else if (value.bitLength() <= Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.USHORT;
}
else if (value.bitLength() <= Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UINT;
}
else if (value.bitLength() <= Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.ULONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a ulong", expression.getLexicalPhrase());
}
}
Type type = new PrimitiveType(false, primitiveTypeType, null);
expression.setType(type);
return type;
}
else if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
Type leftType = checkTypes(logicalExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(logicalExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow all floating types
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating())
{
// disallow short-circuit operators for any types but boolean
if (logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_AND || logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_OR)
{
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN)
{
logicalExpression.setType(leftType);
return leftType;
}
throw new ConceptualException("The short-circuit operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
// allow all (non-short-circuit) boolean/integer operations if the types match
if (leftPrimitiveType == rightPrimitiveType)
{
logicalExpression.setType(leftType);
return leftType;
}
// both types are now integers or booleans
// if one can be converted to the other (left -> right or right -> left), then do the conversion
if (leftType.canAssign(rightType))
{
logicalExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
logicalExpression.setType(rightType);
return rightType;
}
}
}
throw new ConceptualException("The operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
else if (expression instanceof MinusExpression)
{
Type type = checkTypes(((MinusExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
// allow the unary minus operator to automatically convert from unsigned to signed integer values
if (primitiveTypeType == PrimitiveTypeType.UBYTE)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.BYTE, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.USHORT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.SHORT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.UINT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.INT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.ULONG)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.LONG, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType != PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The unary operator '-' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
Type leftType = checkTypes(shiftExpression.getLeftExpression(), compilationUnit);
Type rightType = checkTypes(shiftExpression.getRightExpression(), compilationUnit);
if (leftType instanceof PrimitiveType && rightType instanceof PrimitiveType && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow floating point types and booleans
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating() &&
leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN &&
!rightPrimitiveType.isSigned())
{
// we know that both types are integers here, and the shift operator should always take the type of the left argument,
// so we will later convert the right type to the left type, whatever it is
shiftExpression.setType(leftType);
return leftType;
}
}
throw new ConceptualException("The operator '" + shiftExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", shiftExpression.getLexicalPhrase());
}
else if (expression instanceof ThisExpression)
{
// the type has already been resolved by the Resolver
return expression.getType();
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Expression[] subExpressions = tupleExpression.getSubExpressions();
Type[] subTypes = new Type[subExpressions.length];
for (int i = 0; i < subTypes.length; i++)
{
subTypes[i] = checkTypes(subExpressions[i], compilationUnit);
}
TupleType type = new TupleType(false, subTypes, null);
tupleExpression.setType(type);
return type;
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
Type type = checkTypes(indexExpression.getExpression(), compilationUnit);
if (!(type instanceof TupleType))
{
throw new ConceptualException("Cannot index into the non-tuple type: " + type, indexExpression.getLexicalPhrase());
}
if (type.isNullable())
{
throw new ConceptualException("Cannot index into a nullable tuple type: " + type, indexExpression.getLexicalPhrase());
}
TupleType tupleType = (TupleType) type;
IntegerLiteral indexLiteral = indexExpression.getIndexLiteral();
BigInteger value = indexLiteral.getValue();
Type[] subTypes = tupleType.getSubTypes();
// using 1 based indexing, do a bounds check and find the result type
if (value.compareTo(BigInteger.valueOf(1)) < 0 || value.compareTo(BigInteger.valueOf(subTypes.length)) > 0)
{
throw new ConceptualException("Index " + value + " does not exist in a tuple of type " + tupleType, indexExpression.getLexicalPhrase());
}
Type indexType = subTypes[value.intValue() - 1];
indexExpression.setType(indexType);
return indexType;
}
else if (expression instanceof VariableExpression)
{
Type type = ((VariableExpression) expression).getResolvedVariable().getType();
expression.setType(type);
return type;
}
throw new ConceptualException("Internal type checking error: Unknown expression type", expression.getLexicalPhrase());
}
| public static Type checkTypes(Expression expression, CompilationUnit compilationUnit) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
Type leftType = checkTypes(arithmeticExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(arithmeticExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
arithmeticExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
arithmeticExpression.setType(rightType);
return rightType;
}
// the type will now only be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
}
}
throw new ConceptualException("The operator '" + arithmeticExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", arithmeticExpression.getLexicalPhrase());
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
Type type = checkTypes(arrayAccessExpression.getArrayExpression(), compilationUnit);
if (!(type instanceof ArrayType) || type.isNullable())
{
throw new ConceptualException("Array accesses are not defined for type " + type, arrayAccessExpression.getLexicalPhrase());
}
Type dimensionType = checkTypes(arrayAccessExpression.getDimensionExpression(), compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(dimensionType))
{
throw new ConceptualException("Cannot use an expression of type " + dimensionType + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, dimensionType.getLexicalPhrase());
}
Type baseType = ((ArrayType) type).getBaseType();
arrayAccessExpression.setType(baseType);
return baseType;
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression e : creationExpression.getDimensionExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!ArrayLengthMember.ARRAY_LENGTH_TYPE.canAssign(type))
{
throw new ConceptualException("Cannot use an expression of type " + type + " as an array dimension, or convert it to type " + ArrayLengthMember.ARRAY_LENGTH_TYPE, e.getLexicalPhrase());
}
}
}
Type baseType = creationExpression.getType().getBaseType();
if (creationExpression.getValueExpressions() == null)
{
if (!baseType.isNullable())
{
throw new ConceptualException("Cannot create an array of '" + baseType + "' without an initialiser.", creationExpression.getLexicalPhrase());
}
}
else
{
for (Expression e : creationExpression.getValueExpressions())
{
Type type = checkTypes(e, compilationUnit);
if (!baseType.canAssign(type))
{
throw new ConceptualException("Cannot add an expression of type " + type + " to an array of type " + baseType, e.getLexicalPhrase());
}
}
}
return creationExpression.getType();
}
else if (expression instanceof BitwiseNotExpression)
{
Type type = checkTypes(((BitwiseNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
if (!primitiveTypeType.isFloating())
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The operator '~' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BooleanLiteralExpression)
{
Type type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
expression.setType(type);
return type;
}
else if (expression instanceof BooleanNotExpression)
{
Type type = checkTypes(((BooleanNotExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable() && ((PrimitiveType) type).getPrimitiveTypeType() == PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
throw new ConceptualException("The operator '!' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof BracketedExpression)
{
Type type = checkTypes(((BracketedExpression) expression).getExpression(), compilationUnit);
expression.setType(type);
return type;
}
else if (expression instanceof CastExpression)
{
Type exprType = checkTypes(((CastExpression) expression).getExpression(), compilationUnit);
Type castedType = expression.getType();
if (exprType.canAssign(castedType) || castedType.canAssign(exprType))
{
// if the assignment works in reverse (i.e. the casted type can be assigned to the expression) then it can be casted back
// (also allow it if the assignment works forwards, although really that should be a warning about an unnecessary cast)
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
if (exprType instanceof PrimitiveType && castedType instanceof PrimitiveType && !exprType.isNullable() && !castedType.isNullable())
{
// allow non-floating primitive types with the same bit count to be casted to each other
PrimitiveTypeType exprPrimitiveTypeType = ((PrimitiveType) exprType).getPrimitiveTypeType();
PrimitiveTypeType castedPrimitiveTypeType = ((PrimitiveType) castedType).getPrimitiveTypeType();
if (!exprPrimitiveTypeType.isFloating() && !castedPrimitiveTypeType.isFloating() &&
exprPrimitiveTypeType.getBitCount() == castedPrimitiveTypeType.getBitCount())
{
// return the type of the cast expression (it has already been set during parsing)
return expression.getType();
}
}
throw new ConceptualException("Cannot cast from '" + exprType + "' to '" + castedType + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
ComparisonOperator operator = comparisonExpression.getOperator();
Type leftType = checkTypes(comparisonExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(comparisonExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN &&
(comparisonExpression.getOperator() == ComparisonOperator.EQUAL || comparisonExpression.getOperator() == ComparisonOperator.NOT_EQUAL))
{
// comparing booleans is only valid when using '==' or '!='
comparisonExpression.setComparisonType((PrimitiveType) leftType);
PrimitiveType type = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(type);
return type;
}
if (leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN)
{
if (leftType.canAssign(rightType))
{
comparisonExpression.setComparisonType((PrimitiveType) leftType);
}
else if (rightType.canAssign(leftType))
{
comparisonExpression.setComparisonType((PrimitiveType) rightType);
}
else
{
// comparisonType will be null if no conversion can be done, e.g. if leftType is UINT and rightType is INT
// but since comparing numeric types should always be valid, we just set the comparisonType to null anyway
// and let the code generator handle it by converting to larger signed types first
comparisonExpression.setComparisonType(null);
}
// comparing any numeric types is always valid
Type resultType = new PrimitiveType(false, PrimitiveTypeType.BOOLEAN, null);
comparisonExpression.setType(resultType);
return resultType;
}
}
throw new ConceptualException("The '" + operator + "' operator is not defined for types '" + leftType + "' and '" + rightType + "'", comparisonExpression.getLexicalPhrase());
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
// no need to do the following type check here, it has already been done during name resolution, in order to resolve the member (as long as this field access has a base expression, and not a base type)
// Type type = checkTypes(fieldAccessExpression.getBaseExpression(), compilationUnit);
if (fieldAccessExpression.getBaseExpression() != null)
{
Type baseExpressionType = fieldAccessExpression.getBaseExpression().getType();
if (baseExpressionType.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the field '" + fieldAccessExpression.getFieldName() + "' on something which is nullable. Consider using the '?.' operator.", fieldAccessExpression.getLexicalPhrase());
}
}
Member member = fieldAccessExpression.getResolvedMember();
Type type;
if (member instanceof Field)
{
type = ((Field) member).getType();
}
else if (member instanceof ArrayLengthMember)
{
type = ArrayLengthMember.ARRAY_LENGTH_TYPE;
}
else if (member instanceof Method)
{
// TODO: add function types properly and remove this restriction
throw new ConceptualException("Cannot yet access a method as a field", fieldAccessExpression.getLexicalPhrase());
}
else
{
throw new IllegalStateException("Unknown member type in a FieldAccessExpression: " + member);
}
fieldAccessExpression.setType(type);
return type;
}
else if (expression instanceof FloatingLiteralExpression)
{
String floatingString = ((FloatingLiteralExpression) expression).getLiteral().toString();
if (Float.parseFloat(floatingString) == Double.parseDouble(floatingString))
{
// the value fits in a float, so that is its initial type (which will automatically be casted to double if necessary)
Type type = new PrimitiveType(false, PrimitiveTypeType.FLOAT, null);
expression.setType(type);
return type;
}
Type type = new PrimitiveType(false, PrimitiveTypeType.DOUBLE, null);
expression.setType(type);
return type;
}
else if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression functionCallExpression = (FunctionCallExpression) expression;
Expression[] arguments = functionCallExpression.getArguments();
Parameter[] parameters = null;
Type[] parameterTypes = null;
String name = null;
Type returnType;
if (functionCallExpression.getResolvedMethod() != null)
{
if (functionCallExpression.getResolvedBaseExpression() != null)
{
Type type = checkTypes(functionCallExpression.getResolvedBaseExpression(), compilationUnit);
if (type.isNullable())
{
// TODO: add the '?.' operator, which this exception refers to
throw new ConceptualException("Cannot access the method '" + functionCallExpression.getResolvedMethod().getName() + "' on something which is nullable. Consider using the '?.' operator.", functionCallExpression.getLexicalPhrase());
}
Set<Member> memberSet = type.getMembers(functionCallExpression.getResolvedMethod().getName());
if (!memberSet.contains(functionCallExpression.getResolvedMethod()))
{
throw new ConceptualException("The method '" + functionCallExpression.getResolvedMethod().getName() + "' does not exist for type '" + type + "'", functionCallExpression.getLexicalPhrase());
}
}
parameters = functionCallExpression.getResolvedMethod().getParameters();
returnType = functionCallExpression.getResolvedMethod().getReturnType();
name = functionCallExpression.getResolvedMethod().getName();
}
else if (functionCallExpression.getResolvedConstructor() != null)
{
parameters = functionCallExpression.getResolvedConstructor().getParameters();
returnType = new NamedType(false, functionCallExpression.getResolvedConstructor().getContainingDefinition());
name = functionCallExpression.getResolvedConstructor().getName();
}
else if (functionCallExpression.getResolvedBaseExpression() != null)
{
Expression baseExpression = functionCallExpression.getResolvedBaseExpression();
Type baseType = checkTypes(baseExpression, compilationUnit);
if (baseType.isNullable())
{
throw new ConceptualException("Cannot call a nullable function.", functionCallExpression.getLexicalPhrase());
}
if (!(baseType instanceof FunctionType))
{
throw new ConceptualException("Cannot call something which is not a method or a constructor", functionCallExpression.getLexicalPhrase());
}
parameterTypes = ((FunctionType) baseType).getParameterTypes();
returnType = ((FunctionType) baseType).getReturnType();
}
else
{
throw new IllegalArgumentException("Unresolved function call: " + functionCallExpression);
}
if (parameterTypes == null)
{
parameterTypes = new Type[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
parameterTypes[i] = parameters[i].getType();
}
}
if (arguments.length != parameterTypes.length)
{
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < parameterTypes.length; i++)
{
buffer.append(parameterTypes[i]);
if (i != parameterTypes.length - 1)
{
buffer.append(", ");
}
}
throw new ConceptualException("The function '" + (name == null ? "" : name) + "(" + buffer + ")' is not defined to take " + arguments.length + " arguments", functionCallExpression.getLexicalPhrase());
}
for (int i = 0; i < arguments.length; i++)
{
Type type = checkTypes(arguments[i], compilationUnit);
if (!parameterTypes[i].canAssign(type))
{
throw new ConceptualException("Cannot pass an argument of type '" + type + "' as a parameter of type '" + parameterTypes[i] + "'", arguments[i].getLexicalPhrase());
}
}
functionCallExpression.setType(returnType);
return returnType;
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
Type conditionType = checkTypes(inlineIf.getCondition(), compilationUnit);
if (!(conditionType instanceof PrimitiveType) || conditionType.isNullable() || ((PrimitiveType) conditionType).getPrimitiveTypeType() != PrimitiveTypeType.BOOLEAN)
{
throw new ConceptualException("A conditional must be of type '" + PrimitiveTypeType.BOOLEAN.name + "', not '" + conditionType + "'", inlineIf.getCondition().getLexicalPhrase());
}
Type thenType = checkTypes(inlineIf.getThenExpression(), compilationUnit);
Type elseType = checkTypes(inlineIf.getElseExpression(), compilationUnit);
if (thenType.canAssign(elseType))
{
inlineIf.setType(thenType);
return thenType;
}
if (elseType.canAssign(thenType))
{
inlineIf.setType(elseType);
return elseType;
}
throw new ConceptualException("The types of the then and else clauses of this inline if expression are incompatible, they are: " + thenType + " and " + elseType, inlineIf.getLexicalPhrase());
}
else if (expression instanceof IntegerLiteralExpression)
{
BigInteger value = ((IntegerLiteralExpression) expression).getLiteral().getValue();
PrimitiveTypeType primitiveTypeType;
if (value.signum() < 0)
{
// the number must be signed
// check that bitLength() < SIZE to find out which signed type to use
// use strictly less than because bitLength() excludes the sign bit
if (value.bitLength() < Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.BYTE;
}
else if (value.bitLength() < Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.SHORT;
}
else if (value.bitLength() < Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.INT;
}
else if (value.bitLength() < Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.LONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a long", expression.getLexicalPhrase());
}
}
else
{
// the number is assumed to be unsigned
// use a '<=' check against the size this time, because we don't need to store a sign bit
if (value.bitLength() <= Byte.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UBYTE;
}
else if (value.bitLength() <= Short.SIZE)
{
primitiveTypeType = PrimitiveTypeType.USHORT;
}
else if (value.bitLength() <= Integer.SIZE)
{
primitiveTypeType = PrimitiveTypeType.UINT;
}
else if (value.bitLength() <= Long.SIZE)
{
primitiveTypeType = PrimitiveTypeType.ULONG;
}
else
{
throw new ConceptualException("Integer literal will not fit into a ulong", expression.getLexicalPhrase());
}
}
Type type = new PrimitiveType(false, primitiveTypeType, null);
expression.setType(type);
return type;
}
else if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
Type leftType = checkTypes(logicalExpression.getLeftSubExpression(), compilationUnit);
Type rightType = checkTypes(logicalExpression.getRightSubExpression(), compilationUnit);
if ((leftType instanceof PrimitiveType) && (rightType instanceof PrimitiveType) && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow all floating types
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating())
{
// disallow short-circuit operators for any types but boolean
if (logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_AND || logicalExpression.getOperator() == LogicalOperator.SHORT_CIRCUIT_OR)
{
if (leftPrimitiveType == PrimitiveTypeType.BOOLEAN && rightPrimitiveType == PrimitiveTypeType.BOOLEAN)
{
logicalExpression.setType(leftType);
return leftType;
}
throw new ConceptualException("The short-circuit operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
// allow all (non-short-circuit) boolean/integer operations if the types match
if (leftPrimitiveType == rightPrimitiveType)
{
logicalExpression.setType(leftType);
return leftType;
}
// both types are now integers or booleans
// if one can be converted to the other (left -> right or right -> left), then do the conversion
if (leftType.canAssign(rightType))
{
logicalExpression.setType(leftType);
return leftType;
}
if (rightType.canAssign(leftType))
{
logicalExpression.setType(rightType);
return rightType;
}
}
}
throw new ConceptualException("The operator '" + logicalExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", logicalExpression.getLexicalPhrase());
}
else if (expression instanceof MinusExpression)
{
Type type = checkTypes(((MinusExpression) expression).getExpression(), compilationUnit);
if (type instanceof PrimitiveType && !type.isNullable())
{
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
// allow the unary minus operator to automatically convert from unsigned to signed integer values
if (primitiveTypeType == PrimitiveTypeType.UBYTE)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.BYTE, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.USHORT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.SHORT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.UINT)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.INT, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType == PrimitiveTypeType.ULONG)
{
PrimitiveType signedType = new PrimitiveType(false, PrimitiveTypeType.LONG, null);
expression.setType(signedType);
return signedType;
}
if (primitiveTypeType != PrimitiveTypeType.BOOLEAN)
{
expression.setType(type);
return type;
}
}
throw new ConceptualException("The unary operator '-' is not defined for type '" + type + "'", expression.getLexicalPhrase());
}
else if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
Type leftType = checkTypes(shiftExpression.getLeftExpression(), compilationUnit);
Type rightType = checkTypes(shiftExpression.getRightExpression(), compilationUnit);
if (leftType instanceof PrimitiveType && rightType instanceof PrimitiveType && !leftType.isNullable() && !rightType.isNullable())
{
PrimitiveTypeType leftPrimitiveType = ((PrimitiveType) leftType).getPrimitiveTypeType();
PrimitiveTypeType rightPrimitiveType = ((PrimitiveType) rightType).getPrimitiveTypeType();
// disallow floating point types and booleans
if (!leftPrimitiveType.isFloating() && !rightPrimitiveType.isFloating() &&
leftPrimitiveType != PrimitiveTypeType.BOOLEAN && rightPrimitiveType != PrimitiveTypeType.BOOLEAN &&
!rightPrimitiveType.isSigned())
{
// we know that both types are integers here, and the shift operator should always take the type of the left argument,
// so we will later convert the right type to the left type, whatever it is
shiftExpression.setType(leftType);
return leftType;
}
}
throw new ConceptualException("The operator '" + shiftExpression.getOperator() + "' is not defined for types '" + leftType + "' and '" + rightType + "'", shiftExpression.getLexicalPhrase());
}
else if (expression instanceof ThisExpression)
{
// the type has already been resolved by the Resolver
return expression.getType();
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Expression[] subExpressions = tupleExpression.getSubExpressions();
Type[] subTypes = new Type[subExpressions.length];
for (int i = 0; i < subTypes.length; i++)
{
subTypes[i] = checkTypes(subExpressions[i], compilationUnit);
}
TupleType type = new TupleType(false, subTypes, null);
tupleExpression.setType(type);
return type;
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
Type type = checkTypes(indexExpression.getExpression(), compilationUnit);
if (!(type instanceof TupleType))
{
throw new ConceptualException("Cannot index into the non-tuple type: " + type, indexExpression.getLexicalPhrase());
}
if (type.isNullable())
{
throw new ConceptualException("Cannot index into a nullable tuple type: " + type, indexExpression.getLexicalPhrase());
}
TupleType tupleType = (TupleType) type;
IntegerLiteral indexLiteral = indexExpression.getIndexLiteral();
BigInteger value = indexLiteral.getValue();
Type[] subTypes = tupleType.getSubTypes();
// using 1 based indexing, do a bounds check and find the result type
if (value.compareTo(BigInteger.valueOf(1)) < 0 || value.compareTo(BigInteger.valueOf(subTypes.length)) > 0)
{
throw new ConceptualException("Index " + value + " does not exist in a tuple of type " + tupleType, indexExpression.getLexicalPhrase());
}
Type indexType = subTypes[value.intValue() - 1];
indexExpression.setType(indexType);
return indexType;
}
else if (expression instanceof VariableExpression)
{
Type type = ((VariableExpression) expression).getResolvedVariable().getType();
expression.setType(type);
return type;
}
throw new ConceptualException("Internal type checking error: Unknown expression type", expression.getLexicalPhrase());
}
|
diff --git a/src/main/java/org/noisyteam/samples/spring/validation/validator/PersonValidator.java b/src/main/java/org/noisyteam/samples/spring/validation/validator/PersonValidator.java
index bcfd21e..98c85e0 100644
--- a/src/main/java/org/noisyteam/samples/spring/validation/validator/PersonValidator.java
+++ b/src/main/java/org/noisyteam/samples/spring/validation/validator/PersonValidator.java
@@ -1,26 +1,28 @@
package org.noisyteam.samples.spring.validation.validator;
import org.noisyteam.samples.spring.validation.model.Person;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Class for validation of binded Person objects.
*
* @author Roman Romanchuk ([email protected])
*/
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
- ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
- ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty");
+ ValidationUtils
+ .rejectIfEmpty(e, "name", "name.empty", "Can't be empty");
+ ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty",
+ "Can't be empty");
}
}
| true | true | public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty");
}
| public void validate(Object obj, Errors e) {
ValidationUtils
.rejectIfEmpty(e, "name", "name.empty", "Can't be empty");
ValidationUtils.rejectIfEmpty(e, "nickname", "nickname.empty",
"Can't be empty");
}
|
diff --git a/freeplane/src/org/freeplane/features/format/DateFormatParser.java b/freeplane/src/org/freeplane/features/format/DateFormatParser.java
index c77fa2ad6..927fc2c6e 100644
--- a/freeplane/src/org/freeplane/features/format/DateFormatParser.java
+++ b/freeplane/src/org/freeplane/features/format/DateFormatParser.java
@@ -1,71 +1,71 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2011 Volker Boerchers
*
* This file author is Volker Boerchers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormatParser extends Parser {
private final SimpleDateFormat parser;
private final String missingFields;
private boolean forbidLeadingSpaces;
public DateFormatParser(final String format) {
super(Parser.STYLE_DATE, getTypeDependingOnFormat(format), format);
forbidLeadingSpaces = (format.charAt(0) != ' ');
parser = new SimpleDateFormat(format.replaceFirst("^\\s", ""));
parser.setLenient(false);
missingFields = (format.contains("y") ? "" : "y") //
+ (format.contains("M") ? "" : "M") //
+ (format.contains("d") ? "" : "d");
}
private static String getTypeDependingOnFormat(final String format) {
// if it contains minute format -> datetime
return format.contains("m") ? IFormattedObject.TYPE_DATETIME : IFormattedObject.TYPE_DATE;
}
@Override
Object parse(String string) {
if (string == null || (forbidLeadingSpaces && string.charAt(0) == ' '))
return null;
final ParsePosition parsePosition = new ParsePosition(0);
Date date = parser.parse(string, parsePosition);
if (parsePosition.getIndex() != string.length())
return null;
if (missingFields.length() != 0) {
final Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.setTime(date);
if (missingFields.contains("y"))
calendar.set(Calendar.YEAR, year);
if (missingFields.contains("M"))
calendar.set(Calendar.MONTH, month);
- if (missingFields.contains("y"))
+ if (missingFields.contains("d"))
calendar.set(Calendar.DAY_OF_MONTH, day);
date = calendar.getTime();
}
return FormattedDate.createDefaultFormattedDate(date.getTime(), getType());
}
}
| true | true | Object parse(String string) {
if (string == null || (forbidLeadingSpaces && string.charAt(0) == ' '))
return null;
final ParsePosition parsePosition = new ParsePosition(0);
Date date = parser.parse(string, parsePosition);
if (parsePosition.getIndex() != string.length())
return null;
if (missingFields.length() != 0) {
final Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.setTime(date);
if (missingFields.contains("y"))
calendar.set(Calendar.YEAR, year);
if (missingFields.contains("M"))
calendar.set(Calendar.MONTH, month);
if (missingFields.contains("y"))
calendar.set(Calendar.DAY_OF_MONTH, day);
date = calendar.getTime();
}
return FormattedDate.createDefaultFormattedDate(date.getTime(), getType());
}
| Object parse(String string) {
if (string == null || (forbidLeadingSpaces && string.charAt(0) == ' '))
return null;
final ParsePosition parsePosition = new ParsePosition(0);
Date date = parser.parse(string, parsePosition);
if (parsePosition.getIndex() != string.length())
return null;
if (missingFields.length() != 0) {
final Calendar calendar = Calendar.getInstance();
final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.setTime(date);
if (missingFields.contains("y"))
calendar.set(Calendar.YEAR, year);
if (missingFields.contains("M"))
calendar.set(Calendar.MONTH, month);
if (missingFields.contains("d"))
calendar.set(Calendar.DAY_OF_MONTH, day);
date = calendar.getTime();
}
return FormattedDate.createDefaultFormattedDate(date.getTime(), getType());
}
|
diff --git a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/ingestion/IngestionAction.java b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/ingestion/IngestionAction.java
index d80987e..2e13d11 100644
--- a/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/ingestion/IngestionAction.java
+++ b/src/gb-actions-unredd/script/src/main/java/it/geosolutions/geobatch/unredd/script/ingestion/IngestionAction.java
@@ -1,719 +1,719 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* https://github.com/nfms4redd/nfms-geobatch
* Copyright (C) 2007-2012 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* 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 it.geosolutions.geobatch.unredd.script.ingestion;
//import it.geosolutions.geobatch.unredd.script.util.rasterize.Rasterize;
import it.geosolutions.filesystemmonitor.monitor.FileSystemEvent;
import it.geosolutions.filesystemmonitor.monitor.FileSystemEventType;
import it.geosolutions.geobatch.annotations.Action;
import it.geosolutions.geobatch.flow.event.action.ActionException;
import it.geosolutions.geobatch.flow.event.action.BaseAction;
import it.geosolutions.geobatch.unredd.script.exception.FlowException;
import it.geosolutions.geobatch.unredd.script.exception.PostGisException;
import it.geosolutions.geobatch.unredd.script.model.Request;
import it.geosolutions.geobatch.unredd.script.util.FlowUtil;
import it.geosolutions.geobatch.unredd.script.util.GeoStoreUtil;
import it.geosolutions.geobatch.unredd.script.util.GeoTiff;
import it.geosolutions.geobatch.unredd.script.util.Mosaic;
import it.geosolutions.geobatch.unredd.script.util.PostGISUtils;
import it.geosolutions.geobatch.unredd.script.util.RequestJDOMReader;
import it.geosolutions.geobatch.unredd.script.util.rasterize.GDALRasterize;
import it.geosolutions.geostore.core.model.Resource;
import it.geosolutions.unredd.geostore.model.UNREDDFormat;
import it.geosolutions.unredd.geostore.model.UNREDDLayer;
import it.geosolutions.unredd.geostore.model.UNREDDLayer.Attributes;
import it.geosolutions.unredd.geostore.model.UNREDDLayerUpdate;
import it.geosolutions.unredd.geostore.utils.NameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.geotools.gce.geotiff.GeoTiffReader;
import org.opengis.coverage.grid.GridEnvelope;
import org.opengis.geometry.Envelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This single Action contains the complete Ingestion flow.
*
* @author Luca Paolino - [email protected]
*/
@Action(configurationClass=IngestionConfiguration.class)
public class IngestionAction extends BaseAction<FileSystemEvent> {
private final static Logger LOGGER = LoggerFactory.getLogger(IngestionAction.class);
private final IngestionConfiguration cfg;
private static final String INFO_XML = "info.xml";
private static final String DEFAULT_MOSAIC_STYLE = "raster";
private static final String DATA_DIR_NAME="data";
public IngestionAction(IngestionConfiguration configuration)
throws ActionException {
super(configuration);
this.cfg = configuration;
}
/**
* Main loop on input files.
* Single file processing is called on execute(File inputZipFile)
*/
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events)
throws ActionException {
final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();
LOGGER.warn("Ingestion flow running");
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Performing basic checks");
}
// control if directories and PostGISUtils exist
basicChecks();
while (!events.isEmpty()) {
final FileSystemEvent ev = events.remove();
try {
if (ev != null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Processing incoming event: " + ev.getSource());
}
File inputZipFile = ev.getSource(); // this is the input zip file
File out = execute(inputZipFile);
ret.add(new FileSystemEvent(out, FileSystemEventType.FILE_ADDED));
} else {
LOGGER.error("NULL event: skipping...");
continue;
}
} catch (ActionException ex) { // ActionEx have already been processed
LOGGER.error(ex.getMessage(), ex);
throw ex;
} catch (Exception ex) {
final String message = "GeostoreAction.execute(): Unable to produce the output: "
+ ex.getLocalizedMessage();
LOGGER.error(message, ex);
throw new ActionException(this, message);
}
}
return ret;
}
/**
* Performs some basic checks on configuration values.
*
* @throws ActionException
*/
public void basicChecks() throws ActionException {
if ( cfg.getOriginalDataTargetDir() == null || ! cfg.getOriginalDataTargetDir().canWrite() || ! cfg.getOriginalDataTargetDir().isDirectory()){
LOGGER.warn("OriginalDataTargetDir is not setted or has been wrong specified or GeoBatch doesn't have write permissions");
}
if(cfg.getRetilerConfiguration() == null){
throw new ActionException(this, "RetilerConfiguration not set");
}
if(cfg.getGeoStoreConfig() == null){
throw new ActionException(this, "GeoStoreConfiguration not set");
}
if(cfg.getPostGisConfig() == null){
throw new ActionException(this, "PostGisConfiguration not set");
}
if(cfg.getGeoServerConfig() == null){
LOGGER.warn("GeoServer config is null. GeoServer data will not be refreshed");
}
}
protected File execute(File inputZipFile) throws ActionException, IOException {
this.listenerForwarder.started();
/******************
* Extract information from the zip file
*
****************/
this.listenerForwarder.progressing(5, "Unzipping input file ");
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Extracting files from " + inputZipFile);
}
File unzipDir = new File(getTempDir(), "unzip");
unzipDir.mkdir();
unzipInputFile(inputZipFile, unzipDir); // throws ActionException
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Extraction successfully completed");
}
this.listenerForwarder.progressing(10, "File unzipped");
return executeUnzipped(unzipDir);
}
protected File executeUnzipped(File unzipDir) throws ActionException, IOException {
/*************
*
* read the content of the XML file
*
***********/
this.listenerForwarder.progressing(10, "Parsing " + INFO_XML);
File infoXmlFile = new File(unzipDir, INFO_XML);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Reading XML parameters from " + infoXmlFile);
}
Request request = null;
try {
request = RequestJDOMReader.parseFile(infoXmlFile);
} catch (Exception e) {
throw new ActionException(this, "Error reading info.xml file, Are you sure to have built the input zip pkg in the right way? Note that all the content must be placed in the zip root folder, no any other subfolder are allowed..." , e);
}
if(request.getFormat() == null) {
throw new ActionException(this, "the format cannot be null.");
}
final String layername = request.getLayername();
if (layername==null)
throw new ActionException(this, "the layername cannot be null.");
final String year = request.getYear();
if (year==null)
throw new ActionException(this, "the year cannot be null.");
if( ! year.matches("\\d{4}")) {
throw new ActionException(this, "Bad format for year parameter ("+year+")");
}
final String month = request.getMonth();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+month+")");
final String day = request.getDay();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+day+")");
final String srcFilename = request.buildFileName();
// build the name of the snapshot
final String layerUpdateName = NameUtils.buildLayerUpdateName(layername, year, month, day);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Info: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
}
this.listenerForwarder.progressing(12, "Info from xml file: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("XML parameter settings : [layer name = " + layername + "], [year = " + year + "], [month = " + month + "], [day = " + day + "], [ file name = " + srcFilename + "]");
LOGGER.debug("XML parameter settings : [layer update name = " + layerUpdateName + "]");
}
File unzippedDataDir = new File(unzipDir, DATA_DIR_NAME);
File dataFile = new File(unzippedDataDir, srcFilename);
if( ! dataFile.isFile()) {
throw new ActionException(this, "Could not read main data file " + dataFile);
}
/*****************/
GeoStoreUtil geostore = new GeoStoreUtil(cfg.getGeoStoreConfig(), this.getTempDir());
/******************
* Load Layer data
******************/
this.listenerForwarder.progressing(15, "Searching layer in GeoStore");
final Resource layerRes;
try {
layerRes = geostore.searchLayer(layername);
} catch(Exception e) {
throw new ActionException(this, "Error loading Layer "+layername, e);
}
if(layerRes == null)
throw new ActionException(this, "Layer not found: "+layername);
UNREDDLayer layer = new UNREDDLayer(layerRes);
LOGGER.info("Layer resource found ");
if( ! layer.getAttribute(Attributes.LAYERTYPE).equalsIgnoreCase(request.getFormat().getName()))
throw new ActionException(this, "Bad Layer format "
+ "(declared:"+ request.getFormat().getName()
+ ", expected:"+layer.getAttribute(Attributes.LAYERTYPE) );
// this attribute is read for moving the raster file to the destination directory, not for rasterization
String mosaicDirPath = layer.getAttribute(UNREDDLayer.Attributes.MOSAICPATH);
if( mosaicDirPath == null) {
- throw new ActionException(this, "Null mosaic directory for layer:"+layername);
+ throw new ActionException(this, "Null mosaic directory for layer: '" + layername + "'... check the layer configuration on geostore");
}
File mosaicDir = new File(mosaicDirPath);
if( ! mosaicDir.isDirectory() && ! mosaicDir.isAbsolute()) {
- throw new ActionException(this, "Bad mosaic directory for layer:"+layername+": " + mosaicDir);
+ throw new ActionException(this, "Bad mosaic directory for layer '" + layername + "': " + mosaicDir + " doesn't exist... create it or check the layer configuration on geostore");
}
// ******************
// Check for LayerUpdate
// ******************
this.listenerForwarder.progressing(20, "Check for existing LayerUpdate in GeoStore");
Resource existingLayerUpdate = null;
try {
existingLayerUpdate = geostore.searchLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layerSnapshot=" + layerUpdateName + "]");
throw new ActionException(this, "Error searching for a LayerUpdate (layer:"+layername+" year:"+year+ " month:"+month+")", e);
}
if (existingLayerUpdate != null) {
throw new ActionException(this, "LayerUpdate already exists (layer:"+layername+" year:"+year+ " month:"+month+")");
}
/********************************
*
* Image processing
*
*******************************/
final File rasterFile;
if (request.getFormat() == UNREDDFormat.VECTOR ) {
rasterFile = processVector(dataFile, layername, year, month, day, layer, mosaicDir);
} else {
rasterFile = processRaster(dataFile, layer, mosaicDir, layername);
}
// *** Image processing has finished
// ********************
// Create LayerUpdate
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Adding LayerUpdate into GeoStore");
}
this.listenerForwarder.progressing(70, "Adding LayerUpdate into GeoStore");
try {
geostore.insertLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layername=" + layername + ", year=" + year + ", month=" + month + "]");
throw new ActionException(this, "Error while inserting a LayerUpdate", e);
}
// ********************
// Run stats
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Starting statistic processing");
}
this.listenerForwarder.progressing(80, "Starting statistic processing");
FlowUtil flowUtil= new FlowUtil(getTempDir(), getConfigDir());
try {
flowUtil.runStatsAndScripts(layername, year, month, day, rasterFile, geostore);
} catch (FlowException e) {
throw new ActionException(this, e.getMessage(), e);
}
/*************************
* Copy orig data
*************************/
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Moving original data");
}
this.listenerForwarder.progressing(90, "Moving original data");
LOGGER.warn("*** TODO: move original files"); // TODO
// File srcDir = new File(unzipPath, ORIG_DIR);
// if (!srcDir.exists()) {
// LOGGER.warn("Original data not found"); // no problem in this case
// } else {
// File destDirRelative = new File(cfg.repositoryDir, destRelativePath);
// File destDirComplete = new File(destDirRelative, layerUpdateName);
// LOGGER.info("Moving "+srcDir.getCanonicalPath()+" to "+destDirComplete.getAbsolutePath());
// FileUtils.copyDirectoryToDirectory(srcDir, destDirComplete);
// }
// finish action
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Ingestion action succesfully completed");
}
this.listenerForwarder.completed();
this.listenerForwarder.progressing(100, "Action successfully completed");
//*******************************************************************
// postgisUtils.getPgDatastore().dispose(); // shouldnt it be run in a finally{} block?
// add the event to the return queue
return rasterFile;
}
/**
* Process raster data.
* <OL>
* <LI>check extent</LI>
* <LI>check pixel size</LI>
* <LI>retile</LI>
* <LI>create overviews</LI>
* <LI>call ImageMosaic action</LI>
* <OL>
* <LI>copy raster into mosaic dir</LI>
* <LI>add granule in tile db</LI>
* <LI>refresh geoserver cache</LI>
* </OL>
* </OL>
*
* @param dataFile input raster
* @param layer
* @param mosaicDir
* @param layername
* @return
* @throws ActionException
* @throws NumberFormatException
*/
protected File processRaster(File dataFile, UNREDDLayer layer, File mosaicDir, final String layername) throws ActionException, NumberFormatException {
this.listenerForwarder.progressing(25, "Checking raster extents");
checkRasterSize(dataFile, layer);
File rasterFile;
try {
LOGGER.info("Starting retiling for " + dataFile);
this.listenerForwarder.progressing(30, "Starting retiling");
rasterFile = GeoTiff.retile(cfg.getRetilerConfiguration(), dataFile, getTempDir()); // retile replaces the original input file
LOGGER.info("Retiling completed into " + rasterFile);
} catch (Exception e) {
throw new ActionException(this, "Error while retiling " + dataFile, e);
}
// === embedOverviews
LOGGER.info("Starting overviews");
this.listenerForwarder.progressing(40, "Starting overviews");
try {
rasterFile = GeoTiff.embedOverviews(cfg.getOverviewsEmbedderConfiguration(), rasterFile, getTempDir());
} catch (Exception e) {
throw new ActionException(this, "Error creating overviews on " + rasterFile, e);
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Geoserver mosaic update started "+cfg);
}
this.listenerForwarder.progressing(60, "Adding new time coordinate in GeoServer");
// Publish data on GeoServer
// mosaic action will
// - copy the raster into the mosaic dir (with current filename)
// - add the granule in the tile db
try {
String style = layer.getAttribute(UNREDDLayer.Attributes.LAYERSTYLE);
if(style==null || style.isEmpty()){
style = DEFAULT_MOSAIC_STYLE;
}
StringBuilder msg = new StringBuilder();
msg.append("Publishing the Mosaic Granule with Style -> ");
msg.append(style);
LOGGER.info(msg.toString());
double [] bbox = new double[4];
bbox[0] = Double.valueOf(layer.getAttribute(Attributes.RASTERX0));
bbox[1] = Double.valueOf(layer.getAttribute(Attributes.RASTERY0));
bbox[2] = Double.valueOf(layer.getAttribute(Attributes.RASTERX1));
bbox[3] = Double.valueOf(layer.getAttribute(Attributes.RASTERY1));
Mosaic mosaic = new Mosaic(cfg.getGeoServerConfig(), mosaicDir, getTempDir(), getConfigDir());
mosaic.add(cfg.getGeoServerConfig().getWorkspace(), layername, rasterFile, "EPSG:4326", bbox, style, cfg.getDatastorePath());
} catch (Exception e) {
this.listenerForwarder.progressing(60, "Error in ImageMosaic: " + e.getMessage());
LOGGER.error("Error in ImageMosaic: " + e.getMessage(), e);
throw new ActionException(this, "Error updating mosaic " + rasterFile.getName(), e);
}
File expectedMosaicTile = new File(mosaicDir, dataFile.getName());
if(expectedMosaicTile.exists()) {
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Mosaic granule is in the mosaic dir: " + expectedMosaicTile);
}
} else {
LOGGER.error("Mosaic granule not found: " + expectedMosaicTile);
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Geoserver mosaic update completed");
}
return rasterFile;
}
/**
* Process vector data.
* <OL>
* <LI>check attributes matching</LI>
* <LI>copy shp into pg</LI>
* <LI>rasterize</LI>
* <LI>create overviews</LI>
* <LI>copy raster into mosaic dir</LI>
* </OL>
*
* @param dataFile the shapefile to be processes
* @param layername the bare name of the layer
* @param year the 4-digits year
* @param month the month, may be null
* @param layer UNREDDLayer info, contains data about rasterization
* @param mosaicDir destination directory
*
* @return the raster File, ready to be used for computing stats
*
* @throws ActionException
* @throws IOException
*/
protected File processVector(File dataFile, final String layername, final String year, final String month, final String day, UNREDDLayer layer, File mosaicDir) throws ActionException, IOException {
LOGGER.info("Starting PostGIS ingestion for " + dataFile);
this.listenerForwarder.progressing(25, "Starting PostGIS ingestion");
try {
int cp = PostGISUtils.shapeToPostGis(dataFile, cfg.getPostGisConfig(), layername, year, month, day);
this.listenerForwarder.progressing(29, "Copied "+cp+ " features");
} catch (PostGisException e) {
LOGGER.error("Error ingesting shapefile: " + e.getMessage());
throw new ActionException(this, "Error ingesting shapefile: " + e.getMessage(), e);
}
File rasterFile;
LOGGER.info("Starting rasterization");
this.listenerForwarder.progressing(30, "Starting rasterization");
try {
GDALRasterize rasterize = new GDALRasterize( cfg.getRasterizeConfig(), cfg.getConfigDir(), getTempDir());
rasterFile = rasterize.run(layer, new UNREDDLayerUpdate(layername, year, month, day), dataFile);
} catch (Exception e) {
throw new ActionException(this, "Error while rasterizing "+dataFile+": " + e.getMessage(), e);
}
LOGGER.info("Starting overviews");
this.listenerForwarder.progressing(40, "Starting overviews");
try {
rasterFile = GeoTiff.embedOverviews(cfg.getOverviewsEmbedderConfiguration(), rasterFile, getTempDir());
} catch (Exception e) {
throw new ActionException(this, "Error creating overviews on " + rasterFile, e);
}
//=== Move final raster file into its mosaic dir
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Moving raster file into mosaic dir");
}
this.listenerForwarder.progressing(50, "Copying raster into mosaic dir");
String finalRasterName = NameUtils.buildTifFileName(layername, year, month, day);
File destFile = new File(mosaicDir, finalRasterName);
if(destFile.exists())
throw new ActionException(this, "Destination file in mosaic dir already exists " + destFile);
FileUtils.copyFile(rasterFile, destFile);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Raster file moved into mosaic dir: " + destFile);
}
return rasterFile;
}
/**
* @param inputZipFile
* @param unzipDir
* @throws ActionException
*/
public void unzipInputFile(File inputZipFile, File unzipDir) throws ActionException {
LOGGER.debug("Unzipping " + inputZipFile + " into " + unzipDir);
ArchiveInputStream in = null;
try {
final InputStream is = new FileInputStream(inputZipFile);
in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
ZipArchiveEntry entry;
while( (entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
File currentFile = new File(unzipDir, entry.getName());
if(entry.isDirectory()) {
LOGGER.info("Unzipping dir " + entry);
FileUtils.forceMkdir(currentFile);
} else {
LOGGER.info("Unzipping file " + entry);
//create parent dir if needed
File parent = currentFile.getParentFile();
if( ! parent.exists()) {
if(LOGGER.isInfoEnabled())
LOGGER.info("Forcing creation of parent dir " + parent);
FileUtils.forceMkdir(parent);
}
OutputStream out = new FileOutputStream(currentFile);
IOUtils.copy(in, out);
out.flush();
IOUtils.closeQuietly(out);
}
}
LOGGER.info("Zip extracted in " + unzipDir);
} catch (Exception e) {
throw new ActionException(this, "Error extracting from " + inputZipFile, e);
} finally {
IOUtils.closeQuietly(in);
}
}
// /**
// * Ingesto
// * @param layer
// * @param layerUpdate
// * @param shapeFile
// * @return
// * @throws ActionException
// */
// protected File processVector(UNREDDLayer layer, UNREDDLayerUpdate layerUpdate, File shapeFile) throws ActionException {
//
// try {
// PostGISUtils.shapeToPostGis(shapeFile, cfg.getPostGisConfig(),
// layerUpdate.getAttribute(UNREDDLayerUpdate.Attributes.LAYER),
// layerUpdate.getAttribute(UNREDDLayerUpdate.Attributes.YEAR),
// layerUpdate.getAttribute(UNREDDLayerUpdate.Attributes.MONTH));
// } catch (PostGisException e) {
// LOGGER.error("Error ingesting shapefile: " + e.getMessage());
// throw new ActionException(this, "Error ingesting shapefile: " + e.getMessage(), e);
// }
//
//
// File rasterFile = null;
// try {
// GDALRasterize rasterize = new GDALRasterize( cfg.getRasterizeConfig(), cfg.getConfigDir(), getTempDir());
// rasterFile = rasterize.run(layer, layerUpdate, shapeFile);
// } catch (Exception e) {
// throw new ActionException(this, "Error while rasterizing "+shapeFile+": " + e.getMessage(), e);
// }
// // at this point the raster is also tiled, we do must skip the tiling action and go to the embedOverviews
//
// return rasterFile;
// }
/**
* Check that raster size and extent are the expected ones.
*
* @param dataFile The input data field to be checked
* @param layer the geostore resource containing the expected values
*
* @throws ActionException
* @throws NumberFormatException
*/
protected void checkRasterSize(File dataFile, UNREDDLayer layer) throws ActionException, NumberFormatException {
//= check that raster size is the expected one
GeoTiffReader reader;
try {
reader = new GeoTiffReader(dataFile);
} catch (Exception e) {
throw new ActionException(this, "Error reading tiff file " + dataFile, e);
}
GridEnvelope ge = reader.getOriginalGridRange();
// GridCoverage2D gc2d = reader.read(null);
// GridGeometry2D gg2d = gc2d.getGridGeometry();
// GridEnvelope ge = gg2d.getGridRange();
try {
int expectedW = Float.valueOf(layer.getAttribute(Attributes.RASTERPIXELWIDTH)).intValue();
int expectedH = Float.valueOf(layer.getAttribute(Attributes.RASTERPIXELHEIGHT)).intValue();
int foundW = ge.getSpan(0);
int foundH = ge.getSpan(1);
if ( expectedW != foundW || expectedH != foundH ) {
throw new ActionException(this, "Bad raster size " + foundW + "x" + foundH + ", expected " + expectedW + "x" + expectedH);
}
//= check that extent is the expected one
// checkCoord(layer, Attributes.RASTERX0)
double expectedX0 = Double.valueOf(layer.getAttribute(Attributes.RASTERX0));
double expectedX1 = Double.valueOf(layer.getAttribute(Attributes.RASTERX1));
double expectedY0 = Double.valueOf(layer.getAttribute(Attributes.RASTERY0));
double expectedY1 = Double.valueOf(layer.getAttribute(Attributes.RASTERY1));
Envelope env = reader.getOriginalEnvelope();
// Envelope env = gc2d.getEnvelope();
double foundX0 = env.getMinimum(0);
double foundX1 = env.getMaximum(0);
double foundY0 = env.getMinimum(1);
double foundY1 = env.getMaximum(1);
if ( ! nearEnough(expectedX0, foundX0) || !nearEnough(expectedX1, foundX1) ||
! nearEnough(expectedY0, foundY0) || ! nearEnough(expectedY1, foundY1) ) {
throw new ActionException(this, "Bad raster extent X[" + foundX0 + "," + foundX1 + "] Y[" + foundY0 + "," + foundY1 + "]"
+ " expected X[" + expectedX0 + "," + expectedX1 + "] Y[" + expectedY0 + "," + expectedY1 + "]");
}
} catch (ActionException e) {
throw e;
} catch (Exception e) {
throw new ActionException(this,"Error while checking raster dimensions", e);
}
}
private final static double EXTENT_TRESHOLD = 0.000001;
protected static boolean nearEnough(double d1, double d2) {
double delta = Math.abs(d1 - d2 );
if(delta == 0)
return true;
if( delta < EXTENT_TRESHOLD && LOGGER.isInfoEnabled()) {
LOGGER.info("Delta not zero:" + d1 + "," + d2);
return true;
}
return false;
}
@Override
public boolean checkConfiguration() {
return true;
}
}
| false | true | protected File executeUnzipped(File unzipDir) throws ActionException, IOException {
/*************
*
* read the content of the XML file
*
***********/
this.listenerForwarder.progressing(10, "Parsing " + INFO_XML);
File infoXmlFile = new File(unzipDir, INFO_XML);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Reading XML parameters from " + infoXmlFile);
}
Request request = null;
try {
request = RequestJDOMReader.parseFile(infoXmlFile);
} catch (Exception e) {
throw new ActionException(this, "Error reading info.xml file, Are you sure to have built the input zip pkg in the right way? Note that all the content must be placed in the zip root folder, no any other subfolder are allowed..." , e);
}
if(request.getFormat() == null) {
throw new ActionException(this, "the format cannot be null.");
}
final String layername = request.getLayername();
if (layername==null)
throw new ActionException(this, "the layername cannot be null.");
final String year = request.getYear();
if (year==null)
throw new ActionException(this, "the year cannot be null.");
if( ! year.matches("\\d{4}")) {
throw new ActionException(this, "Bad format for year parameter ("+year+")");
}
final String month = request.getMonth();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+month+")");
final String day = request.getDay();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+day+")");
final String srcFilename = request.buildFileName();
// build the name of the snapshot
final String layerUpdateName = NameUtils.buildLayerUpdateName(layername, year, month, day);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Info: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
}
this.listenerForwarder.progressing(12, "Info from xml file: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("XML parameter settings : [layer name = " + layername + "], [year = " + year + "], [month = " + month + "], [day = " + day + "], [ file name = " + srcFilename + "]");
LOGGER.debug("XML parameter settings : [layer update name = " + layerUpdateName + "]");
}
File unzippedDataDir = new File(unzipDir, DATA_DIR_NAME);
File dataFile = new File(unzippedDataDir, srcFilename);
if( ! dataFile.isFile()) {
throw new ActionException(this, "Could not read main data file " + dataFile);
}
/*****************/
GeoStoreUtil geostore = new GeoStoreUtil(cfg.getGeoStoreConfig(), this.getTempDir());
/******************
* Load Layer data
******************/
this.listenerForwarder.progressing(15, "Searching layer in GeoStore");
final Resource layerRes;
try {
layerRes = geostore.searchLayer(layername);
} catch(Exception e) {
throw new ActionException(this, "Error loading Layer "+layername, e);
}
if(layerRes == null)
throw new ActionException(this, "Layer not found: "+layername);
UNREDDLayer layer = new UNREDDLayer(layerRes);
LOGGER.info("Layer resource found ");
if( ! layer.getAttribute(Attributes.LAYERTYPE).equalsIgnoreCase(request.getFormat().getName()))
throw new ActionException(this, "Bad Layer format "
+ "(declared:"+ request.getFormat().getName()
+ ", expected:"+layer.getAttribute(Attributes.LAYERTYPE) );
// this attribute is read for moving the raster file to the destination directory, not for rasterization
String mosaicDirPath = layer.getAttribute(UNREDDLayer.Attributes.MOSAICPATH);
if( mosaicDirPath == null) {
throw new ActionException(this, "Null mosaic directory for layer:"+layername);
}
File mosaicDir = new File(mosaicDirPath);
if( ! mosaicDir.isDirectory() && ! mosaicDir.isAbsolute()) {
throw new ActionException(this, "Bad mosaic directory for layer:"+layername+": " + mosaicDir);
}
// ******************
// Check for LayerUpdate
// ******************
this.listenerForwarder.progressing(20, "Check for existing LayerUpdate in GeoStore");
Resource existingLayerUpdate = null;
try {
existingLayerUpdate = geostore.searchLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layerSnapshot=" + layerUpdateName + "]");
throw new ActionException(this, "Error searching for a LayerUpdate (layer:"+layername+" year:"+year+ " month:"+month+")", e);
}
if (existingLayerUpdate != null) {
throw new ActionException(this, "LayerUpdate already exists (layer:"+layername+" year:"+year+ " month:"+month+")");
}
/********************************
*
* Image processing
*
*******************************/
final File rasterFile;
if (request.getFormat() == UNREDDFormat.VECTOR ) {
rasterFile = processVector(dataFile, layername, year, month, day, layer, mosaicDir);
} else {
rasterFile = processRaster(dataFile, layer, mosaicDir, layername);
}
// *** Image processing has finished
// ********************
// Create LayerUpdate
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Adding LayerUpdate into GeoStore");
}
this.listenerForwarder.progressing(70, "Adding LayerUpdate into GeoStore");
try {
geostore.insertLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layername=" + layername + ", year=" + year + ", month=" + month + "]");
throw new ActionException(this, "Error while inserting a LayerUpdate", e);
}
// ********************
// Run stats
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Starting statistic processing");
}
this.listenerForwarder.progressing(80, "Starting statistic processing");
FlowUtil flowUtil= new FlowUtil(getTempDir(), getConfigDir());
try {
flowUtil.runStatsAndScripts(layername, year, month, day, rasterFile, geostore);
} catch (FlowException e) {
throw new ActionException(this, e.getMessage(), e);
}
/*************************
* Copy orig data
*************************/
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Moving original data");
}
this.listenerForwarder.progressing(90, "Moving original data");
LOGGER.warn("*** TODO: move original files"); // TODO
// File srcDir = new File(unzipPath, ORIG_DIR);
// if (!srcDir.exists()) {
// LOGGER.warn("Original data not found"); // no problem in this case
// } else {
// File destDirRelative = new File(cfg.repositoryDir, destRelativePath);
// File destDirComplete = new File(destDirRelative, layerUpdateName);
// LOGGER.info("Moving "+srcDir.getCanonicalPath()+" to "+destDirComplete.getAbsolutePath());
// FileUtils.copyDirectoryToDirectory(srcDir, destDirComplete);
// }
// finish action
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Ingestion action succesfully completed");
}
this.listenerForwarder.completed();
this.listenerForwarder.progressing(100, "Action successfully completed");
//*******************************************************************
// postgisUtils.getPgDatastore().dispose(); // shouldnt it be run in a finally{} block?
// add the event to the return queue
return rasterFile;
}
| protected File executeUnzipped(File unzipDir) throws ActionException, IOException {
/*************
*
* read the content of the XML file
*
***********/
this.listenerForwarder.progressing(10, "Parsing " + INFO_XML);
File infoXmlFile = new File(unzipDir, INFO_XML);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Reading XML parameters from " + infoXmlFile);
}
Request request = null;
try {
request = RequestJDOMReader.parseFile(infoXmlFile);
} catch (Exception e) {
throw new ActionException(this, "Error reading info.xml file, Are you sure to have built the input zip pkg in the right way? Note that all the content must be placed in the zip root folder, no any other subfolder are allowed..." , e);
}
if(request.getFormat() == null) {
throw new ActionException(this, "the format cannot be null.");
}
final String layername = request.getLayername();
if (layername==null)
throw new ActionException(this, "the layername cannot be null.");
final String year = request.getYear();
if (year==null)
throw new ActionException(this, "the year cannot be null.");
if( ! year.matches("\\d{4}")) {
throw new ActionException(this, "Bad format for year parameter ("+year+")");
}
final String month = request.getMonth();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+month+")");
final String day = request.getDay();
if(month!= null && ! month.matches("\\d\\d?") )
throw new ActionException(this, "Bad format for month parameter ("+day+")");
final String srcFilename = request.buildFileName();
// build the name of the snapshot
final String layerUpdateName = NameUtils.buildLayerUpdateName(layername, year, month, day);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Info: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
}
this.listenerForwarder.progressing(12, "Info from xml file: layername:" + layername + " year:"+year + " month:"+month + " day:"+day);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("XML parameter settings : [layer name = " + layername + "], [year = " + year + "], [month = " + month + "], [day = " + day + "], [ file name = " + srcFilename + "]");
LOGGER.debug("XML parameter settings : [layer update name = " + layerUpdateName + "]");
}
File unzippedDataDir = new File(unzipDir, DATA_DIR_NAME);
File dataFile = new File(unzippedDataDir, srcFilename);
if( ! dataFile.isFile()) {
throw new ActionException(this, "Could not read main data file " + dataFile);
}
/*****************/
GeoStoreUtil geostore = new GeoStoreUtil(cfg.getGeoStoreConfig(), this.getTempDir());
/******************
* Load Layer data
******************/
this.listenerForwarder.progressing(15, "Searching layer in GeoStore");
final Resource layerRes;
try {
layerRes = geostore.searchLayer(layername);
} catch(Exception e) {
throw new ActionException(this, "Error loading Layer "+layername, e);
}
if(layerRes == null)
throw new ActionException(this, "Layer not found: "+layername);
UNREDDLayer layer = new UNREDDLayer(layerRes);
LOGGER.info("Layer resource found ");
if( ! layer.getAttribute(Attributes.LAYERTYPE).equalsIgnoreCase(request.getFormat().getName()))
throw new ActionException(this, "Bad Layer format "
+ "(declared:"+ request.getFormat().getName()
+ ", expected:"+layer.getAttribute(Attributes.LAYERTYPE) );
// this attribute is read for moving the raster file to the destination directory, not for rasterization
String mosaicDirPath = layer.getAttribute(UNREDDLayer.Attributes.MOSAICPATH);
if( mosaicDirPath == null) {
throw new ActionException(this, "Null mosaic directory for layer: '" + layername + "'... check the layer configuration on geostore");
}
File mosaicDir = new File(mosaicDirPath);
if( ! mosaicDir.isDirectory() && ! mosaicDir.isAbsolute()) {
throw new ActionException(this, "Bad mosaic directory for layer '" + layername + "': " + mosaicDir + " doesn't exist... create it or check the layer configuration on geostore");
}
// ******************
// Check for LayerUpdate
// ******************
this.listenerForwarder.progressing(20, "Check for existing LayerUpdate in GeoStore");
Resource existingLayerUpdate = null;
try {
existingLayerUpdate = geostore.searchLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layerSnapshot=" + layerUpdateName + "]");
throw new ActionException(this, "Error searching for a LayerUpdate (layer:"+layername+" year:"+year+ " month:"+month+")", e);
}
if (existingLayerUpdate != null) {
throw new ActionException(this, "LayerUpdate already exists (layer:"+layername+" year:"+year+ " month:"+month+")");
}
/********************************
*
* Image processing
*
*******************************/
final File rasterFile;
if (request.getFormat() == UNREDDFormat.VECTOR ) {
rasterFile = processVector(dataFile, layername, year, month, day, layer, mosaicDir);
} else {
rasterFile = processRaster(dataFile, layer, mosaicDir, layername);
}
// *** Image processing has finished
// ********************
// Create LayerUpdate
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Adding LayerUpdate into GeoStore");
}
this.listenerForwarder.progressing(70, "Adding LayerUpdate into GeoStore");
try {
geostore.insertLayerUpdate(layername, year, month, day);
} catch (Exception e) {
LOGGER.debug("Parameter : [layername=" + layername + ", year=" + year + ", month=" + month + "]");
throw new ActionException(this, "Error while inserting a LayerUpdate", e);
}
// ********************
// Run stats
// ********************
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Starting statistic processing");
}
this.listenerForwarder.progressing(80, "Starting statistic processing");
FlowUtil flowUtil= new FlowUtil(getTempDir(), getConfigDir());
try {
flowUtil.runStatsAndScripts(layername, year, month, day, rasterFile, geostore);
} catch (FlowException e) {
throw new ActionException(this, e.getMessage(), e);
}
/*************************
* Copy orig data
*************************/
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Moving original data");
}
this.listenerForwarder.progressing(90, "Moving original data");
LOGGER.warn("*** TODO: move original files"); // TODO
// File srcDir = new File(unzipPath, ORIG_DIR);
// if (!srcDir.exists()) {
// LOGGER.warn("Original data not found"); // no problem in this case
// } else {
// File destDirRelative = new File(cfg.repositoryDir, destRelativePath);
// File destDirComplete = new File(destDirRelative, layerUpdateName);
// LOGGER.info("Moving "+srcDir.getCanonicalPath()+" to "+destDirComplete.getAbsolutePath());
// FileUtils.copyDirectoryToDirectory(srcDir, destDirComplete);
// }
// finish action
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Ingestion action succesfully completed");
}
this.listenerForwarder.completed();
this.listenerForwarder.progressing(100, "Action successfully completed");
//*******************************************************************
// postgisUtils.getPgDatastore().dispose(); // shouldnt it be run in a finally{} block?
// add the event to the return queue
return rasterFile;
}
|
diff --git a/src/TeacherTable.java b/src/TeacherTable.java
index 4c72d9a..c27439f 100644
--- a/src/TeacherTable.java
+++ b/src/TeacherTable.java
@@ -1,274 +1,275 @@
import java.awt.Color;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class TeacherTable implements TableModelListener, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
TeacherDB teachers;
JTable table;
DefaultTableModel tm;
JFrame frame;
Object[][] data;
String[] columnNames = { "Name", "Math Class Levels",
"Reading Class Levels", "Language Arts Class Levels" };
TeacherController controller;
ClassFactory clsFac;
public TeacherTable(JFrame f, TeacherDB t, ClassFactory cf) {
clsFac = cf;
teachers = t;
frame = f;
data = new Object[300][4];
for (int i = 0; i < 300; i++) {
for (int j = 0; j < 4; j++)
data[i][j] = "";
}
tm = new DefaultTableModel(data, columnNames);
table = new JTable();
table.setModel(tm);
tm.addTableModelListener(this);
update();
}
public void update() {
populateTable();
renderTable();
}
public void renderTable() {
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
table.setRowHeight(20);
table.setCellSelectionEnabled(true);
}
public JTable getTeacherTable() {
return table;
}
// Make the object [][] representation of students to be added into the
// JTable
public void populateTable() {
int i = 0;
data = new Object[300][4];
if (teachers.getSize() > 0) {
ArrayList<Teachers> tList = teachers.getTeachers();
Iterator<Teachers> it = tList.iterator();
while (it.hasNext()) {
Teachers t = it.next();
data[i][0] = t.getName();
StringBuilder line = new StringBuilder();
ArrayList<Integer> mClasses = t
.getPreference(Teachers.Type.MATH);
for (int j = 0; j < mClasses.size(); j++) {
line.append(mClasses.get(j) + ";");
}
data[i][1] = line.toString();
line = new StringBuilder();
ArrayList<Integer> rClasses = t
.getPreference(Teachers.Type.READ);
for (int j = 0; j < rClasses.size(); j++) {
line.append(rClasses.get(j) + ";");
}
data[i][2] = line.toString();
line = new StringBuilder();
ArrayList<Integer> lClasses = t.getPreference(Teachers.Type.LA);
for (int j = 0; j < lClasses.size(); j++) {
line.append(lClasses.get(j) + ";");
}
data[i][3] = line.toString();
i++;
}
}
// Add an empty row
while (i < 300) {
data[i][0] = "";
data[i][1] = "";
i++;
}
tm.setDataVector(data, columnNames);
}
@Override
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if (row < 0 || column < 0)
return;
TableModel model = (TableModel) e.getSource();
Object d = model.getValueAt(row, column);
data[row][column] = d;
boolean isBlank = Utilities.isBlank(d.toString());
if (row > 0 && Utilities.isBlank(data[row - 1][0].toString())
&& !isBlank) {
JOptionPane.showMessageDialog(frame,
"Please do not leave open rows within the table");
table.setValueAt("", row, column);
return;
}
String currName = data[row][0].toString();
Teachers t;
boolean newTeacher = false;
if (teachers.hasTeacher(currName)) {
t = teachers.getTeacher(currName);
} else {
t = new Teachers(currName, clsFac);
newTeacher = true;
}
switch (column) {
case 0:
if (isBlank) {
//cleanTeacherDB();
} else {
boolean isRepeat = false;
for (int i = 0; i < 300; i ++) {
if (d.toString().equals(data[i][0].toString()) && i != row)
isRepeat = true;
}
if (isRepeat) {
JOptionPane
.showMessageDialog(frame,
"A teacher with that name already exists in the scheduling system.");
table.setValueAt("", row, column);
} else {
t.setName(d.toString());
+ System.out.println(t.getName());
}
}
- cleanTeacherDB();
+ //cleanTeacherDB();
break;
case 1:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.MATH);
}
break;
case 2:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.READ);
}
break;
case 3:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.LA);
}
break;
}
if (!isBlank) {
if (newTeacher) {
teachers.addTeacher(t);
} else {
teachers.modifyTeacher(currName, t);
}
}
tm.setDataVector(data, columnNames);
renderTable();
}
/*
* I apologize for the inefficiency of this, but given the small data set,
* it shouldn't be awful
*/
private void cleanTeacherDB() {
List<Teachers> tchrs = teachers.getTeachers();
for (int i = 0; i < tchrs.size(); i++) {
Teachers t = tchrs.get(i);
String name = t.getName();
for (int j = 0; j < teachers.getSize(); j++) {
if (name.equals(data[j][0].toString())) {
return;
}
}
// if we got here, the student is not in the data array anymore
teachers.removeTeacher(name);
}
update();
}
}
| false | true | public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if (row < 0 || column < 0)
return;
TableModel model = (TableModel) e.getSource();
Object d = model.getValueAt(row, column);
data[row][column] = d;
boolean isBlank = Utilities.isBlank(d.toString());
if (row > 0 && Utilities.isBlank(data[row - 1][0].toString())
&& !isBlank) {
JOptionPane.showMessageDialog(frame,
"Please do not leave open rows within the table");
table.setValueAt("", row, column);
return;
}
String currName = data[row][0].toString();
Teachers t;
boolean newTeacher = false;
if (teachers.hasTeacher(currName)) {
t = teachers.getTeacher(currName);
} else {
t = new Teachers(currName, clsFac);
newTeacher = true;
}
switch (column) {
case 0:
if (isBlank) {
//cleanTeacherDB();
} else {
boolean isRepeat = false;
for (int i = 0; i < 300; i ++) {
if (d.toString().equals(data[i][0].toString()) && i != row)
isRepeat = true;
}
if (isRepeat) {
JOptionPane
.showMessageDialog(frame,
"A teacher with that name already exists in the scheduling system.");
table.setValueAt("", row, column);
} else {
t.setName(d.toString());
}
}
cleanTeacherDB();
break;
case 1:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.MATH);
}
break;
case 2:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.READ);
}
break;
case 3:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.LA);
}
break;
}
if (!isBlank) {
if (newTeacher) {
teachers.addTeacher(t);
} else {
teachers.modifyTeacher(currName, t);
}
}
tm.setDataVector(data, columnNames);
renderTable();
}
| public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
if (row < 0 || column < 0)
return;
TableModel model = (TableModel) e.getSource();
Object d = model.getValueAt(row, column);
data[row][column] = d;
boolean isBlank = Utilities.isBlank(d.toString());
if (row > 0 && Utilities.isBlank(data[row - 1][0].toString())
&& !isBlank) {
JOptionPane.showMessageDialog(frame,
"Please do not leave open rows within the table");
table.setValueAt("", row, column);
return;
}
String currName = data[row][0].toString();
Teachers t;
boolean newTeacher = false;
if (teachers.hasTeacher(currName)) {
t = teachers.getTeacher(currName);
} else {
t = new Teachers(currName, clsFac);
newTeacher = true;
}
switch (column) {
case 0:
if (isBlank) {
//cleanTeacherDB();
} else {
boolean isRepeat = false;
for (int i = 0; i < 300; i ++) {
if (d.toString().equals(data[i][0].toString()) && i != row)
isRepeat = true;
}
if (isRepeat) {
JOptionPane
.showMessageDialog(frame,
"A teacher with that name already exists in the scheduling system.");
table.setValueAt("", row, column);
} else {
t.setName(d.toString());
System.out.println(t.getName());
}
}
//cleanTeacherDB();
break;
case 1:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.MATH);
}
break;
case 2:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.READ);
}
break;
case 3:
if (data[row][0].toString().isEmpty()) {
if (!isBlank) {
JOptionPane.showMessageDialog(frame,
"Please provide a name first.\n");
table.setValueAt("", row, column);
}
} else {
String[] classList = d.toString().split(";");
ArrayList<Integer> classes = new ArrayList<Integer>();
for (int i = 0; i < classList.length; i++) {
try {
int tmp = Integer.parseInt(classList[i]);
classes.add(tmp);
} catch (NumberFormatException ne) {
// maybe an error here, but they probably wont be
// inputting integers so we'll need to do conversions
}
}
t.setPreference(classes, Teachers.Type.LA);
}
break;
}
if (!isBlank) {
if (newTeacher) {
teachers.addTeacher(t);
} else {
teachers.modifyTeacher(currName, t);
}
}
tm.setDataVector(data, columnNames);
renderTable();
}
|
diff --git a/src/lib-vnc-lightweight-history/src/biz/vnc/zimbra/lighthistoryzimlet/MailHistoryLogging.java b/src/lib-vnc-lightweight-history/src/biz/vnc/zimbra/lighthistoryzimlet/MailHistoryLogging.java
index 4aee8bb..abbd515 100644
--- a/src/lib-vnc-lightweight-history/src/biz/vnc/zimbra/lighthistoryzimlet/MailHistoryLogging.java
+++ b/src/lib-vnc-lightweight-history/src/biz/vnc/zimbra/lighthistoryzimlet/MailHistoryLogging.java
@@ -1,279 +1,279 @@
/*
http://www.vnc.biz
Copyright 2012, VNC - Virtual Network Consult GmbH
Released under GPL Licenses.
*/
package biz.vnc.zimbra.lighthistoryzimlet;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import biz.vnc.zimbra.util.JSPUtil;
import biz.vnc.zimbra.util.ZLog;
import com.zimbra.cs.account.soap.SoapProvisioning.Options;
import com.zimbra.cs.zclient.ZMailbox;
import com.zimbra.cs.account.soap.SoapProvisioning;
import com.zimbra.cs.account.Domain;
import java.util.List;
public class MailHistoryLogging {
public static final String DELIVERED = "1";
public static final String MOVE = "2";
public static final String DELETE = "3";
public static Thread internalthread = null,externalthread=null;
public static FileInputStream fstream=null,filestream=null;
public static SoapProvisioning provisioning;
static {
try{
fstream=new FileInputStream("/opt/zimbra/log/mailbox.log");
filestream = new FileInputStream("/var/log/zimbra.log");
internalthread = new Thread(new RecipientExternalMailHistoryLogging(filestream));
externalthread = new Thread(new RecipientInternalMailHistoryLogging(fstream));
Options options = new Options();
options.setLocalConfigAuth(true);
provisioning = new SoapProvisioning(options);
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while static method called", e);
}
internalthread.start();
externalthread.start();
}
public static String getDataFromBracket(String name) {
if (name == null) {
return null;
}
if (name.contains("<")) {
return name.substring(name.indexOf("<")+1, name.indexOf(">",name.indexOf("<")));
}
return name;
}
}
class RecipientExternalMailHistoryLogging extends Thread {
public static FileInputStream filestream=null;
public RecipientExternalMailHistoryLogging (FileInputStream fstream) {
filestream = fstream;
}
public void run() {
while (true) {
try {
getExternalMailEvents();
Thread.sleep(2000);
continue;
} catch (Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error in run method while ExternalMailHistoryLogging", e);
}
}
}
public void getExternalMailEvents() {
try {
DataInputStream in = new DataInputStream(filestream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String senderName=null;
String receiverName=null;
String message_id = null;
String strLine;
while ((strLine = br.readLine()) != null) {
String messageId =null;
String receivers = null;
String sender = null;
if(strLine.contains("FWD via SMTP")) {
receivers = strLine.substring(strLine.indexOf("->"),strLine.indexOf(",BODY"));
sender = MailHistoryLogging.getDataFromBracket(strLine.split("->")[0].split(":")[4]);
}
if(strLine.contains("message-id")) {
message_id=MailHistoryLogging.getDataFromBracket(strLine.split("=")[1]);
}
if(message_id!=null && receivers!=null) {
for(String receiver : receivers.split(",")) {
receiver = MailHistoryLogging.getDataFromBracket(receiver);
if(isExternalMail(receiver)) {
DataBaseUtil.writeHistory(message_id, sender, receiver, MailHistoryLogging.DELIVERED,"","");
}
}
}
}
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while getting External Mail Event ", e);
}
}
synchronized public boolean isExternalMail(String receiver) {
List<Domain> alldomains = null;
boolean result = false;
int flag =1;
String receiverdomain = receiver.split("@")[1];
try {
Options options = new Options();
options.setLocalConfigAuth(true);
SoapProvisioning provisioning = new SoapProvisioning(options);
alldomains = provisioning.getAllDomains();
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while getting Domains List ", e);
}
for(int i=0; i<alldomains.size(); i++) {
if(alldomains.get(i).getName().equals(receiverdomain)) {
flag =0;
}
}
if(flag == 1) {
result = true;
} else {
result = false;
}
return result;
}
}
class RecipientInternalMailHistoryLogging extends Thread {
public static FileInputStream filestream=null;
public RecipientInternalMailHistoryLogging(FileInputStream stream) {
filestream = stream;
}
public void run() {
while (true) {
try {
getInternalMailEvents();
Thread.sleep(2000);
continue;
} catch (Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while run method in InternalMailHistoryLogging", e);
}
}
}
public void getInternalMailEvents() {
try {
DataInputStream in = new DataInputStream(filestream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine,msgId=null,receivermsgId;
String senderName=null;
String receiverName=null;
while ((strLine = br.readLine()) != null) {
if(strLine.contains("lmtp - Delivering")) {
String senderdata[] = strLine.split(",");
for(String sender:senderdata) {
if(sender.contains("sender")) {
senderName = sender.split("=")[1];
}
if(sender.contains("msgid")) {
msgId = MailHistoryLogging.getDataFromBracket(sender.split("=")[1]);
}
}
}
if(strLine.contains("mailop - Adding Message")) {
String receiverdata[] = strLine.split(",");
for(String receive:receiverdata) {
if(receive.contains("name")) {
receiverName = receive.split("=")[1].split(";")[0];
}
if(receive.contains("Message-ID")) {
receivermsgId = MailHistoryLogging.getDataFromBracket(receive.split("=")[1]);
if(msgId !=null) {
if(msgId.equals(receivermsgId)) {
String smallMessageId = strLine.split("id=")[2].split(",")[0];
ZLog.info("biz_vnc_lightweight_history", "smallid : "+smallMessageId);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+msgId);
ZLog.info("biz_vnc_lightweight_history", "Sender : "+senderName);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiverName);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELIVERED);
DataBaseUtil.writeHistory(msgId, senderName, receiverName, MailHistoryLogging.DELIVERED,smallMessageId,"");
}
}
}
}
}
if(strLine.contains("mailop - Moving Conversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
- String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
+ String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
- ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
+ ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
- if(moveMessageId!=null) {
- DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
+ if(!messageId.equals("")) {
+ DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving Message")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
- String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
+ String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
- ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
+ ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
- if(moveMessageId!=null) {
- DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
+ if(!messageId.equals("")) {
+ DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving VirtualConversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
- String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
+ String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
- ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
+ ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
- if(moveMessageId!=null) {
- DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
+ if(!messageId.equals("")) {
+ DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("Deleting items")) {
String deletedId = strLine.split(":")[4];
deletedId = deletedId.substring(0,deletedId.length()-1).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
if(strLine.contains("mailop - Deleting Message")) {
String deletedId = strLine.split("id")[2];
deletedId = deletedId.substring(1,deletedId.length()-2).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
}
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while getting Internal Mail Event from Log file", e);
}
}
}
| false | true | public void getInternalMailEvents() {
try {
DataInputStream in = new DataInputStream(filestream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine,msgId=null,receivermsgId;
String senderName=null;
String receiverName=null;
while ((strLine = br.readLine()) != null) {
if(strLine.contains("lmtp - Delivering")) {
String senderdata[] = strLine.split(",");
for(String sender:senderdata) {
if(sender.contains("sender")) {
senderName = sender.split("=")[1];
}
if(sender.contains("msgid")) {
msgId = MailHistoryLogging.getDataFromBracket(sender.split("=")[1]);
}
}
}
if(strLine.contains("mailop - Adding Message")) {
String receiverdata[] = strLine.split(",");
for(String receive:receiverdata) {
if(receive.contains("name")) {
receiverName = receive.split("=")[1].split(";")[0];
}
if(receive.contains("Message-ID")) {
receivermsgId = MailHistoryLogging.getDataFromBracket(receive.split("=")[1]);
if(msgId !=null) {
if(msgId.equals(receivermsgId)) {
String smallMessageId = strLine.split("id=")[2].split(",")[0];
ZLog.info("biz_vnc_lightweight_history", "smallid : "+smallMessageId);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+msgId);
ZLog.info("biz_vnc_lightweight_history", "Sender : "+senderName);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiverName);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELIVERED);
DataBaseUtil.writeHistory(msgId, senderName, receiverName, MailHistoryLogging.DELIVERED,smallMessageId,"");
}
}
}
}
}
if(strLine.contains("mailop - Moving Conversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(moveMessageId!=null) {
DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving Message")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(moveMessageId!=null) {
DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving VirtualConversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String moveMessageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+moveMessageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(moveMessageId!=null) {
DataBaseUtil.writeMoveHistory(moveMessageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("Deleting items")) {
String deletedId = strLine.split(":")[4];
deletedId = deletedId.substring(0,deletedId.length()-1).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
if(strLine.contains("mailop - Deleting Message")) {
String deletedId = strLine.split("id")[2];
deletedId = deletedId.substring(1,deletedId.length()-2).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
}
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while getting Internal Mail Event from Log file", e);
}
}
| public void getInternalMailEvents() {
try {
DataInputStream in = new DataInputStream(filestream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine,msgId=null,receivermsgId;
String senderName=null;
String receiverName=null;
while ((strLine = br.readLine()) != null) {
if(strLine.contains("lmtp - Delivering")) {
String senderdata[] = strLine.split(",");
for(String sender:senderdata) {
if(sender.contains("sender")) {
senderName = sender.split("=")[1];
}
if(sender.contains("msgid")) {
msgId = MailHistoryLogging.getDataFromBracket(sender.split("=")[1]);
}
}
}
if(strLine.contains("mailop - Adding Message")) {
String receiverdata[] = strLine.split(",");
for(String receive:receiverdata) {
if(receive.contains("name")) {
receiverName = receive.split("=")[1].split(";")[0];
}
if(receive.contains("Message-ID")) {
receivermsgId = MailHistoryLogging.getDataFromBracket(receive.split("=")[1]);
if(msgId !=null) {
if(msgId.equals(receivermsgId)) {
String smallMessageId = strLine.split("id=")[2].split(",")[0];
ZLog.info("biz_vnc_lightweight_history", "smallid : "+smallMessageId);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+msgId);
ZLog.info("biz_vnc_lightweight_history", "Sender : "+senderName);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiverName);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELIVERED);
DataBaseUtil.writeHistory(msgId, senderName, receiverName, MailHistoryLogging.DELIVERED,smallMessageId,"");
}
}
}
}
}
if(strLine.contains("mailop - Moving Conversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(!messageId.equals("")) {
DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving Message")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(!messageId.equals("")) {
DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("mailop - Moving VirtualConversation")) {
String moveinfoid = strLine.split(",")[1].split("INFO")[0];
String moveId = strLine.split(":")[4];
String receiver = strLine.split("]")[1].split("=")[1].split(";")[0];
moveId = moveId.substring(0,moveId.length()-1).trim();
String messageId=DataBaseUtil.getMsgId(moveId,receiver);
String folderName = strLine.split("Folder")[1].split("\\(")[0].trim();
ZLog.info("biz_vnc_lightweight_history", "Moving to : "+folderName);
ZLog.info("biz_vnc_lightweight_history", "message_id : "+messageId);
ZLog.info("biz_vnc_lightweight_history", "small_id : "+moveId);
ZLog.info("biz_vnc_lightweight_history", "info_id : "+moveinfoid);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.MOVE);
if(!messageId.equals("")) {
DataBaseUtil.writeMoveHistory(messageId, "", receiver, MailHistoryLogging.MOVE, moveId, moveinfoid,folderName);
}
}
if(strLine.contains("Deleting items")) {
String deletedId = strLine.split(":")[4];
deletedId = deletedId.substring(0,deletedId.length()-1).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
if(strLine.contains("mailop - Deleting Message")) {
String deletedId = strLine.split("id")[2];
deletedId = deletedId.substring(1,deletedId.length()-2).trim();
String receiver =strLine.split("]")[1].split("=")[1].split(";")[0];
ZLog.info("biz_vnc_lightweight_history", "small ID : "+deletedId);
ZLog.info("biz_vnc_lightweight_history", "Receiver : "+receiver);
ZLog.info("biz_vnc_lightweight_history", "Event : "+MailHistoryLogging.DELETE);
DataBaseUtil.writeDeleteHistory(deletedId,receiver);
}
}
} catch(Exception e) {
ZLog.err("biz_vnc_lightweight_history", "Error while getting Internal Mail Event from Log file", e);
}
}
|
diff --git a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/selection/RowSelectionModel.java b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/selection/RowSelectionModel.java
index 41070a90..ed3cdc8c 100644
--- a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/selection/RowSelectionModel.java
+++ b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/selection/RowSelectionModel.java
@@ -1,387 +1,388 @@
/*******************************************************************************
* Copyright (c) 2012 Original authors and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Original authors and others - initial API and implementation
******************************************************************************/
package org.eclipse.nebula.widgets.nattable.selection;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.nebula.widgets.nattable.coordinate.Range;
import org.eclipse.nebula.widgets.nattable.data.IRowDataProvider;
import org.eclipse.nebula.widgets.nattable.data.IRowIdAccessor;
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
import org.eclipse.swt.graphics.Rectangle;
public class RowSelectionModel<R> implements IRowSelectionModel<R> {
protected final SelectionLayer selectionLayer;
protected final IRowDataProvider<R> rowDataProvider;
protected final IRowIdAccessor<R> rowIdAccessor;
private boolean multipleSelectionAllowed;
protected Map<Serializable, R> selectedRows;
protected Rectangle lastSelectedRange; // *live* reference to last range parameter used in addSelection(range)
protected Set<Serializable> lastSelectedRowIds;
protected final ReadWriteLock selectionsLock;
public RowSelectionModel(SelectionLayer selectionLayer, IRowDataProvider<R> rowDataProvider, IRowIdAccessor<R> rowIdAccessor) {
this(selectionLayer, rowDataProvider, rowIdAccessor, true);
}
public RowSelectionModel(SelectionLayer selectionLayer, IRowDataProvider<R> rowDataProvider, IRowIdAccessor<R> rowIdAccessor, boolean multipleSelectionAllowed) {
this.selectionLayer = selectionLayer;
this.rowDataProvider = rowDataProvider;
this.rowIdAccessor = rowIdAccessor;
this.multipleSelectionAllowed = multipleSelectionAllowed;
selectedRows = new HashMap<Serializable, R>();
selectionsLock = new ReentrantReadWriteLock();
}
public boolean isMultipleSelectionAllowed() {
return multipleSelectionAllowed;
}
public void setMultipleSelectionAllowed(boolean multipleSelectionAllowed) {
this.multipleSelectionAllowed = multipleSelectionAllowed;
}
public void addSelection(int columnPosition, int rowPosition) {
selectionsLock.writeLock().lock();
try {
if (!multipleSelectionAllowed) {
selectedRows.clear();
}
R rowObject = getRowObjectByPosition(rowPosition);
if (rowObject != null) {
Serializable rowId = rowIdAccessor.getRowId(rowObject);
selectedRows.put(rowId, rowObject);
}
} finally {
selectionsLock.writeLock().unlock();
}
}
public void addSelection(Rectangle range) {
selectionsLock.writeLock().lock();
try {
if (multipleSelectionAllowed) {
if (range.equals(lastSelectedRange)) {
// Unselect all previously selected rowIds
if (lastSelectedRowIds != null) {
for (Serializable rowId : lastSelectedRowIds) {
selectedRows.remove(rowId);
}
}
}
} else {
selectedRows.clear();
}
Map<Serializable, R> rowsToSelect = new HashMap<Serializable, R>();
- for (int rowPosition = range.y; rowPosition < range.y + range.height; rowPosition++) {
+ int maxY = Math.min(range.y + range.height, selectionLayer.getRowCount());
+ for (int rowPosition = range.y; rowPosition < maxY; rowPosition++) {
R rowObject = getRowObjectByPosition(rowPosition);
if (rowObject != null) {
Serializable rowId = rowIdAccessor.getRowId(rowObject);
rowsToSelect.put(rowId, rowObject);
}
}
selectedRows.putAll(rowsToSelect);
if (range.equals(lastSelectedRange)) {
lastSelectedRowIds = rowsToSelect.keySet();
} else {
lastSelectedRowIds = null;
}
lastSelectedRange = range;
} finally {
selectionsLock.writeLock().unlock();
}
}
public void clearSelection() {
selectionsLock.writeLock().lock();
try {
selectedRows.clear();
} finally {
selectionsLock.writeLock().unlock();
}
}
public void clearSelection(int columnPosition, int rowPosition) {
selectionsLock.writeLock().lock();
try {
Serializable rowId = getRowIdByPosition(rowPosition);
selectedRows.remove(rowId);
} finally {
selectionsLock.writeLock().unlock();
}
}
public void clearSelection(Rectangle removedSelection) {
selectionsLock.writeLock().lock();
try {
for (int rowPosition = removedSelection.y; rowPosition < removedSelection.y + removedSelection.height; rowPosition++) {
clearSelection(0, rowPosition);
}
} finally {
selectionsLock.writeLock().unlock();
}
}
public void clearSelection(R rowObject) {
selectionsLock.writeLock().lock();
try {
selectedRows.values().remove(rowObject);
} finally {
selectionsLock.writeLock().unlock();
}
};
public boolean isEmpty() {
selectionsLock.readLock().lock();
try {
return selectedRows.isEmpty();
} finally {
selectionsLock.readLock().unlock();
}
}
public List<Rectangle> getSelections() {
List<Rectangle> selectionRectangles = new ArrayList<Rectangle>();
selectionsLock.readLock().lock();
try {
int width = selectionLayer.getColumnCount();
for (Serializable rowId : selectedRows.keySet()) {
int rowPosition = getRowPositionById(rowId);
selectionRectangles.add(new Rectangle(0, rowPosition, width, 1));
}
} finally {
selectionsLock.readLock().unlock();
}
return selectionRectangles;
}
// Cell features
public boolean isCellPositionSelected(int columnPosition, int rowPosition) {
ILayerCell cell = selectionLayer.getCellByPosition(columnPosition, rowPosition);
int cellOriginRowPosition = cell.getOriginRowPosition();
for (int testRowPosition = cellOriginRowPosition; testRowPosition < cellOriginRowPosition + cell.getRowSpan(); testRowPosition++) {
if (isRowPositionSelected(testRowPosition)) {
return true;
}
}
return false;
}
// Column features
public int[] getSelectedColumnPositions() {
if (!isEmpty()) {
selectionsLock.readLock().lock();
int columnCount;
try {
columnCount = selectionLayer.getColumnCount();
} finally {
selectionsLock.readLock().unlock();
}
int[] columns = new int[columnCount];
for (int i = 0; i < columnCount; i++) {
columns[i] = i;
}
return columns;
}
return new int[] {};
}
public boolean isColumnPositionSelected(int columnPosition) {
selectionsLock.readLock().lock();
try {
return !selectedRows.isEmpty();
} finally {
selectionsLock.readLock().unlock();
}
}
public int[] getFullySelectedColumnPositions(int fullySelectedColumnRowCount) {
selectionsLock.readLock().lock();
try {
if (isColumnPositionFullySelected(0, fullySelectedColumnRowCount)) {
return getSelectedColumnPositions();
}
} finally {
selectionsLock.readLock().unlock();
}
return new int[] {};
}
public boolean isColumnPositionFullySelected(int columnPosition, int fullySelectedColumnRowCount) {
selectionsLock.readLock().lock();
try {
int selectedRowCount = selectedRows.size();
if (selectedRowCount == 0) {
return false;
}
return selectedRowCount == fullySelectedColumnRowCount;
} finally {
selectionsLock.readLock().unlock();
}
}
// Row features
public List<R> getSelectedRowObjects() {
final List<R> rowObjects = new ArrayList<R>();
this.selectionsLock.readLock().lock();
try {
rowObjects.addAll(this.selectedRows.values());
} finally {
this.selectionsLock.readLock().unlock();
}
return rowObjects;
}
public int getSelectedRowCount() {
selectionsLock.readLock().lock();
try {
return selectedRows.size();
} finally {
selectionsLock.readLock().unlock();
}
}
public Set<Range> getSelectedRowPositions() {
Set<Range> selectedRowRanges = new HashSet<Range>();
selectionsLock.readLock().lock();
try {
for (Serializable rowId : selectedRows.keySet()) {
int rowPosition = getRowPositionById(rowId);
selectedRowRanges.add(new Range(rowPosition, rowPosition + 1));
}
} finally {
selectionsLock.readLock().unlock();
}
return selectedRowRanges;
}
public boolean isRowPositionSelected(int rowPosition) {
selectionsLock.readLock().lock();
try {
Serializable rowId = getRowIdByPosition(rowPosition);
return selectedRows.containsKey(rowId);
} finally {
selectionsLock.readLock().unlock();
}
}
public int[] getFullySelectedRowPositions(int rowWidth) {
selectionsLock.readLock().lock();
try {
int selectedRowCount = selectedRows.size();
int[] selectedRowPositions = new int[selectedRowCount];
int i = 0;
for (Serializable rowId : selectedRows.keySet()) {
selectedRowPositions[i] = getRowPositionById(rowId);
i++;
}
return selectedRowPositions;
} finally {
selectionsLock.readLock().unlock();
}
}
public boolean isRowPositionFullySelected(int rowPosition, int rowWidth) {
return isRowPositionSelected(rowPosition);
}
private Serializable getRowIdByPosition(int rowPosition) {
R rowObject = getRowObjectByPosition(rowPosition);
if (rowObject != null) {
Serializable rowId = rowIdAccessor.getRowId(rowObject);
return rowId;
}
return null;
}
private R getRowObjectByPosition(int rowPosition) {
selectionsLock.readLock().lock();
try {
int rowIndex = selectionLayer.getRowIndexByPosition(rowPosition);
if (rowIndex >= 0) {
try {
R rowObject = rowDataProvider.getRowObject(rowIndex);
return rowObject;
} catch (Exception e) {
// row index is invalid for the data provider
}
}
} finally {
selectionsLock.readLock().unlock();
}
return null;
}
private int getRowPositionById(Serializable rowId) {
selectionsLock.readLock().lock();
try {
R rowObject = selectedRows.get(rowId);
int rowIndex = rowDataProvider.indexOfRowObject(rowObject);
if(rowIndex == -1){
return -1;
}
int rowPosition = selectionLayer.getRowPositionByIndex(rowIndex);
return rowPosition;
} finally {
selectionsLock.readLock().unlock();
}
}
}
| true | true | public void addSelection(Rectangle range) {
selectionsLock.writeLock().lock();
try {
if (multipleSelectionAllowed) {
if (range.equals(lastSelectedRange)) {
// Unselect all previously selected rowIds
if (lastSelectedRowIds != null) {
for (Serializable rowId : lastSelectedRowIds) {
selectedRows.remove(rowId);
}
}
}
} else {
selectedRows.clear();
}
Map<Serializable, R> rowsToSelect = new HashMap<Serializable, R>();
for (int rowPosition = range.y; rowPosition < range.y + range.height; rowPosition++) {
R rowObject = getRowObjectByPosition(rowPosition);
if (rowObject != null) {
Serializable rowId = rowIdAccessor.getRowId(rowObject);
rowsToSelect.put(rowId, rowObject);
}
}
selectedRows.putAll(rowsToSelect);
if (range.equals(lastSelectedRange)) {
lastSelectedRowIds = rowsToSelect.keySet();
} else {
lastSelectedRowIds = null;
}
lastSelectedRange = range;
} finally {
selectionsLock.writeLock().unlock();
}
}
| public void addSelection(Rectangle range) {
selectionsLock.writeLock().lock();
try {
if (multipleSelectionAllowed) {
if (range.equals(lastSelectedRange)) {
// Unselect all previously selected rowIds
if (lastSelectedRowIds != null) {
for (Serializable rowId : lastSelectedRowIds) {
selectedRows.remove(rowId);
}
}
}
} else {
selectedRows.clear();
}
Map<Serializable, R> rowsToSelect = new HashMap<Serializable, R>();
int maxY = Math.min(range.y + range.height, selectionLayer.getRowCount());
for (int rowPosition = range.y; rowPosition < maxY; rowPosition++) {
R rowObject = getRowObjectByPosition(rowPosition);
if (rowObject != null) {
Serializable rowId = rowIdAccessor.getRowId(rowObject);
rowsToSelect.put(rowId, rowObject);
}
}
selectedRows.putAll(rowsToSelect);
if (range.equals(lastSelectedRange)) {
lastSelectedRowIds = rowsToSelect.keySet();
} else {
lastSelectedRowIds = null;
}
lastSelectedRange = range;
} finally {
selectionsLock.writeLock().unlock();
}
}
|
diff --git a/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/editors/completion/LocationDeterminator.java b/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/editors/completion/LocationDeterminator.java
index 3115b5c6..9df89944 100644
--- a/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/editors/completion/LocationDeterminator.java
+++ b/drools-eclipse/drools-eclipse-plugin/src/main/java/org/drools/eclipse/editors/completion/LocationDeterminator.java
@@ -1,560 +1,567 @@
package org.drools.eclipse.editors.completion;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.drools.compiler.DrlParser;
import org.drools.compiler.DroolsParserException;
import org.drools.lang.descr.AccumulateDescr;
import org.drools.lang.descr.AndDescr;
import org.drools.lang.descr.BaseDescr;
import org.drools.lang.descr.CollectDescr;
import org.drools.lang.descr.PatternDescr;
import org.drools.lang.descr.EvalDescr;
import org.drools.lang.descr.ExistsDescr;
import org.drools.lang.descr.FieldConstraintDescr;
import org.drools.lang.descr.FromDescr;
import org.drools.lang.descr.NotDescr;
import org.drools.lang.descr.OrDescr;
import org.drools.lang.descr.PackageDescr;
import org.drools.lang.descr.RestrictionConnectiveDescr;
import org.drools.lang.descr.RuleDescr;
public class LocationDeterminator {
static final Pattern PATTERN_PATTERN_START = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_OPERATOR = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_CONTAINS_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+contains\\s+[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_MATCHES_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+matches\\s+[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_EXCLUDES_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+excludes\\s+[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_IN_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+(not\\s+)?in\\s+[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_MEMBER_OF_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+(not\\s+)?memberOf\\s+[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_COMPARATOR_ARGUMENT = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s*([<>=!]+)\\s*[^\\s<>!=:]*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_CONTAINS_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+contains\\s+[^\\s<>!=:,]+\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_MATCHES_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+matches\\s+[^\\s<>!=:,]+\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_EXCLUDES_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+excludes\\s+[^\\s<>!=:,]+\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_IN_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+(not\\s+)?in\\s+\\([^\\)]+\\)\\s*", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_MEMBER_OF_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s+(not\\s+)?memberOf\\s+[^\\s<>!=:,]+\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN_COMPARATOR_END = Pattern.compile(".*[(,](\\s*(\\S*)\\s*:)?\\s*([^\\s<>!=:\\(\\)]+)\\s*([<>=!]+)\\s*[^\\s<>!=:,]+\\s+", Pattern.DOTALL);
static final Pattern PATTERN_PATTERN = Pattern.compile("((\\S+)\\s*:\\s*)?(\\S+)\\s*(\\(.*)", Pattern.DOTALL);
static final Pattern EXISTS_PATTERN = Pattern.compile(".*\\s+exists\\s*\\(?\\s*((\\S*)\\s*:)?\\s*\\S*", Pattern.DOTALL);
static final Pattern NOT_PATTERN = Pattern.compile(".*\\s+not\\s*\\(?\\s*((\\S*)\\s*:)?\\s*\\S*", Pattern.DOTALL);
static final Pattern EVAL_PATTERN = Pattern.compile(".*\\s+eval\\s*\\(\\s*([(^\\))(\\([^\\)]*\\)?)]*)", Pattern.DOTALL);
static final Pattern FROM_PATTERN = Pattern.compile(".*\\)\\s+from\\s+", Pattern.DOTALL);
static final Pattern ACCUMULATE_PATTERN = Pattern.compile(".*\\)\\s+from\\s+accumulate\\s*\\(\\s*", Pattern.DOTALL);
static final Pattern ACCUMULATE_PATTERN_INIT = Pattern.compile(".*,\\s*init\\s*\\(\\s*(.*)", Pattern.DOTALL);
static final Pattern ACCUMULATE_PATTERN_ACTION = Pattern.compile(".*,\\s*init\\s*\\(\\s*(.*)\\)\\s*,\\s*action\\s*\\(\\s*(.*)", Pattern.DOTALL);
static final Pattern ACCUMULATE_PATTERN_RESULT = Pattern.compile(".*,\\s*init\\s*\\(\\s*(.*)\\)\\s*,\\s*action\\s*\\(\\s*(.*)\\)\\s*,\\s*result\\s*\\(\\s*(.*)", Pattern.DOTALL);
static final Pattern COLLECT_PATTERN = Pattern.compile(".*\\)\\s+from\\s+collect\\s*\\(\\s*", Pattern.DOTALL);
static final Pattern THEN_PATTERN = Pattern.compile(".*\n\\s*when\\s*(.*)\n\\s*then\\s*(.*)", Pattern.DOTALL);
static final int LOCATION_UNKNOWN = 0;
static final int LOCATION_LHS_BEGIN_OF_CONDITION = 1;
static final int LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS = 2;
static final int LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR = 3;
static final int LOCATION_LHS_BEGIN_OF_CONDITION_NOT = 4;
static final int LOCATION_LHS_INSIDE_CONDITION_START = 100;
static final int LOCATION_LHS_INSIDE_CONDITION_OPERATOR = 101;
static final int LOCATION_LHS_INSIDE_CONDITION_ARGUMENT = 102;
static final int LOCATION_LHS_INSIDE_CONDITION_END = 103;
static final int LOCATION_LHS_INSIDE_EVAL = 200;
static final int LOCATION_LHS_FROM = 300;
static final int LOCATION_LHS_FROM_COLLECT = 301;
static final int LOCATION_LHS_FROM_ACCUMULATE = 302;
static final int LOCATION_LHS_FROM_ACCUMULATE_INIT = 303;
static final int LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE = 304;
static final int LOCATION_LHS_FROM_ACCUMULATE_ACTION = 305;
static final int LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE = 306;
static final int LOCATION_LHS_FROM_ACCUMULATE_RESULT = 307;
static final int LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE = 308;
static final int LOCATION_RHS = 1000;
static final int LOCATION_RULE_HEADER = 2000;
static final String LOCATION_PROPERTY_CLASS_NAME = "ClassName";
static final String LOCATION_PROPERTY_PROPERTY_NAME = "PropertyName";
static final String LOCATION_PROPERTY_OPERATOR = "Operator";
static final String LOCATION_EVAL_CONTENT = "EvalContent";
static final String LOCATION_FROM_CONTENT = "FromContent";
static final String LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT = "FromAccumulateInitContent";
static final String LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT = "FromAccumulateActionContent";
static final String LOCATION_PROPERTY_FROM_ACCUMULATE_RESULT_CONTENT = "FromAccumulateResultContent";
static final String LOCATION_LHS_CONTENT = "LHSContent";
static final String LOCATION_RHS_CONTENT = "RHSContent";
static final String LOCATION_HEADER_CONTENT = "HeaderContent";
private LocationDeterminator() {
}
public static class Location {
private int type;
private Map properties = new HashMap();
public Location(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setProperty(String name, Object value) {
properties.put(name, value);
}
public Object getProperty(String name) {
return properties.get(name);
}
void setType(int type) {
this.type = type;
}
}
public static Location getLocation(String backText) {
DrlParser parser = new DrlParser();
try {
PackageDescr packageDescr = parser.parse(backText);
List rules = packageDescr.getRules();
if (rules != null && rules.size() == 1) {
return determineLocationForDescr((RuleDescr) rules.get(0), backText);
}
} catch (DroolsParserException exc) {
// do nothing
}
return new Location(LOCATION_UNKNOWN);
}
public static Location determineLocationForDescr(BaseDescr descr, String backText) {
if (descr instanceof RuleDescr) {
RuleDescr ruleDescr = (RuleDescr) descr;
Object o = ruleDescr.getConsequence();
if (o == null) {
Matcher matcher = THEN_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_RHS);
location.setProperty(LOCATION_LHS_CONTENT, matcher.group(1));
location.setProperty(LOCATION_RHS_CONTENT, matcher.group(2));
return location;
}
}
AndDescr lhs = ruleDescr.getLhs();
if (lhs == null) {
return new Location(LOCATION_RULE_HEADER);
}
List subDescrs = lhs.getDescrs();
if (subDescrs.size() == 0) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
matcher = FROM_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM);
location.setProperty(LOCATION_FROM_CONTENT, "");
return location;
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
BaseDescr subDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
if (endReached(subDescr)) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
return determineLocationForDescr(subDescr, backText);
} else if (descr instanceof PatternDescr) {
PatternDescr patternDescr = (PatternDescr) descr;
// int locationType;
// String propertyName = null;
// String evaluator = null;
// boolean endOfConstraint = false;
// List subDescrs = columnDescr.getDescrs();
// if (subDescrs.size() > 0) {
// BaseDescr lastDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
// if (lastDescr.getEndCharacter() != -1) {
// endOfConstraint = true;
// }
// if (lastDescr instanceof FieldConstraintDescr) {
// FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
// propertyName = lastFieldDescr.getFieldName();
// List restrictions = lastFieldDescr.getRestrictions();
// if (restrictions.size() > 0) {
// RestrictionDescr restriction = (RestrictionDescr) restrictions.get(restrictions.size() - 1);
// if (restriction instanceof LiteralRestrictionDescr) {
// LiteralRestrictionDescr literal = (LiteralRestrictionDescr) restriction;
// evaluator = literal.getEvaluator();
// } else if (restriction instanceof VariableRestrictionDescr) {
// VariableRestrictionDescr variable = (VariableRestrictionDescr) restriction;
// evaluator = variable.getEvaluator();
// }
// }
// }
// }
// if (endOfConstraint) {
// locationType = LOCATION_INSIDE_CONDITION_END;
// } else if (evaluator != null) {
// locationType = LOCATION_INSIDE_CONDITION_ARGUMENT;
// } else if (propertyName != null) {
// locationType = LOCATION_INSIDE_CONDITION_OPERATOR;
// } else {
// locationType = LOCATION_INSIDE_CONDITION_START;
// }
// Location location = new Location(locationType);
// location.setProperty(LOCATION_PROPERTY_CLASS_NAME, columnDescr.getObjectType());
// location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, propertyName);
// location.setProperty(LOCATION_PROPERTY_OPERATOR, evaluator);
// return location;
// TODO: this is not completely safe, there are rare occasions where this could fail
Pattern pattern = Pattern.compile(".*(" + patternDescr.getObjectType() + ")\\s*\\((.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(backText);
String patternContents = null;
while (matcher.find()) {
patternContents = "(" + matcher.group(2);
}
if (patternContents == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
List subDescrs = patternDescr.getDescrs();
if (subDescrs.size() > 0) {
Object lastDescr = subDescrs.get(subDescrs.size() - 1);
if (lastDescr instanceof FieldConstraintDescr) {
FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
List restrictions = lastFieldDescr.getRestrictions();
+ // if there are multiple restrictions, filter out all the rest so that
+ // only the last one remains
+ if (restrictions.size() > 2) {
+ Object last = restrictions.get(restrictions.size() - 2);
+ if (last instanceof RestrictionConnectiveDescr) {
+ RestrictionConnectiveDescr lastRestr = (RestrictionConnectiveDescr) last;
+ char connective = '&';
+ if (lastRestr.getConnective() == RestrictionConnectiveDescr.OR) {
+ connective = '|';
+ }
+ int connectiveLocation = patternContents.lastIndexOf(connective);
+ patternContents = "( " + lastFieldDescr.getFieldName() + " " + patternContents.substring(connectiveLocation + 1);
+ }
+ }
if (restrictions.size() > 1) {
- // if there are multiple restrictions, filter out all the rest so that
- // only the last one remains
Object last = restrictions.get(restrictions.size() - 1);
if (last instanceof RestrictionConnectiveDescr) {
RestrictionConnectiveDescr lastRestr = (RestrictionConnectiveDescr) last;
char connective = '&';
if (lastRestr.getConnective() == RestrictionConnectiveDescr.OR) {
connective = '|';
}
int connectiveLocation = patternContents.lastIndexOf(connective);
patternContents = "( " + lastFieldDescr.getFieldName() + " " + patternContents.substring(connectiveLocation + 1);
}
-// else {
-// Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
-// location.setProperty(LOCATION_PROPERTY_CLASS_NAME, patternDescr.getObjectType());
-// return location;
-// }
}
}
}
return getLocationForPatttern(patternContents, patternDescr.getObjectType());
} else if (descr instanceof ExistsDescr) {
List subDescrs = ((ExistsDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
Location result = determineLocationForDescr(subDescr, backText);
if (result.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
result.setType(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
return result;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof NotDescr) {
List subDescrs = ((NotDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return location;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof AndDescr) {
List subDescrs = ((AndDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof OrDescr) {
List subDescrs = ((OrDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof FromDescr) {
Location location = new Location(LOCATION_LHS_FROM);
String content = CompletionUtil.stripWhiteSpace(backText);
location.setProperty(LOCATION_FROM_CONTENT, content);
return location;
} else if (descr instanceof AccumulateDescr) {
Matcher matcher = ACCUMULATE_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String accumulateText = backText.substring(end);
matcher = ACCUMULATE_PATTERN_RESULT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_RESULT_CONTENT, matcher.group(3));
return location;
}
matcher = ACCUMULATE_PATTERN_ACTION.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
return location;
}
matcher = ACCUMULATE_PATTERN_INIT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
return location;
}
matcher = PATTERN_PATTERN.matcher(accumulateText);
if (matcher.matches()) {
String className = matcher.group(3);
String patternContents = matcher.group(4);
return getLocationForPatttern(patternContents, className);
}
return new Location(LOCATION_LHS_FROM_ACCUMULATE);
} else if (descr instanceof CollectDescr) {
Matcher matcher = COLLECT_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String collectText = backText.substring(end);
matcher = PATTERN_PATTERN.matcher(collectText);
if (matcher.matches()) {
String className = matcher.group(3);
String columnContents = matcher.group(4);
return getLocationForPatttern(columnContents, className);
}
return new Location(LOCATION_LHS_FROM_COLLECT);
} else if (descr instanceof EvalDescr) {
Matcher matcher = EVAL_PATTERN.matcher(backText);
if (matcher.matches()) {
String content = matcher.group(1);
Location location = new Location(LOCATION_LHS_INSIDE_EVAL);
location.setProperty(LOCATION_EVAL_CONTENT, content);
return location;
}
}
return new Location(LOCATION_UNKNOWN);
}
private static boolean endReached(BaseDescr descr) {
if (descr == null) {
return false;
}
if (descr instanceof PatternDescr) {
return descr.getEndCharacter() != -1;
} else if (descr instanceof ExistsDescr) {
List descrs = ((ExistsDescr) descr).getDescrs();
if (descrs.isEmpty()) {
return false;
}
return endReached((BaseDescr) descrs.get(0));
} else if (descr instanceof NotDescr) {
List descrs = ((NotDescr) descr).getDescrs();
if (descrs.isEmpty()) {
return false;
}
return endReached((BaseDescr) descrs.get(0));
} else if (descr instanceof NotDescr) {
List descrs = ((NotDescr) descr).getDescrs();
if (descrs.isEmpty()) {
return false;
}
return endReached((BaseDescr) descrs.get(0));
} else if (descr instanceof AndDescr) {
List descrs = ((AndDescr) descr).getDescrs();
if (descrs.size() != 2) {
return false;
}
return endReached((BaseDescr) descrs.get(0))
&& endReached((BaseDescr) descrs.get(1));
} else if (descr instanceof OrDescr) {
List descrs = ((OrDescr) descr).getDescrs();
if (descrs.size() != 2) {
return false;
}
return endReached((BaseDescr) descrs.get(0))
&& endReached((BaseDescr) descrs.get(1));
} else if (descr instanceof EvalDescr) {
return ((EvalDescr) descr).getContent() != null;
}
return descr.getEndCharacter() != -1;
// else if (descr instanceof AccumulateDescr) {
// return ((AccumulateDescr) descr).getResultCode() != null;
// } else if (descr instanceof CollectDescr) {
// return ((CollectDescr) descr).getSourceColumn() != null;
// }
// return false;
}
private static Location getLocationForPatttern(String patternContents, String className) {
Matcher matcher = PATTERN_PATTERN_OPERATOR.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_OPERATOR);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
return location;
}
matcher = PATTERN_PATTERN_COMPARATOR_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, matcher.group(4));
return location;
}
matcher = PATTERN_PATTERN_CONTAINS_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, "contains");
return location;
}
matcher = PATTERN_PATTERN_EXCLUDES_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, "excludes");
return location;
}
matcher = PATTERN_PATTERN_IN_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, "in");
return location;
}
matcher = PATTERN_PATTERN_MEMBER_OF_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, "memberOf");
return location;
}
matcher = PATTERN_PATTERN_MATCHES_ARGUMENT.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_ARGUMENT);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, matcher.group(3));
location.setProperty(LOCATION_PROPERTY_OPERATOR, "matches");
return location;
}
matcher = PATTERN_PATTERN_CONTAINS_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_MATCHES_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_EXCLUDES_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_IN_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_MEMBER_OF_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_COMPARATOR_END.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
matcher = PATTERN_PATTERN_START.matcher(patternContents);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_START);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
location.setProperty(LOCATION_PROPERTY_CLASS_NAME, className);
return location;
}
}
| false | true | public static Location determineLocationForDescr(BaseDescr descr, String backText) {
if (descr instanceof RuleDescr) {
RuleDescr ruleDescr = (RuleDescr) descr;
Object o = ruleDescr.getConsequence();
if (o == null) {
Matcher matcher = THEN_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_RHS);
location.setProperty(LOCATION_LHS_CONTENT, matcher.group(1));
location.setProperty(LOCATION_RHS_CONTENT, matcher.group(2));
return location;
}
}
AndDescr lhs = ruleDescr.getLhs();
if (lhs == null) {
return new Location(LOCATION_RULE_HEADER);
}
List subDescrs = lhs.getDescrs();
if (subDescrs.size() == 0) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
matcher = FROM_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM);
location.setProperty(LOCATION_FROM_CONTENT, "");
return location;
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
BaseDescr subDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
if (endReached(subDescr)) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
return determineLocationForDescr(subDescr, backText);
} else if (descr instanceof PatternDescr) {
PatternDescr patternDescr = (PatternDescr) descr;
// int locationType;
// String propertyName = null;
// String evaluator = null;
// boolean endOfConstraint = false;
// List subDescrs = columnDescr.getDescrs();
// if (subDescrs.size() > 0) {
// BaseDescr lastDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
// if (lastDescr.getEndCharacter() != -1) {
// endOfConstraint = true;
// }
// if (lastDescr instanceof FieldConstraintDescr) {
// FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
// propertyName = lastFieldDescr.getFieldName();
// List restrictions = lastFieldDescr.getRestrictions();
// if (restrictions.size() > 0) {
// RestrictionDescr restriction = (RestrictionDescr) restrictions.get(restrictions.size() - 1);
// if (restriction instanceof LiteralRestrictionDescr) {
// LiteralRestrictionDescr literal = (LiteralRestrictionDescr) restriction;
// evaluator = literal.getEvaluator();
// } else if (restriction instanceof VariableRestrictionDescr) {
// VariableRestrictionDescr variable = (VariableRestrictionDescr) restriction;
// evaluator = variable.getEvaluator();
// }
// }
// }
// }
// if (endOfConstraint) {
// locationType = LOCATION_INSIDE_CONDITION_END;
// } else if (evaluator != null) {
// locationType = LOCATION_INSIDE_CONDITION_ARGUMENT;
// } else if (propertyName != null) {
// locationType = LOCATION_INSIDE_CONDITION_OPERATOR;
// } else {
// locationType = LOCATION_INSIDE_CONDITION_START;
// }
// Location location = new Location(locationType);
// location.setProperty(LOCATION_PROPERTY_CLASS_NAME, columnDescr.getObjectType());
// location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, propertyName);
// location.setProperty(LOCATION_PROPERTY_OPERATOR, evaluator);
// return location;
// TODO: this is not completely safe, there are rare occasions where this could fail
Pattern pattern = Pattern.compile(".*(" + patternDescr.getObjectType() + ")\\s*\\((.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(backText);
String patternContents = null;
while (matcher.find()) {
patternContents = "(" + matcher.group(2);
}
if (patternContents == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
List subDescrs = patternDescr.getDescrs();
if (subDescrs.size() > 0) {
Object lastDescr = subDescrs.get(subDescrs.size() - 1);
if (lastDescr instanceof FieldConstraintDescr) {
FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
List restrictions = lastFieldDescr.getRestrictions();
if (restrictions.size() > 1) {
// if there are multiple restrictions, filter out all the rest so that
// only the last one remains
Object last = restrictions.get(restrictions.size() - 1);
if (last instanceof RestrictionConnectiveDescr) {
RestrictionConnectiveDescr lastRestr = (RestrictionConnectiveDescr) last;
char connective = '&';
if (lastRestr.getConnective() == RestrictionConnectiveDescr.OR) {
connective = '|';
}
int connectiveLocation = patternContents.lastIndexOf(connective);
patternContents = "( " + lastFieldDescr.getFieldName() + " " + patternContents.substring(connectiveLocation + 1);
}
// else {
// Location location = new Location(LOCATION_LHS_INSIDE_CONDITION_END);
// location.setProperty(LOCATION_PROPERTY_CLASS_NAME, patternDescr.getObjectType());
// return location;
// }
}
}
}
return getLocationForPatttern(patternContents, patternDescr.getObjectType());
} else if (descr instanceof ExistsDescr) {
List subDescrs = ((ExistsDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
Location result = determineLocationForDescr(subDescr, backText);
if (result.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
result.setType(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
return result;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof NotDescr) {
List subDescrs = ((NotDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return location;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof AndDescr) {
List subDescrs = ((AndDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof OrDescr) {
List subDescrs = ((OrDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof FromDescr) {
Location location = new Location(LOCATION_LHS_FROM);
String content = CompletionUtil.stripWhiteSpace(backText);
location.setProperty(LOCATION_FROM_CONTENT, content);
return location;
} else if (descr instanceof AccumulateDescr) {
Matcher matcher = ACCUMULATE_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String accumulateText = backText.substring(end);
matcher = ACCUMULATE_PATTERN_RESULT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_RESULT_CONTENT, matcher.group(3));
return location;
}
matcher = ACCUMULATE_PATTERN_ACTION.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
return location;
}
matcher = ACCUMULATE_PATTERN_INIT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
return location;
}
matcher = PATTERN_PATTERN.matcher(accumulateText);
if (matcher.matches()) {
String className = matcher.group(3);
String patternContents = matcher.group(4);
return getLocationForPatttern(patternContents, className);
}
return new Location(LOCATION_LHS_FROM_ACCUMULATE);
} else if (descr instanceof CollectDescr) {
Matcher matcher = COLLECT_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String collectText = backText.substring(end);
matcher = PATTERN_PATTERN.matcher(collectText);
if (matcher.matches()) {
String className = matcher.group(3);
String columnContents = matcher.group(4);
return getLocationForPatttern(columnContents, className);
}
return new Location(LOCATION_LHS_FROM_COLLECT);
} else if (descr instanceof EvalDescr) {
Matcher matcher = EVAL_PATTERN.matcher(backText);
if (matcher.matches()) {
String content = matcher.group(1);
Location location = new Location(LOCATION_LHS_INSIDE_EVAL);
location.setProperty(LOCATION_EVAL_CONTENT, content);
return location;
}
}
return new Location(LOCATION_UNKNOWN);
}
| public static Location determineLocationForDescr(BaseDescr descr, String backText) {
if (descr instanceof RuleDescr) {
RuleDescr ruleDescr = (RuleDescr) descr;
Object o = ruleDescr.getConsequence();
if (o == null) {
Matcher matcher = THEN_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_RHS);
location.setProperty(LOCATION_LHS_CONTENT, matcher.group(1));
location.setProperty(LOCATION_RHS_CONTENT, matcher.group(2));
return location;
}
}
AndDescr lhs = ruleDescr.getLhs();
if (lhs == null) {
return new Location(LOCATION_RULE_HEADER);
}
List subDescrs = lhs.getDescrs();
if (subDescrs.size() == 0) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
matcher = FROM_PATTERN.matcher(backText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM);
location.setProperty(LOCATION_FROM_CONTENT, "");
return location;
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
BaseDescr subDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
if (endReached(subDescr)) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
return determineLocationForDescr(subDescr, backText);
} else if (descr instanceof PatternDescr) {
PatternDescr patternDescr = (PatternDescr) descr;
// int locationType;
// String propertyName = null;
// String evaluator = null;
// boolean endOfConstraint = false;
// List subDescrs = columnDescr.getDescrs();
// if (subDescrs.size() > 0) {
// BaseDescr lastDescr = (BaseDescr) subDescrs.get(subDescrs.size() - 1);
// if (lastDescr.getEndCharacter() != -1) {
// endOfConstraint = true;
// }
// if (lastDescr instanceof FieldConstraintDescr) {
// FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
// propertyName = lastFieldDescr.getFieldName();
// List restrictions = lastFieldDescr.getRestrictions();
// if (restrictions.size() > 0) {
// RestrictionDescr restriction = (RestrictionDescr) restrictions.get(restrictions.size() - 1);
// if (restriction instanceof LiteralRestrictionDescr) {
// LiteralRestrictionDescr literal = (LiteralRestrictionDescr) restriction;
// evaluator = literal.getEvaluator();
// } else if (restriction instanceof VariableRestrictionDescr) {
// VariableRestrictionDescr variable = (VariableRestrictionDescr) restriction;
// evaluator = variable.getEvaluator();
// }
// }
// }
// }
// if (endOfConstraint) {
// locationType = LOCATION_INSIDE_CONDITION_END;
// } else if (evaluator != null) {
// locationType = LOCATION_INSIDE_CONDITION_ARGUMENT;
// } else if (propertyName != null) {
// locationType = LOCATION_INSIDE_CONDITION_OPERATOR;
// } else {
// locationType = LOCATION_INSIDE_CONDITION_START;
// }
// Location location = new Location(locationType);
// location.setProperty(LOCATION_PROPERTY_CLASS_NAME, columnDescr.getObjectType());
// location.setProperty(LOCATION_PROPERTY_PROPERTY_NAME, propertyName);
// location.setProperty(LOCATION_PROPERTY_OPERATOR, evaluator);
// return location;
// TODO: this is not completely safe, there are rare occasions where this could fail
Pattern pattern = Pattern.compile(".*(" + patternDescr.getObjectType() + ")\\s*\\((.*)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(backText);
String patternContents = null;
while (matcher.find()) {
patternContents = "(" + matcher.group(2);
}
if (patternContents == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION);
}
List subDescrs = patternDescr.getDescrs();
if (subDescrs.size() > 0) {
Object lastDescr = subDescrs.get(subDescrs.size() - 1);
if (lastDescr instanceof FieldConstraintDescr) {
FieldConstraintDescr lastFieldDescr = (FieldConstraintDescr) lastDescr;
List restrictions = lastFieldDescr.getRestrictions();
// if there are multiple restrictions, filter out all the rest so that
// only the last one remains
if (restrictions.size() > 2) {
Object last = restrictions.get(restrictions.size() - 2);
if (last instanceof RestrictionConnectiveDescr) {
RestrictionConnectiveDescr lastRestr = (RestrictionConnectiveDescr) last;
char connective = '&';
if (lastRestr.getConnective() == RestrictionConnectiveDescr.OR) {
connective = '|';
}
int connectiveLocation = patternContents.lastIndexOf(connective);
patternContents = "( " + lastFieldDescr.getFieldName() + " " + patternContents.substring(connectiveLocation + 1);
}
}
if (restrictions.size() > 1) {
Object last = restrictions.get(restrictions.size() - 1);
if (last instanceof RestrictionConnectiveDescr) {
RestrictionConnectiveDescr lastRestr = (RestrictionConnectiveDescr) last;
char connective = '&';
if (lastRestr.getConnective() == RestrictionConnectiveDescr.OR) {
connective = '|';
}
int connectiveLocation = patternContents.lastIndexOf(connective);
patternContents = "( " + lastFieldDescr.getFieldName() + " " + patternContents.substring(connectiveLocation + 1);
}
}
}
}
return getLocationForPatttern(patternContents, patternDescr.getObjectType());
} else if (descr instanceof ExistsDescr) {
List subDescrs = ((ExistsDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
Location result = determineLocationForDescr(subDescr, backText);
if (result.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
result.setType(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
return result;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof NotDescr) {
List subDescrs = ((NotDescr) descr).getDescrs();
if (subDescrs.size() == 0) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
if (subDescrs.size() == 1) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(0);
if (subDescr == null) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return location;
}
return determineLocationForDescr(descr, backText);
} else if (descr instanceof AndDescr) {
List subDescrs = ((AndDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof OrDescr) {
List subDescrs = ((OrDescr) descr).getDescrs();
int size = subDescrs.size();
if (size == 2) {
BaseDescr subDescr = (BaseDescr) subDescrs.get(1);
if (subDescr == null) {
Matcher matcher = EXISTS_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_EXISTS);
}
matcher = NOT_PATTERN.matcher(backText);
if (matcher.matches()) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_NOT);
}return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
} else {
Location location = determineLocationForDescr(subDescr, backText);
if (location.getType() == LOCATION_LHS_BEGIN_OF_CONDITION) {
return new Location(LOCATION_LHS_BEGIN_OF_CONDITION_AND_OR);
}
return location;
}
}
return new Location(LOCATION_UNKNOWN);
} else if (descr instanceof FromDescr) {
Location location = new Location(LOCATION_LHS_FROM);
String content = CompletionUtil.stripWhiteSpace(backText);
location.setProperty(LOCATION_FROM_CONTENT, content);
return location;
} else if (descr instanceof AccumulateDescr) {
Matcher matcher = ACCUMULATE_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String accumulateText = backText.substring(end);
matcher = ACCUMULATE_PATTERN_RESULT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_RESULT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_RESULT_CONTENT, matcher.group(3));
return location;
}
matcher = ACCUMULATE_PATTERN_ACTION.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_ACTION_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_ACTION_CONTENT, matcher.group(2));
return location;
}
matcher = ACCUMULATE_PATTERN_INIT.matcher(accumulateText);
if (matcher.matches()) {
Location location = new Location(LOCATION_LHS_FROM_ACCUMULATE_INIT_INSIDE);
location.setProperty(LOCATION_PROPERTY_FROM_ACCUMULATE_INIT_CONTENT, matcher.group(1));
return location;
}
matcher = PATTERN_PATTERN.matcher(accumulateText);
if (matcher.matches()) {
String className = matcher.group(3);
String patternContents = matcher.group(4);
return getLocationForPatttern(patternContents, className);
}
return new Location(LOCATION_LHS_FROM_ACCUMULATE);
} else if (descr instanceof CollectDescr) {
Matcher matcher = COLLECT_PATTERN.matcher(backText);
int end = -1;
while (matcher.find()) {
end = matcher.end();
}
String collectText = backText.substring(end);
matcher = PATTERN_PATTERN.matcher(collectText);
if (matcher.matches()) {
String className = matcher.group(3);
String columnContents = matcher.group(4);
return getLocationForPatttern(columnContents, className);
}
return new Location(LOCATION_LHS_FROM_COLLECT);
} else if (descr instanceof EvalDescr) {
Matcher matcher = EVAL_PATTERN.matcher(backText);
if (matcher.matches()) {
String content = matcher.group(1);
Location location = new Location(LOCATION_LHS_INSIDE_EVAL);
location.setProperty(LOCATION_EVAL_CONTENT, content);
return location;
}
}
return new Location(LOCATION_UNKNOWN);
}
|
diff --git a/src/com/android/contacts/calllog/DefaultVoicemailNotifier.java b/src/com/android/contacts/calllog/DefaultVoicemailNotifier.java
index c5e8f918b..c20ef3df7 100644
--- a/src/com/android/contacts/calllog/DefaultVoicemailNotifier.java
+++ b/src/com/android/contacts/calllog/DefaultVoicemailNotifier.java
@@ -1,323 +1,323 @@
/*
* 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.contacts.calllog;
import com.android.common.io.MoreCloseables;
import com.android.contacts.CallDetailActivity;
import com.android.contacts.R;
import com.google.common.collect.Maps;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract.PhoneLookup;
import android.text.TextUtils;
import android.util.Log;
import java.util.Map;
/**
* Implementation of {@link VoicemailNotifier} that shows a notification in the
* status bar.
*/
public class DefaultVoicemailNotifier implements VoicemailNotifier {
public static final String TAG = "DefaultVoicemailNotifier";
/** The tag used to identify notifications from this class. */
private static final String NOTIFICATION_TAG = "DefaultVoicemailNotifier";
/** The identifier of the notification of new voicemails. */
private static final int NOTIFICATION_ID = 1;
/** The singleton instance of {@link DefaultVoicemailNotifier}. */
private static DefaultVoicemailNotifier sInstance;
private final Context mContext;
private final NotificationManager mNotificationManager;
private final NewCallsQuery mNewCallsQuery;
private final NameLookupQuery mNameLookupQuery;
private final PhoneNumberHelper mPhoneNumberHelper;
/** Returns the singleton instance of the {@link DefaultVoicemailNotifier}. */
public static synchronized DefaultVoicemailNotifier getInstance(Context context) {
if (sInstance == null) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
ContentResolver contentResolver = context.getContentResolver();
sInstance = new DefaultVoicemailNotifier(context, notificationManager,
createNewCallsQuery(contentResolver),
createNameLookupQuery(contentResolver),
createPhoneNumberHelper(context));
}
return sInstance;
}
private DefaultVoicemailNotifier(Context context,
NotificationManager notificationManager, NewCallsQuery newCallsQuery,
NameLookupQuery nameLookupQuery, PhoneNumberHelper phoneNumberHelper) {
mContext = context;
mNotificationManager = notificationManager;
mNewCallsQuery = newCallsQuery;
mNameLookupQuery = nameLookupQuery;
mPhoneNumberHelper = phoneNumberHelper;
}
/** Updates the notification and notifies of the call with the given URI. */
@Override
public void updateNotification(Uri newCallUri) {
// Lookup the list of new voicemails to include in the notification.
// TODO: Move this into a service, to avoid holding the receiver up.
final NewCall[] newCalls = mNewCallsQuery.query();
if (newCalls.length == 0) {
- Log.e(TAG, "No voicemails to notify about: clear the notification.");
+ // No voicemails to notify about: clear the notification.
clearNotification();
return;
}
Resources resources = mContext.getResources();
// This represents a list of names to include in the notification.
String callers = null;
// Maps each number into a name: if a number is in the map, it has already left a more
// recent voicemail.
final Map<String, String> names = Maps.newHashMap();
// Determine the call corresponding to the new voicemail we have to notify about.
NewCall callToNotify = null;
// Iterate over the new voicemails to determine all the information above.
for (NewCall newCall : newCalls) {
// Check if we already know the name associated with this number.
String name = names.get(newCall.number);
if (name == null) {
// Look it up in the database.
name = mNameLookupQuery.query(newCall.number);
// If we cannot lookup the contact, use the number instead.
if (name == null) {
name = mPhoneNumberHelper.getDisplayNumber(newCall.number, "").toString();
if (TextUtils.isEmpty(name)) {
name = newCall.number;
}
}
names.put(newCall.number, name);
// This is a new caller. Add it to the back of the list of callers.
if (TextUtils.isEmpty(callers)) {
callers = name;
} else {
callers = resources.getString(
R.string.notification_voicemail_callers_list, callers, name);
}
}
// Check if this is the new call we need to notify about.
if (newCallUri != null && newCallUri.equals(newCall.voicemailUri)) {
callToNotify = newCall;
}
}
if (newCallUri != null && callToNotify == null) {
Log.e(TAG, "The new call could not be found in the call log: " + newCallUri);
}
// Determine the title of the notification and the icon for it.
final String title = resources.getQuantityString(
R.plurals.notification_voicemail_title, newCalls.length, newCalls.length);
// TODO: Use the photo of contact if all calls are from the same person.
final int icon = android.R.drawable.stat_notify_voicemail;
Notification notification = new Notification.Builder(mContext)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(callers)
.setDefaults(callToNotify != null ? Notification.DEFAULT_ALL : 0)
.setDeleteIntent(createMarkNewVoicemailsAsOldIntent())
.setAutoCancel(true)
.getNotification();
// Determine the intent to fire when the notification is clicked on.
final Intent contentIntent;
if (newCalls.length == 1) {
// Open the voicemail directly.
contentIntent = new Intent(mContext, CallDetailActivity.class);
contentIntent.setData(newCalls[0].callsUri);
contentIntent.putExtra(CallDetailActivity.EXTRA_VOICEMAIL_URI,
newCalls[0].voicemailUri);
} else {
// Open the call log.
contentIntent = new Intent(Intent.ACTION_VIEW, Calls.CONTENT_URI);
}
notification.contentIntent = PendingIntent.getActivity(mContext, 0, contentIntent, 0);
// The text to show in the ticker, describing the new event.
if (callToNotify != null) {
notification.tickerText = resources.getString(
R.string.notification_new_voicemail_ticker, names.get(callToNotify.number));
}
mNotificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification);
}
/** Creates a pending intent that marks all new voicemails as old. */
private PendingIntent createMarkNewVoicemailsAsOldIntent() {
Intent intent = new Intent(mContext, CallLogNotificationsService.class);
intent.setAction(CallLogNotificationsService.ACTION_MARK_NEW_VOICEMAILS_AS_OLD);
return PendingIntent.getService(mContext, 0, intent, 0);
}
@Override
public void clearNotification() {
mNotificationManager.cancel(NOTIFICATION_TAG, NOTIFICATION_ID);
}
/** Information about a new voicemail. */
private static final class NewCall {
public final Uri callsUri;
public final Uri voicemailUri;
public final String number;
public NewCall(Uri callsUri, Uri voicemailUri, String number) {
this.callsUri = callsUri;
this.voicemailUri = voicemailUri;
this.number = number;
}
}
/** Allows determining the new calls for which a notification should be generated. */
public interface NewCallsQuery {
/**
* Returns the new calls for which a notification should be generated.
*/
public NewCall[] query();
}
/** Create a new instance of {@link NewCallsQuery}. */
public static NewCallsQuery createNewCallsQuery(ContentResolver contentResolver) {
return new DefaultNewCallsQuery(contentResolver);
}
/**
* Default implementation of {@link NewCallsQuery} that looks up the list of new calls to
* notify about in the call log.
*/
private static final class DefaultNewCallsQuery implements NewCallsQuery {
private static final String[] PROJECTION = {
Calls._ID, Calls.NUMBER, Calls.VOICEMAIL_URI
};
private static final int ID_COLUMN_INDEX = 0;
private static final int NUMBER_COLUMN_INDEX = 1;
private static final int VOICEMAIL_URI_COLUMN_INDEX = 2;
private final ContentResolver mContentResolver;
private DefaultNewCallsQuery(ContentResolver contentResolver) {
mContentResolver = contentResolver;
}
@Override
public NewCall[] query() {
final String selection = String.format("%s = 1 AND %s = ?", Calls.NEW, Calls.TYPE);
final String[] selectionArgs = new String[]{ Integer.toString(Calls.VOICEMAIL_TYPE) };
Cursor cursor = null;
try {
cursor = mContentResolver.query(Calls.CONTENT_URI_WITH_VOICEMAIL, PROJECTION,
selection, selectionArgs, Calls.DEFAULT_SORT_ORDER);
NewCall[] newCalls = new NewCall[cursor.getCount()];
while (cursor.moveToNext()) {
newCalls[cursor.getPosition()] = createNewCallsFromCursor(cursor);
}
return newCalls;
} finally {
MoreCloseables.closeQuietly(cursor);
}
}
/** Returns an instance of {@link NewCall} created by using the values of the cursor. */
private NewCall createNewCallsFromCursor(Cursor cursor) {
String voicemailUriString = cursor.getString(VOICEMAIL_URI_COLUMN_INDEX);
Uri callsUri = ContentUris.withAppendedId(
Calls.CONTENT_URI_WITH_VOICEMAIL, cursor.getLong(ID_COLUMN_INDEX));
Uri voicemailUri = voicemailUriString == null ? null : Uri.parse(voicemailUriString);
return new NewCall(callsUri, voicemailUri, cursor.getString(NUMBER_COLUMN_INDEX));
}
}
/** Allows determining the name associated with a given phone number. */
public interface NameLookupQuery {
/**
* Returns the name associated with the given number in the contacts database, or null if
* the number does not correspond to any of the contacts.
* <p>
* If there are multiple contacts with the same phone number, it will return the name of one
* of the matching contacts.
*/
public String query(String number);
}
/** Create a new instance of {@link NameLookupQuery}. */
public static NameLookupQuery createNameLookupQuery(ContentResolver contentResolver) {
return new DefaultNameLookupQuery(contentResolver);
}
/**
* Default implementation of {@link NameLookupQuery} that looks up the name of a contact in the
* contacts database.
*/
private static final class DefaultNameLookupQuery implements NameLookupQuery {
private static final String[] PROJECTION = { PhoneLookup.DISPLAY_NAME };
private static final int DISPLAY_NAME_COLUMN_INDEX = 0;
private final ContentResolver mContentResolver;
private DefaultNameLookupQuery(ContentResolver contentResolver) {
mContentResolver = contentResolver;
}
@Override
public String query(String number) {
Cursor cursor = null;
try {
cursor = mContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)),
PROJECTION, null, null, null);
if (!cursor.moveToFirst()) return null;
return cursor.getString(DISPLAY_NAME_COLUMN_INDEX);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
/**
* Create a new PhoneNumberHelper.
* <p>
* This will cause some Disk I/O, at least the first time it is created, so it should not be
* called from the main thread.
*/
public static PhoneNumberHelper createPhoneNumberHelper(Context context) {
return new PhoneNumberHelper(context.getResources());
}
}
| true | true | public void updateNotification(Uri newCallUri) {
// Lookup the list of new voicemails to include in the notification.
// TODO: Move this into a service, to avoid holding the receiver up.
final NewCall[] newCalls = mNewCallsQuery.query();
if (newCalls.length == 0) {
Log.e(TAG, "No voicemails to notify about: clear the notification.");
clearNotification();
return;
}
Resources resources = mContext.getResources();
// This represents a list of names to include in the notification.
String callers = null;
// Maps each number into a name: if a number is in the map, it has already left a more
// recent voicemail.
final Map<String, String> names = Maps.newHashMap();
// Determine the call corresponding to the new voicemail we have to notify about.
NewCall callToNotify = null;
// Iterate over the new voicemails to determine all the information above.
for (NewCall newCall : newCalls) {
// Check if we already know the name associated with this number.
String name = names.get(newCall.number);
if (name == null) {
// Look it up in the database.
name = mNameLookupQuery.query(newCall.number);
// If we cannot lookup the contact, use the number instead.
if (name == null) {
name = mPhoneNumberHelper.getDisplayNumber(newCall.number, "").toString();
if (TextUtils.isEmpty(name)) {
name = newCall.number;
}
}
names.put(newCall.number, name);
// This is a new caller. Add it to the back of the list of callers.
if (TextUtils.isEmpty(callers)) {
callers = name;
} else {
callers = resources.getString(
R.string.notification_voicemail_callers_list, callers, name);
}
}
// Check if this is the new call we need to notify about.
if (newCallUri != null && newCallUri.equals(newCall.voicemailUri)) {
callToNotify = newCall;
}
}
if (newCallUri != null && callToNotify == null) {
Log.e(TAG, "The new call could not be found in the call log: " + newCallUri);
}
// Determine the title of the notification and the icon for it.
final String title = resources.getQuantityString(
R.plurals.notification_voicemail_title, newCalls.length, newCalls.length);
// TODO: Use the photo of contact if all calls are from the same person.
final int icon = android.R.drawable.stat_notify_voicemail;
Notification notification = new Notification.Builder(mContext)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(callers)
.setDefaults(callToNotify != null ? Notification.DEFAULT_ALL : 0)
.setDeleteIntent(createMarkNewVoicemailsAsOldIntent())
.setAutoCancel(true)
.getNotification();
// Determine the intent to fire when the notification is clicked on.
final Intent contentIntent;
if (newCalls.length == 1) {
// Open the voicemail directly.
contentIntent = new Intent(mContext, CallDetailActivity.class);
contentIntent.setData(newCalls[0].callsUri);
contentIntent.putExtra(CallDetailActivity.EXTRA_VOICEMAIL_URI,
newCalls[0].voicemailUri);
} else {
// Open the call log.
contentIntent = new Intent(Intent.ACTION_VIEW, Calls.CONTENT_URI);
}
notification.contentIntent = PendingIntent.getActivity(mContext, 0, contentIntent, 0);
// The text to show in the ticker, describing the new event.
if (callToNotify != null) {
notification.tickerText = resources.getString(
R.string.notification_new_voicemail_ticker, names.get(callToNotify.number));
}
mNotificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification);
}
| public void updateNotification(Uri newCallUri) {
// Lookup the list of new voicemails to include in the notification.
// TODO: Move this into a service, to avoid holding the receiver up.
final NewCall[] newCalls = mNewCallsQuery.query();
if (newCalls.length == 0) {
// No voicemails to notify about: clear the notification.
clearNotification();
return;
}
Resources resources = mContext.getResources();
// This represents a list of names to include in the notification.
String callers = null;
// Maps each number into a name: if a number is in the map, it has already left a more
// recent voicemail.
final Map<String, String> names = Maps.newHashMap();
// Determine the call corresponding to the new voicemail we have to notify about.
NewCall callToNotify = null;
// Iterate over the new voicemails to determine all the information above.
for (NewCall newCall : newCalls) {
// Check if we already know the name associated with this number.
String name = names.get(newCall.number);
if (name == null) {
// Look it up in the database.
name = mNameLookupQuery.query(newCall.number);
// If we cannot lookup the contact, use the number instead.
if (name == null) {
name = mPhoneNumberHelper.getDisplayNumber(newCall.number, "").toString();
if (TextUtils.isEmpty(name)) {
name = newCall.number;
}
}
names.put(newCall.number, name);
// This is a new caller. Add it to the back of the list of callers.
if (TextUtils.isEmpty(callers)) {
callers = name;
} else {
callers = resources.getString(
R.string.notification_voicemail_callers_list, callers, name);
}
}
// Check if this is the new call we need to notify about.
if (newCallUri != null && newCallUri.equals(newCall.voicemailUri)) {
callToNotify = newCall;
}
}
if (newCallUri != null && callToNotify == null) {
Log.e(TAG, "The new call could not be found in the call log: " + newCallUri);
}
// Determine the title of the notification and the icon for it.
final String title = resources.getQuantityString(
R.plurals.notification_voicemail_title, newCalls.length, newCalls.length);
// TODO: Use the photo of contact if all calls are from the same person.
final int icon = android.R.drawable.stat_notify_voicemail;
Notification notification = new Notification.Builder(mContext)
.setSmallIcon(icon)
.setContentTitle(title)
.setContentText(callers)
.setDefaults(callToNotify != null ? Notification.DEFAULT_ALL : 0)
.setDeleteIntent(createMarkNewVoicemailsAsOldIntent())
.setAutoCancel(true)
.getNotification();
// Determine the intent to fire when the notification is clicked on.
final Intent contentIntent;
if (newCalls.length == 1) {
// Open the voicemail directly.
contentIntent = new Intent(mContext, CallDetailActivity.class);
contentIntent.setData(newCalls[0].callsUri);
contentIntent.putExtra(CallDetailActivity.EXTRA_VOICEMAIL_URI,
newCalls[0].voicemailUri);
} else {
// Open the call log.
contentIntent = new Intent(Intent.ACTION_VIEW, Calls.CONTENT_URI);
}
notification.contentIntent = PendingIntent.getActivity(mContext, 0, contentIntent, 0);
// The text to show in the ticker, describing the new event.
if (callToNotify != null) {
notification.tickerText = resources.getString(
R.string.notification_new_voicemail_ticker, names.get(callToNotify.number));
}
mNotificationManager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification);
}
|
diff --git a/modules/srm/src/main/java/org/dcache/srm/scheduler/SchedulerFactory.java b/modules/srm/src/main/java/org/dcache/srm/scheduler/SchedulerFactory.java
index 5890dd41fe..8656644ae4 100644
--- a/modules/srm/src/main/java/org/dcache/srm/scheduler/SchedulerFactory.java
+++ b/modules/srm/src/main/java/org/dcache/srm/scheduler/SchedulerFactory.java
@@ -1,161 +1,161 @@
package org.dcache.srm.scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import org.dcache.srm.request.BringOnlineFileRequest;
import org.dcache.srm.request.CopyRequest;
import org.dcache.srm.request.GetFileRequest;
import org.dcache.srm.request.Job;
import org.dcache.srm.request.LsFileRequest;
import org.dcache.srm.request.PutFileRequest;
import org.dcache.srm.request.ReserveSpaceRequest;
import org.dcache.srm.util.Configuration;
/**
*
* @author timur
*/
public class SchedulerFactory {
private static final Logger logger = LoggerFactory.getLogger(SchedulerFactory.class);
private final Map<Class<? extends Job>,Scheduler> schedulerMap;
private static SchedulerFactory factory;
private SchedulerFactory(Configuration config, String name) {
schedulerMap = new HashMap<>();
Scheduler lsRequestScheduler = new Scheduler("ls_" + name, LsFileRequest.class);
// scheduler parameters
lsRequestScheduler.setMaxThreadQueueSize(config.getLsReqTQueueSize());
lsRequestScheduler.setThreadPoolSize(config.getLsThreadPoolSize());
lsRequestScheduler.setMaxWaitingJobNum(config.getLsMaxWaitingRequests());
lsRequestScheduler.setMaxReadyQueueSize(config.getLsReadyQueueSize());
lsRequestScheduler.setMaxReadyJobs(config.getLsMaxReadyJobs());
lsRequestScheduler.setMaxNumberOfRetries(config.getLsMaxNumOfRetries());
lsRequestScheduler.setRetryTimeout(config.getLsRetryTimeout());
lsRequestScheduler.setMaxRunningByOwner(config.getLsMaxRunningBySameOwner());
lsRequestScheduler.setPriorityPolicyPlugin(config.getLsPriorityPolicyPlugin());
lsRequestScheduler.start();
schedulerMap.put(LsFileRequest.class,lsRequestScheduler);
Scheduler getRequestScheduler = new Scheduler("get_" + name, GetFileRequest.class);
// scheduler parameters
getRequestScheduler.setMaxThreadQueueSize(config.getGetReqTQueueSize());
getRequestScheduler.setThreadPoolSize(config.getGetThreadPoolSize());
getRequestScheduler.setMaxWaitingJobNum(config.getGetMaxWaitingRequests());
getRequestScheduler.setMaxReadyQueueSize(config.getGetReadyQueueSize());
getRequestScheduler.setMaxReadyJobs(config.getGetMaxReadyJobs());
getRequestScheduler.setMaxNumberOfRetries(config.getGetMaxNumOfRetries());
getRequestScheduler.setRetryTimeout(config.getGetRetryTimeout());
getRequestScheduler.setMaxRunningByOwner(config.getGetMaxRunningBySameOwner());
getRequestScheduler.setPriorityPolicyPlugin(config.getGetPriorityPolicyPlugin());
getRequestScheduler.start();
schedulerMap.put(GetFileRequest.class,getRequestScheduler);
Scheduler bringOnlineRequestScheduler = new Scheduler("bring_online_" + name, BringOnlineFileRequest.class);
// scheduler parameters
bringOnlineRequestScheduler.setMaxThreadQueueSize(config.getBringOnlineReqTQueueSize());
bringOnlineRequestScheduler.setThreadPoolSize(config.getBringOnlineThreadPoolSize());
bringOnlineRequestScheduler.setMaxWaitingJobNum(config.getBringOnlineMaxWaitingRequests());
bringOnlineRequestScheduler.setMaxReadyQueueSize(config.getBringOnlineReadyQueueSize());
bringOnlineRequestScheduler.setMaxReadyJobs(config.getBringOnlineMaxReadyJobs());
bringOnlineRequestScheduler.setMaxNumberOfRetries(config.getBringOnlineMaxNumOfRetries());
bringOnlineRequestScheduler.setRetryTimeout(config.getBringOnlineRetryTimeout());
bringOnlineRequestScheduler.setMaxRunningByOwner(config.getBringOnlineMaxRunningBySameOwner());
bringOnlineRequestScheduler.setPriorityPolicyPlugin(config.getBringOnlinePriorityPolicyPlugin());
bringOnlineRequestScheduler.start();
schedulerMap.put(BringOnlineFileRequest.class,bringOnlineRequestScheduler);
Scheduler putRequestScheduler = new Scheduler("put_" + name, PutFileRequest.class);
// scheduler parameters
putRequestScheduler.setMaxThreadQueueSize(config.getPutReqTQueueSize());
putRequestScheduler.setThreadPoolSize(config.getPutThreadPoolSize());
putRequestScheduler.setMaxWaitingJobNum(config.getPutMaxWaitingRequests());
putRequestScheduler.setMaxReadyQueueSize(config.getPutReadyQueueSize());
putRequestScheduler.setMaxReadyJobs(config.getPutMaxReadyJobs());
putRequestScheduler.setMaxNumberOfRetries(config.getPutMaxNumOfRetries());
putRequestScheduler.setRetryTimeout(config.getPutRetryTimeout());
putRequestScheduler.setMaxRunningByOwner(config.getPutMaxRunningBySameOwner());
putRequestScheduler.setPriorityPolicyPlugin(config.getPutPriorityPolicyPlugin());
putRequestScheduler.start();
schedulerMap.put(PutFileRequest.class,putRequestScheduler);
- Scheduler copyRequestScheduler = new Scheduler("copy_" + name, CopyRequest.class);
+ Scheduler copyRequestScheduler = new Scheduler("copy_" + name, Job.class);
// scheduler parameters
copyRequestScheduler.setMaxThreadQueueSize(config.getCopyReqTQueueSize());
copyRequestScheduler.setThreadPoolSize(config.getCopyThreadPoolSize());
copyRequestScheduler.setMaxWaitingJobNum(config.getCopyMaxWaitingRequests());
copyRequestScheduler.setMaxNumberOfRetries(config.getCopyMaxNumOfRetries());
copyRequestScheduler.setRetryTimeout(config.getCopyRetryTimeout());
copyRequestScheduler.setMaxRunningByOwner(config.getCopyMaxRunningBySameOwner());
copyRequestScheduler.setPriorityPolicyPlugin(config.getCopyPriorityPolicyPlugin());
copyRequestScheduler.start();
schedulerMap.put(CopyRequest.class,copyRequestScheduler);
Scheduler reserveSpaceScheduler = new Scheduler("reserve_space_" + name, ReserveSpaceRequest.class);
reserveSpaceScheduler.setMaxThreadQueueSize(config.getReserveSpaceReqTQueueSize());
reserveSpaceScheduler.setThreadPoolSize(config.getReserveSpaceThreadPoolSize());
reserveSpaceScheduler.setMaxWaitingJobNum(config.getReserveSpaceMaxWaitingRequests());
reserveSpaceScheduler.setMaxReadyQueueSize(config.getReserveSpaceReadyQueueSize());
reserveSpaceScheduler.setMaxReadyJobs(config.getReserveSpaceMaxReadyJobs());
reserveSpaceScheduler.setMaxNumberOfRetries(config.getReserveSpaceMaxNumOfRetries());
reserveSpaceScheduler.setRetryTimeout(config.getReserveSpaceRetryTimeout());
reserveSpaceScheduler.setMaxRunningByOwner(config.getReserveSpaceMaxRunningBySameOwner());
reserveSpaceScheduler.setPriorityPolicyPlugin(config.getReserveSpacePriorityPolicyPlugin());
reserveSpaceScheduler.start();
schedulerMap.put(ReserveSpaceRequest.class,reserveSpaceScheduler);
}
public void shutdown() {
for( Scheduler scheduler : schedulerMap.values()) {
scheduler.stop();
}
}
public static void initSchedulerFactory(Configuration config, String name) {
initSchedulerFactory( new SchedulerFactory(config,name));
}
public synchronized static void initSchedulerFactory(SchedulerFactory afactory) {
if(afactory == null) {
throw new NullPointerException(" factory argument is null");
}
if(factory == null) {
factory = afactory;
} else {
throw new IllegalStateException("already initialized");
}
}
public static synchronized SchedulerFactory getSchedulerFactory() {
if(factory == null) {
throw new IllegalStateException("not initialized");
}
return factory;
}
public Scheduler getScheduler(Job job) {
if(job == null) {
throw new IllegalArgumentException("job is null");
}
return getScheduler(job.getClass());
}
public Scheduler getScheduler(Class<? extends Job> jobType) {
Scheduler scheduler = schedulerMap.get(jobType);
if(scheduler != null) {
return scheduler;
}
throw new UnsupportedOperationException(
"Scheduler for class "+jobType+ " is not supported");
}
}
| true | true | private SchedulerFactory(Configuration config, String name) {
schedulerMap = new HashMap<>();
Scheduler lsRequestScheduler = new Scheduler("ls_" + name, LsFileRequest.class);
// scheduler parameters
lsRequestScheduler.setMaxThreadQueueSize(config.getLsReqTQueueSize());
lsRequestScheduler.setThreadPoolSize(config.getLsThreadPoolSize());
lsRequestScheduler.setMaxWaitingJobNum(config.getLsMaxWaitingRequests());
lsRequestScheduler.setMaxReadyQueueSize(config.getLsReadyQueueSize());
lsRequestScheduler.setMaxReadyJobs(config.getLsMaxReadyJobs());
lsRequestScheduler.setMaxNumberOfRetries(config.getLsMaxNumOfRetries());
lsRequestScheduler.setRetryTimeout(config.getLsRetryTimeout());
lsRequestScheduler.setMaxRunningByOwner(config.getLsMaxRunningBySameOwner());
lsRequestScheduler.setPriorityPolicyPlugin(config.getLsPriorityPolicyPlugin());
lsRequestScheduler.start();
schedulerMap.put(LsFileRequest.class,lsRequestScheduler);
Scheduler getRequestScheduler = new Scheduler("get_" + name, GetFileRequest.class);
// scheduler parameters
getRequestScheduler.setMaxThreadQueueSize(config.getGetReqTQueueSize());
getRequestScheduler.setThreadPoolSize(config.getGetThreadPoolSize());
getRequestScheduler.setMaxWaitingJobNum(config.getGetMaxWaitingRequests());
getRequestScheduler.setMaxReadyQueueSize(config.getGetReadyQueueSize());
getRequestScheduler.setMaxReadyJobs(config.getGetMaxReadyJobs());
getRequestScheduler.setMaxNumberOfRetries(config.getGetMaxNumOfRetries());
getRequestScheduler.setRetryTimeout(config.getGetRetryTimeout());
getRequestScheduler.setMaxRunningByOwner(config.getGetMaxRunningBySameOwner());
getRequestScheduler.setPriorityPolicyPlugin(config.getGetPriorityPolicyPlugin());
getRequestScheduler.start();
schedulerMap.put(GetFileRequest.class,getRequestScheduler);
Scheduler bringOnlineRequestScheduler = new Scheduler("bring_online_" + name, BringOnlineFileRequest.class);
// scheduler parameters
bringOnlineRequestScheduler.setMaxThreadQueueSize(config.getBringOnlineReqTQueueSize());
bringOnlineRequestScheduler.setThreadPoolSize(config.getBringOnlineThreadPoolSize());
bringOnlineRequestScheduler.setMaxWaitingJobNum(config.getBringOnlineMaxWaitingRequests());
bringOnlineRequestScheduler.setMaxReadyQueueSize(config.getBringOnlineReadyQueueSize());
bringOnlineRequestScheduler.setMaxReadyJobs(config.getBringOnlineMaxReadyJobs());
bringOnlineRequestScheduler.setMaxNumberOfRetries(config.getBringOnlineMaxNumOfRetries());
bringOnlineRequestScheduler.setRetryTimeout(config.getBringOnlineRetryTimeout());
bringOnlineRequestScheduler.setMaxRunningByOwner(config.getBringOnlineMaxRunningBySameOwner());
bringOnlineRequestScheduler.setPriorityPolicyPlugin(config.getBringOnlinePriorityPolicyPlugin());
bringOnlineRequestScheduler.start();
schedulerMap.put(BringOnlineFileRequest.class,bringOnlineRequestScheduler);
Scheduler putRequestScheduler = new Scheduler("put_" + name, PutFileRequest.class);
// scheduler parameters
putRequestScheduler.setMaxThreadQueueSize(config.getPutReqTQueueSize());
putRequestScheduler.setThreadPoolSize(config.getPutThreadPoolSize());
putRequestScheduler.setMaxWaitingJobNum(config.getPutMaxWaitingRequests());
putRequestScheduler.setMaxReadyQueueSize(config.getPutReadyQueueSize());
putRequestScheduler.setMaxReadyJobs(config.getPutMaxReadyJobs());
putRequestScheduler.setMaxNumberOfRetries(config.getPutMaxNumOfRetries());
putRequestScheduler.setRetryTimeout(config.getPutRetryTimeout());
putRequestScheduler.setMaxRunningByOwner(config.getPutMaxRunningBySameOwner());
putRequestScheduler.setPriorityPolicyPlugin(config.getPutPriorityPolicyPlugin());
putRequestScheduler.start();
schedulerMap.put(PutFileRequest.class,putRequestScheduler);
Scheduler copyRequestScheduler = new Scheduler("copy_" + name, CopyRequest.class);
// scheduler parameters
copyRequestScheduler.setMaxThreadQueueSize(config.getCopyReqTQueueSize());
copyRequestScheduler.setThreadPoolSize(config.getCopyThreadPoolSize());
copyRequestScheduler.setMaxWaitingJobNum(config.getCopyMaxWaitingRequests());
copyRequestScheduler.setMaxNumberOfRetries(config.getCopyMaxNumOfRetries());
copyRequestScheduler.setRetryTimeout(config.getCopyRetryTimeout());
copyRequestScheduler.setMaxRunningByOwner(config.getCopyMaxRunningBySameOwner());
copyRequestScheduler.setPriorityPolicyPlugin(config.getCopyPriorityPolicyPlugin());
copyRequestScheduler.start();
schedulerMap.put(CopyRequest.class,copyRequestScheduler);
Scheduler reserveSpaceScheduler = new Scheduler("reserve_space_" + name, ReserveSpaceRequest.class);
reserveSpaceScheduler.setMaxThreadQueueSize(config.getReserveSpaceReqTQueueSize());
reserveSpaceScheduler.setThreadPoolSize(config.getReserveSpaceThreadPoolSize());
reserveSpaceScheduler.setMaxWaitingJobNum(config.getReserveSpaceMaxWaitingRequests());
reserveSpaceScheduler.setMaxReadyQueueSize(config.getReserveSpaceReadyQueueSize());
reserveSpaceScheduler.setMaxReadyJobs(config.getReserveSpaceMaxReadyJobs());
reserveSpaceScheduler.setMaxNumberOfRetries(config.getReserveSpaceMaxNumOfRetries());
reserveSpaceScheduler.setRetryTimeout(config.getReserveSpaceRetryTimeout());
reserveSpaceScheduler.setMaxRunningByOwner(config.getReserveSpaceMaxRunningBySameOwner());
reserveSpaceScheduler.setPriorityPolicyPlugin(config.getReserveSpacePriorityPolicyPlugin());
reserveSpaceScheduler.start();
schedulerMap.put(ReserveSpaceRequest.class,reserveSpaceScheduler);
}
| private SchedulerFactory(Configuration config, String name) {
schedulerMap = new HashMap<>();
Scheduler lsRequestScheduler = new Scheduler("ls_" + name, LsFileRequest.class);
// scheduler parameters
lsRequestScheduler.setMaxThreadQueueSize(config.getLsReqTQueueSize());
lsRequestScheduler.setThreadPoolSize(config.getLsThreadPoolSize());
lsRequestScheduler.setMaxWaitingJobNum(config.getLsMaxWaitingRequests());
lsRequestScheduler.setMaxReadyQueueSize(config.getLsReadyQueueSize());
lsRequestScheduler.setMaxReadyJobs(config.getLsMaxReadyJobs());
lsRequestScheduler.setMaxNumberOfRetries(config.getLsMaxNumOfRetries());
lsRequestScheduler.setRetryTimeout(config.getLsRetryTimeout());
lsRequestScheduler.setMaxRunningByOwner(config.getLsMaxRunningBySameOwner());
lsRequestScheduler.setPriorityPolicyPlugin(config.getLsPriorityPolicyPlugin());
lsRequestScheduler.start();
schedulerMap.put(LsFileRequest.class,lsRequestScheduler);
Scheduler getRequestScheduler = new Scheduler("get_" + name, GetFileRequest.class);
// scheduler parameters
getRequestScheduler.setMaxThreadQueueSize(config.getGetReqTQueueSize());
getRequestScheduler.setThreadPoolSize(config.getGetThreadPoolSize());
getRequestScheduler.setMaxWaitingJobNum(config.getGetMaxWaitingRequests());
getRequestScheduler.setMaxReadyQueueSize(config.getGetReadyQueueSize());
getRequestScheduler.setMaxReadyJobs(config.getGetMaxReadyJobs());
getRequestScheduler.setMaxNumberOfRetries(config.getGetMaxNumOfRetries());
getRequestScheduler.setRetryTimeout(config.getGetRetryTimeout());
getRequestScheduler.setMaxRunningByOwner(config.getGetMaxRunningBySameOwner());
getRequestScheduler.setPriorityPolicyPlugin(config.getGetPriorityPolicyPlugin());
getRequestScheduler.start();
schedulerMap.put(GetFileRequest.class,getRequestScheduler);
Scheduler bringOnlineRequestScheduler = new Scheduler("bring_online_" + name, BringOnlineFileRequest.class);
// scheduler parameters
bringOnlineRequestScheduler.setMaxThreadQueueSize(config.getBringOnlineReqTQueueSize());
bringOnlineRequestScheduler.setThreadPoolSize(config.getBringOnlineThreadPoolSize());
bringOnlineRequestScheduler.setMaxWaitingJobNum(config.getBringOnlineMaxWaitingRequests());
bringOnlineRequestScheduler.setMaxReadyQueueSize(config.getBringOnlineReadyQueueSize());
bringOnlineRequestScheduler.setMaxReadyJobs(config.getBringOnlineMaxReadyJobs());
bringOnlineRequestScheduler.setMaxNumberOfRetries(config.getBringOnlineMaxNumOfRetries());
bringOnlineRequestScheduler.setRetryTimeout(config.getBringOnlineRetryTimeout());
bringOnlineRequestScheduler.setMaxRunningByOwner(config.getBringOnlineMaxRunningBySameOwner());
bringOnlineRequestScheduler.setPriorityPolicyPlugin(config.getBringOnlinePriorityPolicyPlugin());
bringOnlineRequestScheduler.start();
schedulerMap.put(BringOnlineFileRequest.class,bringOnlineRequestScheduler);
Scheduler putRequestScheduler = new Scheduler("put_" + name, PutFileRequest.class);
// scheduler parameters
putRequestScheduler.setMaxThreadQueueSize(config.getPutReqTQueueSize());
putRequestScheduler.setThreadPoolSize(config.getPutThreadPoolSize());
putRequestScheduler.setMaxWaitingJobNum(config.getPutMaxWaitingRequests());
putRequestScheduler.setMaxReadyQueueSize(config.getPutReadyQueueSize());
putRequestScheduler.setMaxReadyJobs(config.getPutMaxReadyJobs());
putRequestScheduler.setMaxNumberOfRetries(config.getPutMaxNumOfRetries());
putRequestScheduler.setRetryTimeout(config.getPutRetryTimeout());
putRequestScheduler.setMaxRunningByOwner(config.getPutMaxRunningBySameOwner());
putRequestScheduler.setPriorityPolicyPlugin(config.getPutPriorityPolicyPlugin());
putRequestScheduler.start();
schedulerMap.put(PutFileRequest.class,putRequestScheduler);
Scheduler copyRequestScheduler = new Scheduler("copy_" + name, Job.class);
// scheduler parameters
copyRequestScheduler.setMaxThreadQueueSize(config.getCopyReqTQueueSize());
copyRequestScheduler.setThreadPoolSize(config.getCopyThreadPoolSize());
copyRequestScheduler.setMaxWaitingJobNum(config.getCopyMaxWaitingRequests());
copyRequestScheduler.setMaxNumberOfRetries(config.getCopyMaxNumOfRetries());
copyRequestScheduler.setRetryTimeout(config.getCopyRetryTimeout());
copyRequestScheduler.setMaxRunningByOwner(config.getCopyMaxRunningBySameOwner());
copyRequestScheduler.setPriorityPolicyPlugin(config.getCopyPriorityPolicyPlugin());
copyRequestScheduler.start();
schedulerMap.put(CopyRequest.class,copyRequestScheduler);
Scheduler reserveSpaceScheduler = new Scheduler("reserve_space_" + name, ReserveSpaceRequest.class);
reserveSpaceScheduler.setMaxThreadQueueSize(config.getReserveSpaceReqTQueueSize());
reserveSpaceScheduler.setThreadPoolSize(config.getReserveSpaceThreadPoolSize());
reserveSpaceScheduler.setMaxWaitingJobNum(config.getReserveSpaceMaxWaitingRequests());
reserveSpaceScheduler.setMaxReadyQueueSize(config.getReserveSpaceReadyQueueSize());
reserveSpaceScheduler.setMaxReadyJobs(config.getReserveSpaceMaxReadyJobs());
reserveSpaceScheduler.setMaxNumberOfRetries(config.getReserveSpaceMaxNumOfRetries());
reserveSpaceScheduler.setRetryTimeout(config.getReserveSpaceRetryTimeout());
reserveSpaceScheduler.setMaxRunningByOwner(config.getReserveSpaceMaxRunningBySameOwner());
reserveSpaceScheduler.setPriorityPolicyPlugin(config.getReserveSpacePriorityPolicyPlugin());
reserveSpaceScheduler.start();
schedulerMap.put(ReserveSpaceRequest.class,reserveSpaceScheduler);
}
|
diff --git a/grails/src/java/org/codehaus/groovy/grails/web/servlet/ErrorHandlingServlet.java b/grails/src/java/org/codehaus/groovy/grails/web/servlet/ErrorHandlingServlet.java
index 045f3658d..ff27abd45 100644
--- a/grails/src/java/org/codehaus/groovy/grails/web/servlet/ErrorHandlingServlet.java
+++ b/grails/src/java/org/codehaus/groovy/grails/web/servlet/ErrorHandlingServlet.java
@@ -1,221 +1,222 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.servlet;
import com.opensymphony.module.sitemesh.*;
import com.opensymphony.sitemesh.*;
import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext;
import com.opensymphony.sitemesh.compatability.DecoratorMapper2DecoratorSelector;
import com.opensymphony.sitemesh.compatability.HTMLPage2Content;
import org.codehaus.groovy.grails.web.errors.GrailsWrappedRuntimeException;
import org.codehaus.groovy.grails.web.errors.GrailsExceptionResolver;
import org.codehaus.groovy.grails.web.mapping.UrlMappingInfo;
import org.codehaus.groovy.grails.web.mapping.UrlMappingsHolder;
import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestFilter;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.grails.web.sitemesh.FactoryHolder;
import org.codehaus.groovy.grails.web.util.WebUtils;
import org.codehaus.groovy.grails.web.util.IncludedContent;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.util.Collections;
/**
* A servlet for handling errors
*
* @author mike
* @since 1.0-RC1
*/
public class ErrorHandlingServlet extends GrailsDispatcherServlet {
private static final String TEXT_HTML = "text/html";
private static final String GSP_SUFFIX = ".gsp";
private static final String JSP_SUFFIX = ".jsp";
protected HttpServletRequest checkMultipart(HttpServletRequest request) throws MultipartException {
return request; // ignore multipart requests when an error occurs
}
protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
int statusCode;
if (request.getAttribute("javax.servlet.error.status_code") != null) {
statusCode = Integer.parseInt(request.getAttribute("javax.servlet.error.status_code").toString());
}
else {
statusCode = 500;
}
Throwable t = null;
if(request.getAttribute("javax.servlet.error.exception") != null) {
t = (Throwable)request.getAttribute("javax.servlet.error.exception");
if(!(t instanceof GrailsWrappedRuntimeException) && request.getAttribute("exception") == null) {
request.setAttribute("exception", new GrailsWrappedRuntimeException(getServletContext(), t));
}
}
final UrlMappingsHolder urlMappingsHolder = lookupUrlMappings();
UrlMappingInfo matchedInfo = null;
if(t!=null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, t);
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, GrailsExceptionResolver.getRootCause(t));
}
}
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode);
}
final UrlMappingInfo urlMappingInfo = matchedInfo;
if (urlMappingInfo != null) {
GrailsWebRequestFilter grailsWebRequestFilter = new GrailsWebRequestFilter();
grailsWebRequestFilter.setServletContext(getServletContext());
grailsWebRequestFilter.doFilter(request, response, new FilterChain() {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
final GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
urlMappingInfo.configure(webRequest);
String viewName = urlMappingInfo.getViewName();
if(viewName == null || viewName.endsWith(GSP_SUFFIX) || viewName.endsWith(JSP_SUFFIX)) {
IncludedContent includeResult = WebUtils.includeForUrlMappingInfo(request, response, urlMappingInfo, Collections.EMPTY_MAP);
if(includeResult.getRedirectURL()!=null) {
response.sendRedirect(includeResult.getRedirectURL());
}
else {
final Factory factory = FactoryHolder.getFactory();
PageParser parser = getPageParser(factory, response);
Page p = parser != null ? parser.parse(includeResult.getContent().toCharArray()) : null;
String layout = p != null ? p.getProperty("meta.layout") : null;
if(layout != null && p != null) {
final HTMLPage2Content content = new HTMLPage2Content((HTMLPage) p);
DecoratorSelector decoratorSelector = new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper());
SiteMeshWebAppContext webAppContext = new SiteMeshWebAppContext(request, response, webRequest.getServletContext());
com.opensymphony.sitemesh.Decorator d = decoratorSelector.selectDecorator(content, webAppContext);
if(d!=null) {
+ response.setContentType(includeResult.getContentType());
d.render(content, webAppContext);
}
else {
writeOriginal(response, includeResult);
}
}
else {
writeOriginal(response, includeResult);
}
}
}
else {
ViewResolver viewResolver = WebUtils.lookupViewResolver(getServletContext());
if(viewResolver != null) {
View v;
try {
v = WebUtils.resolveView(request, urlMappingInfo, viewName, viewResolver);
v.render(Collections.EMPTY_MAP, request, response);
} catch (Exception e) {
throw new UrlMappingException("Error mapping onto view ["+viewName+"]: " + e.getMessage(),e);
}
}
}
}
});
}
else {
renderDefaultResponse(response, statusCode);
}
}
private void writeOriginal(HttpServletResponse response, IncludedContent includeResult) {
try {
PrintWriter printWriter;
response.setContentType(includeResult.getContentType());
try {
printWriter= response.getWriter();
}
catch (IllegalStateException e) {
printWriter = new PrintWriter(new OutputStreamWriter(response.getOutputStream()));
}
printWriter.write(includeResult.getContent());
printWriter.flush();
}
catch (IOException e) {
throw new ControllerExecutionException("Error writing out error page: " + e.getMessage(),e);
}
}
private PageParser getPageParser(Factory factory, HttpServletResponse response) {
if(factory!=null) {
PageParser pageParser = factory.getPageParser(response.getContentType() != null ? response.getContentType() : "text/html");
if(pageParser == null) {
pageParser = factory.getPageParser("text/html;charset=UTF-8");
}
return pageParser;
}
return null;
}
private void renderDefaultResponse(HttpServletResponse response, int statusCode) throws IOException {
if (statusCode == 404) {
renderDefaultResponse(response, statusCode, "Not Found", "Page not found.");
}
else {
renderDefaultResponse(response, statusCode, "Internal Error", "Internal server error.");
}
}
private void renderDefaultResponse(HttpServletResponse response, int statusCode, String title, String text) throws IOException {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setContentType(TEXT_HTML);
Writer writer = response.getWriter();
writer.write("<HTML>\n<HEAD>\n<TITLE>Error " + statusCode + " - " + title);
writer.write("</TITLE>\n<BODY>\n<H2>Error " + statusCode + " - " + title + ".</H2>\n");
writer.write(text + "<BR/>");
for (int i = 0; i < 20; i++)
writer.write("\n<!-- Padding for IE -->");
writer.write("\n</BODY>\n</HTML>\n");
writer.flush();
}
private UrlMappingsHolder lookupUrlMappings() {
WebApplicationContext wac =
WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
return (UrlMappingsHolder)wac.getBean(UrlMappingsHolder.BEAN_ID);
}
}
| true | true | protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
int statusCode;
if (request.getAttribute("javax.servlet.error.status_code") != null) {
statusCode = Integer.parseInt(request.getAttribute("javax.servlet.error.status_code").toString());
}
else {
statusCode = 500;
}
Throwable t = null;
if(request.getAttribute("javax.servlet.error.exception") != null) {
t = (Throwable)request.getAttribute("javax.servlet.error.exception");
if(!(t instanceof GrailsWrappedRuntimeException) && request.getAttribute("exception") == null) {
request.setAttribute("exception", new GrailsWrappedRuntimeException(getServletContext(), t));
}
}
final UrlMappingsHolder urlMappingsHolder = lookupUrlMappings();
UrlMappingInfo matchedInfo = null;
if(t!=null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, t);
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, GrailsExceptionResolver.getRootCause(t));
}
}
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode);
}
final UrlMappingInfo urlMappingInfo = matchedInfo;
if (urlMappingInfo != null) {
GrailsWebRequestFilter grailsWebRequestFilter = new GrailsWebRequestFilter();
grailsWebRequestFilter.setServletContext(getServletContext());
grailsWebRequestFilter.doFilter(request, response, new FilterChain() {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
final GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
urlMappingInfo.configure(webRequest);
String viewName = urlMappingInfo.getViewName();
if(viewName == null || viewName.endsWith(GSP_SUFFIX) || viewName.endsWith(JSP_SUFFIX)) {
IncludedContent includeResult = WebUtils.includeForUrlMappingInfo(request, response, urlMappingInfo, Collections.EMPTY_MAP);
if(includeResult.getRedirectURL()!=null) {
response.sendRedirect(includeResult.getRedirectURL());
}
else {
final Factory factory = FactoryHolder.getFactory();
PageParser parser = getPageParser(factory, response);
Page p = parser != null ? parser.parse(includeResult.getContent().toCharArray()) : null;
String layout = p != null ? p.getProperty("meta.layout") : null;
if(layout != null && p != null) {
final HTMLPage2Content content = new HTMLPage2Content((HTMLPage) p);
DecoratorSelector decoratorSelector = new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper());
SiteMeshWebAppContext webAppContext = new SiteMeshWebAppContext(request, response, webRequest.getServletContext());
com.opensymphony.sitemesh.Decorator d = decoratorSelector.selectDecorator(content, webAppContext);
if(d!=null) {
d.render(content, webAppContext);
}
else {
writeOriginal(response, includeResult);
}
}
else {
writeOriginal(response, includeResult);
}
}
}
else {
ViewResolver viewResolver = WebUtils.lookupViewResolver(getServletContext());
if(viewResolver != null) {
View v;
try {
v = WebUtils.resolveView(request, urlMappingInfo, viewName, viewResolver);
v.render(Collections.EMPTY_MAP, request, response);
} catch (Exception e) {
throw new UrlMappingException("Error mapping onto view ["+viewName+"]: " + e.getMessage(),e);
}
}
}
}
});
}
else {
renderDefaultResponse(response, statusCode);
}
}
| protected void doDispatch(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
int statusCode;
if (request.getAttribute("javax.servlet.error.status_code") != null) {
statusCode = Integer.parseInt(request.getAttribute("javax.servlet.error.status_code").toString());
}
else {
statusCode = 500;
}
Throwable t = null;
if(request.getAttribute("javax.servlet.error.exception") != null) {
t = (Throwable)request.getAttribute("javax.servlet.error.exception");
if(!(t instanceof GrailsWrappedRuntimeException) && request.getAttribute("exception") == null) {
request.setAttribute("exception", new GrailsWrappedRuntimeException(getServletContext(), t));
}
}
final UrlMappingsHolder urlMappingsHolder = lookupUrlMappings();
UrlMappingInfo matchedInfo = null;
if(t!=null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, t);
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode, GrailsExceptionResolver.getRootCause(t));
}
}
if(matchedInfo == null) {
matchedInfo = urlMappingsHolder.matchStatusCode(statusCode);
}
final UrlMappingInfo urlMappingInfo = matchedInfo;
if (urlMappingInfo != null) {
GrailsWebRequestFilter grailsWebRequestFilter = new GrailsWebRequestFilter();
grailsWebRequestFilter.setServletContext(getServletContext());
grailsWebRequestFilter.doFilter(request, response, new FilterChain() {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
final GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
urlMappingInfo.configure(webRequest);
String viewName = urlMappingInfo.getViewName();
if(viewName == null || viewName.endsWith(GSP_SUFFIX) || viewName.endsWith(JSP_SUFFIX)) {
IncludedContent includeResult = WebUtils.includeForUrlMappingInfo(request, response, urlMappingInfo, Collections.EMPTY_MAP);
if(includeResult.getRedirectURL()!=null) {
response.sendRedirect(includeResult.getRedirectURL());
}
else {
final Factory factory = FactoryHolder.getFactory();
PageParser parser = getPageParser(factory, response);
Page p = parser != null ? parser.parse(includeResult.getContent().toCharArray()) : null;
String layout = p != null ? p.getProperty("meta.layout") : null;
if(layout != null && p != null) {
final HTMLPage2Content content = new HTMLPage2Content((HTMLPage) p);
DecoratorSelector decoratorSelector = new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper());
SiteMeshWebAppContext webAppContext = new SiteMeshWebAppContext(request, response, webRequest.getServletContext());
com.opensymphony.sitemesh.Decorator d = decoratorSelector.selectDecorator(content, webAppContext);
if(d!=null) {
response.setContentType(includeResult.getContentType());
d.render(content, webAppContext);
}
else {
writeOriginal(response, includeResult);
}
}
else {
writeOriginal(response, includeResult);
}
}
}
else {
ViewResolver viewResolver = WebUtils.lookupViewResolver(getServletContext());
if(viewResolver != null) {
View v;
try {
v = WebUtils.resolveView(request, urlMappingInfo, viewName, viewResolver);
v.render(Collections.EMPTY_MAP, request, response);
} catch (Exception e) {
throw new UrlMappingException("Error mapping onto view ["+viewName+"]: " + e.getMessage(),e);
}
}
}
}
});
}
else {
renderDefaultResponse(response, statusCode);
}
}
|
diff --git a/collections/ArrayUtils.java b/collections/ArrayUtils.java
index 2a1af06..6b42b71 100644
--- a/collections/ArrayUtils.java
+++ b/collections/ArrayUtils.java
@@ -1,101 +1,101 @@
package collections;
import collections.array.CharArray;
import collections.array.DoubleArray;
import collections.array.IntArray;
import collections.array.LongArray;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
/**
* Created with IntelliJ IDEA.
* User: riad
*/
public class ArrayUtils {
public static void sort(int[] array) {
Collections.sort(new IntArray(array));
}
public static void sort(double[] array) {
Collections.sort(new DoubleArray(array));
}
public static void sort(long[] array) {
Collections.sort(new LongArray(array));
}
public static void sort(char[] array) {
Collections.sort(new CharArray(array));
}
public static <T extends Comparable<? super T>> void sort(T[] array) {
Arrays.sort(array);
}
public static void sort(int[] array, Comparator<Integer> comparator) {
Collections.sort(new IntArray(array), comparator);
}
public static void sort(double[] array, Comparator<Double> comparator) {
Collections.sort(new DoubleArray(array), comparator);
}
public static void sort(long[] array, Comparator<Long> comparator) {
Collections.sort(new LongArray(array), comparator);
}
public static void sort(char[] array, Comparator<Character> comparator) {
Collections.sort(new CharArray(array), comparator);
}
public static <T> void sort(T[] array, Comparator<? super T> comparator) {
Arrays.sort(array, comparator);
}
/**
* @param array array to reverse
* @param from inclusive
* @param to exclusive
* if (from == to) nothing happens
*/
private static void reverse(int[] array, int from, int to) {
int length = to - from;
for (int i = 0; i < length / 2; ++i) {
int tmp = array[from + i];
array[from + i] = array[to - i - 1];
array[to - i - 1] = tmp;
}
}
public static boolean nextPermutation(int[] array) {
for (int i = array.length - 2; i >= 0; --i) {
if (array[i] < array[i + 1]) {
int lastGreater = i + 1;
while (lastGreater + 1 < array.length && array[lastGreater + 1] > array[i]) {
++lastGreater;
}
int tmp = array[i];
array[i] = array[lastGreater];
array[lastGreater] = tmp;
reverse(array, i + 1, array.length);
return true;
}
}
- reverse(array, 0, array.length - 1);
+ reverse(array, 0, array.length);
return false;
}
public static int upperBound(long[] a, long v){
int l = -1, r = a.length;
while(l + 1< r){
int c = l + (r - l) / 2;
if(a[c] > v)
r = c;
else
l = c;
}
return r;
}
}
| true | true | public static boolean nextPermutation(int[] array) {
for (int i = array.length - 2; i >= 0; --i) {
if (array[i] < array[i + 1]) {
int lastGreater = i + 1;
while (lastGreater + 1 < array.length && array[lastGreater + 1] > array[i]) {
++lastGreater;
}
int tmp = array[i];
array[i] = array[lastGreater];
array[lastGreater] = tmp;
reverse(array, i + 1, array.length);
return true;
}
}
reverse(array, 0, array.length - 1);
return false;
}
| public static boolean nextPermutation(int[] array) {
for (int i = array.length - 2; i >= 0; --i) {
if (array[i] < array[i + 1]) {
int lastGreater = i + 1;
while (lastGreater + 1 < array.length && array[lastGreater + 1] > array[i]) {
++lastGreater;
}
int tmp = array[i];
array[i] = array[lastGreater];
array[lastGreater] = tmp;
reverse(array, i + 1, array.length);
return true;
}
}
reverse(array, 0, array.length);
return false;
}
|
diff --git a/ufd/GCDProxy.java b/ufd/GCDProxy.java
index 44f34a0a..9877b1cd 100644
--- a/ufd/GCDProxy.java
+++ b/ufd/GCDProxy.java
@@ -1,255 +1,255 @@
/*
* $Id$
*/
package edu.jas.ufd;
import java.util.List;
import java.util.ArrayList;
//import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.CancellationException;
//import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
//import edu.jas.structure.RingElem;
import edu.jas.structure.GcdRingElem;
//import edu.jas.structure.RingFactory;
//import edu.jas.kern.PreemptingException;
import edu.jas.kern.ComputerThreads;
import edu.jas.poly.GenPolynomial;
import edu.jas.ufd.GreatestCommonDivisor;
import edu.jas.ufd.GreatestCommonDivisorAbstract;
//import edu.jas.ufd.GreatestCommonDivisorSubres;
//import edu.jas.ufd.GreatestCommonDivisorPrimitive;
//import edu.jas.ufd.GreatestCommonDivisorModular;
//import edu.jas.ufd.GreatestCommonDivisorModEval;
/**
* Greatest common divisor parallel proxy.
* @author Heinz Kredel
*/
public class GCDProxy<C extends GcdRingElem<C>>
extends GreatestCommonDivisorAbstract<C> {
// implements GreatestCommonDivisor<C> {
private static final Logger logger = Logger.getLogger(GCDProxy.class);
private boolean debug = logger.isInfoEnabled(); //logger.isInfoEnabled();
/**
* GCD engines.
*/
public final GreatestCommonDivisor<C> e1;
public final GreatestCommonDivisor<C> e2;
/**
* Thread pool.
*/
protected ExecutorService pool;
/**
* Thread pool size.
*/
protected static final int anzahl = 3;
/*
* Thread poll intervall.
*/
protected static final int dauer = 5;
/**
* Proxy constructor.
*/
public GCDProxy(GreatestCommonDivisor<C> e1, GreatestCommonDivisor<C> e2 ) {
this.e1 = e1;
this.e2 = e2;
if ( pool == null ) {
//pool = Executors.newFixedThreadPool(anzahl);
pool = ComputerThreads.getPool();
}
}
/*
* Terminate proxy.
* no more required.
public void terminate() {
if ( pool == null ) {
logger.info("already terminated");
return;
}
// synchronized( pool ) {
List<Runnable> r = pool.shutdownNow();
if ( r.size() != 0 ) {
// throw new RuntimeException("there are unfinished tasks " + r);
// System.out.println("there are " + r.size() + " unfinished tasks ");
logger.info("there are " + r.size() + " unfinished tasks ");
}
pool = null;
//}
}
*/
/** Get the String representation as RingFactory.
* @see java.lang.Object#toString()
*/
public String toString() {
return "GCDProxy[ "
+ e1.getClass().getName() + ", "
+ e2.getClass().getName() + " ]";
}
/**
* Univariate GenPolynomial greatest comon divisor.
* Uses pseudoRemainder for remainder.
* @param P univariate GenPolynomial.
* @param S univariate GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<C> baseGcd( GenPolynomial<C> P,
GenPolynomial<C> S ) {
throw new RuntimeException("baseGcd not implemented");
}
/**
* Univariate GenPolynomial recursive greatest comon divisor.
* Uses pseudoRemainder for remainder.
* @param P univariate recursive GenPolynomial.
* @param S univariate recursive GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<GenPolynomial<C>>
recursiveGcd( GenPolynomial<GenPolynomial<C>> P,
GenPolynomial<GenPolynomial<C>> S ) {
throw new RuntimeException("recursiveGcd not implemented");
}
/**
* GenPolynomial greatest comon divisor.
* Main entry driver method.
* @param P GenPolynomial.
* @param S GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<C> gcd( final GenPolynomial<C> P, final GenPolynomial<C> S ) {
GenPolynomial<C> g = null;
Callable<GenPolynomial<C>> c0;
Callable<GenPolynomial<C>> c1;
List<Callable<GenPolynomial<C>>> cs = new ArrayList<Callable<GenPolynomial<C>>>(2);
cs.add( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
GenPolynomial<C> g = e1.gcd(P,S);
if ( debug ) {
logger.info("GCDProxy done e1 " + e1.getClass().getName());
}
return g;
}
}
);
cs.add( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
GenPolynomial<C> g = e2.gcd(P,S);
if ( debug ) {
logger.info("GCDProxy done e2 " + e2.getClass().getName());
}
return g;
}
}
);
try {
g = pool.invokeAny( cs );
} catch (InterruptedException ignored) {
logger.info("InterruptedException " + ignored);
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
logger.info("ExecutionException " + e);
Thread.currentThread().interrupt();
}
return g;
}
/**
* GenPolynomial greatest comon divisor.
* Main entry driver method.
* @param P GenPolynomial.
* @param S GenPolynomial.
* @return gcd(P,S).
*/
public GenPolynomial<C> gcdOld( final GenPolynomial<C> P, final GenPolynomial<C> S ) {
GenPolynomial<C> g = null;
Future<GenPolynomial<C>> f0;
Future<GenPolynomial<C>> f1;
f0 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e1.gcd(P,S);
}
}
);
f1 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e2.gcd(P,S);
}
}
);
while ( g == null ) {
try {
if ( g == null && f0.isDone() /*&& ! f0.isCancelled()*/ ) {
g = f0.get();
f1.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e1 " + e1);
}
}
if ( g == null && f1.isDone() /*&& ! f1.isCancelled()*/ ) {
g = f1.get();
f0.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e2 " + e2);
}
}
if ( g == null ) {
- Thread.currentThread().sleep(dauer);
+ Thread.sleep(dauer);
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (CancellationException ignored) {
Thread.currentThread().interrupt();
} catch (ExecutionException ignored) {
Thread.currentThread().interrupt();
}
}
if ( !f0.isDone() || !f1.isDone() ) {
logger.info("GCDProxy not done, f0 = " + f0 + ", f1 = " + f1);
}
return g;
}
}
| true | true | public GenPolynomial<C> gcdOld( final GenPolynomial<C> P, final GenPolynomial<C> S ) {
GenPolynomial<C> g = null;
Future<GenPolynomial<C>> f0;
Future<GenPolynomial<C>> f1;
f0 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e1.gcd(P,S);
}
}
);
f1 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e2.gcd(P,S);
}
}
);
while ( g == null ) {
try {
if ( g == null && f0.isDone() /*&& ! f0.isCancelled()*/ ) {
g = f0.get();
f1.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e1 " + e1);
}
}
if ( g == null && f1.isDone() /*&& ! f1.isCancelled()*/ ) {
g = f1.get();
f0.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e2 " + e2);
}
}
if ( g == null ) {
Thread.currentThread().sleep(dauer);
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (CancellationException ignored) {
Thread.currentThread().interrupt();
} catch (ExecutionException ignored) {
Thread.currentThread().interrupt();
}
}
if ( !f0.isDone() || !f1.isDone() ) {
logger.info("GCDProxy not done, f0 = " + f0 + ", f1 = " + f1);
}
return g;
}
| public GenPolynomial<C> gcdOld( final GenPolynomial<C> P, final GenPolynomial<C> S ) {
GenPolynomial<C> g = null;
Future<GenPolynomial<C>> f0;
Future<GenPolynomial<C>> f1;
f0 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e1.gcd(P,S);
}
}
);
f1 = pool.submit( new Callable<GenPolynomial<C>>() {
public GenPolynomial<C> call() {
return e2.gcd(P,S);
}
}
);
while ( g == null ) {
try {
if ( g == null && f0.isDone() /*&& ! f0.isCancelled()*/ ) {
g = f0.get();
f1.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e1 " + e1);
}
}
if ( g == null && f1.isDone() /*&& ! f1.isCancelled()*/ ) {
g = f1.get();
f0.cancel(true);
if ( debug ) {
logger.info("GCDProxy done e2 " + e2);
}
}
if ( g == null ) {
Thread.sleep(dauer);
}
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
} catch (CancellationException ignored) {
Thread.currentThread().interrupt();
} catch (ExecutionException ignored) {
Thread.currentThread().interrupt();
}
}
if ( !f0.isDone() || !f1.isDone() ) {
logger.info("GCDProxy not done, f0 = " + f0 + ", f1 = " + f1);
}
return g;
}
|
diff --git a/src/com/vaadin/tests/featurebrowser/FeatureLabel.java b/src/com/vaadin/tests/featurebrowser/FeatureLabel.java
index e3e02eed4..f12a76b39 100644
--- a/src/com/vaadin/tests/featurebrowser/FeatureLabel.java
+++ b/src/com/vaadin/tests/featurebrowser/FeatureLabel.java
@@ -1,78 +1,77 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.tests.featurebrowser;
import com.vaadin.ui.Component;
import com.vaadin.ui.Form;
import com.vaadin.ui.Label;
import com.vaadin.ui.OrderedLayout;
public class FeatureLabel extends Feature {
public FeatureLabel() {
super();
}
@Override
protected Component getDemoComponent() {
final OrderedLayout l = new OrderedLayout();
final Label lab = new Label("Label text");
l.addComponent(lab);
// Properties
propertyPanel = new PropertyPanel(lab);
final Form ap = propertyPanel.createBeanPropertySet(new String[] {
"contentMode", "value" });
ap.replaceWithSelect("contentMode", new Object[] {
new Integer(Label.CONTENT_PREFORMATTED),
new Integer(Label.CONTENT_TEXT),
new Integer(Label.CONTENT_XHTML),
- new Integer(Label.CONTENT_XML) },
- new Object[] { "Preformatted", "Text", "UIDL (Must be valid)",
- "XHTML Fragment(Must be valid)",
- "XML (Subtree with namespace)" });
+ new Integer(Label.CONTENT_XML) }, new Object[] {
+ "Preformatted", "Text", "XHTML Fragment(Must be valid)",
+ "XML (Subtree with namespace)" });
propertyPanel.addProperties("Label Properties", ap);
setJavadocURL("ui/Label.html");
return l;
}
@Override
protected String getExampleSrc() {
return "Label l = new Label(\"Caption\");\n";
}
/**
* @see com.vaadin.tests.featurebrowser.Feature#getDescriptionXHTML()
*/
@Override
protected String getDescriptionXHTML() {
return "Labels components are for captions and plain text. "
+ "By default, it is a light-weight component for presenting "
+ "text content in application, but it can be also used to present "
+ "formatted information and even XML."
+ "<br /><br />"
+ "Label can also be directly associated with data property to display "
+ "information from different data sources automatically. This makes it "
+ "trivial to present the current user in the corner of applications main window. "
+ "<br /><br />"
+ "On the demo tab you can try out how the different properties affect "
+ "the presentation of the component.";
}
@Override
protected String getImage() {
return "icon_demo.png";
}
@Override
protected String getTitle() {
return "Label";
}
}
| true | true | protected Component getDemoComponent() {
final OrderedLayout l = new OrderedLayout();
final Label lab = new Label("Label text");
l.addComponent(lab);
// Properties
propertyPanel = new PropertyPanel(lab);
final Form ap = propertyPanel.createBeanPropertySet(new String[] {
"contentMode", "value" });
ap.replaceWithSelect("contentMode", new Object[] {
new Integer(Label.CONTENT_PREFORMATTED),
new Integer(Label.CONTENT_TEXT),
new Integer(Label.CONTENT_XHTML),
new Integer(Label.CONTENT_XML) },
new Object[] { "Preformatted", "Text", "UIDL (Must be valid)",
"XHTML Fragment(Must be valid)",
"XML (Subtree with namespace)" });
propertyPanel.addProperties("Label Properties", ap);
setJavadocURL("ui/Label.html");
return l;
}
| protected Component getDemoComponent() {
final OrderedLayout l = new OrderedLayout();
final Label lab = new Label("Label text");
l.addComponent(lab);
// Properties
propertyPanel = new PropertyPanel(lab);
final Form ap = propertyPanel.createBeanPropertySet(new String[] {
"contentMode", "value" });
ap.replaceWithSelect("contentMode", new Object[] {
new Integer(Label.CONTENT_PREFORMATTED),
new Integer(Label.CONTENT_TEXT),
new Integer(Label.CONTENT_XHTML),
new Integer(Label.CONTENT_XML) }, new Object[] {
"Preformatted", "Text", "XHTML Fragment(Must be valid)",
"XML (Subtree with namespace)" });
propertyPanel.addProperties("Label Properties", ap);
setJavadocURL("ui/Label.html");
return l;
}
|
diff --git a/org.eclipse.jubula.rc.javafx/src/org/eclipse/jubula/rc/javafx/tester/adapter/ButtonBaseAdapter.java b/org.eclipse.jubula.rc.javafx/src/org/eclipse/jubula/rc/javafx/tester/adapter/ButtonBaseAdapter.java
index 186d77104..62bc21ace 100644
--- a/org.eclipse.jubula.rc.javafx/src/org/eclipse/jubula/rc/javafx/tester/adapter/ButtonBaseAdapter.java
+++ b/org.eclipse.jubula.rc.javafx/src/org/eclipse/jubula/rc/javafx/tester/adapter/ButtonBaseAdapter.java
@@ -1,87 +1,87 @@
/*******************************************************************************
* Copyright (c) 2013 BREDEX GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* BREDEX GmbH - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.jubula.rc.javafx.tester.adapter;
import java.util.concurrent.Callable;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Toggle;
import org.eclipse.jubula.rc.common.exception.StepExecutionException;
import org.eclipse.jubula.rc.common.tester.adapter.interfaces.IButtonComponent;
import org.eclipse.jubula.rc.javafx.driver.EventThreadQueuerJavaFXImpl;
import org.eclipse.jubula.tools.objects.event.EventFactory;
import org.eclipse.jubula.tools.objects.event.TestErrorEvent;
/**
* Implementation of the button interface as an adapter which holds the
* <code>javax.swing.AbstractButton</code>.
*
* @author BREDEX GmbH
* @created 30.10.2013
*/
public class ButtonBaseAdapter extends JavaFXComponentAdapter<ButtonBase>
implements IButtonComponent {
/**
* Creates an object with the adapted Button.
*
* @param objectToAdapt
* this must be an object of the Type <code>ButtonBase</code>
*/
public ButtonBaseAdapter(ButtonBase objectToAdapt) {
super(objectToAdapt);
}
@Override
public String getText() {
String text = EventThreadQueuerJavaFXImpl.invokeAndWait("getText", //$NON-NLS-1$
new Callable<String>() {
@Override
public String call() throws Exception {
return getRealComponent().getText();
}
});
return text;
}
@Override
public boolean isSelected() {
final ButtonBase real = getRealComponent();
- if (real.getClass().isAssignableFrom(Toggle.class)) {
+ if (real instanceof Toggle) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((Toggle) real).isSelected();
}
});
} else if (real instanceof CheckBox) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((CheckBox) real).isSelected();
}
});
}
throw new StepExecutionException(
"The Button is not a RadioButton and CheckBoxButton", //$NON-NLS-1$
EventFactory
.createActionError(
TestErrorEvent.UNSUPPORTED_OPERATION_ERROR));
}
}
| true | true | public boolean isSelected() {
final ButtonBase real = getRealComponent();
if (real.getClass().isAssignableFrom(Toggle.class)) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((Toggle) real).isSelected();
}
});
} else if (real instanceof CheckBox) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((CheckBox) real).isSelected();
}
});
}
throw new StepExecutionException(
"The Button is not a RadioButton and CheckBoxButton", //$NON-NLS-1$
EventFactory
.createActionError(
TestErrorEvent.UNSUPPORTED_OPERATION_ERROR));
}
| public boolean isSelected() {
final ButtonBase real = getRealComponent();
if (real instanceof Toggle) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((Toggle) real).isSelected();
}
});
} else if (real instanceof CheckBox) {
return EventThreadQueuerJavaFXImpl.invokeAndWait(
"isSelected", new Callable<Boolean>() { //$NON-NLS-1$
@Override
public Boolean call() throws Exception {
return ((CheckBox) real).isSelected();
}
});
}
throw new StepExecutionException(
"The Button is not a RadioButton and CheckBoxButton", //$NON-NLS-1$
EventFactory
.createActionError(
TestErrorEvent.UNSUPPORTED_OPERATION_ERROR));
}
|
diff --git a/src/test/unit/gov/nist/javax/sip/parser/ContactParserTest.java b/src/test/unit/gov/nist/javax/sip/parser/ContactParserTest.java
index 4608a3ff..c7f92f78 100755
--- a/src/test/unit/gov/nist/javax/sip/parser/ContactParserTest.java
+++ b/src/test/unit/gov/nist/javax/sip/parser/ContactParserTest.java
@@ -1,61 +1,62 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), and others.
* This software is has been contributed to the public domain.
* As a result, a formal license is not needed to use the software.
*
* This software is provided "AS IS."
* NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
*
*/
/*
* Created on Jul 27, 2004
*
*The JAIN-SIP project
*/
package test.unit.gov.nist.javax.sip.parser;
import gov.nist.javax.sip.parser.ContactParser;
/**
* Test case for contact parser
*
* @author mranga
*/
public class ContactParserTest extends ParserTestCase {
public void testParser() {
String contact[] = {
"Contact:<sip:[email protected]:5000;transport=udp>;expires=3600\n",
"Contact:BigGuy<sip:[email protected]:5000>;expires=3600\n",
"Contact: sip:[email protected]:5060\n",
"Contact: sip:[email protected]\n",
"Contact: Bo Bob Biggs\n"
+ "< sip:[email protected]?Route=%3Csip:sip.example.com%3E >\n",
"Contact: Joe Bob Briggs <sip:[email protected]>\n",
"Contact: \"Mr. Watson\" <sip:[email protected]>"
+ " ; q=0.7; expires=3600,\"Mr. Watson\" <mailto:[email protected]>"
+ ";q=0.1\n",
"Contact: LittleGuy <sip:[email protected];user=phone>"
+ ",<sip:[email protected];user=phone>,tel:+1-972-555-2222"
+ "\n",
"Contact:*\n",
"Contact:BigGuy<sip:[email protected];5000>;Expires=3600\n" ,
"Contact: sip:[email protected];expires=600;q=0.5\n",
+ "Contact: <sip:abc%[email protected]>\n",
// pmusgrave - add +sip-instance tests (outbound & gruu drafts)
"Contact: <sip:[email protected]>;+sip-instance=\"<urn:uid:f81d-5463>\"\n" };
super.testParser(ContactParser.class, contact);
}
}
| true | true | public void testParser() {
String contact[] = {
"Contact:<sip:[email protected]:5000;transport=udp>;expires=3600\n",
"Contact:BigGuy<sip:[email protected]:5000>;expires=3600\n",
"Contact: sip:[email protected]:5060\n",
"Contact: sip:[email protected]\n",
"Contact: Bo Bob Biggs\n"
+ "< sip:[email protected]?Route=%3Csip:sip.example.com%3E >\n",
"Contact: Joe Bob Briggs <sip:[email protected]>\n",
"Contact: \"Mr. Watson\" <sip:[email protected]>"
+ " ; q=0.7; expires=3600,\"Mr. Watson\" <mailto:[email protected]>"
+ ";q=0.1\n",
"Contact: LittleGuy <sip:[email protected];user=phone>"
+ ",<sip:[email protected];user=phone>,tel:+1-972-555-2222"
+ "\n",
"Contact:*\n",
"Contact:BigGuy<sip:[email protected];5000>;Expires=3600\n" ,
"Contact: sip:[email protected];expires=600;q=0.5\n",
// pmusgrave - add +sip-instance tests (outbound & gruu drafts)
"Contact: <sip:[email protected]>;+sip-instance=\"<urn:uid:f81d-5463>\"\n" };
super.testParser(ContactParser.class, contact);
}
| public void testParser() {
String contact[] = {
"Contact:<sip:[email protected]:5000;transport=udp>;expires=3600\n",
"Contact:BigGuy<sip:[email protected]:5000>;expires=3600\n",
"Contact: sip:[email protected]:5060\n",
"Contact: sip:[email protected]\n",
"Contact: Bo Bob Biggs\n"
+ "< sip:[email protected]?Route=%3Csip:sip.example.com%3E >\n",
"Contact: Joe Bob Briggs <sip:[email protected]>\n",
"Contact: \"Mr. Watson\" <sip:[email protected]>"
+ " ; q=0.7; expires=3600,\"Mr. Watson\" <mailto:[email protected]>"
+ ";q=0.1\n",
"Contact: LittleGuy <sip:[email protected];user=phone>"
+ ",<sip:[email protected];user=phone>,tel:+1-972-555-2222"
+ "\n",
"Contact:*\n",
"Contact:BigGuy<sip:[email protected];5000>;Expires=3600\n" ,
"Contact: sip:[email protected];expires=600;q=0.5\n",
"Contact: <sip:abc%[email protected]>\n",
// pmusgrave - add +sip-instance tests (outbound & gruu drafts)
"Contact: <sip:[email protected]>;+sip-instance=\"<urn:uid:f81d-5463>\"\n" };
super.testParser(ContactParser.class, contact);
}
|
diff --git a/webapp/app/controllers/modules2/RawTimeSeriesProcessor.java b/webapp/app/controllers/modules2/RawTimeSeriesProcessor.java
index 492a21d0..9d206453 100644
--- a/webapp/app/controllers/modules2/RawTimeSeriesProcessor.java
+++ b/webapp/app/controllers/modules2/RawTimeSeriesProcessor.java
@@ -1,180 +1,180 @@
package controllers.modules2;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.util.BigInt;
import gov.nrel.util.Utility;
import com.alvazan.orm.api.base.NoSqlEntityManager;
import com.alvazan.orm.api.z3api.NoSqlTypedSession;
import com.alvazan.orm.api.z3api.QueryResult;
import com.alvazan.orm.api.z5api.NoSqlSession;
import com.alvazan.orm.api.z8spi.KeyValue;
import com.alvazan.orm.api.z8spi.action.Column;
import com.alvazan.orm.api.z8spi.iter.AbstractCursor;
import com.alvazan.orm.api.z8spi.iter.Cursor;
import com.alvazan.orm.api.z8spi.meta.DboColumnMeta;
import com.alvazan.orm.api.z8spi.meta.DboTableMeta;
import com.alvazan.orm.api.z8spi.meta.TypedRow;
import com.alvazan.play.NoSql;
import controllers.modules2.framework.ReadResult;
import controllers.modules2.framework.TSRelational;
import controllers.modules2.framework.VisitorInfo;
public class RawTimeSeriesProcessor implements RawSubProcessor {
private static final Logger log = LoggerFactory.getLogger(RawTimeSeriesProcessor.class);
private DboTableMeta meta;
private Long currentPartitionId;
private byte[] endBytes;
private byte[] startBytes;
private Long start;
private Long end;
private AbstractCursor<Column> cursor;
private Long partitionSize;
private DboColumnMeta colMeta;
private boolean reverse = false;
private String url;
private Long startPartition;
private boolean noData;
@Override
public void init(DboTableMeta meta, Long start, Long end, String url, VisitorInfo visitor) {
this.meta = meta;
this.url = url;
this.reverse = visitor.isReversed();
partitionSize = meta.getTimeSeriesPartionSize();
currentPartitionId = partition(start, partitionSize);
if(reverse)
currentPartitionId = partition(end, partitionSize);
startPartition = currentPartitionId;
this.startBytes = meta.getIdColumnMeta().convertToStorage2(new BigInteger(start+""));
this.endBytes = meta.getIdColumnMeta().convertToStorage2(new BigInteger(end+""));
this.start = start;
this.end = end;
colMeta = meta.getAllColumns().iterator().next();
if (log.isInfoEnabled())
log.info("Setting up for reading partitions, partId="+currentPartitionId+" start="+start);
}
private Long partition(Long time, long partitionSize) {
if(time == null)
return null;
long partitionId = (time / partitionSize)*partitionSize;
if(partitionId < 0) {
//if partitionId is less than 0, it incorrectly ends up in the higher partition -20/50*50 = 0 and 20/50*50=0 when -20/50*50 needs to be -50 partitionId
if(Long.MIN_VALUE+partitionSize >= partitionId)
partitionId = Long.MIN_VALUE;
else
partitionId -= partitionSize; //subtract one partition size off of the id
}
return partitionId;
}
@Override
public ReadResult read() {
AbstractCursor<Column> cursor;
try {
if(noData)
return new ReadResult();
else if(reverse)
cursor = getReverseCursor();
else
cursor = getCursorWithResults();
} catch(NoDataException e) {
String time1 = convert(startPartition);
String time2 = convert(currentPartitionId);
noData = true;
return new ReadResult("", "We scanned partitions from time="+time1+" to time="+time2+" and found no data so are exiting. perhaps add a start time and end time to your url");
}
if(cursor == null)
return new ReadResult();
return translate(cursor.getCurrent());
}
private String convert(long startPartition2) {
DateTime dt = new DateTime(startPartition2);
return dt+"";
}
private AbstractCursor<Column> getReverseCursor() {
if(cursor != null && cursor.previous()) {
return cursor;
- } else if(currentPartitionId < start)
+ } else if(currentPartitionId < (start-partitionSize))
return null;
int count = 0;
do {
NoSqlTypedSession em = NoSql.em().getTypedSession();
NoSqlSession raw = em.getRawSession();
byte[] rowKeyPostFix = meta.getIdColumnMeta().convertToStorage2(new BigInteger(""+currentPartitionId));
byte[] rowKey = meta.getIdColumnMeta().formVirtRowKey(rowKeyPostFix);
cursor = raw.columnSlice(meta, rowKey, startBytes, endBytes, 200);
cursor.afterLast();
currentPartitionId -= partitionSize;
if(cursor.previous())
return cursor;
count++;
} while(currentPartitionId > start && count < 20);
if(count >= 20)
throw new NoDataException("no data in 20 partitions found...not continuing");
return null;
}
private AbstractCursor<Column> getCursorWithResults() {
if(cursor != null && cursor.next()) {
return cursor;
} else if(currentPartitionId > end)
return null;
int count = 0;
do {
NoSqlTypedSession em = NoSql.em().getTypedSession();
NoSqlSession raw = em.getRawSession();
byte[] rowKeyPostFix = meta.getIdColumnMeta().convertToStorage2(new BigInteger(""+currentPartitionId));
byte[] rowKey = meta.getIdColumnMeta().formVirtRowKey(rowKeyPostFix);
cursor = raw.columnSlice(meta, rowKey, startBytes, endBytes, 200);
currentPartitionId += partitionSize;
if(cursor.next())
return cursor;
count++;
} while(currentPartitionId < end && count < 20);
if(count >= 20)
throw new NoDataException("no data in 20 partitions found...not continuing");
return null;
}
private ReadResult translate(Column current) {
byte[] name = current.getName();
byte[] value = current.getValue();
Object time = meta.getIdColumnMeta().convertFromStorage2(name);
Object val = colMeta.convertFromStorage2(value);
//TODO: parameterize timeColumn and valueColumn from options
TSRelational tv = new TSRelational("time", "value");
tv.put("time", time);
tv.put(colMeta.getColumnName(), val);
return new ReadResult(url, tv);
}
}
| true | true | private AbstractCursor<Column> getReverseCursor() {
if(cursor != null && cursor.previous()) {
return cursor;
} else if(currentPartitionId < start)
return null;
int count = 0;
do {
NoSqlTypedSession em = NoSql.em().getTypedSession();
NoSqlSession raw = em.getRawSession();
byte[] rowKeyPostFix = meta.getIdColumnMeta().convertToStorage2(new BigInteger(""+currentPartitionId));
byte[] rowKey = meta.getIdColumnMeta().formVirtRowKey(rowKeyPostFix);
cursor = raw.columnSlice(meta, rowKey, startBytes, endBytes, 200);
cursor.afterLast();
currentPartitionId -= partitionSize;
if(cursor.previous())
return cursor;
count++;
} while(currentPartitionId > start && count < 20);
if(count >= 20)
throw new NoDataException("no data in 20 partitions found...not continuing");
return null;
}
| private AbstractCursor<Column> getReverseCursor() {
if(cursor != null && cursor.previous()) {
return cursor;
} else if(currentPartitionId < (start-partitionSize))
return null;
int count = 0;
do {
NoSqlTypedSession em = NoSql.em().getTypedSession();
NoSqlSession raw = em.getRawSession();
byte[] rowKeyPostFix = meta.getIdColumnMeta().convertToStorage2(new BigInteger(""+currentPartitionId));
byte[] rowKey = meta.getIdColumnMeta().formVirtRowKey(rowKeyPostFix);
cursor = raw.columnSlice(meta, rowKey, startBytes, endBytes, 200);
cursor.afterLast();
currentPartitionId -= partitionSize;
if(cursor.previous())
return cursor;
count++;
} while(currentPartitionId > start && count < 20);
if(count >= 20)
throw new NoDataException("no data in 20 partitions found...not continuing");
return null;
}
|
diff --git a/src/main/java/com/censoredsoftware/demigods/engine/command/DevelopmentCommands.java b/src/main/java/com/censoredsoftware/demigods/engine/command/DevelopmentCommands.java
index 931bf810..b9c3b943 100644
--- a/src/main/java/com/censoredsoftware/demigods/engine/command/DevelopmentCommands.java
+++ b/src/main/java/com/censoredsoftware/demigods/engine/command/DevelopmentCommands.java
@@ -1,247 +1,248 @@
package com.censoredsoftware.demigods.engine.command;
import com.censoredsoftware.censoredlib.helper.WrappedCommand;
import com.censoredsoftware.censoredlib.util.Images;
import com.censoredsoftware.demigods.engine.Demigods;
import com.censoredsoftware.demigods.engine.battle.Battle;
import com.censoredsoftware.demigods.engine.data.DataManager;
import com.censoredsoftware.demigods.engine.player.DCharacter;
import com.censoredsoftware.demigods.engine.player.DPlayer;
import com.censoredsoftware.demigods.engine.structure.Structure;
import com.censoredsoftware.demigods.engine.structure.StructureData;
import com.censoredsoftware.demigods.greek.structure.Altar;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.Sets;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Player;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.Set;
public class DevelopmentCommands extends WrappedCommand
{
public DevelopmentCommands()
{
super(Demigods.PLUGIN, false);
}
@Override
public Set<String> getCommands()
{
return Sets.newHashSet("obelisk", "test2", "test3"); // "test1", "hspawn", "nearestaltar"
}
@Override
public boolean processCommand(CommandSender sender, Command command, String[] args)
{
// if(command.getName().equalsIgnoreCase("test1")) return test1(sender, args);
if(command.getName().equalsIgnoreCase("test2")) return test2(sender, args);
else if(command.getName().equalsIgnoreCase("test3")) return test3(sender, args);
// else if(command.getName().equalsIgnoreCase("hspawn")) return hspawn(sender);
// else if(command.getName().equalsIgnoreCase("nearestaltar")) return nearestAltar(sender);
else if(command.getName().equalsIgnoreCase("obelisk")) return obelisk(sender, args);
return false;
}
private static boolean test1(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
for(Battle battle : Battle.Util.getAllActive())
battle.end();
return true;
}
private static boolean test2(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
try
{
player.sendMessage(" ");
URL doge = new URL(args[0]);
BufferedImage veryImage = ImageIO.read(doge);
veryImage = Images.getScaledImage(veryImage, 128, 128);
if(player.isOp()) Images.convertImageToSchematic(veryImage).generate(player.getLocation());
player.sendMessage(" ");
}
catch(Throwable suchError)
{
player.sendMessage(ChatColor.RED + "many problems. " + suchError.getMessage());
+ suchError.printStackTrace();
}
return true;
// Player player = (Player) sender;
// StructureData obelisk = Structure.Util.getInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_GRIEFING);
// if(obelisk != null)
// {
// Get all of the connected obelisks
// for(StructureData save : Structure.Util.getStructureWeb(obelisk, Structure.Flag.NO_GRIEFING, 20))
// {
// if(save == obelisk) continue;
// player.sendMessage(save.getId().toString());
// }
// }
// else player.sendMessage(ChatColor.RED + "No Obelisk found.");
// return true;
// Player player = (Player) sender;
// Messages.broadcast(ChatColor.RED + "Removing all non-altar structures.");
// for(StructureData save : Collections2.filter(StructureData.Util.loadAll(), new Predicate<StructureData>()
// {
// @Override
// public boolean apply(StructureData structure)
// {
// return !structure.getType().equals(GreekStructure.ALTAR);
// }
// }))
// save.remove();
// Messages.broadcast(ChatColor.RED + "All non-altar structures have been removed.");
// if(Demigods.ERROR_NOISE) Errors.triggerError(ChatColor.GREEN + player.getName(), new ColoredStringBuilder().gray(" " + Unicodes.getRightwardArrow() + " ").red("Test error.").build());
// return true;
}
private static boolean test3(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
Images.sendMapImage(player, Images.getPlayerHead(player.getName()));
return true;
}
private static boolean hspawn(CommandSender sender)
{
Player player = (Player) sender;
// This SHOULD happen automatically, but bukkit doesn't do this, so we need to.
if(player.isInsideVehicle() && player.getVehicle() instanceof Horse)
{
Horse horse = (Horse) player.getVehicle();
horse.eject();
horse.teleport(player.getWorld().getSpawnLocation());
horse.setPassenger(player);
player.sendMessage(ChatColor.YELLOW + "Teleported to spawn...");
}
return true;
}
private static boolean nearestAltar(CommandSender sender)
{
Player player = (Player) sender;
if(Altar.Util.isAltarNearby(player.getLocation()))
{
StructureData save = Altar.Util.getAltarNearby(player.getLocation());
player.teleport(save.getReferenceLocation().clone().add(2.0, 1.5, 0));
player.sendMessage(ChatColor.YELLOW + "Nearest Altar found.");
}
else player.sendMessage(ChatColor.YELLOW + "There is no alter nearby.");
return true;
}
/**
* Temp command while testing obelisks.
*/
private static boolean obelisk(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
if(args.length != 3)
{
player.sendMessage(ChatColor.RED + "Not enough arguments.");
return false;
}
StructureData obelisk = Structure.Util.getInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_GRIEFING);
if(obelisk != null)
{
DCharacter character = DPlayer.Util.getPlayer(player).getCurrent();
if(!obelisk.getOwner().equals(character.getId()))
{
player.sendMessage(ChatColor.RED + "You don't control this Obelisk.");
return true;
}
DCharacter workWith = obeliskGetCharacter(args[1], args[2]);
if(workWith == null)
{
player.sendMessage(ChatColor.RED + "Character/Player (" + args[2] + ") not found.");
return true;
}
if(!DCharacter.Util.areAllied(workWith, character))
{
player.sendMessage(ChatColor.RED + "You are not allied with " + workWith.getDeity().getColor() + character.getName() + ChatColor.RED + ".");
return true;
}
if(args[0].equalsIgnoreCase("add"))
{
if(!obelisk.getMembers().contains(workWith.getId()))
{
obelisk.addMember(workWith.getId());
player.sendMessage(workWith.getDeity().getColor() + workWith.getName() + ChatColor.YELLOW + " has been added to the Obelisk!");
}
else player.sendMessage(ChatColor.RED + "Already a member.");
}
else if(args[0].equalsIgnoreCase("remove"))
{
if(obelisk.getMembers().contains(workWith.getId()))
{
obelisk.removeMember(workWith.getId());
player.sendMessage(workWith.getDeity().getColor() + workWith.getName() + ChatColor.YELLOW + " has been removed from the Obelisk!");
}
else player.sendMessage(ChatColor.RED + "Not a member.");
}
}
else player.sendMessage(ChatColor.RED + "No Obelisk found.");
return true;
}
private static DCharacter obeliskGetCharacter(String type, final String name)
{
if(type.equalsIgnoreCase("character")) return DCharacter.Util.getCharacterByName(name);
if(!type.equalsIgnoreCase("player")) return null;
try
{
return Iterators.find(DataManager.players.values().iterator(), new Predicate<DPlayer>()
{
@Override
public boolean apply(DPlayer dPlayer)
{
return dPlayer.getPlayerName().equals(name);
}
}).getCurrent();
}
catch(NoSuchElementException ignored)
{}
return null;
}
}
| true | true | private static boolean test2(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
try
{
player.sendMessage(" ");
URL doge = new URL(args[0]);
BufferedImage veryImage = ImageIO.read(doge);
veryImage = Images.getScaledImage(veryImage, 128, 128);
if(player.isOp()) Images.convertImageToSchematic(veryImage).generate(player.getLocation());
player.sendMessage(" ");
}
catch(Throwable suchError)
{
player.sendMessage(ChatColor.RED + "many problems. " + suchError.getMessage());
}
return true;
// Player player = (Player) sender;
// StructureData obelisk = Structure.Util.getInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_GRIEFING);
// if(obelisk != null)
// {
// Get all of the connected obelisks
// for(StructureData save : Structure.Util.getStructureWeb(obelisk, Structure.Flag.NO_GRIEFING, 20))
// {
// if(save == obelisk) continue;
// player.sendMessage(save.getId().toString());
// }
// }
// else player.sendMessage(ChatColor.RED + "No Obelisk found.");
// return true;
// Player player = (Player) sender;
// Messages.broadcast(ChatColor.RED + "Removing all non-altar structures.");
// for(StructureData save : Collections2.filter(StructureData.Util.loadAll(), new Predicate<StructureData>()
// {
// @Override
// public boolean apply(StructureData structure)
// {
// return !structure.getType().equals(GreekStructure.ALTAR);
// }
// }))
// save.remove();
// Messages.broadcast(ChatColor.RED + "All non-altar structures have been removed.");
// if(Demigods.ERROR_NOISE) Errors.triggerError(ChatColor.GREEN + player.getName(), new ColoredStringBuilder().gray(" " + Unicodes.getRightwardArrow() + " ").red("Test error.").build());
// return true;
}
| private static boolean test2(CommandSender sender, final String[] args)
{
Player player = (Player) sender;
try
{
player.sendMessage(" ");
URL doge = new URL(args[0]);
BufferedImage veryImage = ImageIO.read(doge);
veryImage = Images.getScaledImage(veryImage, 128, 128);
if(player.isOp()) Images.convertImageToSchematic(veryImage).generate(player.getLocation());
player.sendMessage(" ");
}
catch(Throwable suchError)
{
player.sendMessage(ChatColor.RED + "many problems. " + suchError.getMessage());
suchError.printStackTrace();
}
return true;
// Player player = (Player) sender;
// StructureData obelisk = Structure.Util.getInRadiusWithFlag(player.getLocation(), Structure.Flag.NO_GRIEFING);
// if(obelisk != null)
// {
// Get all of the connected obelisks
// for(StructureData save : Structure.Util.getStructureWeb(obelisk, Structure.Flag.NO_GRIEFING, 20))
// {
// if(save == obelisk) continue;
// player.sendMessage(save.getId().toString());
// }
// }
// else player.sendMessage(ChatColor.RED + "No Obelisk found.");
// return true;
// Player player = (Player) sender;
// Messages.broadcast(ChatColor.RED + "Removing all non-altar structures.");
// for(StructureData save : Collections2.filter(StructureData.Util.loadAll(), new Predicate<StructureData>()
// {
// @Override
// public boolean apply(StructureData structure)
// {
// return !structure.getType().equals(GreekStructure.ALTAR);
// }
// }))
// save.remove();
// Messages.broadcast(ChatColor.RED + "All non-altar structures have been removed.");
// if(Demigods.ERROR_NOISE) Errors.triggerError(ChatColor.GREEN + player.getName(), new ColoredStringBuilder().gray(" " + Unicodes.getRightwardArrow() + " ").red("Test error.").build());
// return true;
}
|
diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ImplicitTokenGrantIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ImplicitTokenGrantIntegrationTests.java
index e074b693d..e70387d3a 100644
--- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ImplicitTokenGrantIntegrationTests.java
+++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ImplicitTokenGrantIntegrationTests.java
@@ -1,101 +1,101 @@
/*
* Copyright 2006-2011 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.cloudfoundry.identity.uaa.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Arrays;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* Tests implicit grant using a direct posting of credentials to the /authorize endpoint and
* also with an intermediate form login.
*
* @author Dave Syer
*/
public class ImplicitTokenGrantIntegrationTests {
@Rule
public ServerRunning serverRunning = ServerRunning.isRunning();
private String implicitUrl() {
URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "token")
.queryParam("client_id", "vmc").queryParam("redirect_uri", "http://anywhere")
.queryParam("scope", "read").build();
return uri.toString();
}
@Test
public void authzViaJsonEndpointSucceedsWithCorrectCredentials() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String credentials = "{ \"username\":\"marissa\", \"password\":\"koala\" }";
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("credentials", credentials);
ResponseEntity<Void> result = serverRunning.postForResponse(implicitUrl(), headers, formData);
assertNotNull(result.getHeaders().getLocation());
assertTrue(result.getHeaders().getLocation().toString().matches("http://anywhere#access_token=.+"));
}
@Test
public void authzWithIntermediateFormLoginSucceeds() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<Void> result = serverRunning.getForResponse(implicitUrl(), headers);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
String location = result.getHeaders().getLocation().toString();
String cookie = result.getHeaders().getFirst("Set-Cookie");
assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
headers.set("Cookie", cookie);
ResponseEntity<String> response = serverRunning.getForString(location, headers);
// should be directed to the login screen...
- assertTrue(response.getBody().contains("uaa/login.do"));
+ assertTrue(response.getBody().contains("/login.do"));
assertTrue(response.getBody().contains("username"));
assertTrue(response.getBody().contains("password"));
location = "/login.do";
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("username", "marissa");
formData.add("password", "koala");
result = serverRunning.postForRedirect(location, headers, formData);
System.err.println(result.getStatusCode());
System.err.println(result.getHeaders());
assertNotNull(result.getHeaders().getLocation());
assertTrue(result.getHeaders().getLocation().toString().matches("http://anywhere#access_token=.+"));
}
}
| true | true | public void authzWithIntermediateFormLoginSucceeds() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<Void> result = serverRunning.getForResponse(implicitUrl(), headers);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
String location = result.getHeaders().getLocation().toString();
String cookie = result.getHeaders().getFirst("Set-Cookie");
assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
headers.set("Cookie", cookie);
ResponseEntity<String> response = serverRunning.getForString(location, headers);
// should be directed to the login screen...
assertTrue(response.getBody().contains("uaa/login.do"));
assertTrue(response.getBody().contains("username"));
assertTrue(response.getBody().contains("password"));
location = "/login.do";
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("username", "marissa");
formData.add("password", "koala");
result = serverRunning.postForRedirect(location, headers, formData);
System.err.println(result.getStatusCode());
System.err.println(result.getHeaders());
assertNotNull(result.getHeaders().getLocation());
assertTrue(result.getHeaders().getLocation().toString().matches("http://anywhere#access_token=.+"));
}
| public void authzWithIntermediateFormLoginSucceeds() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.TEXT_HTML));
ResponseEntity<Void> result = serverRunning.getForResponse(implicitUrl(), headers);
assertEquals(HttpStatus.FOUND, result.getStatusCode());
String location = result.getHeaders().getLocation().toString();
String cookie = result.getHeaders().getFirst("Set-Cookie");
assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
headers.set("Cookie", cookie);
ResponseEntity<String> response = serverRunning.getForString(location, headers);
// should be directed to the login screen...
assertTrue(response.getBody().contains("/login.do"));
assertTrue(response.getBody().contains("username"));
assertTrue(response.getBody().contains("password"));
location = "/login.do";
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add("username", "marissa");
formData.add("password", "koala");
result = serverRunning.postForRedirect(location, headers, formData);
System.err.println(result.getStatusCode());
System.err.println(result.getHeaders());
assertNotNull(result.getHeaders().getLocation());
assertTrue(result.getHeaders().getLocation().toString().matches("http://anywhere#access_token=.+"));
}
|
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/ExistingBugEditor.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/ExistingBugEditor.java
index 3c24c01e3..d1969b431 100644
--- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/ExistingBugEditor.java
+++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/bugzilla/ui/editor/ExistingBugEditor.java
@@ -1,1009 +1,1013 @@
/*******************************************************************************
* Copyright (c) 2003 - 2005 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.bugzilla.ui.editor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.login.LoginException;
import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.CompareUI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceColors;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylar.bugzilla.core.Attribute;
import org.eclipse.mylar.bugzilla.core.BugPost;
import org.eclipse.mylar.bugzilla.core.BugReport;
import org.eclipse.mylar.bugzilla.core.BugzillaException;
import org.eclipse.mylar.bugzilla.core.BugzillaPlugin;
import org.eclipse.mylar.bugzilla.core.BugzillaRepository;
import org.eclipse.mylar.bugzilla.core.Comment;
import org.eclipse.mylar.bugzilla.core.IBugzillaBug;
import org.eclipse.mylar.bugzilla.core.IBugzillaConstants;
import org.eclipse.mylar.bugzilla.core.Operation;
import org.eclipse.mylar.bugzilla.core.PossibleBugzillaFailureException;
import org.eclipse.mylar.bugzilla.core.compare.BugzillaCompareInput;
import org.eclipse.mylar.bugzilla.core.internal.HtmlStreamTokenizer;
import org.eclipse.mylar.bugzilla.ui.OfflineView;
import org.eclipse.mylar.bugzilla.ui.WebBrowserDialog;
import org.eclipse.mylar.bugzilla.ui.actions.RefreshBugzillaReportsAction;
import org.eclipse.mylar.bugzilla.ui.favorites.actions.AddToFavoritesAction;
import org.eclipse.mylar.bugzilla.ui.outline.BugzillaOutlineNode;
import org.eclipse.mylar.bugzilla.ui.outline.BugzillaReportSelection;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.tasklist.ui.views.TaskListView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.internal.Workbench;
/**
* An editor used to view a bug report that exists on a server. It uses a
* <code>BugReport</code> object to store the data.
*/
public class ExistingBugEditor extends AbstractBugEditor
{
protected Set<String> removeCC = new HashSet<String>();
protected BugzillaCompareInput compareInput;
protected Button compareButton;
protected Button[] radios;
protected Control[] radioOptions;
protected List keyWordsList;
protected Text keywordsText;
protected List ccList;
protected Text ccText;
protected Text addCommentsText;
protected BugReport bug;
public String getNewCommentText(){
return addCommentsTextBox.getText();
}
/**
* Creates a new <code>ExistingBugEditor</code>.
*/
public ExistingBugEditor() {
super();
// Set up the input for comparing the bug report to the server
CompareConfiguration config = new CompareConfiguration();
config.setLeftEditable(false);
config.setRightEditable(false);
config.setLeftLabel("Local Bug Report");
config.setRightLabel("Remote Bug Report");
config.setLeftImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
config.setRightImage(PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT));
compareInput = new BugzillaCompareInput(config);
}
@SuppressWarnings("deprecation")
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
if (!(input instanceof ExistingBugEditorInput))
throw new PartInitException("Invalid Input: Must be ExistingBugEditorInput");
ExistingBugEditorInput ei = (ExistingBugEditorInput) input;
setSite(site);
setInput(input);
bugzillaInput = ei;
model = BugzillaOutlineNode.parseBugReport(bugzillaInput.getBug());
bug = ei.getBug();
restoreBug();
isDirty = false;
updateEditorTitle();
}
/**
* This overrides the existing implementation in order to add
* an "add to favorites" option to the context menu.
*
* @see org.eclipse.mylar.bugzilla.ui.AbstractBugEditor#createContextMenu()
*/
@Override
protected void createContextMenu() {
contextMenuManager = new MenuManager("#BugEditor");
contextMenuManager.setRemoveAllWhenShown(true);
contextMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(new AddToFavoritesAction(ExistingBugEditor.this));
manager.add(new Separator());
manager.add(cutAction);
manager.add(copyAction);
manager.add(pasteAction);
manager.add(new Separator());
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
if (currentSelectedText == null ||
currentSelectedText.getSelectionText().length() == 0) {
copyAction.setEnabled(false);
}
else {
copyAction.setEnabled(true);
}
}
});
getSite().registerContextMenu("#BugEditor", contextMenuManager,
getSite().getSelectionProvider());
}
@Override
protected void addRadioButtons(Composite buttonComposite) {
int i = 0;
Button selected = null;
radios = new Button[bug.getOperations().size()];
radioOptions = new Control[bug.getOperations().size()];
for (Iterator<Operation> it = bug.getOperations().iterator(); it.hasNext(); ) {
Operation o = it.next();
radios[i] = new Button(buttonComposite, SWT.RADIO);
radios[i].setFont(TEXT_FONT);
GridData radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
if (!o.hasOptions() && !o.isInput())
radioData.horizontalSpan = 4;
else
radioData.horizontalSpan = 3;
radioData.heightHint = 20;
String opName = o.getOperationName();
opName = opName.replaceAll("</.*>", "");
opName = opName.replaceAll("<.*>", "");
radios[i].setText(opName);
radios[i].setLayoutData(radioData);
radios[i].setBackground(background);
radios[i].addSelectionListener(new RadioButtonListener());
radios[i].addListener(SWT.FocusIn, new GenericListener());
if (o.hasOptions()) {
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 1;
radioData.heightHint = 20;
radioData.widthHint = 100;
radioOptions[i] = new Combo(
buttonComposite,
SWT.NO_BACKGROUND
| SWT.MULTI
| SWT.V_SCROLL
| SWT.READ_ONLY);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
radioOptions[i].setBackground(background);
Object [] a = o.getOptionNames().toArray();
Arrays.sort(a);
for (int j = 0; j < a.length; j++) {
((Combo)radioOptions[i]).add((String) a[j]);
}
((Combo)radioOptions[i]).select(0);
((Combo)radioOptions[i]).addSelectionListener(new RadioButtonListener());
} else if(o.isInput()){
radioData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
radioData.horizontalSpan = 1;
radioData.widthHint = 120;
radioOptions[i] = new Text(
buttonComposite,
SWT.BORDER | SWT.SINGLE);
radioOptions[i].setFont(TEXT_FONT);
radioOptions[i].setLayoutData(radioData);
radioOptions[i].setBackground(background);
((Text)radioOptions[i]).setText(o.getInputValue());
((Text)radioOptions[i]).addModifyListener(new RadioButtonListener());
}
if (i == 0 || o.isChecked()) {
if(selected != null)
selected.setSelection(false);
selected = radios[i];
radios[i].setSelection(true);
if(o.hasOptions() && o.getOptionSelection() != null){
int j = 0;
for(String s: ((Combo)radioOptions[i]).getItems()){
if(s.compareTo(o.getOptionSelection()) == 0){
((Combo)radioOptions[i]).select(j);
}
j++;
}
}
bug.setSelectedOperation(o);
}
i++;
}
}
@Override
protected void addActionButtons(Composite buttonComposite) {
super.addActionButtons(buttonComposite);
compareButton = new Button(buttonComposite, SWT.NONE);
compareButton.setFont(TEXT_FONT);
GridData compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
compareButtonData.widthHint = 100;
compareButtonData.heightHint = 20;
compareButton.setText("Compare");
compareButton.setLayoutData(compareButtonData);
compareButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
OpenCompareEditorJob compareJob = new OpenCompareEditorJob("Comparing bug with remote server...");
compareJob.schedule();
}
});
compareButton.addListener(SWT.FocusIn, new GenericListener());
// TODO used for spell checking. Add back when we want to support this
// checkSpellingButton = new Button(buttonComposite, SWT.NONE);
// checkSpellingButton.setFont(TEXT_FONT);
// compareButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// compareButtonData.widthHint = 100;
// compareButtonData.heightHint = 20;
// checkSpellingButton.setText("CheckSpelling");
// checkSpellingButton.setLayoutData(compareButtonData);
// checkSpellingButton.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// checkSpelling();
// }
// });
// checkSpellingButton.addListener(SWT.FocusIn, new GenericListener());
}
/**
* @return Returns the compareInput.
*/
public BugzillaCompareInput getCompareInput() {
return compareInput;
}
@Override
public IBugzillaBug getBug() {
return bug;
}
@Override
protected String getTitleString() {
return bug.getLabel() + ": " + checkText(bug.getAttribute("Summary").getNewValue());
}
private String toCommaSeparatedList(String[] strings) {
StringBuffer buffer = new StringBuffer();
for(int i = 0; i < strings.length; i++) {
buffer.append(strings[i]);
if (i != strings.length - 1) {
buffer.append(",");
}
}
return buffer.toString();
}
@Override
protected void submitBug() {
+ submitButton.setEnabled(false);
ExistingBugEditor.this.showBusy(true);
final BugPost form = new BugPost();
// set the url for the bug to be submitted to
setURL(form, "process_bug.cgi");
// go through all of the attributes and add them to the bug post
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if (a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && !a.isHidden()) {
String value = a.getNewValue();
// add the attribute to the bug post
form.add(a.getParameterName(), checkText(value));
}
else if(a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && a.isHidden()) {
// we have a hidden attribute and we should send it back.
form.add(a.getParameterName(), a.getValue());
}
}
// make sure that the comment is broken up into 80 character lines
bug.setNewNewComment(formatText(bug.getNewNewComment()));
// add the summary to the bug post
form.add("short_desc", bug.getAttribute("Summary").getNewValue());
if(removeCC != null && removeCC.size() > 0){
String[] s = new String[removeCC.size()];
form.add("cc", toCommaSeparatedList(removeCC.toArray(s)));
form.add("removecc", "true");
}
// add the operation to the bug post
Operation o = bug.getSelectedOperation();
if (o == null)
form.add("knob", "none");
else {
form.add("knob", o.getKnobName());
if(o.hasOptions()) {
String sel = o.getOptionValue(o.getOptionSelection());
form.add(o.getOptionName(), sel);
} else if (o.isInput()){
String sel = o.getInputValue();
form.add(o.getInputName(), sel);
}
}
form.add("form_name", "process_bug");
// add the new comment to the bug post if there is some text in it
if(bug.getNewNewComment().length() != 0) {
form.add("comment", bug.getNewNewComment());
}
final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(final IProgressMonitor monitor)
throws CoreException {
try {
form.post();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable(){
public void run() {
// TODO what do we do if the editor is closed
if (ExistingBugEditor.this != null
&& !ExistingBugEditor.this.isDisposed()) {
changeDirtyStatus(false);
BugzillaPlugin.getDefault().getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.closeEditor(ExistingBugEditor.this, true);
}
OfflineView.removeReport(bug);
}
});
} catch (final BugzillaException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
BugzillaPlugin.getDefault().logAndShowExceptionDetailsDialog(
e,
"occurred while posting the bug.",
"I/O Error");
}
});
+ submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final PossibleBugzillaFailureException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
WebBrowserDialog.openAcceptAgreement(null,
"Possible Bugzilla Failure",
"Bugzilla may not have posted your bug.\n" + e.getMessage(),
form.getError());
BugzillaPlugin.log(e);
}
});
+ submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final LoginException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(null,
"Login Error",
"Bugzilla could not post your bug since your login name or password is incorrect.\nPlease check your settings in the bugzilla preferences. ");
}
});
+ submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
}
}
};
Job job = new Job("Submitting Bug"){
@Override
protected IStatus run(IProgressMonitor monitor) {
try{
op.run(monitor);
} catch (Exception e){
MylarPlugin.log(e, "Failed to submit bug");
return new Status(Status.ERROR, "org.eclipse.mylar.bugzilla.ui", Status.ERROR, "Failed to submit bug", e);
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run() {
if(TaskListView.getDefault() != null &&
TaskListView.getDefault().getViewer() != null){
new RefreshBugzillaReportsAction().run();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();
}
@Override
protected void createDescriptionLayout() {
// Description Area
Composite descriptionComposite = new Composite(infoArea, SWT.NONE);
GridLayout descriptionLayout = new GridLayout();
descriptionLayout.numColumns = 4;
descriptionComposite.setLayout(descriptionLayout);
descriptionComposite.setBackground(background);
GridData descriptionData = new GridData(GridData.FILL_BOTH);
descriptionData.horizontalSpan = 1;
descriptionData.grabExcessVerticalSpace = false;
descriptionComposite.setLayoutData(descriptionData);
// End Description Area
StyledText t = newLayout(descriptionComposite, 4, "Description:", HEADER);
t.addListener(SWT.FocusIn, new DescriptionListener());
t = newLayout(descriptionComposite, 4, bug.getDescription(), VALUE);
t.setFont(COMMENT_FONT);
t.addListener(SWT.FocusIn, new DescriptionListener());
texts.add(textsindex, t);
textHash.put(bug.getDescription(), t);
textsindex++;
}
@Override
protected void createCommentLayout() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// Additional (read-only) Comments Area
Composite addCommentsComposite = new Composite(infoArea, SWT.NONE);
GridLayout addCommentsLayout = new GridLayout();
addCommentsLayout.numColumns = 4;
addCommentsComposite.setLayout(addCommentsLayout);
addCommentsComposite.setBackground(background);
GridData addCommentsData = new GridData(GridData.FILL_BOTH);
addCommentsData.horizontalSpan = 1;
addCommentsData.grabExcessVerticalSpace = false;
addCommentsComposite.setLayoutData(addCommentsData);
// End Additional (read-only) Comments Area
StyledText t = null;
for (Iterator<Comment> it = bug.getComments().iterator(); it.hasNext(); ) {
Comment comment = it.next();
String commentHeader = "Additional comment #" + comment.getNumber() + " from "
+ comment.getAuthorName() + " on "
+ df.format(comment.getCreated());
t = newLayout(addCommentsComposite, 4, commentHeader, HEADER);
t.addListener(SWT.FocusIn, new CommentListener(comment));
t = newLayout(addCommentsComposite, 4, comment.getText(), VALUE);
t.setFont(COMMENT_FONT);
t.addListener(SWT.FocusIn, new CommentListener(comment));
//code for outline
texts.add(textsindex, t);
textHash.put(comment, t);
textsindex++;
}
// Additional Comments Text
Composite addCommentsTitleComposite =
new Composite(addCommentsComposite, SWT.NONE);
GridLayout addCommentsTitleLayout = new GridLayout();
addCommentsTitleLayout.horizontalSpacing = 0;
addCommentsTitleLayout.marginWidth = 0;
addCommentsTitleComposite.setLayout(addCommentsTitleLayout);
addCommentsTitleComposite.setBackground(background);
GridData addCommentsTitleData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
addCommentsTitleData.horizontalSpan = 4;
addCommentsTitleData.grabExcessVerticalSpace = false;
addCommentsTitleComposite.setLayoutData(addCommentsTitleData);
newLayout(
addCommentsTitleComposite,
4,
"Additional Comments:",
HEADER).addListener(SWT.FocusIn, new NewCommentListener());
addCommentsText =
new Text(
addCommentsComposite,
SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
addCommentsText.setFont(COMMENT_FONT);
GridData addCommentsTextData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
addCommentsTextData.horizontalSpan = 4;
addCommentsTextData.widthHint = DESCRIPTION_WIDTH;
addCommentsTextData.heightHint = DESCRIPTION_HEIGHT;
addCommentsText.setLayoutData(addCommentsTextData);
addCommentsText.setText(bug.getNewComment());
addCommentsText.addListener(SWT.KeyUp, new Listener() {
public void handleEvent(Event event) {
String sel = addCommentsText.getText();
if (!(bug.getNewNewComment().equals(sel))) {
bug.setNewNewComment(sel);
changeDirtyStatus(true);
}
validateInput();
}
});
addCommentsText.addListener(SWT.FocusIn, new NewCommentListener());
// End Additional Comments Text
addCommentsTextBox = addCommentsText;
this.createSeparatorSpace(addCommentsComposite);
}
@Override
protected void addKeywordsList(String keywords, Composite attributesComposite) {
newLayout(attributesComposite, 1, "Keywords:", PROPERTY);
keywordsText = new Text(attributesComposite, SWT.BORDER);
keywordsText.setFont(TEXT_FONT);
keywordsText.setEditable(false);
keywordsText.setForeground(foreground);
keywordsText.setBackground(JFaceColors.getErrorBackground(display));
GridData keywordsData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
keywordsData.horizontalSpan = 2;
keywordsData.widthHint = 200;
keywordsText.setLayoutData(keywordsData);
keywordsText.setText(keywords);
keywordsText.addListener(SWT.FocusIn, new GenericListener());
keyWordsList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
keyWordsList.setFont(TEXT_FONT);
GridData keyWordsTextData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
keyWordsTextData.horizontalSpan = 1;
keyWordsTextData.widthHint = 125;
keyWordsTextData.heightHint = 40;
keyWordsList.setLayoutData(keyWordsTextData);
// initialize the keywords list with valid values
java.util.List<String> keywordList = bug.getKeywords();
if (keywordList != null) {
for (Iterator<String> it = keywordList.iterator(); it.hasNext(); ) {
String keyword = it.next();
keyWordsList.add(keyword);
}
// get the selected keywords for the bug
StringTokenizer st = new StringTokenizer(keywords, ",", false);
ArrayList<Integer> indicies = new ArrayList<Integer>();
while (st.hasMoreTokens()) {
String s = st.nextToken().trim();
int index = keyWordsList.indexOf(s);
if (index != -1)
indicies.add(new Integer(index));
}
// select the keywords that were selected for the bug
int length = indicies.size();
int[] sel = new int[length];
for (int i = 0; i < length; i++) {
sel[i] = indicies.get(i).intValue();
}
keyWordsList.select(sel);
}
keyWordsList.addSelectionListener(new KeywordListener());
keyWordsList.addListener(SWT.FocusIn, new GenericListener());
}
@Override
protected void addCCList(String ccValue, Composite attributesComposite) {
newLayout(attributesComposite, 1, "Add CC:", PROPERTY);
ccText = new Text(attributesComposite, SWT.BORDER);
ccText.setFont(TEXT_FONT);
ccText.setEditable(true);
ccText.setForeground(foreground);
ccText.setBackground(background);
GridData ccData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ccData.horizontalSpan = 1;
ccData.widthHint = 200;
ccText.setLayoutData(ccData);
ccText.setText(ccValue);
ccText.addListener(SWT.FocusIn, new GenericListener());
ccText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
changeDirtyStatus(true);
Attribute a = bug.getAttributeForKnobName("newcc");
if(a != null){
a.setNewValue(ccText.getText());
}
}
});
newLayout(attributesComposite, 1, "CC: (Select to remove)", PROPERTY);
ccList = new List(attributesComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER);
ccList.setFont(TEXT_FONT);
GridData ccListData =
new GridData(GridData.HORIZONTAL_ALIGN_FILL);
ccListData.horizontalSpan = 1;
ccListData.widthHint = 125;
ccListData.heightHint = 40;
ccList.setLayoutData(ccListData);
// initialize the keywords list with valid values
Set<String> ccs = bug.getCC();
if (ccs != null) {
for (Iterator<String> it = ccs.iterator(); it.hasNext(); ) {
String cc = it.next();
ccList.add(HtmlStreamTokenizer.unescape(cc));
}
}
ccList.addSelectionListener(new SelectionListener(){
public void widgetSelected(SelectionEvent e) {
changeDirtyStatus(true);
for(String cc: ccList.getItems()){
int index = ccList.indexOf(cc);
if(ccList.isSelected(index)){
removeCC.add(cc);
} else {
removeCC.remove(cc);
}
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
ccList.addListener(SWT.FocusIn, new GenericListener());
}
@Override
protected void updateBug() {
// go through all of the attributes and update the main values to the new ones
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if(a.getNewValue().compareTo(a.getValue()) != 0){
bug.setHasChanged(true);
}
a.setValue(a.getNewValue());
}
if(bug.getNewComment().compareTo(bug.getNewNewComment()) != 0){
bug.setHasChanged(true);
}
// Update some other fields as well.
bug.setNewComment(bug.getNewNewComment());
}
@Override
protected void restoreBug() {
if(bug == null)
return;
// go through all of the attributes and restore the new values to the main ones
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
a.setNewValue(a.getValue());
}
// Restore some other fields as well.
bug.setNewNewComment(bug.getNewComment());
}
/**
* This job opens a compare editor to compare the current state of the bug
* in the editor with the bug on the server.
*/
protected class OpenCompareEditorJob extends Job {
public OpenCompareEditorJob(String name) {
super(name);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
final BugReport serverBug;
try {
serverBug = BugzillaRepository.getInstance().getBug(bug.getId());
// If no bug was found on the server, throw an exception so that the
// user gets the same message that appears when there is a problem reading the server.
if (serverBug == null)
throw new Exception();
} catch (Exception e) {
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openInformation(Workbench.getInstance().getActiveWorkbenchWindow().getShell(),
"Could not open bug.", "Bug #" + bug.getId() + " could not be read from the server.");
}
});
return new Status(IStatus.OK, IBugzillaConstants.PLUGIN_ID, IStatus.OK, "Could not get the bug report from the server.", null);
}
Workbench.getInstance().getDisplay().asyncExec(new Runnable() {
public void run() {
compareInput.setTitle("Bug #" + bug.getId());
compareInput.setLeft(bug);
compareInput.setRight(serverBug);
CompareUI.openCompareEditor(compareInput);
}
});
return new Status(IStatus.OK, IBugzillaConstants.PLUGIN_ID, IStatus.OK, "", null);
}
}
/**
* Class to handle the selection change of the keywords.
*/
protected class KeywordListener implements SelectionListener {
/*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected(SelectionEvent arg0) {
changeDirtyStatus(true);
// get the selected keywords and create a string to submit
StringBuffer keywords = new StringBuffer();
String [] sel = keyWordsList.getSelection();
// allow unselecting 1 keyword when it is the only one selected
if(keyWordsList.getSelectionCount() == 1) {
int index = keyWordsList.getSelectionIndex();
String keyword = keyWordsList.getItem(index);
if (bug.getAttribute("Keywords").getNewValue().equals(keyword))
keyWordsList.deselectAll();
}
for(int i = 0; i < keyWordsList.getSelectionCount(); i++) {
keywords.append(sel[i]);
if (i != keyWordsList.getSelectionCount()-1) {
keywords.append(",");
}
}
bug.getAttribute("Keywords").setNewValue(keywords.toString());
// update the keywords text field
keywordsText.setText(keywords.toString());
}
/*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected(SelectionEvent arg0) {
// no need to listen to this
}
}
/**
* A listener for selection of the description field.
*/
protected class DescriptionListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), "Description", true, bug.getSummary()))));
}
}
/**
* A listener for selection of a comment.
*/
protected class CommentListener implements Listener {
/** The comment that this listener is for. */
private Comment comment;
/**
* Creates a new <code>CommentListener</code>.
* @param comment The comment that this listener is for.
*/
public CommentListener(Comment comment) {
this.comment = comment;
}
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), comment.getCreated().toString(), comment, bug.getSummary()))));
}
}
/**
* A listener for selection of the textbox where a new comment is entered
* in.
*/
protected class NewCommentListener implements Listener {
public void handleEvent(Event event) {
fireSelectionChanged(new SelectionChangedEvent(selectionProvider, new StructuredSelection(new BugzillaReportSelection(bug.getId(), bug.getServer(), "New Comment", false, bug.getSummary()))));
}
}
/**
* Class to handle the selection change of the radio buttons.
*/
protected class RadioButtonListener implements SelectionListener, ModifyListener {
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
Button selected = null;
for (int i = 0; i < radios.length; i++) {
if (radios[i].getSelection())
selected = radios[i];
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected){
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
Operation o = bug.getOperation(radios[i].getText());
bug.setSelectedOperation(o);
ExistingBugEditor.this.changeDirtyStatus(true);
}
else if(e.widget == radioOptions[i]) {
Operation o = bug.getOperation(radios[i].getText());
o.setOptionSelection(((Combo)radioOptions[i]).getItem(((Combo)radioOptions[i]).getSelectionIndex()));
if(bug.getSelectedOperation() != null)
bug.getSelectedOperation().setChecked(false);
o.setChecked(true);
bug.setSelectedOperation(o);
radios[i].setSelection(true);
if(selected != null && selected != radios[i]){
selected.setSelection(false);
}
ExistingBugEditor.this.changeDirtyStatus(true);
}
}
validateInput();
}
public void modifyText(ModifyEvent e) {
Button selected = null;
for (int i = 0; i < radios.length; i++) {
if (radios[i].getSelection())
selected = radios[i];
}
// determine the operation to do to the bug
for (int i = 0; i < radios.length; i++) {
if (radios[i] != e.widget && radios[i] != selected){
radios[i].setSelection(false);
}
if (e.widget == radios[i]) {
Operation o = bug.getOperation(radios[i].getText());
bug.setSelectedOperation(o);
ExistingBugEditor.this.changeDirtyStatus(true);
}
else if(e.widget == radioOptions[i]) {
Operation o = bug.getOperation(radios[i].getText());
o.setInputValue(((Text)radioOptions[i]).getText());
if(bug.getSelectedOperation() != null)
bug.getSelectedOperation().setChecked(false);
o.setChecked(true);
bug.setSelectedOperation(o);
radios[i].setSelection(true);
if(selected != null && selected != radios[i]){
selected.setSelection(false);
}
ExistingBugEditor.this.changeDirtyStatus(true);
}
}
validateInput();
}
}
private void validateInput() {
Operation o = bug.getSelectedOperation();
if(o != null && o.getKnobName().compareTo("resolve") == 0 && (addCommentsText.getText() == null || addCommentsText.getText().equals(""))){
submitButton.setEnabled(false);
} else{
submitButton.setEnabled(true);
}
}
@Override
public void handleSummaryEvent() {
String sel = summaryText.getText();
Attribute a = getBug().getAttribute("Summary");
if (!(a.getNewValue().equals(sel))) {
a.setNewValue(sel);
changeDirtyStatus(true);
}
}
// TODO used for spell checking. Add back when we want to support this
// protected Button checkSpellingButton;
//
// private void checkSpelling() {
// SpellingContext context= new SpellingContext();
// context.setContentType(Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT));
// IDocument document = new Document(addCommentsTextBox.getText());
// ISpellingProblemCollector collector= new SpellingProblemCollector(document);
// EditorsUI.getSpellingService().check(document, context, collector, new NullProgressMonitor());
// }
//
// private class SpellingProblemCollector implements ISpellingProblemCollector {
//
// private IDocument document;
//
// private SpellingDialog spellingDialog;
//
// public SpellingProblemCollector(IDocument document){
// this.document = document;
// spellingDialog = new SpellingDialog(Display.getCurrent().getActiveShell(), "Spell Checking", document);
// }
//
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#accept(org.eclipse.ui.texteditor.spelling.SpellingProblem)
// */
// public void accept(SpellingProblem problem) {
// try {
// int line= document.getLineOfOffset(problem.getOffset()) + 1;
// String word= document.get(problem.getOffset(), problem.getLength());
// System.out.println(word);
// for(ICompletionProposal proposal : problem.getProposals()){
// System.out.println(">>>" + proposal.getDisplayString());
// }
//
// spellingDialog.open(word, problem.getProposals());
//
// } catch (BadLocationException x) {
// // drop this SpellingProblem
// }
// }
//
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#beginCollecting()
// */
// public void beginCollecting() {
//
// }
//
// /*
// * @see org.eclipse.ui.texteditor.spelling.ISpellingProblemCollector#endCollecting()
// */
// public void endCollecting() {
// MessageDialog.openInformation(Display.getCurrent().getActiveShell(), "Spell Checking Finished", "The spell check has finished");
// }
// }
}
| false | true | protected void submitBug() {
ExistingBugEditor.this.showBusy(true);
final BugPost form = new BugPost();
// set the url for the bug to be submitted to
setURL(form, "process_bug.cgi");
// go through all of the attributes and add them to the bug post
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if (a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && !a.isHidden()) {
String value = a.getNewValue();
// add the attribute to the bug post
form.add(a.getParameterName(), checkText(value));
}
else if(a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && a.isHidden()) {
// we have a hidden attribute and we should send it back.
form.add(a.getParameterName(), a.getValue());
}
}
// make sure that the comment is broken up into 80 character lines
bug.setNewNewComment(formatText(bug.getNewNewComment()));
// add the summary to the bug post
form.add("short_desc", bug.getAttribute("Summary").getNewValue());
if(removeCC != null && removeCC.size() > 0){
String[] s = new String[removeCC.size()];
form.add("cc", toCommaSeparatedList(removeCC.toArray(s)));
form.add("removecc", "true");
}
// add the operation to the bug post
Operation o = bug.getSelectedOperation();
if (o == null)
form.add("knob", "none");
else {
form.add("knob", o.getKnobName());
if(o.hasOptions()) {
String sel = o.getOptionValue(o.getOptionSelection());
form.add(o.getOptionName(), sel);
} else if (o.isInput()){
String sel = o.getInputValue();
form.add(o.getInputName(), sel);
}
}
form.add("form_name", "process_bug");
// add the new comment to the bug post if there is some text in it
if(bug.getNewNewComment().length() != 0) {
form.add("comment", bug.getNewNewComment());
}
final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(final IProgressMonitor monitor)
throws CoreException {
try {
form.post();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable(){
public void run() {
// TODO what do we do if the editor is closed
if (ExistingBugEditor.this != null
&& !ExistingBugEditor.this.isDisposed()) {
changeDirtyStatus(false);
BugzillaPlugin.getDefault().getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.closeEditor(ExistingBugEditor.this, true);
}
OfflineView.removeReport(bug);
}
});
} catch (final BugzillaException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
BugzillaPlugin.getDefault().logAndShowExceptionDetailsDialog(
e,
"occurred while posting the bug.",
"I/O Error");
}
});
ExistingBugEditor.this.showBusy(false);
} catch (final PossibleBugzillaFailureException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
WebBrowserDialog.openAcceptAgreement(null,
"Possible Bugzilla Failure",
"Bugzilla may not have posted your bug.\n" + e.getMessage(),
form.getError());
BugzillaPlugin.log(e);
}
});
ExistingBugEditor.this.showBusy(false);
} catch (final LoginException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(null,
"Login Error",
"Bugzilla could not post your bug since your login name or password is incorrect.\nPlease check your settings in the bugzilla preferences. ");
}
});
ExistingBugEditor.this.showBusy(false);
}
}
};
Job job = new Job("Submitting Bug"){
@Override
protected IStatus run(IProgressMonitor monitor) {
try{
op.run(monitor);
} catch (Exception e){
MylarPlugin.log(e, "Failed to submit bug");
return new Status(Status.ERROR, "org.eclipse.mylar.bugzilla.ui", Status.ERROR, "Failed to submit bug", e);
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run() {
if(TaskListView.getDefault() != null &&
TaskListView.getDefault().getViewer() != null){
new RefreshBugzillaReportsAction().run();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();
}
| protected void submitBug() {
submitButton.setEnabled(false);
ExistingBugEditor.this.showBusy(true);
final BugPost form = new BugPost();
// set the url for the bug to be submitted to
setURL(form, "process_bug.cgi");
// go through all of the attributes and add them to the bug post
for (Iterator<Attribute> it = bug.getAttributes().iterator(); it.hasNext(); ) {
Attribute a = it.next();
if (a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && !a.isHidden()) {
String value = a.getNewValue();
// add the attribute to the bug post
form.add(a.getParameterName(), checkText(value));
}
else if(a != null && a.getParameterName() != null && a.getParameterName().compareTo("") != 0 && a.isHidden()) {
// we have a hidden attribute and we should send it back.
form.add(a.getParameterName(), a.getValue());
}
}
// make sure that the comment is broken up into 80 character lines
bug.setNewNewComment(formatText(bug.getNewNewComment()));
// add the summary to the bug post
form.add("short_desc", bug.getAttribute("Summary").getNewValue());
if(removeCC != null && removeCC.size() > 0){
String[] s = new String[removeCC.size()];
form.add("cc", toCommaSeparatedList(removeCC.toArray(s)));
form.add("removecc", "true");
}
// add the operation to the bug post
Operation o = bug.getSelectedOperation();
if (o == null)
form.add("knob", "none");
else {
form.add("knob", o.getKnobName());
if(o.hasOptions()) {
String sel = o.getOptionValue(o.getOptionSelection());
form.add(o.getOptionName(), sel);
} else if (o.isInput()){
String sel = o.getInputValue();
form.add(o.getInputName(), sel);
}
}
form.add("form_name", "process_bug");
// add the new comment to the bug post if there is some text in it
if(bug.getNewNewComment().length() != 0) {
form.add("comment", bug.getNewNewComment());
}
final WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
protected void execute(final IProgressMonitor monitor)
throws CoreException {
try {
form.post();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable(){
public void run() {
// TODO what do we do if the editor is closed
if (ExistingBugEditor.this != null
&& !ExistingBugEditor.this.isDisposed()) {
changeDirtyStatus(false);
BugzillaPlugin.getDefault().getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.closeEditor(ExistingBugEditor.this, true);
}
OfflineView.removeReport(bug);
}
});
} catch (final BugzillaException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
BugzillaPlugin.getDefault().logAndShowExceptionDetailsDialog(
e,
"occurred while posting the bug.",
"I/O Error");
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final PossibleBugzillaFailureException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
WebBrowserDialog.openAcceptAgreement(null,
"Possible Bugzilla Failure",
"Bugzilla may not have posted your bug.\n" + e.getMessage(),
form.getError());
BugzillaPlugin.log(e);
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
} catch (final LoginException e) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(null,
"Login Error",
"Bugzilla could not post your bug since your login name or password is incorrect.\nPlease check your settings in the bugzilla preferences. ");
}
});
submitButton.setEnabled(true);
ExistingBugEditor.this.showBusy(false);
}
}
};
Job job = new Job("Submitting Bug"){
@Override
protected IStatus run(IProgressMonitor monitor) {
try{
op.run(monitor);
} catch (Exception e){
MylarPlugin.log(e, "Failed to submit bug");
return new Status(Status.ERROR, "org.eclipse.mylar.bugzilla.ui", Status.ERROR, "Failed to submit bug", e);
}
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run() {
if(TaskListView.getDefault() != null &&
TaskListView.getDefault().getViewer() != null){
new RefreshBugzillaReportsAction().run();
}
}
});
return Status.OK_STATUS;
}
};
job.schedule();
}
|
diff --git a/NestedFragments/src/com/example/newspinproj/TaskFragment.java b/NestedFragments/src/com/example/newspinproj/TaskFragment.java
index 7f3a130..ab94b81 100644
--- a/NestedFragments/src/com/example/newspinproj/TaskFragment.java
+++ b/NestedFragments/src/com/example/newspinproj/TaskFragment.java
@@ -1,219 +1,221 @@
package com.example.newspinproj;
//import android.app.ListFragment;
import java.util.ArrayList;
import Model.DataContainer;
import Model.Task;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class TaskFragment extends ListFragment {
private View view = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Task> copy;
Bundle bundle = getArguments();
if (bundle == null) {
copy = DataContainer.getTasks();
if (copy == null) {
copy = new ArrayList<Task>();
}
} else {
String date = bundle.getString("date");
String group = bundle.getString("group");
if(date != null && group != null) {
copy = DataContainer.getTasksbyGroupandDay(group, date);
} else if (date != null) {
copy = DataContainer.getListByDay(date);
} else if (group != null) {
copy = DataContainer.getTasksByGroup(group);
} else {
copy = new ArrayList<Task>();
}
}
ArrayList<Task> values = new ArrayList<Task>(copy);
System.out.println(values.toString());
setListAdapter(new MobileArrayAdapter(this.getActivity(), values));
}
static TaskFragment newInstance(int num) {
TaskFragment f = new TaskFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (true || view == null)
view = inflater.inflate(R.layout.task_fragment, container, false);
return view;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// get selected items
/*
* String selectedValue = ((Task) getListAdapter().getItem(position))
* .getname();
*/
// Toast.makeText(this.getActivity(), selectedValue,
// Toast.LENGTH_SHORT).show();
String selectedValue = ((Task) getListAdapter().getItem(position))
.getname();
String selectedTime = (String) ((Task) getListAdapter().getItem(
position)).getTime();
String selectedgroup = (String) ((Task) getListAdapter().getItem(
position)).getGroup();
String selectedutid = (String) ((Task) getListAdapter().getItem(
position)).getutid();
String selectedmem = ((Task) getListAdapter().getItem(position))
.getunfilteredunames();
//
Intent i = new Intent(getActivity(), TaskDetailsActivity.class);
i.putExtra("taskname", selectedValue);
i.putExtra("tasktime", selectedTime);
i.putExtra("taskgroup", selectedgroup);
i.putExtra("people", selectedmem);
i.putExtra("utid", selectedutid);
startActivity(i);
}
/*
@Override
public void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}*/
@Override
public void onDestroyView() {
// super.onDestroyView();
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
if (null != parentViewGroup) {
parentViewGroup.removeView(view);
// view=null;
}
super.onDestroyView();
}
/*
* @Override public void onAttach(Activity activity) {
* super.onAttach(activity);
*
* Toast.makeText(activity.getApplicationContext(),
* String.valueOf(this.getId()), Toast.LENGTH_SHORT).show();
*
* }
*/
/*
* @Override public void onStop() { super.onStop();
* System.out.println("Tasks stopped"); }
*
* @Override public void onPause() { super.onStop();
* System.out.println("Tasks paused"); }
*
* @Override public void onResume() { System.out.println("Tasks resumed");
*
* super.onResume(); }
*/
private class MobileArrayAdapter extends ArrayAdapter<Task> {
private final Context context;
private final ArrayList<Task> values;
public MobileArrayAdapter(Context context, ArrayList<Task> values2) {
super(context, R.layout.listviewlayout, values2);
this.context = context;
this.values = values2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("got a value set");
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listviewlayout, parent,
false);
TextView taskNameView = (TextView) rowView
.findViewById(R.id.taskName);
TextView taskTimeView = (TextView) rowView
.findViewById(R.id.taskTime);
TextView taskGroupView = (TextView) rowView
.findViewById(R.id.taskGroup);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
taskNameView.setText(values.get(position).getname());
taskTimeView.setText(values.get(position).getTime());
taskGroupView.setText(values.get(position).getGroup());
- //Boolean isLeader = DataContainer.getFullLeaderNames(groupName).contains(name);
+ String groupName = values.get(position).getGroup();
+ String fullname = DataContainer.getFullnameForUser(DataContainer.username);
+ Boolean isLeader = DataContainer.getFullLeaderNames(groupName).contains(fullname);
//Boolean isLeader = name.startsWith("M");
- Boolean isLeader = true;
- ImageView leaderIcon = (ImageView) view.findViewById(R.id.star);
+ //Boolean isLeader = true;
+ ImageView leaderIcon = (ImageView) rowView.findViewById(R.id.star);
leaderIcon.setVisibility(isLeader ? View.VISIBLE : View.INVISIBLE);
/*
* Typeface tf = Typeface.defaultFromStyle(Typeface.ITALIC);
* taskTimeView.setTypeface(tf);
*/
// Change icon based on name
String s = values.get(position).getname();
// System.out.println(s);
if (s.equals("Take out the trash")) {
imageView.setImageResource(R.drawable.trash);
} else if (s.equals("Dish duty")) {
imageView.setImageResource(R.drawable.dishes);
} else if (s.equals("Clean-up")) {
imageView.setImageResource(R.drawable.cleanup);
} else if (s.equals("Water the plants")) {
imageView.setImageResource(R.drawable.plants);
} else if (s.equals("Feed the pets")) {
imageView.setImageResource(R.drawable.pet);
} else {
imageView.setImageResource(R.drawable.custom);
}
return rowView;
}
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("got a value set");
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listviewlayout, parent,
false);
TextView taskNameView = (TextView) rowView
.findViewById(R.id.taskName);
TextView taskTimeView = (TextView) rowView
.findViewById(R.id.taskTime);
TextView taskGroupView = (TextView) rowView
.findViewById(R.id.taskGroup);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
taskNameView.setText(values.get(position).getname());
taskTimeView.setText(values.get(position).getTime());
taskGroupView.setText(values.get(position).getGroup());
//Boolean isLeader = DataContainer.getFullLeaderNames(groupName).contains(name);
//Boolean isLeader = name.startsWith("M");
Boolean isLeader = true;
ImageView leaderIcon = (ImageView) view.findViewById(R.id.star);
leaderIcon.setVisibility(isLeader ? View.VISIBLE : View.INVISIBLE);
/*
* Typeface tf = Typeface.defaultFromStyle(Typeface.ITALIC);
* taskTimeView.setTypeface(tf);
*/
// Change icon based on name
String s = values.get(position).getname();
// System.out.println(s);
if (s.equals("Take out the trash")) {
imageView.setImageResource(R.drawable.trash);
} else if (s.equals("Dish duty")) {
imageView.setImageResource(R.drawable.dishes);
} else if (s.equals("Clean-up")) {
imageView.setImageResource(R.drawable.cleanup);
} else if (s.equals("Water the plants")) {
imageView.setImageResource(R.drawable.plants);
} else if (s.equals("Feed the pets")) {
imageView.setImageResource(R.drawable.pet);
} else {
imageView.setImageResource(R.drawable.custom);
}
return rowView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("got a value set");
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listviewlayout, parent,
false);
TextView taskNameView = (TextView) rowView
.findViewById(R.id.taskName);
TextView taskTimeView = (TextView) rowView
.findViewById(R.id.taskTime);
TextView taskGroupView = (TextView) rowView
.findViewById(R.id.taskGroup);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
taskNameView.setText(values.get(position).getname());
taskTimeView.setText(values.get(position).getTime());
taskGroupView.setText(values.get(position).getGroup());
String groupName = values.get(position).getGroup();
String fullname = DataContainer.getFullnameForUser(DataContainer.username);
Boolean isLeader = DataContainer.getFullLeaderNames(groupName).contains(fullname);
//Boolean isLeader = name.startsWith("M");
//Boolean isLeader = true;
ImageView leaderIcon = (ImageView) rowView.findViewById(R.id.star);
leaderIcon.setVisibility(isLeader ? View.VISIBLE : View.INVISIBLE);
/*
* Typeface tf = Typeface.defaultFromStyle(Typeface.ITALIC);
* taskTimeView.setTypeface(tf);
*/
// Change icon based on name
String s = values.get(position).getname();
// System.out.println(s);
if (s.equals("Take out the trash")) {
imageView.setImageResource(R.drawable.trash);
} else if (s.equals("Dish duty")) {
imageView.setImageResource(R.drawable.dishes);
} else if (s.equals("Clean-up")) {
imageView.setImageResource(R.drawable.cleanup);
} else if (s.equals("Water the plants")) {
imageView.setImageResource(R.drawable.plants);
} else if (s.equals("Feed the pets")) {
imageView.setImageResource(R.drawable.pet);
} else {
imageView.setImageResource(R.drawable.custom);
}
return rowView;
}
|
diff --git a/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java b/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java
index a3aedca..ac71fee 100644
--- a/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java
+++ b/src/main/java/org/esa/beam/meris/icol/graphgen/GraphGenMain.java
@@ -1,84 +1,84 @@
/*
* Copyright (C) 2010 Brockmann Consult GmbH ([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 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam.meris.icol.graphgen;
import org.esa.beam.framework.dataio.ProductIO;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.gpf.GPF;
import org.esa.beam.framework.gpf.Operator;
import org.esa.beam.meris.icol.meris.MerisOp;
import org.esa.beam.meris.icol.tm.TmOp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Test tool for the {@link GraphGen} class.
* <pre>
* Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]
* </pre>
*
* @author Thomas Storm
* @author Norman Fomferra
*/
public class GraphGenMain {
static {
GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis();
}
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]");
}
String productPath = args[0];
String graphmlPath = args[1];
String opSelector = args[2];
- String hideBandsArg = args[3];
- String hideProductsArg = args[4];
+ String hideBandsArg = args.length > 3 ? args[3] : null;
+ String hideProductsArg = args.length > 4 ? args[4] : null;
Operator op;
if (opSelector.equalsIgnoreCase("meris")) {
op = new MerisOp();
} else if (opSelector.equalsIgnoreCase("landsat")) {
op = new TmOp();
} else {
throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'.");
}
final Product sourceProduct = ProductIO.readProduct(new File(productPath));
op.setSourceProduct(sourceProduct);
final Product targetProduct = op.getTargetProduct();
FileWriter fileWriter = new FileWriter(new File(graphmlPath));
BufferedWriter writer = new BufferedWriter(fileWriter);
final GraphGen graphGen = new GraphGen();
- boolean hideBands = args.length >= 4 && Boolean.parseBoolean(hideBandsArg);
- final boolean hideProducts = args.length >= 5 && Boolean.parseBoolean(hideProductsArg);
+ boolean hideBands = hideBandsArg != null && Boolean.parseBoolean(hideBandsArg);
+ final boolean hideProducts = hideProductsArg != null && Boolean.parseBoolean(hideProductsArg);
if (hideProducts) {
hideBands = true;
}
GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts);
graphGen.generateGraph(targetProduct, handler);
writer.close();
}
}
| false | true | public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]");
}
String productPath = args[0];
String graphmlPath = args[1];
String opSelector = args[2];
String hideBandsArg = args[3];
String hideProductsArg = args[4];
Operator op;
if (opSelector.equalsIgnoreCase("meris")) {
op = new MerisOp();
} else if (opSelector.equalsIgnoreCase("landsat")) {
op = new TmOp();
} else {
throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'.");
}
final Product sourceProduct = ProductIO.readProduct(new File(productPath));
op.setSourceProduct(sourceProduct);
final Product targetProduct = op.getTargetProduct();
FileWriter fileWriter = new FileWriter(new File(graphmlPath));
BufferedWriter writer = new BufferedWriter(fileWriter);
final GraphGen graphGen = new GraphGen();
boolean hideBands = args.length >= 4 && Boolean.parseBoolean(hideBandsArg);
final boolean hideProducts = args.length >= 5 && Boolean.parseBoolean(hideProductsArg);
if (hideProducts) {
hideBands = true;
}
GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts);
graphGen.generateGraph(targetProduct, handler);
writer.close();
}
| public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Usage: GraphGenMain <productPath> <graphmlPath> 'meris'|'landsat' [[<hideBands>] <hideProducts>]");
}
String productPath = args[0];
String graphmlPath = args[1];
String opSelector = args[2];
String hideBandsArg = args.length > 3 ? args[3] : null;
String hideProductsArg = args.length > 4 ? args[4] : null;
Operator op;
if (opSelector.equalsIgnoreCase("meris")) {
op = new MerisOp();
} else if (opSelector.equalsIgnoreCase("landsat")) {
op = new TmOp();
} else {
throw new IllegalArgumentException("argument 3 must be 'meris' or 'landsat'.");
}
final Product sourceProduct = ProductIO.readProduct(new File(productPath));
op.setSourceProduct(sourceProduct);
final Product targetProduct = op.getTargetProduct();
FileWriter fileWriter = new FileWriter(new File(graphmlPath));
BufferedWriter writer = new BufferedWriter(fileWriter);
final GraphGen graphGen = new GraphGen();
boolean hideBands = hideBandsArg != null && Boolean.parseBoolean(hideBandsArg);
final boolean hideProducts = hideProductsArg != null && Boolean.parseBoolean(hideProductsArg);
if (hideProducts) {
hideBands = true;
}
GraphMLHandler handler = new GraphMLHandler(writer, hideBands, hideProducts);
graphGen.generateGraph(targetProduct, handler);
writer.close();
}
|
diff --git a/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java b/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
index 0b5f141ec..ab861ccbb 100644
--- a/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
+++ b/luni/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
@@ -1,165 +1,168 @@
/*
* 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 javax.net.ssl;
import java.net.InetAddress;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.security.auth.x500.X500Principal;
/**
* A HostnameVerifier consistent with <a
* href="http://www.ietf.org/rfc/rfc2818.txt">RFC 2818</a>.
*
* @hide accessible via HttpsURLConnection.getDefaultHostnameVerifier()
*/
public final class DefaultHostnameVerifier implements HostnameVerifier {
private static final int ALT_DNS_NAME = 2;
private static final int ALT_IPA_NAME = 7;
public final boolean verify(String host, SSLSession session) {
try {
Certificate[] certificates = session.getPeerCertificates();
return verify(host, (X509Certificate) certificates[0]);
} catch (SSLException e) {
return false;
}
}
public boolean verify(String host, X509Certificate certificate) {
return InetAddress.isNumeric(host)
? verifyIpAddress(host, certificate)
: verifyHostName(host, certificate);
}
/**
* Returns true if {@code certificate} matches {@code ipAddress}.
*/
private boolean verifyIpAddress(String ipAddress, X509Certificate certificate) {
for (String altName : getSubjectAltNames(certificate, ALT_IPA_NAME)) {
if (ipAddress.equalsIgnoreCase(altName)) {
return true;
}
}
return false;
}
/**
* Returns true if {@code certificate} matches {@code hostName}.
*/
private boolean verifyHostName(String hostName, X509Certificate certificate) {
hostName = hostName.toLowerCase(Locale.US);
boolean hasDns = false;
for (String altName : getSubjectAltNames(certificate, ALT_DNS_NAME)) {
hasDns = true;
if (verifyHostName(hostName, altName)) {
return true;
}
}
if (!hasDns) {
X500Principal principal = certificate.getSubjectX500Principal();
String cn = new DistinguishedNameParser(principal).find("cn");
if (cn != null) {
return verifyHostName(hostName, cn);
}
}
return false;
}
private List<String> getSubjectAltNames(X509Certificate certificate, int type) {
List<String> result = new ArrayList<String>();
try {
Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
if (subjectAltNames == null) {
return Collections.emptyList();
}
for (Object subjectAltName : subjectAltNames) {
List<?> entry = (List<?>) subjectAltName;
if (entry == null || entry.size() < 2) {
continue;
}
Integer altNameType = (Integer) entry.get(0);
if (altNameType == null) {
continue;
}
if (altNameType == type) {
String altName = (String) entry.get(1);
if (altName != null) {
result.add(altName);
}
}
}
return result;
} catch (CertificateParsingException e) {
return Collections.emptyList();
}
}
/**
* Returns true if {@code hostName} matches the name or pattern {@code cn}.
*
* @param hostName lowercase host name.
* @param cn certificate host name. May include wildcards like
* {@code *.android.com}.
*/
public boolean verifyHostName(String hostName, String cn) {
if (hostName == null || hostName.isEmpty() || cn == null || cn.isEmpty()) {
return false;
}
cn = cn.toLowerCase(Locale.US);
if (!cn.contains("*")) {
return hostName.equals(cn);
}
if (cn.startsWith("*.") && hostName.regionMatches(0, cn, 2, cn.length() - 2)) {
return true; // "*.foo.com" matches "foo.com"
}
int asterisk = cn.indexOf('*');
int dot = cn.indexOf('.');
if (asterisk > dot) {
return false; // malformed; wildcard must be in the first part of the cn
}
if (!hostName.regionMatches(0, cn, 0, asterisk)) {
return false; // prefix before '*' doesn't match
}
int suffixLength = cn.length() - (asterisk + 1);
int suffixStart = hostName.length() - suffixLength;
if (hostName.indexOf('.', asterisk) < suffixStart) {
- return false; // wildcard '*' can't match a '.'
+ // TODO: remove workaround for android.clients.google.com http://b/5426333
+ if (!hostName.equals("android.clients.google.com")) {
+ return false; // wildcard '*' can't match a '.'
+ }
}
if (!hostName.regionMatches(suffixStart, cn, asterisk + 1, suffixLength)) {
return false; // suffix after '*' doesn't match
}
return true;
}
}
| true | true | public boolean verifyHostName(String hostName, String cn) {
if (hostName == null || hostName.isEmpty() || cn == null || cn.isEmpty()) {
return false;
}
cn = cn.toLowerCase(Locale.US);
if (!cn.contains("*")) {
return hostName.equals(cn);
}
if (cn.startsWith("*.") && hostName.regionMatches(0, cn, 2, cn.length() - 2)) {
return true; // "*.foo.com" matches "foo.com"
}
int asterisk = cn.indexOf('*');
int dot = cn.indexOf('.');
if (asterisk > dot) {
return false; // malformed; wildcard must be in the first part of the cn
}
if (!hostName.regionMatches(0, cn, 0, asterisk)) {
return false; // prefix before '*' doesn't match
}
int suffixLength = cn.length() - (asterisk + 1);
int suffixStart = hostName.length() - suffixLength;
if (hostName.indexOf('.', asterisk) < suffixStart) {
return false; // wildcard '*' can't match a '.'
}
if (!hostName.regionMatches(suffixStart, cn, asterisk + 1, suffixLength)) {
return false; // suffix after '*' doesn't match
}
return true;
}
| public boolean verifyHostName(String hostName, String cn) {
if (hostName == null || hostName.isEmpty() || cn == null || cn.isEmpty()) {
return false;
}
cn = cn.toLowerCase(Locale.US);
if (!cn.contains("*")) {
return hostName.equals(cn);
}
if (cn.startsWith("*.") && hostName.regionMatches(0, cn, 2, cn.length() - 2)) {
return true; // "*.foo.com" matches "foo.com"
}
int asterisk = cn.indexOf('*');
int dot = cn.indexOf('.');
if (asterisk > dot) {
return false; // malformed; wildcard must be in the first part of the cn
}
if (!hostName.regionMatches(0, cn, 0, asterisk)) {
return false; // prefix before '*' doesn't match
}
int suffixLength = cn.length() - (asterisk + 1);
int suffixStart = hostName.length() - suffixLength;
if (hostName.indexOf('.', asterisk) < suffixStart) {
// TODO: remove workaround for android.clients.google.com http://b/5426333
if (!hostName.equals("android.clients.google.com")) {
return false; // wildcard '*' can't match a '.'
}
}
if (!hostName.regionMatches(suffixStart, cn, asterisk + 1, suffixLength)) {
return false; // suffix after '*' doesn't match
}
return true;
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java b/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
index 7589f565..562b8552 100644
--- a/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
+++ b/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
@@ -1,3801 +1,3797 @@
/*******************************************************************************
* <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM>
* research group.
*
* Copyright 2005-2010 <e-UCM> research group.
*
* You can access a list of all the contributors to <e-Adventure> at:
* http://e-adventure.e-ucm.es/contributors
*
* <e-UCM> is a research group of the Department of Software Engineering
* and Artificial Intelligence at the Complutense University of Madrid
* (School of Computer Science).
*
* C Profesor Jose Garcia Santesmases sn,
* 28040 Madrid (Madrid), Spain.
*
* For more info please visit: <http://e-adventure.e-ucm.es> or
* <http://www.e-ucm.es>
*
* ****************************************************************************
*
* This file is part of <e-Adventure>, version 1.2.
*
* <e-Adventure> is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* <e-Adventure> is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with <e-Adventure>. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.eucm.eadventure.editor.control;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import es.eucm.eadventure.common.auxiliar.AssetsConstants;
import es.eucm.eadventure.common.auxiliar.File;
import es.eucm.eadventure.common.auxiliar.ReleaseFolders;
import es.eucm.eadventure.common.auxiliar.ReportDialog;
import es.eucm.eadventure.common.auxiliar.SpecialAssetPaths;
import es.eucm.eadventure.common.data.adventure.AdventureData;
import es.eucm.eadventure.common.data.adventure.DescriptorData;
import es.eucm.eadventure.common.data.adventure.DescriptorData.DefaultClickAction;
import es.eucm.eadventure.common.data.adventure.DescriptorData.Perspective;
import es.eucm.eadventure.common.data.animation.Animation;
import es.eucm.eadventure.common.data.animation.Frame;
import es.eucm.eadventure.common.data.chapter.Chapter;
import es.eucm.eadventure.common.data.chapter.Trajectory;
import es.eucm.eadventure.common.data.chapter.elements.NPC;
import es.eucm.eadventure.common.data.chapter.elements.Player;
import es.eucm.eadventure.common.gui.TC;
import es.eucm.eadventure.common.loader.Loader;
import es.eucm.eadventure.common.loader.incidences.Incidence;
import es.eucm.eadventure.editor.auxiliar.filefilters.EADFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.FolderFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.JARFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.XMLFileFilter;
import es.eucm.eadventure.editor.control.config.ConfigData;
import es.eucm.eadventure.editor.control.config.ProjectConfigData;
import es.eucm.eadventure.editor.control.config.SCORMConfigData;
import es.eucm.eadventure.editor.control.controllers.AdventureDataControl;
import es.eucm.eadventure.editor.control.controllers.AssetsController;
import es.eucm.eadventure.editor.control.controllers.DataControlWithResources;
import es.eucm.eadventure.editor.control.controllers.EditorImageLoader;
import es.eucm.eadventure.editor.control.controllers.VarFlagsController;
import es.eucm.eadventure.editor.control.controllers.adaptation.AdaptationProfilesDataControl;
import es.eucm.eadventure.editor.control.controllers.assessment.AssessmentProfilesDataControl;
import es.eucm.eadventure.editor.control.controllers.atrezzo.AtrezzoDataControl;
import es.eucm.eadventure.editor.control.controllers.character.NPCDataControl;
import es.eucm.eadventure.editor.control.controllers.general.AdvancedFeaturesDataControl;
import es.eucm.eadventure.editor.control.controllers.general.ChapterDataControl;
import es.eucm.eadventure.editor.control.controllers.general.ChapterListDataControl;
import es.eucm.eadventure.editor.control.controllers.general.ResourcesDataControl;
import es.eucm.eadventure.editor.control.controllers.item.ItemDataControl;
import es.eucm.eadventure.editor.control.controllers.metadata.lom.LOMDataControl;
import es.eucm.eadventure.editor.control.controllers.scene.SceneDataControl;
import es.eucm.eadventure.editor.control.tools.Tool;
import es.eucm.eadventure.editor.control.tools.general.SwapPlayerModeTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.AddChapterTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.DeleteChapterTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.MoveChapterTool;
import es.eucm.eadventure.editor.control.writer.AnimationWriter;
import es.eucm.eadventure.editor.control.writer.Writer;
import es.eucm.eadventure.editor.data.support.IdentifierSummary;
import es.eucm.eadventure.editor.data.support.VarFlagSummary;
import es.eucm.eadventure.editor.gui.LoadingScreen;
import es.eucm.eadventure.editor.gui.MainWindow;
import es.eucm.eadventure.editor.gui.displaydialogs.InvalidReportDialog;
import es.eucm.eadventure.editor.gui.editdialogs.AdventureDataDialog;
import es.eucm.eadventure.editor.gui.editdialogs.ExportToLOMDialog;
import es.eucm.eadventure.editor.gui.editdialogs.GraphicConfigDialog;
import es.eucm.eadventure.editor.gui.editdialogs.SearchDialog;
import es.eucm.eadventure.editor.gui.editdialogs.VarsFlagsDialog;
import es.eucm.eadventure.editor.gui.editdialogs.customizeguidialog.CustomizeGUIDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.ims.IMSDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.lomdialog.LOMDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.lomes.LOMESDialog;
import es.eucm.eadventure.editor.gui.startdialog.FrameForInitialDialogs;
import es.eucm.eadventure.editor.gui.startdialog.StartDialog;
import es.eucm.eadventure.engine.EAdventureDebug;
/**
* This class is the main controller of the application. It holds the main
* operations and data to control the editor.
*
* @author Bruno Torijano Bueno
*/
/*
* @updated by Javier Torrente. New functionalities added - Support for .ead files. Therefore <e-Adventure> files are no
* longer .zip but .ead
*/
public class Controller {
/**
* Id for the complete chapter data element.
*/
public static final int CHAPTER = 0;
/**
* Id for the scenes list element.
*/
public static final int SCENES_LIST = 1;
/**
* Id for the scene element.
*/
public static final int SCENE = 2;
/**
* Id for the exits list element.
*/
public static final int EXITS_LIST = 3;
/**
* Id for the exit element.
*/
public static final int EXIT = 4;
/**
* Id for the item references list element.
*/
public static final int ITEM_REFERENCES_LIST = 5;
/**
* Id for the item reference element.
*/
public static final int ITEM_REFERENCE = 6;
/**
* Id for the NPC references list element.
*/
public static final int NPC_REFERENCES_LIST = 7;
/**
* Id for the NPC reference element.
*/
public static final int NPC_REFERENCE = 8;
/**
* Id for the cutscenes list element.
*/
public static final int CUTSCENES_LIST = 9;
/**
* Id for the slidescene element.
*/
public static final int CUTSCENE_SLIDES = 10;
public static final int CUTSCENE = 910;
public static final int CUTSCENE_VIDEO = 37;
/**
* Id for the books list element.
*/
public static final int BOOKS_LIST = 11;
/**
* Id for the book element.
*/
public static final int BOOK = 12;
/**
* Id for the book paragraphs list element.
*/
public static final int BOOK_PARAGRAPHS_LIST = 13;
/**
* Id for the title paragraph element.
*/
public static final int BOOK_TITLE_PARAGRAPH = 14;
/**
* Id for the text paragraph element.
*/
public static final int BOOK_TEXT_PARAGRAPH = 15;
/**
* Id for the bullet paragraph element.
*/
public static final int BOOK_BULLET_PARAGRAPH = 16;
/**
* Id for the image paragraph element.
*/
public static final int BOOK_IMAGE_PARAGRAPH = 17;
/**
* Id for the items list element.
*/
public static final int ITEMS_LIST = 18;
/**
* Id for the item element.
*/
public static final int ITEM = 19;
/**
* Id for the actions list element.
*/
public static final int ACTIONS_LIST = 20;
/**
* Id for the "Examine" action element.
*/
public static final int ACTION_EXAMINE = 21;
/**
* Id for the "Grab" action element.
*/
public static final int ACTION_GRAB = 22;
/**
* Id for the "Use" action element.
*/
public static final int ACTION_USE = 23;
/**
* Id for the "Custom" action element.
*/
public static final int ACTION_CUSTOM = 230;
/**
* Id for the "Talk to" action element.
*/
public static final int ACTION_TALK_TO = 231;
/**
* Id for the "Use with" action element.
*/
public static final int ACTION_USE_WITH = 24;
/**
* Id for the "Give to" action element.
*/
public static final int ACTION_GIVE_TO = 25;
/**
* Id for the "Drag-to" action element.
*/
public static final int ACTION_DRAG_TO = 251;
/**
* Id for the "Custom interact" action element.
*/
public static final int ACTION_CUSTOM_INTERACT = 250;
/**
* Id for the player element.
*/
public static final int PLAYER = 26;
/**
* Id for the NPCs list element.
*/
public static final int NPCS_LIST = 27;
/**
* Id for the NPC element.
*/
public static final int NPC = 28;
/**
* Id for the conversation references list element.
*/
public static final int CONVERSATION_REFERENCES_LIST = 29;
/**
* Id for the conversation reference element.
*/
public static final int CONVERSATION_REFERENCE = 30;
/**
* Id for the conversations list element.
*/
public static final int CONVERSATIONS_LIST = 31;
/**
* Id for the tree conversation element.
*/
public static final int CONVERSATION_TREE = 32;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_GRAPH = 33;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_DIALOGUE_LINE = 330;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_OPTION_LINE = 331;
/**
* Id for the resources element.
*/
public static final int RESOURCES = 34;
/**
* Id for the next scene element.
*/
public static final int NEXT_SCENE = 35;
/**
* If for the end scene element.
*/
public static final int END_SCENE = 36;
/**
* Id for Assessment Rule
*/
public static final int ASSESSMENT_RULE = 38;
/**
* Id for Adaptation Rule
*/
public static final int ADAPTATION_RULE = 39;
/**
* Id for Assessment Rules
*/
public static final int ASSESSMENT_PROFILE = 40;
/**
* Id for Adaptation Rules
*/
public static final int ADAPTATION_PROFILE = 41;
/**
* Id for the styled book element.
*/
public static final int STYLED_BOOK = 42;
/**
* Id for the page of a STYLED_BOK.
*/
public static final int BOOK_PAGE = 43;
/**
* Id for timers.
*/
public static final int TIMER = 44;
/**
* Id for the list of timers.
*/
public static final int TIMERS_LIST = 45;
/**
* Id for the advanced features node.
*/
public static final int ADVANCED_FEATURES = 46;
/**
* Id for the assessment profiles node.
*/
public static final int ASSESSSMENT_PROFILES = 47;
/**
* Id for the adaptation profiles node.
*/
public static final int ADAPTATION_PROFILES = 48;
/**
* Id for timed assessment rules
*/
public static final int TIMED_ASSESSMENT_RULE = 49;
/**
* Id for active areas list.
*/
public static final int ACTIVE_AREAS_LIST = 50;
/**
* Id for active area
*/
public static final int ACTIVE_AREA = 51;
/**
* Id for barriers list.
*/
public static final int BARRIERS_LIST = 52;
/**
* Id for barrier
*/
public static final int BARRIER = 53;
/**
* Id for global state
*/
public static final int GLOBAL_STATE = 54;
/**
* Id for global state list
*/
public static final int GLOBAL_STATE_LIST = 55;
/**
* Id for macro
*/
public static final int MACRO = 56;
/**
* Id for macro list
*/
public static final int MACRO_LIST = 57;
/**
* Id for atrezzo item element
*/
public static final int ATREZZO = 58;
/**
* Id for atrezzo list element
*/
public static final int ATREZZO_LIST = 59;
/**
* Id for atrezzo reference
*/
public static final int ATREZZO_REFERENCE = 60;
/**
* Id for atrezzo references list
*/
public static final int ATREZZO_REFERENCES_LIST = 61;
public static final int NODE = 62;
public static final int SIDE = 63;
public static final int TRAJECTORY = 64;
public static final int ANIMATION = 65;
public static final int EFFECT = 66;
//TYPES OF EAD FILES
public static final int FILE_ADVENTURE_1STPERSON_PLAYER = 0;
public static final int FILE_ADVENTURE_3RDPERSON_PLAYER = 1;
public static final int FILE_ASSESSMENT = 2;
public static final int FILE_ADAPTATION = 3;
/**
* Identifiers for differents scorm profiles
*/
public static final int SCORM12 = 0;
public static final int SCORM2004 = 1;
public static final int AGREGA = 2;
/**
* Singleton instance.
*/
private static Controller controllerInstance = null;
/**
* The main window of the application.
*/
private MainWindow mainWindow;
/**
* The complete path to the current open ZIP file.
*/
private String currentZipFile;
/**
* The path to the folder that holds the open file.
*/
private String currentZipPath;
/**
* The name of the file that is being currently edited. Used only to display
* info.
*/
private String currentZipName;
/**
* The data of the adventure being edited.
*/
private AdventureDataControl adventureDataControl;
/**
* Stores if the data has been modified since the last save.
*/
private boolean dataModified;
/**
* Stores the file that contains the GUI strings.
*/
private String languageFile;
private LoadingScreen loadingScreen;
private String lastDialogDirectory;
/*private boolean isTempFile = false;
public boolean isTempFile( ) {
return isTempFile;
}*/
private ChapterListDataControl chaptersController;
private AutoSave autoSave;
private Timer autoSaveTimer;
private boolean isLomEs = false;
/**
* Store all effects selection. Connects the type of effect with the number
* of times that has been used
*/
// private SelectedEffectsController selectedEffects;
/**
* Void and private constructor.
*/
private Controller( ) {
chaptersController = new ChapterListDataControl( );
}
private String getCurrentExportSaveFolder( ) {
return ReleaseFolders.exportsFolder( ).getAbsolutePath( );
}
public String getCurrentLoadFolder( ) {
return ReleaseFolders.projectsFolder( ).getAbsolutePath( );
}
public void setLastDirectory( String directory ) {
this.lastDialogDirectory = directory;
}
public String getLastDirectory( ) {
if( lastDialogDirectory != null ) {
return lastDialogDirectory;
}
else
return ReleaseFolders.projectsFolder( ).getAbsolutePath( );
}
/**
* Returns the instance of the controller.
*
* @return The instance of the controller
*/
public static Controller getInstance( ) {
if( controllerInstance == null )
controllerInstance = new Controller( );
return controllerInstance;
}
public int playerMode( ) {
return adventureDataControl.getPlayerMode( );
}
/**
* Initializing function.
*/
public void init( String arg ) {
// Load the configuration
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
SCORMConfigData.init( );
// Create necessary folders if no created befor
File projectsFolder = ReleaseFolders.projectsFolder( );
if( !projectsFolder.exists( ) ) {
projectsFolder.mkdirs( );
}
File tempFolder = ReleaseFolders.webTempFolder( );
if( !tempFolder.exists( ) ) {
projectsFolder.mkdirs( );
}
File exportsFolder = ReleaseFolders.exportsFolder( );
if( !exportsFolder.exists( ) ) {
exportsFolder.mkdirs( );
}
//Create splash screen
loadingScreen = new LoadingScreen( "PRUEBA", getLoadingImage( ), null );
// Set values for language config
languageFile = ReleaseFolders.LANGUAGE_UNKNOWN;
setLanguage( ReleaseFolders.getLanguageFromPath( ConfigData.getLanguangeFile( ) ), false );
// Create a list for the chapters
chaptersController = new ChapterListDataControl( );
// Inits the controller with empty data
currentZipFile = null;
currentZipPath = null;
currentZipName = null;
//adventureData = new AdventureDataControl( TextConstants.getText( "DefaultValue.AdventureTitle" ), TextConstants.getText( "DefaultValue.ChapterTitle" ), TextConstants.getText( "DefaultValue.SceneId" ) );
//selectedChapter = 0;
//chapterDataControlList.add( new ChapterDataControl( getSelectedChapterData( ) ) );
//identifierSummary = new IdentifierSummary( getSelectedChapterData( ) );
dataModified = false;
//Create main window and hide it
mainWindow = new MainWindow( );
// mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
// Prompt the user to create a new adventure or to load one
//while( currentZipFile == null ) {
// Load the options and show the dialog
//StartDialog start = new StartDialog( );
FrameForInitialDialogs start = new FrameForInitialDialogs(true);
if( arg != null ) {
File projectFile = new File( arg );
if( projectFile.exists( ) ) {
if( projectFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = projectFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( projectFile.isDirectory( ) && projectFile.exists( ) )
loadFile( projectFile.getAbsolutePath( ), true );
}
}
else if( ConfigData.showStartDialog( ) ) {
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
//selectedChapter = 0;
}
if( currentZipFile == null ) {
//newFile( FILE_ADVENTURE_3RDPERSON_PLAYER );
//selectedChapter = -1;
mainWindow.reloadData( );
}
/*
* int optionSelected = mainWindow.showOptionDialog( TextConstants.getText( "StartDialog.Title" ),
* TextConstants.getText( "StartDialog.Message" ), options );
* // If the user wants to create a new file, show the dialog if( optionSelected == 0 ) newFile( );
* // If the user wants to load a existing adventure, show the load dialog else if( optionSelected == 1 )
* loadFile( );
* // If the dialog was closed, exit the aplication else if( optionSelected == JOptionPane.CLOSED_OPTION )
* exit( );
*/
//}
// Show the window
/*mainWindow.setEnabled( true );
mainWindow.reloadData( );
try {
Thread.sleep( 1 );
} catch( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
// Create the main window and hide it
//mainWindow.setVisible( false );
// initialize the selected effects container
//selectedEffects = new SelectedEffectsController();
mainWindow.setResizable( true );
//mainWindow.setEnabled( true );
// mainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
/*public void addSelectedEffect(String name){
selectedEffects.addSelectedEffect(name);
}
public SelectedEffectsController getSelectedEffectsController(){
return selectedEffects;
}*/
public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//change the old animations to eaa animations, this method force to save game
changeAllAnimationFormats();
saveFile( false );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Confirm user that the conditions associated to resource block will be deleted
* @return
*/
public boolean askDeleteConditionsResourceBlock(){
int option = mainWindow.showConfirmDialog(TC.get( "ResourceBlock.deleteOnlyOneBlock.title") ,TC.get("ResourceBlock.deleteOnlyOneBlock.message"));
if( option == JOptionPane.YES_OPTION )
return true;
else if( option == JOptionPane.NO_OPTION || option == JOptionPane.CANCEL_OPTION )
return false;
return false;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
if (chId =='&' || chId == '"' || chId == '\'' || chId == '<' || chId =='>' )
isValid = false;
i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.3";
}
public String getEditorVersion( ) {
return "1.3";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
/**
* Change all animation old formats (name_01) for new formats (.eaa)
*/
public void changeAllAnimationFormats(){
//Get al de data controls that can have animations
List<DataControlWithResources> dataControlList = new ArrayList<DataControlWithResources>();
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getCutscenesList( ).getAllCutsceneDataControls( ));
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getNPCsList( ).getAllNPCDataControls( ));
dataControlList.add(chaptersController.getSelectedChapterDataControl( ).getPlayer( ));
// Take the project folder to check if the .eaa animation has been previously created
File projectFolder = new File( Controller.getInstance( ).getProjectFolder( ) );
for (DataControlWithResources dc:dataControlList){
String filename = null;
// iterate the whole list of resourceDataControls looking for all animations
List<ResourcesDataControl> resourcesDataControl = dc.getResources( );
for (ResourcesDataControl rdc :resourcesDataControl){
for (int i=0; i<rdc.getAssetCount( );i++){
if (rdc.getAssetCategory( i ) == AssetsConstants.CATEGORY_ANIMATION ){
String assetPath = rdc.getAssetPath( i );
if ((assetPath==null || assetPath.equals( "" )) /*&& !assetPath.equals( SpecialAssetPaths.ASSET_EMPTY_ANIMATION )*/ ){
assetPath = SpecialAssetPaths.ASSET_EMPTY_ANIMATION;
}
if (!assetPath.toLowerCase( ).endsWith( ".eaa" ) ){
- String path;
+ // String path;
String[] temp = assetPath.split( "/" );
String animationName = temp[temp.length - 1];
- if (assetPath.equals( SpecialAssetPaths.ASSET_EMPTY_ANIMATION ))
- path = AssetsController.CATEGORY_ANIMATION_FOLDER + "/" + animationName;
- else
- path = assetPath;
- if (!new File(projectFolder, path + ".eaa").exists( )){
+ if (!new File(projectFolder, assetPath + ".eaa").exists( )){
filename = AssetsController.TempFileGenerator.generateTempFileOverwriteExisting( animationName, "eaa" );
if( filename != null ) {
File file = new File( filename );
file.create( );
Animation animation = new Animation( animationName, new EditorImageLoader(), 100 );
animation.setDocumentation( rdc.getAssetDescription( i ) );
// add the images of the old animation
ResourcesDataControl.framesFromImages( animation, assetPath);
AnimationWriter.writeAnimation( filename, animation );
rdc.setAssetPath( filename, i );
}
} else {
// if the eaa animation for this old animation was previously created, change only the path (without using Tools, cause this operation
// ask for user confirmation if animation path previously exist)
rdc.changeAssetPath( i , rdc.getAssetPath( i ) + ".eaa");
}
}
}
}
}
}
}
}
| false | true | public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//change the old animations to eaa animations, this method force to save game
changeAllAnimationFormats();
saveFile( false );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Confirm user that the conditions associated to resource block will be deleted
* @return
*/
public boolean askDeleteConditionsResourceBlock(){
int option = mainWindow.showConfirmDialog(TC.get( "ResourceBlock.deleteOnlyOneBlock.title") ,TC.get("ResourceBlock.deleteOnlyOneBlock.message"));
if( option == JOptionPane.YES_OPTION )
return true;
else if( option == JOptionPane.NO_OPTION || option == JOptionPane.CANCEL_OPTION )
return false;
return false;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
if (chId =='&' || chId == '"' || chId == '\'' || chId == '<' || chId =='>' )
isValid = false;
i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.3";
}
public String getEditorVersion( ) {
return "1.3";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
/**
* Change all animation old formats (name_01) for new formats (.eaa)
*/
public void changeAllAnimationFormats(){
//Get al de data controls that can have animations
List<DataControlWithResources> dataControlList = new ArrayList<DataControlWithResources>();
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getCutscenesList( ).getAllCutsceneDataControls( ));
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getNPCsList( ).getAllNPCDataControls( ));
dataControlList.add(chaptersController.getSelectedChapterDataControl( ).getPlayer( ));
// Take the project folder to check if the .eaa animation has been previously created
File projectFolder = new File( Controller.getInstance( ).getProjectFolder( ) );
for (DataControlWithResources dc:dataControlList){
String filename = null;
// iterate the whole list of resourceDataControls looking for all animations
List<ResourcesDataControl> resourcesDataControl = dc.getResources( );
for (ResourcesDataControl rdc :resourcesDataControl){
for (int i=0; i<rdc.getAssetCount( );i++){
if (rdc.getAssetCategory( i ) == AssetsConstants.CATEGORY_ANIMATION ){
String assetPath = rdc.getAssetPath( i );
if ((assetPath==null || assetPath.equals( "" )) /*&& !assetPath.equals( SpecialAssetPaths.ASSET_EMPTY_ANIMATION )*/ ){
assetPath = SpecialAssetPaths.ASSET_EMPTY_ANIMATION;
}
if (!assetPath.toLowerCase( ).endsWith( ".eaa" ) ){
String path;
String[] temp = assetPath.split( "/" );
String animationName = temp[temp.length - 1];
if (assetPath.equals( SpecialAssetPaths.ASSET_EMPTY_ANIMATION ))
path = AssetsController.CATEGORY_ANIMATION_FOLDER + "/" + animationName;
else
path = assetPath;
if (!new File(projectFolder, path + ".eaa").exists( )){
filename = AssetsController.TempFileGenerator.generateTempFileOverwriteExisting( animationName, "eaa" );
if( filename != null ) {
File file = new File( filename );
file.create( );
Animation animation = new Animation( animationName, new EditorImageLoader(), 100 );
animation.setDocumentation( rdc.getAssetDescription( i ) );
// add the images of the old animation
ResourcesDataControl.framesFromImages( animation, assetPath);
AnimationWriter.writeAnimation( filename, animation );
rdc.setAssetPath( filename, i );
}
} else {
// if the eaa animation for this old animation was previously created, change only the path (without using Tools, cause this operation
// ask for user confirmation if animation path previously exist)
rdc.changeAssetPath( i , rdc.getAssetPath( i ) + ".eaa");
}
}
}
}
}
}
}
}
| public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//change the old animations to eaa animations, this method force to save game
changeAllAnimationFormats();
saveFile( false );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Confirm user that the conditions associated to resource block will be deleted
* @return
*/
public boolean askDeleteConditionsResourceBlock(){
int option = mainWindow.showConfirmDialog(TC.get( "ResourceBlock.deleteOnlyOneBlock.title") ,TC.get("ResourceBlock.deleteOnlyOneBlock.message"));
if( option == JOptionPane.YES_OPTION )
return true;
else if( option == JOptionPane.NO_OPTION || option == JOptionPane.CANCEL_OPTION )
return false;
return false;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
if (chId =='&' || chId == '"' || chId == '\'' || chId == '<' || chId =='>' )
isValid = false;
i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.3";
}
public String getEditorVersion( ) {
return "1.3";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
/**
* Change all animation old formats (name_01) for new formats (.eaa)
*/
public void changeAllAnimationFormats(){
//Get al de data controls that can have animations
List<DataControlWithResources> dataControlList = new ArrayList<DataControlWithResources>();
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getCutscenesList( ).getAllCutsceneDataControls( ));
dataControlList.addAll(chaptersController.getSelectedChapterDataControl( ).getNPCsList( ).getAllNPCDataControls( ));
dataControlList.add(chaptersController.getSelectedChapterDataControl( ).getPlayer( ));
// Take the project folder to check if the .eaa animation has been previously created
File projectFolder = new File( Controller.getInstance( ).getProjectFolder( ) );
for (DataControlWithResources dc:dataControlList){
String filename = null;
// iterate the whole list of resourceDataControls looking for all animations
List<ResourcesDataControl> resourcesDataControl = dc.getResources( );
for (ResourcesDataControl rdc :resourcesDataControl){
for (int i=0; i<rdc.getAssetCount( );i++){
if (rdc.getAssetCategory( i ) == AssetsConstants.CATEGORY_ANIMATION ){
String assetPath = rdc.getAssetPath( i );
if ((assetPath==null || assetPath.equals( "" )) /*&& !assetPath.equals( SpecialAssetPaths.ASSET_EMPTY_ANIMATION )*/ ){
assetPath = SpecialAssetPaths.ASSET_EMPTY_ANIMATION;
}
if (!assetPath.toLowerCase( ).endsWith( ".eaa" ) ){
// String path;
String[] temp = assetPath.split( "/" );
String animationName = temp[temp.length - 1];
if (!new File(projectFolder, assetPath + ".eaa").exists( )){
filename = AssetsController.TempFileGenerator.generateTempFileOverwriteExisting( animationName, "eaa" );
if( filename != null ) {
File file = new File( filename );
file.create( );
Animation animation = new Animation( animationName, new EditorImageLoader(), 100 );
animation.setDocumentation( rdc.getAssetDescription( i ) );
// add the images of the old animation
ResourcesDataControl.framesFromImages( animation, assetPath);
AnimationWriter.writeAnimation( filename, animation );
rdc.setAssetPath( filename, i );
}
} else {
// if the eaa animation for this old animation was previously created, change only the path (without using Tools, cause this operation
// ask for user confirmation if animation path previously exist)
rdc.changeAssetPath( i , rdc.getAssetPath( i ) + ".eaa");
}
}
}
}
}
}
}
}
|
diff --git a/src/main/java/org/redmine/ta/RedmineManager.java b/src/main/java/org/redmine/ta/RedmineManager.java
index 52284d8..635fdc0 100644
--- a/src/main/java/org/redmine/ta/RedmineManager.java
+++ b/src/main/java/org/redmine/ta/RedmineManager.java
@@ -1,916 +1,916 @@
/*
Copyright 2010-2011 Alexey Skorokhodov.
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.redmine.ta;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.castor.core.util.Base64Encoder;
import org.redmine.ta.beans.*;
import org.redmine.ta.internal.HttpUtil;
import org.redmine.ta.internal.RedmineXMLGenerator;
import org.redmine.ta.internal.RedmineXMLParser;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
/**
* <b>Entry point</b> for the API: use this class to communicate with Redmine servers.
*
* @author Alexey Skorokhodov
*/
public class RedmineManager {
private static final boolean PRINT_DEBUG = false;
private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
private static final String CHARSET = "UTF-8";
private static final int DEFAULT_OBJECTS_PER_PAGE = 25;
// TODO add tests for "relations" to RedmineManagerTest class
public static enum INCLUDE {
// these values MUST BE exactly as they are written here,
// can't use capital letters or rename.
// they are provided in "?include=..." HTTP request
journals, relations
}
private static enum MODE {
REDMINE_1_0, REDMINE_1_1_OR_CHILIPROJECT_1_2,
}
private String host;
private String apiAccessKey;
private String login;
private String password;
private boolean useBasicAuth = false;
private int objectsPerPage = DEFAULT_OBJECTS_PER_PAGE;
private MODE currentMode = MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2;
private static final Map<Class, String> urls = new HashMap<Class, String>() {
private static final long serialVersionUID = 1L;
{
put(User.class, "users");
put(Issue.class, "issues");
put(Project.class, "projects");
put(TimeEntry.class, "time_entries");
put(SavedQuery.class, "queries");
}
};
private static final String URL_POSTFIX = ".xml";
public RedmineManager(String uri) {
if (uri == null || uri.isEmpty()) {
throw new IllegalArgumentException("The host parameter is NULL or empty");
}
this.host = uri;
}
/**
* Creates an instance of RedmineManager class. Host and apiAccessKey are not checked at this moment.
*
* @param host complete Redmine server web URI, including protocol and port number. Example: http://demo.redmine.org:8080
* @param apiAccessKey Redmine API access key. It is shown on "My Account" / "API access key" webpage
* (check <i>http://redmine_server_url/my/account<i> URL).
* This parameter is <b>optional</b> (can be set to NULL) for Redmine projects, which are "public".
*/
public RedmineManager(String host, String apiAccessKey) {
this(host);
this.apiAccessKey = apiAccessKey;
}
public RedmineManager(String uri, String login, String password) {
this(uri);
this.login = login;
this.password = password;
this.useBasicAuth = true;
}
/**
* Sample usage:
* <p>
*
* <pre>
* {@code
* Issue issueToCreate = new Issue();
* issueToCreate.setSubject("This is the summary line 123");
* Issue newIssue = mgr.createIssue(PROJECT_KEY, issueToCreate);
* }
* <p>
*
* @param projectKey The project "identifier". This is a string key like "project-ABC", NOT a database numeric ID.
* @param issue the Issue object to create on the server.
*
* @return the newly created Issue.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* the project with the given projectKey is not found
* @throws RedmineException
*/
public Issue createIssue(String projectKey, Issue issue) throws IOException,AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues.xml");
HttpPost http = new HttpPost(uri);
String xmlBody = RedmineXMLGenerator.toXML(projectKey, issue);
setEntity(http, xmlBody);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
}
Issue newIssue = RedmineXMLParser.parseIssueFromXML(response.getBody());
return newIssue;
}
private URI createURI(String query) {
return createURI(query, new ArrayList<NameValuePair>());
}
private URI createURI(String query, NameValuePair... param) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (NameValuePair p : param) {
list.add(p);
}
return createURI(query, list);
}
/**
* @param query e.g. "/issues.xml"
* @return URI with auth parameter "key" if not in "basic auth mode.
*/
private URI createURI(String query, List<NameValuePair> params) {
if (!useBasicAuth) {
params.add(new BasicNameValuePair("key", apiAccessKey));
}
URI uri;
try {
URL url = new URL(host);
String path = url.getPath();
if (!query.isEmpty()) {
path += "/" + query;
}
uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path,
URLEncodedUtils.format(params, "UTF-8"), null);
} catch (Exception e) {
throw new RuntimeException(e);
}
return uri;
}
/**
* Note: This method cannot return the updated Issue from Redmine
* because the server does not provide any XML in response.
*
* @param issue the Issue to update on the server. issue.getId() is used for identification.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException the issue with the required ID is not found
* @throws RedmineException
*/
public void updateIssue(Issue issue) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues/" + issue.getId() + ".xml");
HttpPut httpRequest = new HttpPut(uri);
// XXX add "notes" xml node. see http://www.redmine.org/wiki/redmine/Rest_Issues
String NO_PROJECT_KEY = null;
String xmlBody = RedmineXMLGenerator.toXML(NO_PROJECT_KEY, issue);
// System.out.println(xmlBody);
setEntity(httpRequest, xmlBody);
Response response = sendRequest(httpRequest);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Issue with id="+ issue.getId() + " is not found.");
}
}
private void setEntity(HttpEntityEnclosingRequest request, String xmlBody) throws UnsupportedEncodingException {
StringEntity entity = new StringEntity(xmlBody, CHARSET);
entity.setContentType(CONTENT_TYPE);
request.setEntity(entity);
}
private void configureProxy(DefaultHttpClient httpclient) {
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
if (proxyHost != null && proxyPort != null) {
int port = Integer.parseInt(proxyPort);
HttpHost proxy = new HttpHost(proxyHost, port);
httpclient.getParams().setParameter(org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY, proxy);
String proxyUser = System.getProperty("http.proxyUser");
if (proxyUser != null) {
String proxyPassword = System.getProperty("http.proxyPassword");
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, port),
new UsernamePasswordCredentials(proxyUser, proxyPassword));
}
}
}
private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
- throw new AuthenticationException("Forbidden. The API access key you used does not allow this operation. Please check the user has proper permissions.");
+ throw new AuthenticationException("Forbidden. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
class Response {
private int code;
private String body;
public Response(int code, String body) {
super();
this.code = code;
this.body = body;
}
public int getCode() {
return code;
}
public String getBody() {
return body;
}
}
/**
* Load the list of projects available to the user, which is represented by the API access key.
*
* @return list of Project objects
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException
*/
public List<Project> getProjects() throws IOException,AuthenticationException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("include", "trackers"));
try {
return getObjectsList(Project.class, params);
} catch (NotFoundException e) {
throw new RuntimeException("NotFoundException received, which should never happen in this request");
}
}
/**
* There could be several issues with the same summary, so the method returns List.
*
* @param summaryField
*
* @return empty list if not issues with this summary field exist, never NULL
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<Issue> getIssuesBySummary(String projectKey, String summaryField) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("subject", summaryField));
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
return getObjectsList(Issue.class, params);
}
/**
* Generic method to search for issues.
*
* @param pParameters the http parameters key/value pairs to append to the rest api request
*
* @return empty list if not issues with this summary field exist, never NULL
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<Issue> getIssues(Map<String, String> pParameters)
throws IOException, AuthenticationException, NotFoundException,
RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
for (final Entry<String, String> param : pParameters.entrySet()) {
params.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
return getObjectsList(Issue.class, params);
}
/**
*
* @param id the Redmine issue ID
* @param include list of "includes". e.g. "relations", "journals", ...
*
* @return Issue object
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* the issue with the given id is not found on the server
* @throws RedmineException
*/
public Issue getIssueById(Integer id, INCLUDE... include) throws IOException, AuthenticationException, NotFoundException, RedmineException {
String value = join(",", include);
// there's no harm in adding "include" parameter even if it's empty
return getObject(Issue.class, id, new BasicNameValuePair("include", value));
}
private static String join(String delimToUse, INCLUDE... include) {
String delim = "";
StringBuilder sb = new StringBuilder();
for (INCLUDE i : include) {
sb.append(delim).append(i);
delim = delimToUse;
}
return sb.toString();
}
/**
*
* @param projectKey string key like "project-ABC", NOT a database numeric ID
*
* @return Redmine's project
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException the project with the given key is not found
* @throws RedmineException
*/
public Project getProjectByKey(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("projects/" + projectKey + ".xml", new BasicNameValuePair("include", "trackers"));
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
}
return RedmineXMLParser.parseProjectFromXML(response.getBody());
}
/**
* @param projectKey string key like "project-ABC", NOT a database numeric ID
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException if the project with the given key is not found
* @throws RedmineException
*/
public void deleteProject(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
deleteObject(Project.class, projectKey);
}
public void deleteIssue(Integer id) throws IOException,
AuthenticationException, NotFoundException, RedmineException {
deleteObject(Issue.class, Integer.toString(id));
}
/**
*
* @param projectKey
* @param queryId id of the saved query in Redmine. the query must be accessible to the user
* represented by the API access key (if the Redmine project requires authorization).
* This parameter is <b>optional<b>, NULL can be provided to get all available issues.
*
* @return list of Issue objects
* @throws IOException
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
*
* @see Issue
*/
public List<Issue> getIssues(String projectKey, Integer queryId, INCLUDE... include) throws IOException, AuthenticationException, NotFoundException, RedmineException {
// have to load users first because the issues response does not contain the users names
// see http://www.redmine.org/issues/7487
// List<User> users = getUsers();
// Map<Integer, User> idToUserMap = buildIdToUserMap(users);
Set<NameValuePair> params = new HashSet<NameValuePair>();
if (queryId != null) {
params.add(new BasicNameValuePair("query_id", String.valueOf(queryId)));
}
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
String includeStr = join(",", include);
params.add(new BasicNameValuePair("include", includeStr));
List<Issue> issues = getObjectsList(Issue.class, params);
// setUserFields(issues, idToUserMap);
return issues;
}
// private void setUserFields(List<Issue> issues,
// Map<Integer, User> idToUserMap) {
// for (Issue issue : issues) {
// User author = issue.getAuthor();
// if (author != null) {
// User completelyFilledUser = idToUserMap.get(author.getId());
// issue.setAuthor(completelyFilledUser);
// }
// User assignee = issue.getAssignee();
// if (assignee != null) {
// User completelyFilledUser = idToUserMap.get(author.getId());
// issue.setAssignee(completelyFilledUser);
// }
// }
// }
// private Map<Integer, User> buildIdToUserMap(List<User> usersList) {
// Map<Integer, User> idToUserMap = new HashMap<Integer, User>();
// for (User u : usersList) {
// idToUserMap.put(u.getId(), u);
// }
// return idToUserMap;
// }
/**
* This ONLY works with Redmine 1.0. Redmine 1.1 uses "objects per page" parameter instead!
*/
private void addPagingParameters(Set<NameValuePair> params) {
params.add(new BasicNameValuePair("per_page", String.valueOf(objectsPerPage)));
}
/**
* Redmine 1.0 - specific version
*/
private <T> List<T> getObjectsListV104(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<T> objects = new ArrayList<T>();
final int FIRST_REDMINE_PAGE = 1;
int pageNum = FIRST_REDMINE_PAGE;
// Redmine 1.0.4 (and Trunk at this moment - Dec 22, 2010) returns the same page1 when no other pages are available!!
String firstPage=null;
addPagingParameters(params);
// addAuthParameters(params);
do {
//params.add(new BasicNameValuePair("page", String.valueOf(pageNum)));
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(params);
paramsList.add(new BasicNameValuePair("page", String.valueOf(pageNum)));
String query = urls.get(objectClass) + URL_POSTFIX;
URI uri = createURI(query, paramsList);
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
String body = response.getBody();
if (pageNum == FIRST_REDMINE_PAGE) {
firstPage = body;
} else {
// check that the response is NOT equal to the First Page
// - this would indicate that no more pages are available (for Redmine 1.0.*);
if (firstPage.equals(body)) {
// done, no more pages. exit the loop
break;
}
}
List<T> foundItems = RedmineXMLParser.parseObjectsFromXML(objectClass, body);
if (foundItems.size() == 0) {
break;
}
objects.addAll(foundItems);
pageNum++;
} while (true);
return objects;
}
// XXX fix this: why it is Map of string->pair? should be a flat set of params!
private <T> List<T> getObjectsList(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (currentMode.equals(MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2)) {
return getObjectsListV11(objectClass, params);
} else if (currentMode.equals(MODE.REDMINE_1_0)) {
return getObjectsListV104(objectClass, params);
} else {
throw new RuntimeException("unsupported mode:" + currentMode + ". supported modes are: " +
MODE.REDMINE_1_0 + " and " + MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2);
}
}
/**
* Redmine 1.1 / Chiliproject 1.2 - specific version
*/
private <T> List<T> getObjectsListV11(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<T> objects = new ArrayList<T>();
int limit = 25;
params.add(new BasicNameValuePair("limit", String.valueOf(limit)));
int offset = 0;
int totalObjectsFoundOnServer;
do {
//params.add(new BasicNameValuePair("offset", String.valueOf(offset)));
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(params);
paramsList.add(new BasicNameValuePair("offset", String.valueOf(offset)));
String query = urls.get(objectClass) + URL_POSTFIX;
URI uri = createURI(query, paramsList);
debug("URI = " + uri);
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
String body = response.getBody();
totalObjectsFoundOnServer = RedmineXMLParser.parseObjectsTotalCount(body);
List<T> foundItems = RedmineXMLParser.parseObjectsFromXML(objectClass, body);
if (foundItems.size() == 0) {
break;
}
objects.addAll(foundItems);
offset+= foundItems.size();
} while (offset<totalObjectsFoundOnServer);
return objects;
}
private <T> T getObject(Class<T> objectClass, Integer id, NameValuePair... params)
throws IOException, AuthenticationException, NotFoundException,
RedmineException {
String query = urls.get(objectClass) + "/" + id + URL_POSTFIX;
URI uri = createURI(query, params);
String body = sendGet(uri);
return RedmineXMLParser.parseObjectFromXML(objectClass, body);
}
// TODO is there a way to get rid of the 1st parameter and use generics?
private <T> T createObject(Class<T> classs, T obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getCreateURI(obj.getClass());
HttpPost http = new HttpPost(uri);
String xml = RedmineXMLGenerator.toXML(obj);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
return RedmineXMLParser.parseObjectFromXML(classs, response.getBody());
}
/*
* note: This method cannot return the updated object from Redmine
* because the server does not provide any XML in response.
*/
private <T extends Identifiable> void updateObject(Class<T> classs, T obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getUpdateURI(obj.getClass(), Integer.toString(obj.getId()));
HttpPut http = new HttpPut(uri);
String xml = RedmineXMLGenerator.toXML(obj);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
}
private <T extends Identifiable> void deleteObject(Class<T> classs, String id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getUpdateURI(classs, id);
HttpDelete http = new HttpDelete(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
}
private URI getCreateURI(Class zz) throws MalformedURLException {
String query =urls.get(zz) + URL_POSTFIX;
return createURI(query);
}
private URI getUpdateURI(Class zz, String id) throws MalformedURLException {
String query = urls.get(zz) + "/" + id + URL_POSTFIX;
return createURI(query);
}
private String sendGet(URI uri) throws NotFoundException, IOException, AuthenticationException, RedmineException {
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
return response.getBody();
}
/**
* Sample usage:
* <p>
*
* <pre>
* {@code
* Project project = new Project();
* Long timeStamp = Calendar.getInstance().getTimeInMillis();
* String key = "projkey" + timeStamp;
* String name = "project number " + timeStamp;
* String description = "some description for the project";
* project.setIdentifier(key);
* project.setName(name);
* project.setDescription(description);
*
* Project createdProject = mgr.createProject(project);
* }
* </pre>
*
* @param project
* project to create on the server
*
* @return the newly created Project object.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
*/
public Project createProject(Project project) throws IOException,AuthenticationException, RedmineException {
// see bug http://www.redmine.org/issues/7184
URI uri = createURI("projects.xml", new BasicNameValuePair("include", "trackers"));
HttpPost httpPost = new HttpPost(uri);
String createProjectXML = RedmineXMLGenerator.toXML(project);
// System.out.println("create project:" + createProjectXML);
setEntity(httpPost, createProjectXML);
Response response = sendRequest(httpPost);
Project createdProject = RedmineXMLParser.parseProjectFromXML(response.getBody());
return createdProject;
}
/**
*
* @param project
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException
*/
public void updateProject(Project project) throws IOException,
AuthenticationException, RedmineException, NotFoundException {
updateObject(Project.class, project);
}
/**
* This number of objects (tasks, projects, users) will be requested from Redmine server in 1 request.
*/
public int getObjectsPerPage() {
return objectsPerPage;
}
// TODO add junit test
/**
* This number of objects (tasks, projects, users) will be requested from Redmine server in 1 request.
*/
public void setObjectsPerPage(int pageSize) {
this.objectsPerPage = pageSize;
}
/**
* Load the list of users on the server.
* <p><b>This operation requires "Redmine Administrator" permission.</b>
*
* @return list of User objects
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<User> getUsers() throws IOException,AuthenticationException, NotFoundException, RedmineException{
return getObjectsList(User.class, new HashSet<NameValuePair>());
}
public User getUserById(Integer userId) throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObject(User.class, userId);
}
public User getCurrentUser() throws IOException, AuthenticationException, RedmineException{
URI uri = createURI("users/current.xml");
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
return RedmineXMLParser.parseUserFromXML(response.getBody());
}
public User createUser(User user) throws IOException,AuthenticationException, RedmineException, NotFoundException {
return createObject(User.class, user);
}
/**
* This method cannot return the updated object from Redmine
* because the server does not provide any XML in response.
*
* @param user
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException some object is not found. e.g. the user with the given id
*/
public void updateUser(User user) throws IOException,
AuthenticationException, RedmineException, NotFoundException {
updateObject(User.class, user);
}
public List<TimeEntry> getTimeEntries() throws IOException,AuthenticationException, NotFoundException, RedmineException{
return getObjectsList(TimeEntry.class, new HashSet<NameValuePair>());
}
/**
* @param id the database Id of the TimeEntry record
*/
public TimeEntry getTimeEntry(Integer id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObject(TimeEntry.class, id);
}
public List<TimeEntry> getTimeEntriesForIssue(Integer issueId) throws IOException,AuthenticationException, NotFoundException, RedmineException{
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("issue_id", Integer.toString(issueId)));
return getObjectsList(TimeEntry.class, params);
}
public TimeEntry createTimeEntry(TimeEntry obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (!isValidTimeEntry(obj)) {
throw createIllegalTimeEntryException();
}
return createObject(TimeEntry.class, obj);
}
public void updateTimeEntry(TimeEntry obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (!isValidTimeEntry(obj)) {
throw createIllegalTimeEntryException();
}
updateObject(TimeEntry.class, obj);
}
public void deleteTimeEntry(Integer id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
deleteObject(TimeEntry.class, Integer.toString(id));
}
private boolean isValidTimeEntry(TimeEntry obj) {
return obj.getProjectId() != null || obj.getIssueId() != null;
}
private IllegalArgumentException createIllegalTimeEntryException() {
return new IllegalArgumentException("You have to either define a Project or Issue ID for a Time Entry. "
+ "The given Time Entry object has neither defined.");
}
/**
* Get "saved queries" for the given project available to the current user.
*
* <p>This REST API feature was added in Redmine 1.3.0. See http://www.redmine.org/issues/5737
*/
public List<SavedQuery> getSavedQueries(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
return getObjectsList(SavedQuery.class, params);
}
/**
* Get all "saved queries" available to the current user.
*
* <p>This REST API feature was added in Redmine 1.3.0. See http://www.redmine.org/issues/5737
*/
public List<SavedQuery> getSavedQueries() throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObjectsList(SavedQuery.class, new HashSet<NameValuePair>());
}
private static void debug(String string) {
if (PRINT_DEBUG) {
System.out.println(string);
}
}
public IssueRelation createRelation(String projectKey, Integer issueId, Integer issueToId, String type) throws IOException,AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues/" + issueId + "/relations.xml");
HttpPost http = new HttpPost(uri);
IssueRelation toCreate = new IssueRelation();
toCreate.setIssueId(issueId);
toCreate.setIssueToId(issueToId);
toCreate.setType(type);
String xml = RedmineXMLGenerator.toXML(toCreate);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
// if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
// throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
// }
IssueRelation relation = RedmineXMLParser.parseRelationFromXML(response.getBody());
return relation;
}
}
| true | true | private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
throw new AuthenticationException("Forbidden. The API access key you used does not allow this operation. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
| private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
throw new AuthenticationException("Forbidden. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
|
diff --git a/luni/src/test/java/libcore/java/text/OldDateFormatTest.java b/luni/src/test/java/libcore/java/text/OldDateFormatTest.java
index f614d6f2d..6b3885c89 100644
--- a/luni/src/test/java/libcore/java/text/OldDateFormatTest.java
+++ b/luni/src/test/java/libcore/java/text/OldDateFormatTest.java
@@ -1,486 +1,480 @@
/*
* 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 libcore.java.text;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class OldDateFormatTest extends junit.framework.TestCase {
private class MockDateFormat extends DateFormat {
private static final long serialVersionUID = 1L;
public MockDateFormat() {
super();
}
@Override
public Date parse(String source, ParsePosition pos) {
// it is a fake
return null;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition fieldPosition) {
// it is a fake
return null;
}
}
/**
* java.text.DateFormat#DateFormat() Test of method
* java.text.DateFormat#DateFormat().
*/
public void test_Constructor() {
try {
new MockDateFormat();
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#equals(java.lang.Object obj) Test of
* java.text.DateFormat#equals(java.lang.Object obj).
*/
public void test_equalsLjava_lang_Object() {
try {
DateFormat format = DateFormat.getInstance();
DateFormat clone = (DateFormat) format.clone();
assertTrue("Clone and parent are not equaled", format.equals(clone));
assertTrue("Clone is equal to other object", !clone
.equals(DateFormat.getTimeInstance()));
format.setCalendar(Calendar.getInstance());
assertTrue("Clone and parent are not equaled", format.equals(clone));
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#format(java.util.Date) Test of method
* java.text.DateFormat#format(java.util.Date).
*/
public void test_formatLjava_util_Date() {
try {
DateFormat format = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT, Locale.US);
Date current = new Date();
String dtf = format.format(current);
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a");
assertTrue("Incorrect date format", sdf.format(current).equals(dtf));
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#format(Object, StringBuffer, FieldPosition)
* Test of method java.text.DateFormat#format(Object, StringBuffer,
* FieldPosition)
*/
public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
try {
DateFormat format = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT, Locale.US);
Date current = new Date();
StringBuffer toAppend = new StringBuffer();
FieldPosition fp = new FieldPosition(DateFormat.YEAR_FIELD);
StringBuffer sb = format.format(current, toAppend, fp);
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a");
assertTrue("Incorrect date format", sdf.format(current).equals(
sb.toString()));
assertTrue("Incorrect beginIndex of filed position", fp
.getBeginIndex() == sb.lastIndexOf("/") + 1);
assertTrue("Incorrect endIndex of filed position",
fp.getEndIndex() == sb.lastIndexOf("/") + 3);
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
public void test_getTimeZone() {
try {
DateFormat format = DateFormat.getInstance();
TimeZone tz = format.getTimeZone();
//if(1 == 1)
// throw new Exception(tz.getClass().getName());
// We know we are not sun.util so:
// Redundant checking
//assertFalse("Incorrect zone info", tz.getClass().getName().equals(
// "sun.util.calendar.ZoneInfo"));
assertTrue("Incorrect time zone", tz.equals(format.getCalendar()
.getTimeZone()));
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#hashCode() Test of method
* java.text.DateFormat#hashCode().
*/
public void test_hashCode() {
try {
DateFormat df1 = DateFormat.getInstance();
DateFormat df2 = (DateFormat) df1.clone();
assertTrue("Hash codes of clones are not equal",
df1.hashCode() == df2.hashCode());
assertTrue("Hash codes of different objects are the same", df1
.hashCode() != DateFormat.getDateInstance().hashCode());
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#isLenient() Test of method
* java.text.DateFormat#isLenient().
*/
public void test_isLenient() {
DateFormat df = DateFormat.getInstance();
Calendar c = df.getCalendar();
if (df.isLenient()) {
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
c.setLenient(false);
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
fail("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
// expected
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
} else {
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
fail("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
// expected
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
c.setLenient(true);
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
}
/**
* java.text.DateFormat#parse(String)
*/
- public void test_parseLString() {
+ public void test_parseLString() throws Exception {
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
try {
format.parse("not a Date");
fail("should throw ParseException first");
} catch (ParseException pe) {
assertNotNull(pe.getMessage());
}
Date current = new Date();
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("30/30/908 4:50, PDT");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("837039928046");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("Jan 16 1970");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(1, date.getDate());
assertEquals(0, date.getMonth());
assertEquals(70, date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("8:58:44");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("January 31 1970 7:52:34 AM PST");
fail("ParseException was not thrown.");
- } catch(ParseException pe) {
- //expected
+ } catch (ParseException expected) {
}
try {
format.parse("January 31 1970");
fail("ParseException was not thrown.");
- } catch(ParseException pe) {
- //expected
+ } catch (ParseException expected) {
}
format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
- try {
- Date date = format.parse(format.format(current).toString());
- assertEquals(current.getDate(), date.getDate());
- assertEquals(current.getDay(), date.getDay());
- assertEquals(current.getMonth(), date.getMonth());
- assertEquals(current.getYear(), date.getYear());
- assertEquals(current.getHours(), date.getHours());
- assertEquals(current.getMinutes(), date.getMinutes());
- } catch(ParseException pe) {
- fail("ParseException was thrown for current Date.");
+ String formatPattern = ((SimpleDateFormat) format).toPattern();
+ String formattedCurrent = format.format(current);
+ Date date = format.parse(formattedCurrent);
+ // Date has millisecond accuracy, but humans don't use time formats that precise.
+ if (date.getTime() / 1000 != current.getTime() / 1000) {
+ fail(date.getTime() + " != " + current.getTime() +
+ "; " + formatPattern + "; " + formattedCurrent);
}
try {
format.parse("January 16, 1970 8:03:52 PM CET");
fail("ParseException was not thrown.");
- } catch(ParseException pe) {
- //expected
+ } catch (ParseException expected) {
}
}
/**
* java.text.DateFormat#parseObject(String, ParsePosition) Test of
* method java.text.DateFormat#parseObject(String, ParsePosition).
* Case 1: Try to parse correct data string. Case 2: Try to parse
* partialy correct data string. Case 3: Try to use argument
* ParsePosition as null.
*/
public void test_parseObjectLjava_lang_StringLjava_text_ParsePosition() {
DateFormat df = DateFormat.getInstance();
try {
// case 1: Try to parse correct data string.
Date current = new Date();
ParsePosition pp = new ParsePosition(0);
int parseIndex = pp.getIndex();
Date result = (Date) df.parseObject(df.format(current), pp);
assertEquals("Dates are different.", current.getDate(), result.getDate());
assertEquals("Days are different.", current.getDay(), result.getDay());
assertEquals("Months are different.", current.getMonth(), result.getMonth());
assertEquals("Years are different.", current.getYear(), result.getYear());
assertEquals("Hours are different", current.getHours(), result.getHours());
assertEquals("Minutes are diffetrent,", current.getMinutes(), result.getMinutes());
assertTrue("Parse operation return null", result != null);
assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex);
// case 2: Try to parse partially correct data string.
pp.setIndex(0);
char[] cur = df.format(current).toCharArray();
cur[cur.length / 2] = 'Z';
String partialCorrect = new String(cur);
result = (Date) df.parseObject(partialCorrect, pp);
assertTrue("Parse operation return not-null", result == null);
assertTrue("ParseIndex is incorrect", pp.getIndex() == 0);
assertTrue("ParseErrorIndex is incorrect",
pp.getErrorIndex() == cur.length / 2);
pp.setIndex(2);
char[] curDate = df.format(current).toCharArray();
char [] newArray = new char[curDate.length + pp.getIndex()];
for(int i = 0; i < curDate.length; i++) {
newArray[i + pp.getIndex()] = curDate[i];
}
result = (Date) df.parseObject(new String(newArray), pp);
//assertEquals(current, result);
assertEquals("Dates are different.", current.getDate(), result.getDate());
assertEquals("Days are different.", current.getDay(), result.getDay());
assertEquals("Months are different.", current.getMonth(), result.getMonth());
assertEquals("Years are different.", current.getYear(), result.getYear());
assertEquals("Hours are different", current.getHours(), result.getHours());
assertEquals("Minutes are diffetrent,", current.getMinutes(), result.getMinutes());
// case 3: Try to use argument ParsePosition as null.
try {
df.parseObject(df.format(current), null);
fail("Expected NullPointerException was not thrown");
} catch (NullPointerException e) {
// expected
}
assertNull(df.parseObject("test", pp));
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#setLenient(boolean) Test of method
* java.text.DateFormat#setLenient(boolean).
*/
public void test_setLenientZ() {
DateFormat df = DateFormat.getInstance();
Calendar c = df.getCalendar();
try {
c.setLenient(true);
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
c.setLenient(false);
try {
c.set(Calendar.DAY_OF_MONTH, 32);
c.get(Calendar.DAY_OF_MONTH);
fail("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
// expected
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
} catch (Exception e) {
fail("Uexpected exception " + e.toString());
}
}
/**
* java.text.DateFormat#setTimeZone(TimeZone) Test of method
* java.text.DateFormat#setTimeZone(TimeZone).
*/
public void test_setTimeZoneLjava_util_TimeZone() {
try {
DateFormat format = DateFormat.getInstance();
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
format.setTimeZone(tz);
assertTrue("TimeZone is set incorrectly", tz.equals(format
.getTimeZone()));
} catch (Exception e) {
fail("Unexpected exception " + e.toString());
}
}
}
| false | true | public void test_parseLString() {
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
try {
format.parse("not a Date");
fail("should throw ParseException first");
} catch (ParseException pe) {
assertNotNull(pe.getMessage());
}
Date current = new Date();
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("30/30/908 4:50, PDT");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("837039928046");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("Jan 16 1970");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(1, date.getDate());
assertEquals(0, date.getMonth());
assertEquals(70, date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("8:58:44");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("January 31 1970 7:52:34 AM PST");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("January 31 1970");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("January 16, 1970 8:03:52 PM CET");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
}
| public void test_parseLString() throws Exception {
DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
try {
format.parse("not a Date");
fail("should throw ParseException first");
} catch (ParseException pe) {
assertNotNull(pe.getMessage());
}
Date current = new Date();
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("30/30/908 4:50, PDT");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("837039928046");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("Jan 16 1970");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
try {
format.parse("27/08/1998");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(0, date.getHours());
assertEquals(0, date.getMinutes());
assertEquals(0, date.getSeconds());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
format = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(1, date.getDate());
assertEquals(0, date.getMonth());
assertEquals(70, date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("8:58:44");
fail("ParseException was not thrown.");
} catch(ParseException pe) {
//expected
}
format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.US);
try {
Date date = format.parse(format.format(current).toString());
assertEquals(current.getDate(), date.getDate());
assertEquals(current.getDay(), date.getDay());
assertEquals(current.getMonth(), date.getMonth());
assertEquals(current.getYear(), date.getYear());
assertEquals(current.getHours(), date.getHours());
assertEquals(current.getMinutes(), date.getMinutes());
} catch(ParseException pe) {
fail("ParseException was thrown for current Date.");
}
try {
format.parse("January 31 1970 7:52:34 AM PST");
fail("ParseException was not thrown.");
} catch (ParseException expected) {
}
try {
format.parse("January 31 1970");
fail("ParseException was not thrown.");
} catch (ParseException expected) {
}
format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
String formatPattern = ((SimpleDateFormat) format).toPattern();
String formattedCurrent = format.format(current);
Date date = format.parse(formattedCurrent);
// Date has millisecond accuracy, but humans don't use time formats that precise.
if (date.getTime() / 1000 != current.getTime() / 1000) {
fail(date.getTime() + " != " + current.getTime() +
"; " + formatPattern + "; " + formattedCurrent);
}
try {
format.parse("January 16, 1970 8:03:52 PM CET");
fail("ParseException was not thrown.");
} catch (ParseException expected) {
}
}
|
diff --git a/src/ise/gameoflife/genetics/Evolvable.java b/src/ise/gameoflife/genetics/Evolvable.java
index ef565a6..24684e6 100644
--- a/src/ise/gameoflife/genetics/Evolvable.java
+++ b/src/ise/gameoflife/genetics/Evolvable.java
@@ -1,47 +1,49 @@
package ise.gameoflife.genetics;
/**
* An evolvable being that can be evaluated for fitness.
* Its behaviour is defined by a Genome instance of its own type.
* @author Xitong Gao
*/
public class Evolvable
{
protected Genome genome = null;
protected double fitness = -1;
public Genome genome()
{
return this.genome;
}
/**
* Subclasses should override this method
* Always call super for this before doing anything else
* @param aGenome a compatible Genome instance for this
*/
public void setGenome(Genome aGenome)
{
// check if genome is compatible
if (!aGenome.compatibleEvolvable(this))
{
- throw new RuntimeException("Genome (" + aGenome + ") " +
- "is not compatible with Evolvable (" + this +")");
+ throw new RuntimeException(
+ "Genome (" + aGenome.getClass().getName() + ") " +
+ "is not compatible with Evolvable (" +
+ this.getClass().getName() +")");
}
// this.genome = aGenome.clone();
this.genome = aGenome;
}
public double fitness()
{
return this.fitness;
}
public void setFitness()
{
this.fitness = fitness;
}
}
| true | true | public void setGenome(Genome aGenome)
{
// check if genome is compatible
if (!aGenome.compatibleEvolvable(this))
{
throw new RuntimeException("Genome (" + aGenome + ") " +
"is not compatible with Evolvable (" + this +")");
}
// this.genome = aGenome.clone();
this.genome = aGenome;
}
| public void setGenome(Genome aGenome)
{
// check if genome is compatible
if (!aGenome.compatibleEvolvable(this))
{
throw new RuntimeException(
"Genome (" + aGenome.getClass().getName() + ") " +
"is not compatible with Evolvable (" +
this.getClass().getName() +")");
}
// this.genome = aGenome.clone();
this.genome = aGenome;
}
|
diff --git a/src/main/java/tconstruct/worldgen/village/ComponentToolWorkshop.java b/src/main/java/tconstruct/worldgen/village/ComponentToolWorkshop.java
index 5ded31f03..58dd24252 100644
--- a/src/main/java/tconstruct/worldgen/village/ComponentToolWorkshop.java
+++ b/src/main/java/tconstruct/worldgen/village/ComponentToolWorkshop.java
@@ -1,216 +1,216 @@
package tconstruct.worldgen.village;
import java.util.List;
import java.util.Random;
import net.minecraft.init.Blocks;
import net.minecraft.util.WeightedRandomChestContent;
import net.minecraft.world.World;
import net.minecraft.world.gen.structure.StructureBoundingBox;
import net.minecraft.world.gen.structure.StructureComponent;
import net.minecraft.world.gen.structure.StructureVillagePieces;
import net.minecraft.world.gen.structure.StructureVillagePieces.Start;
import tconstruct.blocks.logic.CraftingStationLogic;
import tconstruct.blocks.logic.PatternChestLogic;
import tconstruct.common.TRepo;
public class ComponentToolWorkshop extends StructureVillagePieces.House1
{
private int averageGroundLevel = -1;
public ComponentToolWorkshop()
{
}
public ComponentToolWorkshop(Start villagePiece, int par2, Random par3Random, StructureBoundingBox par4StructureBoundingBox, int par5)
{
super();
this.coordBaseMode = par5;
this.boundingBox = par4StructureBoundingBox;
}
public static ComponentToolWorkshop buildComponent (Start villagePiece, List pieces, Random random, int p1, int p2, int p3, int p4, int p5)
{
StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(p1, p2, p3, 0, 0, 0, 7, 6, 7, p4);
return canVillageGoDeeper(structureboundingbox) && StructureComponent.findIntersecting(pieces, structureboundingbox) == null ? new ComponentToolWorkshop(villagePiece, p5, random,
structureboundingbox, p4) : null;
}
/**
* second Part of Structure generating, this for example places Spiderwebs,
* Mob Spawners, it closes Mineshafts at the end, it adds Fences...
*/
@Override
public boolean addComponentParts (World world, Random random, StructureBoundingBox sbb)
{
if (this.averageGroundLevel < 0)
{
this.averageGroundLevel = this.getAverageGroundLevel(world, sbb);
if (this.averageGroundLevel < 0)
{
return true;
}
this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 4, 0);
}
/**
* arguments: (World worldObj, StructureBoundingBox structBB, int minX,
* int minY, int minZ, int maxX, int maxY, int maxZ, int placeBlockId,
* int replaceBlockId, boolean alwaysreplace)
*/
this.fillWithBlocks(world, sbb, 0, 0, 0, 6, 0, 6, Blocks.cobblestone, Blocks.cobblestone, false); // Base
this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.fence, Blocks.fence, false);
this.fillWithBlocks(world, sbb, 1, 0, 1, 5, 0, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 2, 0, 2, 4, 0, 4, Blocks.wool, Blocks.wool, false);
// this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.log,
// Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 0, 0, 4, 0, Blocks.log, Blocks.log, false); // Edges
this.fillWithBlocks(world, sbb, 0, 1, 6, 0, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 0, 6, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 6, 6, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 1, 0, 1, 5, Blocks.planks, Blocks.planks, false); // Walls
this.fillWithBlocks(world, sbb, 1, 1, 0, 5, 1, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 1, 1, 6, 1, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 1, 6, 5, 1, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 3, 1, 0, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 0, 5, 3, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 3, 1, 6, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 6, 5, 3, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 4, 1, 0, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 0, 5, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 4, 1, 6, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 6, 5, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 1, 1, 5, 5, 5, Blocks.air, Blocks.air, false);
this.fillWithBlocks(world, sbb, 1, 4, 1, 5, 4, 5, Blocks.planks, Blocks.planks, false);
// world, blockID, metadata, x, y, z, bounds
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 0, sbb);// Glass and door
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 2, 2, 0, sbb);
this.placeDoorAtCurrentPosition(world, sbb, random, 3, 1, 0, this.getMetadataWithOffset(Blocks.wooden_door, 1));
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 4, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 2, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 3, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 4, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 0, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 6, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 5, sbb);
int i = this.getMetadataWithOffset(Blocks.ladder, 3); // Ladders
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 1, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 3, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 4, 5, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 0, 1, 1, 1, sbb); // Inside
this.generateStructurePatternChestContents(world, sbb, random, 1, 1, 2, TRepo.tinkerHousePatterns.getItems(random), TRepo.tinkerHousePatterns.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 5, 1,
// 1, 2, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 1, 1, 1, 3, sbb);
this.generateStructureCraftingStationContents(world, sbb, random, 1, 1, 4, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.craftingStationWood, 0,
// 1, 1, 4, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 10, 1, 1, 5, sbb);
// ChestGenHooks info = ChestGenHooks.getInfo("TinkerHouse");
this.generateStructureChestContents(world, sbb, random, 4, 1, 5, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, Block.chest, i, 4, 1, 5,
// sbb);
i = this.getMetadataWithOffset(Blocks.piston, 3);
this.placeBlockAtCurrentPosition(world, Blocks.piston, i, 5, 1, 5, sbb);
- for (int l = 0; l < 6; ++l)
+ for (int l = 0; l < 7; ++l)
{
- for (int i1 = 0; i1 < 9; ++i1)
+ for (int i1 = 0; i1 < 7; ++i1)
{
this.clearCurrentPositionBlocksUpwards(world, i1, 9, l, sbb);
this.func_151554_b(world, Blocks.cobblestone, 0, i1, -1, l, sbb);
}
}
this.spawnVillagers(world, sbb, 3, 1, 3, 1);
return true;
}
protected boolean generateStructureCraftingStationContents (World world, StructureBoundingBox par2StructureBoundingBox, Random random, int x, int y, int z, WeightedRandomChestContent[] content,
int par8)
{
int posX = this.getXWithOffset(x, z);
int posY = this.getYWithOffset(y);
int posZ = this.getZWithOffset(x, z);
if (par2StructureBoundingBox.isVecInside(posX, posY, posZ) && world.getBlock(posX, posY, posZ) != Blocks.chest)
{
world.setBlock(posX, posY, posZ, TRepo.craftingStationWood, 5, 2);
CraftingStationLogic logic = (CraftingStationLogic) world.getTileEntity(posX, posY, posZ);
if (logic != null)
{
WeightedRandomChestContent.generateChestContents(random, content, logic, par8);
}
return true;
}
else
{
return false;
}
}
protected boolean generateStructurePatternChestContents (World world, StructureBoundingBox par2StructureBoundingBox, Random random, int x, int y, int z, WeightedRandomChestContent[] content,
int par8)
{
int posX = this.getXWithOffset(x, z);
int posY = this.getYWithOffset(y);
int posZ = this.getZWithOffset(x, z);
if (par2StructureBoundingBox.isVecInside(posX, posY, posZ) && world.getBlock(posX, posY, posZ) != Blocks.chest)
{
world.setBlock(posX, posY, posZ, TRepo.toolStationWood, 5, 2);
PatternChestLogic logic = (PatternChestLogic) world.getTileEntity(posX, posY, posZ);
if (logic != null)
{
WeightedRandomChestContent.generateChestContents(random, content, logic, par8);
}
return true;
}
else
{
return false;
}
}
/**
* Returns the villager type to spawn in this component, based on the number
* of villagers already spawned.
*/
@Override
protected int getVillagerType (int par1)
{
return 78943;
}
}
| false | true | public boolean addComponentParts (World world, Random random, StructureBoundingBox sbb)
{
if (this.averageGroundLevel < 0)
{
this.averageGroundLevel = this.getAverageGroundLevel(world, sbb);
if (this.averageGroundLevel < 0)
{
return true;
}
this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 4, 0);
}
/**
* arguments: (World worldObj, StructureBoundingBox structBB, int minX,
* int minY, int minZ, int maxX, int maxY, int maxZ, int placeBlockId,
* int replaceBlockId, boolean alwaysreplace)
*/
this.fillWithBlocks(world, sbb, 0, 0, 0, 6, 0, 6, Blocks.cobblestone, Blocks.cobblestone, false); // Base
this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.fence, Blocks.fence, false);
this.fillWithBlocks(world, sbb, 1, 0, 1, 5, 0, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 2, 0, 2, 4, 0, 4, Blocks.wool, Blocks.wool, false);
// this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.log,
// Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 0, 0, 4, 0, Blocks.log, Blocks.log, false); // Edges
this.fillWithBlocks(world, sbb, 0, 1, 6, 0, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 0, 6, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 6, 6, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 1, 0, 1, 5, Blocks.planks, Blocks.planks, false); // Walls
this.fillWithBlocks(world, sbb, 1, 1, 0, 5, 1, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 1, 1, 6, 1, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 1, 6, 5, 1, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 3, 1, 0, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 0, 5, 3, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 3, 1, 6, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 6, 5, 3, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 4, 1, 0, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 0, 5, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 4, 1, 6, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 6, 5, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 1, 1, 5, 5, 5, Blocks.air, Blocks.air, false);
this.fillWithBlocks(world, sbb, 1, 4, 1, 5, 4, 5, Blocks.planks, Blocks.planks, false);
// world, blockID, metadata, x, y, z, bounds
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 0, sbb);// Glass and door
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 2, 2, 0, sbb);
this.placeDoorAtCurrentPosition(world, sbb, random, 3, 1, 0, this.getMetadataWithOffset(Blocks.wooden_door, 1));
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 4, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 2, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 3, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 4, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 0, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 6, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 5, sbb);
int i = this.getMetadataWithOffset(Blocks.ladder, 3); // Ladders
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 1, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 3, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 4, 5, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 0, 1, 1, 1, sbb); // Inside
this.generateStructurePatternChestContents(world, sbb, random, 1, 1, 2, TRepo.tinkerHousePatterns.getItems(random), TRepo.tinkerHousePatterns.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 5, 1,
// 1, 2, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 1, 1, 1, 3, sbb);
this.generateStructureCraftingStationContents(world, sbb, random, 1, 1, 4, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.craftingStationWood, 0,
// 1, 1, 4, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 10, 1, 1, 5, sbb);
// ChestGenHooks info = ChestGenHooks.getInfo("TinkerHouse");
this.generateStructureChestContents(world, sbb, random, 4, 1, 5, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, Block.chest, i, 4, 1, 5,
// sbb);
i = this.getMetadataWithOffset(Blocks.piston, 3);
this.placeBlockAtCurrentPosition(world, Blocks.piston, i, 5, 1, 5, sbb);
for (int l = 0; l < 6; ++l)
{
for (int i1 = 0; i1 < 9; ++i1)
{
this.clearCurrentPositionBlocksUpwards(world, i1, 9, l, sbb);
this.func_151554_b(world, Blocks.cobblestone, 0, i1, -1, l, sbb);
}
}
this.spawnVillagers(world, sbb, 3, 1, 3, 1);
return true;
}
| public boolean addComponentParts (World world, Random random, StructureBoundingBox sbb)
{
if (this.averageGroundLevel < 0)
{
this.averageGroundLevel = this.getAverageGroundLevel(world, sbb);
if (this.averageGroundLevel < 0)
{
return true;
}
this.boundingBox.offset(0, this.averageGroundLevel - this.boundingBox.maxY + 4, 0);
}
/**
* arguments: (World worldObj, StructureBoundingBox structBB, int minX,
* int minY, int minZ, int maxX, int maxY, int maxZ, int placeBlockId,
* int replaceBlockId, boolean alwaysreplace)
*/
this.fillWithBlocks(world, sbb, 0, 0, 0, 6, 0, 6, Blocks.cobblestone, Blocks.cobblestone, false); // Base
this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.fence, Blocks.fence, false);
this.fillWithBlocks(world, sbb, 1, 0, 1, 5, 0, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 2, 0, 2, 4, 0, 4, Blocks.wool, Blocks.wool, false);
// this.fillWithBlocks(world, sbb, 0, 5, 0, 6, 5, 6, Blocks.log,
// Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 0, 0, 4, 0, Blocks.log, Blocks.log, false); // Edges
this.fillWithBlocks(world, sbb, 0, 1, 6, 0, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 0, 6, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 1, 6, 6, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 0, 1, 1, 0, 1, 5, Blocks.planks, Blocks.planks, false); // Walls
this.fillWithBlocks(world, sbb, 1, 1, 0, 5, 1, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 1, 1, 6, 1, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 1, 6, 5, 1, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 3, 1, 0, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 0, 5, 3, 0, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 6, 3, 1, 6, 3, 5, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 1, 3, 6, 5, 3, 6, Blocks.planks, Blocks.planks, false);
this.fillWithBlocks(world, sbb, 0, 4, 1, 0, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 0, 5, 4, 0, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 6, 4, 1, 6, 4, 5, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 4, 6, 5, 4, 6, Blocks.log, Blocks.log, false);
this.fillWithBlocks(world, sbb, 1, 1, 1, 5, 5, 5, Blocks.air, Blocks.air, false);
this.fillWithBlocks(world, sbb, 1, 4, 1, 5, 4, 5, Blocks.planks, Blocks.planks, false);
// world, blockID, metadata, x, y, z, bounds
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 0, sbb);// Glass and door
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 2, 2, 0, sbb);
this.placeDoorAtCurrentPosition(world, sbb, random, 3, 1, 0, this.getMetadataWithOffset(Blocks.wooden_door, 1));
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 4, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 0, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 1, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 2, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 3, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 4, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 5, 2, 6, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 0, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 0, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 1, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 2, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.planks, 0, 6, 2, 3, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 4, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.glass_pane, 0, 6, 2, 5, sbb);
int i = this.getMetadataWithOffset(Blocks.ladder, 3); // Ladders
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 1, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 2, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 3, 5, sbb);
this.placeBlockAtCurrentPosition(world, Blocks.ladder, i, 3, 4, 5, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 0, 1, 1, 1, sbb); // Inside
this.generateStructurePatternChestContents(world, sbb, random, 1, 1, 2, TRepo.tinkerHousePatterns.getItems(random), TRepo.tinkerHousePatterns.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 5, 1,
// 1, 2, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 1, 1, 1, 3, sbb);
this.generateStructureCraftingStationContents(world, sbb, random, 1, 1, 4, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, TRepo.craftingStationWood, 0,
// 1, 1, 4, sbb);
this.placeBlockAtCurrentPosition(world, TRepo.toolStationWood, 10, 1, 1, 5, sbb);
// ChestGenHooks info = ChestGenHooks.getInfo("TinkerHouse");
this.generateStructureChestContents(world, sbb, random, 4, 1, 5, TRepo.tinkerHouseChest.getItems(random), TRepo.tinkerHouseChest.getCount(random));
// this.placeBlockAtCurrentPosition(world, Block.chest, i, 4, 1, 5,
// sbb);
i = this.getMetadataWithOffset(Blocks.piston, 3);
this.placeBlockAtCurrentPosition(world, Blocks.piston, i, 5, 1, 5, sbb);
for (int l = 0; l < 7; ++l)
{
for (int i1 = 0; i1 < 7; ++i1)
{
this.clearCurrentPositionBlocksUpwards(world, i1, 9, l, sbb);
this.func_151554_b(world, Blocks.cobblestone, 0, i1, -1, l, sbb);
}
}
this.spawnVillagers(world, sbb, 3, 1, 3, 1);
return true;
}
|
diff --git a/src/PawnPiece.java b/src/PawnPiece.java
index de91f96..9456e3e 100644
--- a/src/PawnPiece.java
+++ b/src/PawnPiece.java
@@ -1,35 +1,35 @@
public class PawnPiece extends Piece
{
public PawnPiece(boolean white, int xCord, int yCord, Piece[][] pieceBoard, boolean[][]whiteMoves, boolean[][]blackMoves)
{
super(white, xCord, yCord, pieceBoard,whiteMoves,blackMoves);
this.pieceType = "Pawn";
isPawn = true;
}
public void setMoves()
{
getColorValue();
int cVal = getColorValue();
int y=(yCord+cVal); //for black and white
if(isValid(xCord,y))
{
if(isEmpty(xCord,y))
canMove[xCord][y] = true;
if(isValid(xCord+1,y)&&!isEmpty(xCord+1,y))
canMove[xCord+1][y] = true;
if(isValid(xCord-1,y)&&!isEmpty(xCord-1,y))
canMove[xCord-1][y] = true;
- if(!moved&&isEmpty(xCord,y+cVal)&&isEmpty(xCord,y+cVal))
+ if(!moved&&isEmpty(xCord,y)&&isEmpty(xCord,y+cVal))
canMove[xCord][y+cVal] = true;
}
addBlackAndWhiteMoves();
}
}
| true | true | public void setMoves()
{
getColorValue();
int cVal = getColorValue();
int y=(yCord+cVal); //for black and white
if(isValid(xCord,y))
{
if(isEmpty(xCord,y))
canMove[xCord][y] = true;
if(isValid(xCord+1,y)&&!isEmpty(xCord+1,y))
canMove[xCord+1][y] = true;
if(isValid(xCord-1,y)&&!isEmpty(xCord-1,y))
canMove[xCord-1][y] = true;
if(!moved&&isEmpty(xCord,y+cVal)&&isEmpty(xCord,y+cVal))
canMove[xCord][y+cVal] = true;
}
addBlackAndWhiteMoves();
}
| public void setMoves()
{
getColorValue();
int cVal = getColorValue();
int y=(yCord+cVal); //for black and white
if(isValid(xCord,y))
{
if(isEmpty(xCord,y))
canMove[xCord][y] = true;
if(isValid(xCord+1,y)&&!isEmpty(xCord+1,y))
canMove[xCord+1][y] = true;
if(isValid(xCord-1,y)&&!isEmpty(xCord-1,y))
canMove[xCord-1][y] = true;
if(!moved&&isEmpty(xCord,y)&&isEmpty(xCord,y+cVal))
canMove[xCord][y+cVal] = true;
}
addBlackAndWhiteMoves();
}
|
diff --git a/src/test/java/com/github/fge/jsonschema/syntax/checkers/common/ExclusiveMaximumSyntaxCheckerTest.java b/src/test/java/com/github/fge/jsonschema/syntax/checkers/common/ExclusiveMaximumSyntaxCheckerTest.java
index 9ec86ad9..9672cbe9 100644
--- a/src/test/java/com/github/fge/jsonschema/syntax/checkers/common/ExclusiveMaximumSyntaxCheckerTest.java
+++ b/src/test/java/com/github/fge/jsonschema/syntax/checkers/common/ExclusiveMaximumSyntaxCheckerTest.java
@@ -1,30 +1,30 @@
/*
* Copyright (c) 2013, Francis Galiegue <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser 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
* Lesser 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 com.github.fge.jsonschema.syntax.checkers.common;
import com.fasterxml.jackson.core.JsonProcessingException;
public final class ExclusiveMaximumSyntaxCheckerTest
extends CommonSyntaxCheckersTest
{
public ExclusiveMaximumSyntaxCheckerTest()
throws JsonProcessingException
{
- super("exclusiveMinimum");
+ super("exclusiveMaximum");
}
}
| true | true | public ExclusiveMaximumSyntaxCheckerTest()
throws JsonProcessingException
{
super("exclusiveMinimum");
}
| public ExclusiveMaximumSyntaxCheckerTest()
throws JsonProcessingException
{
super("exclusiveMaximum");
}
|
diff --git a/src/test/org/jdesktop/swingx/renderer/IconValuesTest.java b/src/test/org/jdesktop/swingx/renderer/IconValuesTest.java
index 1e93b642..d53b471b 100644
--- a/src/test/org/jdesktop/swingx/renderer/IconValuesTest.java
+++ b/src/test/org/jdesktop/swingx/renderer/IconValuesTest.java
@@ -1,48 +1,48 @@
/*
* $Id$
*
* Copyright 2008 Sun Microsystems, Inc., 4150 Network Circle,
* Santa Clara, California 95054, U.S.A. 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 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.jdesktop.swingx.renderer;
import java.io.File;
import junit.framework.TestCase;
/**
*
* @author Karl George Schaefer
*/
public class IconValuesTest extends TestCase {
public void testFileIconWithNonFile() {
Object o = new Object();
assertEquals(IconValue.NONE.getIcon(o),
IconValues.FILE_ICON.getIcon(o));
}
//not asserting the output of file icon just that it isn't none
public void testFileIconWithFile() throws Exception {
File f = File.createTempFile("ivt", "tmp");
f.deleteOnExit();
- assertEquals(IconValue.NONE.getIcon(f),
+ assertNotSame(IconValue.NONE.getIcon(f),
IconValues.FILE_ICON.getIcon(f));
}
}
| true | true | public void testFileIconWithFile() throws Exception {
File f = File.createTempFile("ivt", "tmp");
f.deleteOnExit();
assertEquals(IconValue.NONE.getIcon(f),
IconValues.FILE_ICON.getIcon(f));
}
| public void testFileIconWithFile() throws Exception {
File f = File.createTempFile("ivt", "tmp");
f.deleteOnExit();
assertNotSame(IconValue.NONE.getIcon(f),
IconValues.FILE_ICON.getIcon(f));
}
|
diff --git a/paranamer/src/java/com/thoughtworks/paranamer/CachingParanamer.java b/paranamer/src/java/com/thoughtworks/paranamer/CachingParanamer.java
index 951aafa..90b46f1 100644
--- a/paranamer/src/java/com/thoughtworks/paranamer/CachingParanamer.java
+++ b/paranamer/src/java/com/thoughtworks/paranamer/CachingParanamer.java
@@ -1,82 +1,86 @@
/***
*
* Copyright (c) 2007 Paul Hammant
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders 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.thoughtworks.paranamer;
import java.lang.reflect.AccessibleObject;
import java.util.WeakHashMap;
/**
* Implementation of Paranamer which delegate to another Paranamer implementation, adding caching functionality to speed up usage.
*
* @author Paul Hammant
* @author Mauro Talevi
*/
public class CachingParanamer implements Paranamer {
public static final String __PARANAMER_DATA = "v1.0 \n"
+ "com.thoughtworks.paranamer.CachingParanamer <init> com.thoughtworks.paranamer.Paranamer delegate \n"
+ "com.thoughtworks.paranamer.CachingParanamer lookupParameterNames java.lang.AccessibleObject methodOrConstructor \n"
+ "com.thoughtworks.paranamer.CachingParanamer lookupParameterNames java.lang.AccessibleObject, boolean methodOrCtor,throwExceptionIfMissing \n";
private final Paranamer delegate;
private final WeakHashMap<AccessibleObject,String[]> methodCache = new WeakHashMap<AccessibleObject,String[]>();
/**
* Uses a DefaultParanamer as the implementation it delegates to.
*/
public CachingParanamer() {
this(new DefaultParanamer());
}
/**
* Specify a Paranamer instance to delegates to.
* @param delegate the paranamer instance to use
*/
public CachingParanamer(Paranamer delegate) {
this.delegate = delegate;
}
public String[] lookupParameterNames(AccessibleObject methodOrConstructor) {
return lookupParameterNames(methodOrConstructor, true);
}
public String[] lookupParameterNames(AccessibleObject methodOrCtor, boolean throwExceptionIfMissing) {
if(methodCache.containsKey(methodOrCtor)) {
- return methodCache.get(methodOrCtor);
+ // refer PARANAMER-19
+ String[] strings = methodCache.get(methodOrCtor);
+ if (strings != null) {
+ return strings;
+ }
}
String[] names = delegate.lookupParameterNames(methodOrCtor, throwExceptionIfMissing);
methodCache.put(methodOrCtor, names);
return names;
}
}
| true | true | public String[] lookupParameterNames(AccessibleObject methodOrCtor, boolean throwExceptionIfMissing) {
if(methodCache.containsKey(methodOrCtor)) {
return methodCache.get(methodOrCtor);
}
String[] names = delegate.lookupParameterNames(methodOrCtor, throwExceptionIfMissing);
methodCache.put(methodOrCtor, names);
return names;
}
| public String[] lookupParameterNames(AccessibleObject methodOrCtor, boolean throwExceptionIfMissing) {
if(methodCache.containsKey(methodOrCtor)) {
// refer PARANAMER-19
String[] strings = methodCache.get(methodOrCtor);
if (strings != null) {
return strings;
}
}
String[] names = delegate.lookupParameterNames(methodOrCtor, throwExceptionIfMissing);
methodCache.put(methodOrCtor, names);
return names;
}
|
diff --git a/src/main/java/org/testng/junit/JUnitUtils.java b/src/main/java/org/testng/junit/JUnitUtils.java
index f3a6f3f4..096a1a95 100644
--- a/src/main/java/org/testng/junit/JUnitUtils.java
+++ b/src/main/java/org/testng/junit/JUnitUtils.java
@@ -1,692 +1,693 @@
package org.testng.junit;
import org.testng.IClass;
import org.testng.IRetryAnalyzer;
import org.testng.ITestClass;
import org.testng.ITestNGMethod;
import org.testng.TestNGException;
import org.testng.collections.Lists;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlTest;
import java.lang.reflect.Method;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
/**
* Help methods for JUnit
*
* @author cbeust
* @date Jan 14, 2006
*/
public class JUnitUtils {
private static final String[] EMTPY_STRINGARRAY= new String[0];
private static final ITestNGMethod[] EMPTY_METHODARRAY= new ITestNGMethod[0];
/**
* An <code>ITestNMethod</code> implementation for test methods in JUnit.
*
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*/
public static class JUnitTestMethod implements ITestNGMethod {
private static final long serialVersionUID = -415785273985919220L;
private final ITestClass m_testClass;
private final Class m_methodClass;
private final Object[] m_instances;
private final long[] m_instanceHashes;
private transient Method m_method;
private String m_methodName= "N/A";
private String m_signature;
private int m_currentInvocationCount = 0;
private int m_parameterInvocationCount = 0;
private List<Integer> m_invocationNumbers;
private long m_date;
private String m_id;
transient private IRetryAnalyzer retryAnalyzer = null;
private List<Integer> m_failedInvocationNumbers;
public JUnitTestMethod(Test test, JUnitTestClass testClass) {
m_testClass= testClass;
m_instances= new Object[] {test};
m_instanceHashes= new long[] {test.hashCode()};
m_methodClass= test.getClass();
init(test);
testClass.getTestMethodList().add(this);
}
private void init(Test test) {
if(TestCase.class.isAssignableFrom(test.getClass())) {
TestCase tc= (TestCase) test;
m_methodName= tc.getName();
m_signature= m_methodClass.getName() + "." + m_methodName + "()";
try {
m_method= test.getClass().getMethod(tc.getName(), new Class[0]);
}
catch(Exception ex) {
- throw new TestNGException("cannot retrieve JUnit method", ex);
+ throw new TestNGException("Cannot find JUnit method "
+ + tc.getClass() + "." + tc.getName(), ex);
}
}
}
/**
* @see org.testng.ITestNGMethod#getDate()
*/
@Override
public long getDate() {
return m_date;
}
/**
* @see org.testng.ITestNGMethod#getDescription()
*/
@Override
public String getDescription() {
return "";
}
/**
* @see org.testng.ITestNGMethod#getId()
*/
@Override
public String getId() {
return m_id;
}
/**
* @see org.testng.ITestNGMethod#getInstanceHashCodes()
*/
@Override
public long[] getInstanceHashCodes() {
return m_instanceHashes;
}
/**
* @see org.testng.ITestNGMethod#getInstances()
*/
@Override
public Object[] getInstances() {
return m_instances;
}
/**
* @see org.testng.ITestNGMethod#getMethod()
*/
@Override
public Method getMethod() {
return m_method;
}
/**
* @see org.testng.ITestNGMethod#getMethodName()
*/
@Override
public String getMethodName() {
return m_methodName;
}
/**
* @see org.testng.ITestNGMethod#getRealClass()
*/
@Override
public Class getRealClass() {
return m_methodClass;
}
/**
* @see org.testng.ITestNGMethod#setDate(long)
*/
@Override
public void setDate(long date) {
m_date= date;
}
/**
* @see org.testng.ITestNGMethod#setId(long)
*/
@Override
public void setId(String id) {
m_id= id;
}
@Override
public int compareTo(Object o) {
int result = -2;
Class thisClass = getRealClass();
Class otherClass = ((ITestNGMethod) o).getRealClass();
if (thisClass.isAssignableFrom(otherClass)) {
result = -1;
} else if (otherClass.isAssignableFrom(thisClass)) {
result = 1;
} else if (equals(o)) {
result = 0;
}
return result;
}
// default values
/**
* @see org.testng.ITestNGMethod#isTest()
*/
@Override
public boolean isTest() {
return true;
}
/**
* @see org.testng.ITestNGMethod#canRunFromClass(org.testng.IClass)
*/
@Override
public boolean canRunFromClass(IClass testClass) {
throw new IllegalStateException("canRunFromClass is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#setTestClass(org.testng.ITestClass)
*/
@Override
public void setTestClass(ITestClass cls) {
throw new IllegalStateException("setTestClass is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#getTestClass()
*/
@Override
public ITestClass getTestClass() {
return m_testClass;
}
/**
* @see org.testng.ITestNGMethod#addMethodDependedUpon(java.lang.String)
*/
@Override
public void addMethodDependedUpon(String methodName) {
throw new IllegalStateException("addMethodDependedUpon is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#setMissingGroup(java.lang.String)
*/
@Override
public void setMissingGroup(String group) {
throw new IllegalStateException("setMissingGroup is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#getAfterGroups()
*/
@Override
public String[] getAfterGroups() {
return EMTPY_STRINGARRAY;
}
/**
* @see org.testng.ITestNGMethod#getBeforeGroups()
*/
@Override
public String[] getBeforeGroups() {
return EMTPY_STRINGARRAY;
}
/**
* @see org.testng.ITestNGMethod#getGroups()
*/
@Override
public String[] getGroups() {
return EMTPY_STRINGARRAY;
}
/**
* @see org.testng.ITestNGMethod#getGroupsDependedUpon()
*/
@Override
public String[] getGroupsDependedUpon() {
return EMTPY_STRINGARRAY;
}
/**
* @see org.testng.ITestNGMethod#getInvocationCount()
*/
@Override
public int getInvocationCount() {
return 1;
}
/**
* @see org.testng.ITestNGMethod#getMethodsDependedUpon()
*/
@Override
public String[] getMethodsDependedUpon() {
return EMTPY_STRINGARRAY;
}
/**
* @see org.testng.ITestNGMethod#getMissingGroup()
*/
@Override
public String getMissingGroup() {
return null;
}
/**
* @see org.testng.ITestNGMethod#getSuccessPercentage()
*/
@Override
public int getSuccessPercentage() {
return 100;
}
/**
* @see org.testng.ITestNGMethod#getThreadPoolSize()
*/
@Override
public int getThreadPoolSize() {
return 1;
}
/**
* @see org.testng.ITestNGMethod#getTimeOut()
*/
@Override
public long getTimeOut() {
return 0L;
}
@Override
public void setTimeOut(long timeOut) {
// ignore
}
/**
* @see org.testng.ITestNGMethod#isAfterClassConfiguration()
*/
@Override
public boolean isAfterClassConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isAfterGroupsConfiguration()
*/
@Override
public boolean isAfterGroupsConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isAfterMethodConfiguration()
*/
@Override
public boolean isAfterMethodConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isAfterSuiteConfiguration()
*/
@Override
public boolean isAfterSuiteConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isAfterTestConfiguration()
*/
@Override
public boolean isAfterTestConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isAlwaysRun()
*/
@Override
public boolean isAlwaysRun() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isBeforeClassConfiguration()
*/
@Override
public boolean isBeforeClassConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isBeforeGroupsConfiguration()
*/
@Override
public boolean isBeforeGroupsConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isBeforeMethodConfiguration()
*/
@Override
public boolean isBeforeMethodConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isBeforeSuiteConfiguration()
*/
@Override
public boolean isBeforeSuiteConfiguration() {
return false;
}
/**
* @see org.testng.ITestNGMethod#isBeforeTestConfiguration()
*/
@Override
public boolean isBeforeTestConfiguration() {
return false;
}
@Override
public int getCurrentInvocationCount() {
return m_currentInvocationCount;
}
@Override
public void incrementCurrentInvocationCount() {
m_currentInvocationCount++;
}
@Override
public void setParameterInvocationCount(int n) {
m_parameterInvocationCount = n;
}
@Override
public int getParameterInvocationCount() {
return m_parameterInvocationCount;
}
@Override
public String toString() {
return m_signature;
}
@Override
public ITestNGMethod clone() {
throw new IllegalStateException("clone is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#setInvocationCount(int)
*/
@Override
public void setInvocationCount(int count) {
throw new IllegalStateException("setInvocationCount is not supported for JUnit");
}
/**
* @see org.testng.ITestNGMethod#setThreadPoolSize(int)
*/
@Override
public void setThreadPoolSize(int threadPoolSize) {
throw new IllegalStateException("setThreadPoolSize is not supported for JUnit");
}
@Override
public IRetryAnalyzer getRetryAnalyzer() {
return retryAnalyzer;
}
@Override
public void setRetryAnalyzer(IRetryAnalyzer retryAnalyzer) {
this.retryAnalyzer = retryAnalyzer;
}
@Override
public void setSkipFailedInvocations(boolean skip) {
// nop
}
@Override
public boolean skipFailedInvocations() {
return false;
}
@Override
public void setIgnoreMissingDependencies(boolean ignore) {
// nop
}
@Override
public boolean ignoreMissingDependencies() {
return false;
}
public boolean isFirstTimeOnly() {
return false;
}
public boolean isLastTimeOnly() {
return false;
}
@Override
public long getInvocationTimeOut() {
return 0;
}
@Override
public List<Integer> getInvocationNumbers() {
return m_invocationNumbers;
}
@Override
public void setInvocationNumbers(List<Integer> count) {
m_invocationNumbers = count;
}
@Override
public List<Integer> getFailedInvocationNumbers() {
return m_failedInvocationNumbers;
}
@Override
public void addFailedInvocationNumber(int number) {
m_failedInvocationNumbers.add(number);
}
@Override
public int getPriority() {
return 0;
}
@Override
public void setPriority(int priority) {
// ignored
}
}
/**
* An <code>ITestClass</code> implementation for test methods in JUnit.
*
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*/
public static class JUnitTestClass implements ITestClass {
/**
*
*/
private static final long serialVersionUID = 405598615794850925L;
private List<ITestNGMethod> m_testMethods= Lists.newArrayList();
private Class m_realClass;
private Object[] m_instances;
private long[] m_instanceHashes;
public JUnitTestClass(Test test) {
m_realClass= test.getClass();
m_instances= new Object[] {test};
m_instanceHashes= new long[] {test.hashCode()};
}
List<ITestNGMethod> getTestMethodList() {
return m_testMethods;
}
/**
* @see org.testng.ITestClass#getInstanceCount()
*/
@Override
public int getInstanceCount() {
return 1;
}
/**
* @see org.testng.ITestClass#getInstanceHashCodes()
*/
@Override
public long[] getInstanceHashCodes() {
return m_instanceHashes;
}
@Override
public Object[] getInstances(boolean reuse) {
return m_instances;
}
/**
* @see org.testng.ITestClass#getTestMethods()
*/
@Override
public ITestNGMethod[] getTestMethods() {
return m_testMethods.toArray(new ITestNGMethod[m_testMethods.size()]);
}
/**
* @see org.testng.ITestClass#getAfterClassMethods()
*/
@Override
public ITestNGMethod[] getAfterClassMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getAfterGroupsMethods()
*/
@Override
public ITestNGMethod[] getAfterGroupsMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getAfterSuiteMethods()
*/
@Override
public ITestNGMethod[] getAfterSuiteMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getAfterTestConfigurationMethods()
*/
@Override
public ITestNGMethod[] getAfterTestConfigurationMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getAfterTestMethods()
*/
@Override
public ITestNGMethod[] getAfterTestMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getBeforeClassMethods()
*/
@Override
public ITestNGMethod[] getBeforeClassMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getBeforeGroupsMethods()
*/
@Override
public ITestNGMethod[] getBeforeGroupsMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getBeforeSuiteMethods()
*/
@Override
public ITestNGMethod[] getBeforeSuiteMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getBeforeTestConfigurationMethods()
*/
@Override
public ITestNGMethod[] getBeforeTestConfigurationMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.ITestClass#getBeforeTestMethods()
*/
@Override
public ITestNGMethod[] getBeforeTestMethods() {
return EMPTY_METHODARRAY;
}
/**
* @see org.testng.IClass#addInstance(java.lang.Object)
*/
@Override
public void addInstance(Object instance) {
throw new IllegalStateException("addInstance is not supported for JUnit");
}
/**
* @see org.testng.IClass#getName()
*/
@Override
public String getName() {
return m_realClass.getName();
}
/**
* @see org.testng.IClass#getRealClass()
*/
@Override
public Class getRealClass() {
return m_realClass;
}
@Override
public String getTestName() {
return null;
}
@Override
public XmlTest getXmlTest() {
return null;
}
@Override
public XmlClass getXmlClass() {
return null;
}
}
}
| true | true | private void init(Test test) {
if(TestCase.class.isAssignableFrom(test.getClass())) {
TestCase tc= (TestCase) test;
m_methodName= tc.getName();
m_signature= m_methodClass.getName() + "." + m_methodName + "()";
try {
m_method= test.getClass().getMethod(tc.getName(), new Class[0]);
}
catch(Exception ex) {
throw new TestNGException("cannot retrieve JUnit method", ex);
}
}
}
| private void init(Test test) {
if(TestCase.class.isAssignableFrom(test.getClass())) {
TestCase tc= (TestCase) test;
m_methodName= tc.getName();
m_signature= m_methodClass.getName() + "." + m_methodName + "()";
try {
m_method= test.getClass().getMethod(tc.getName(), new Class[0]);
}
catch(Exception ex) {
throw new TestNGException("Cannot find JUnit method "
+ tc.getClass() + "." + tc.getName(), ex);
}
}
}
|
diff --git a/src/main/java/org/redmine/ta/RedmineManager.java b/src/main/java/org/redmine/ta/RedmineManager.java
index 52284d8..635fdc0 100644
--- a/src/main/java/org/redmine/ta/RedmineManager.java
+++ b/src/main/java/org/redmine/ta/RedmineManager.java
@@ -1,916 +1,916 @@
/*
Copyright 2010-2011 Alexey Skorokhodov.
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.redmine.ta;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.castor.core.util.Base64Encoder;
import org.redmine.ta.beans.*;
import org.redmine.ta.internal.HttpUtil;
import org.redmine.ta.internal.RedmineXMLGenerator;
import org.redmine.ta.internal.RedmineXMLParser;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
/**
* <b>Entry point</b> for the API: use this class to communicate with Redmine servers.
*
* @author Alexey Skorokhodov
*/
public class RedmineManager {
private static final boolean PRINT_DEBUG = false;
private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
private static final String CHARSET = "UTF-8";
private static final int DEFAULT_OBJECTS_PER_PAGE = 25;
// TODO add tests for "relations" to RedmineManagerTest class
public static enum INCLUDE {
// these values MUST BE exactly as they are written here,
// can't use capital letters or rename.
// they are provided in "?include=..." HTTP request
journals, relations
}
private static enum MODE {
REDMINE_1_0, REDMINE_1_1_OR_CHILIPROJECT_1_2,
}
private String host;
private String apiAccessKey;
private String login;
private String password;
private boolean useBasicAuth = false;
private int objectsPerPage = DEFAULT_OBJECTS_PER_PAGE;
private MODE currentMode = MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2;
private static final Map<Class, String> urls = new HashMap<Class, String>() {
private static final long serialVersionUID = 1L;
{
put(User.class, "users");
put(Issue.class, "issues");
put(Project.class, "projects");
put(TimeEntry.class, "time_entries");
put(SavedQuery.class, "queries");
}
};
private static final String URL_POSTFIX = ".xml";
public RedmineManager(String uri) {
if (uri == null || uri.isEmpty()) {
throw new IllegalArgumentException("The host parameter is NULL or empty");
}
this.host = uri;
}
/**
* Creates an instance of RedmineManager class. Host and apiAccessKey are not checked at this moment.
*
* @param host complete Redmine server web URI, including protocol and port number. Example: http://demo.redmine.org:8080
* @param apiAccessKey Redmine API access key. It is shown on "My Account" / "API access key" webpage
* (check <i>http://redmine_server_url/my/account<i> URL).
* This parameter is <b>optional</b> (can be set to NULL) for Redmine projects, which are "public".
*/
public RedmineManager(String host, String apiAccessKey) {
this(host);
this.apiAccessKey = apiAccessKey;
}
public RedmineManager(String uri, String login, String password) {
this(uri);
this.login = login;
this.password = password;
this.useBasicAuth = true;
}
/**
* Sample usage:
* <p>
*
* <pre>
* {@code
* Issue issueToCreate = new Issue();
* issueToCreate.setSubject("This is the summary line 123");
* Issue newIssue = mgr.createIssue(PROJECT_KEY, issueToCreate);
* }
* <p>
*
* @param projectKey The project "identifier". This is a string key like "project-ABC", NOT a database numeric ID.
* @param issue the Issue object to create on the server.
*
* @return the newly created Issue.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* the project with the given projectKey is not found
* @throws RedmineException
*/
public Issue createIssue(String projectKey, Issue issue) throws IOException,AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues.xml");
HttpPost http = new HttpPost(uri);
String xmlBody = RedmineXMLGenerator.toXML(projectKey, issue);
setEntity(http, xmlBody);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
}
Issue newIssue = RedmineXMLParser.parseIssueFromXML(response.getBody());
return newIssue;
}
private URI createURI(String query) {
return createURI(query, new ArrayList<NameValuePair>());
}
private URI createURI(String query, NameValuePair... param) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (NameValuePair p : param) {
list.add(p);
}
return createURI(query, list);
}
/**
* @param query e.g. "/issues.xml"
* @return URI with auth parameter "key" if not in "basic auth mode.
*/
private URI createURI(String query, List<NameValuePair> params) {
if (!useBasicAuth) {
params.add(new BasicNameValuePair("key", apiAccessKey));
}
URI uri;
try {
URL url = new URL(host);
String path = url.getPath();
if (!query.isEmpty()) {
path += "/" + query;
}
uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), path,
URLEncodedUtils.format(params, "UTF-8"), null);
} catch (Exception e) {
throw new RuntimeException(e);
}
return uri;
}
/**
* Note: This method cannot return the updated Issue from Redmine
* because the server does not provide any XML in response.
*
* @param issue the Issue to update on the server. issue.getId() is used for identification.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException the issue with the required ID is not found
* @throws RedmineException
*/
public void updateIssue(Issue issue) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues/" + issue.getId() + ".xml");
HttpPut httpRequest = new HttpPut(uri);
// XXX add "notes" xml node. see http://www.redmine.org/wiki/redmine/Rest_Issues
String NO_PROJECT_KEY = null;
String xmlBody = RedmineXMLGenerator.toXML(NO_PROJECT_KEY, issue);
// System.out.println(xmlBody);
setEntity(httpRequest, xmlBody);
Response response = sendRequest(httpRequest);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Issue with id="+ issue.getId() + " is not found.");
}
}
private void setEntity(HttpEntityEnclosingRequest request, String xmlBody) throws UnsupportedEncodingException {
StringEntity entity = new StringEntity(xmlBody, CHARSET);
entity.setContentType(CONTENT_TYPE);
request.setEntity(entity);
}
private void configureProxy(DefaultHttpClient httpclient) {
String proxyHost = System.getProperty("http.proxyHost");
String proxyPort = System.getProperty("http.proxyPort");
if (proxyHost != null && proxyPort != null) {
int port = Integer.parseInt(proxyPort);
HttpHost proxy = new HttpHost(proxyHost, port);
httpclient.getParams().setParameter(org.apache.http.conn.params.ConnRoutePNames.DEFAULT_PROXY, proxy);
String proxyUser = System.getProperty("http.proxyUser");
if (proxyUser != null) {
String proxyPassword = System.getProperty("http.proxyPassword");
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(proxyHost, port),
new UsernamePasswordCredentials(proxyUser, proxyPassword));
}
}
}
private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
- throw new AuthenticationException("Forbidden. The API access key you used does not allow this operation. Please check the user has proper permissions.");
+ throw new AuthenticationException("Forbidden. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
class Response {
private int code;
private String body;
public Response(int code, String body) {
super();
this.code = code;
this.body = body;
}
public int getCode() {
return code;
}
public String getBody() {
return body;
}
}
/**
* Load the list of projects available to the user, which is represented by the API access key.
*
* @return list of Project objects
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException
*/
public List<Project> getProjects() throws IOException,AuthenticationException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("include", "trackers"));
try {
return getObjectsList(Project.class, params);
} catch (NotFoundException e) {
throw new RuntimeException("NotFoundException received, which should never happen in this request");
}
}
/**
* There could be several issues with the same summary, so the method returns List.
*
* @param summaryField
*
* @return empty list if not issues with this summary field exist, never NULL
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<Issue> getIssuesBySummary(String projectKey, String summaryField) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("subject", summaryField));
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
return getObjectsList(Issue.class, params);
}
/**
* Generic method to search for issues.
*
* @param pParameters the http parameters key/value pairs to append to the rest api request
*
* @return empty list if not issues with this summary field exist, never NULL
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<Issue> getIssues(Map<String, String> pParameters)
throws IOException, AuthenticationException, NotFoundException,
RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
for (final Entry<String, String> param : pParameters.entrySet()) {
params.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
return getObjectsList(Issue.class, params);
}
/**
*
* @param id the Redmine issue ID
* @param include list of "includes". e.g. "relations", "journals", ...
*
* @return Issue object
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* the issue with the given id is not found on the server
* @throws RedmineException
*/
public Issue getIssueById(Integer id, INCLUDE... include) throws IOException, AuthenticationException, NotFoundException, RedmineException {
String value = join(",", include);
// there's no harm in adding "include" parameter even if it's empty
return getObject(Issue.class, id, new BasicNameValuePair("include", value));
}
private static String join(String delimToUse, INCLUDE... include) {
String delim = "";
StringBuilder sb = new StringBuilder();
for (INCLUDE i : include) {
sb.append(delim).append(i);
delim = delimToUse;
}
return sb.toString();
}
/**
*
* @param projectKey string key like "project-ABC", NOT a database numeric ID
*
* @return Redmine's project
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException the project with the given key is not found
* @throws RedmineException
*/
public Project getProjectByKey(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("projects/" + projectKey + ".xml", new BasicNameValuePair("include", "trackers"));
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
}
return RedmineXMLParser.parseProjectFromXML(response.getBody());
}
/**
* @param projectKey string key like "project-ABC", NOT a database numeric ID
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException if the project with the given key is not found
* @throws RedmineException
*/
public void deleteProject(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
deleteObject(Project.class, projectKey);
}
public void deleteIssue(Integer id) throws IOException,
AuthenticationException, NotFoundException, RedmineException {
deleteObject(Issue.class, Integer.toString(id));
}
/**
*
* @param projectKey
* @param queryId id of the saved query in Redmine. the query must be accessible to the user
* represented by the API access key (if the Redmine project requires authorization).
* This parameter is <b>optional<b>, NULL can be provided to get all available issues.
*
* @return list of Issue objects
* @throws IOException
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
*
* @see Issue
*/
public List<Issue> getIssues(String projectKey, Integer queryId, INCLUDE... include) throws IOException, AuthenticationException, NotFoundException, RedmineException {
// have to load users first because the issues response does not contain the users names
// see http://www.redmine.org/issues/7487
// List<User> users = getUsers();
// Map<Integer, User> idToUserMap = buildIdToUserMap(users);
Set<NameValuePair> params = new HashSet<NameValuePair>();
if (queryId != null) {
params.add(new BasicNameValuePair("query_id", String.valueOf(queryId)));
}
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
String includeStr = join(",", include);
params.add(new BasicNameValuePair("include", includeStr));
List<Issue> issues = getObjectsList(Issue.class, params);
// setUserFields(issues, idToUserMap);
return issues;
}
// private void setUserFields(List<Issue> issues,
// Map<Integer, User> idToUserMap) {
// for (Issue issue : issues) {
// User author = issue.getAuthor();
// if (author != null) {
// User completelyFilledUser = idToUserMap.get(author.getId());
// issue.setAuthor(completelyFilledUser);
// }
// User assignee = issue.getAssignee();
// if (assignee != null) {
// User completelyFilledUser = idToUserMap.get(author.getId());
// issue.setAssignee(completelyFilledUser);
// }
// }
// }
// private Map<Integer, User> buildIdToUserMap(List<User> usersList) {
// Map<Integer, User> idToUserMap = new HashMap<Integer, User>();
// for (User u : usersList) {
// idToUserMap.put(u.getId(), u);
// }
// return idToUserMap;
// }
/**
* This ONLY works with Redmine 1.0. Redmine 1.1 uses "objects per page" parameter instead!
*/
private void addPagingParameters(Set<NameValuePair> params) {
params.add(new BasicNameValuePair("per_page", String.valueOf(objectsPerPage)));
}
/**
* Redmine 1.0 - specific version
*/
private <T> List<T> getObjectsListV104(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<T> objects = new ArrayList<T>();
final int FIRST_REDMINE_PAGE = 1;
int pageNum = FIRST_REDMINE_PAGE;
// Redmine 1.0.4 (and Trunk at this moment - Dec 22, 2010) returns the same page1 when no other pages are available!!
String firstPage=null;
addPagingParameters(params);
// addAuthParameters(params);
do {
//params.add(new BasicNameValuePair("page", String.valueOf(pageNum)));
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(params);
paramsList.add(new BasicNameValuePair("page", String.valueOf(pageNum)));
String query = urls.get(objectClass) + URL_POSTFIX;
URI uri = createURI(query, paramsList);
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
String body = response.getBody();
if (pageNum == FIRST_REDMINE_PAGE) {
firstPage = body;
} else {
// check that the response is NOT equal to the First Page
// - this would indicate that no more pages are available (for Redmine 1.0.*);
if (firstPage.equals(body)) {
// done, no more pages. exit the loop
break;
}
}
List<T> foundItems = RedmineXMLParser.parseObjectsFromXML(objectClass, body);
if (foundItems.size() == 0) {
break;
}
objects.addAll(foundItems);
pageNum++;
} while (true);
return objects;
}
// XXX fix this: why it is Map of string->pair? should be a flat set of params!
private <T> List<T> getObjectsList(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (currentMode.equals(MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2)) {
return getObjectsListV11(objectClass, params);
} else if (currentMode.equals(MODE.REDMINE_1_0)) {
return getObjectsListV104(objectClass, params);
} else {
throw new RuntimeException("unsupported mode:" + currentMode + ". supported modes are: " +
MODE.REDMINE_1_0 + " and " + MODE.REDMINE_1_1_OR_CHILIPROJECT_1_2);
}
}
/**
* Redmine 1.1 / Chiliproject 1.2 - specific version
*/
private <T> List<T> getObjectsListV11(Class<T> objectClass, Set<NameValuePair> params) throws IOException, AuthenticationException, NotFoundException, RedmineException {
List<T> objects = new ArrayList<T>();
int limit = 25;
params.add(new BasicNameValuePair("limit", String.valueOf(limit)));
int offset = 0;
int totalObjectsFoundOnServer;
do {
//params.add(new BasicNameValuePair("offset", String.valueOf(offset)));
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(params);
paramsList.add(new BasicNameValuePair("offset", String.valueOf(offset)));
String query = urls.get(objectClass) + URL_POSTFIX;
URI uri = createURI(query, paramsList);
debug("URI = " + uri);
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
String body = response.getBody();
totalObjectsFoundOnServer = RedmineXMLParser.parseObjectsTotalCount(body);
List<T> foundItems = RedmineXMLParser.parseObjectsFromXML(objectClass, body);
if (foundItems.size() == 0) {
break;
}
objects.addAll(foundItems);
offset+= foundItems.size();
} while (offset<totalObjectsFoundOnServer);
return objects;
}
private <T> T getObject(Class<T> objectClass, Integer id, NameValuePair... params)
throws IOException, AuthenticationException, NotFoundException,
RedmineException {
String query = urls.get(objectClass) + "/" + id + URL_POSTFIX;
URI uri = createURI(query, params);
String body = sendGet(uri);
return RedmineXMLParser.parseObjectFromXML(objectClass, body);
}
// TODO is there a way to get rid of the 1st parameter and use generics?
private <T> T createObject(Class<T> classs, T obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getCreateURI(obj.getClass());
HttpPost http = new HttpPost(uri);
String xml = RedmineXMLGenerator.toXML(obj);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
return RedmineXMLParser.parseObjectFromXML(classs, response.getBody());
}
/*
* note: This method cannot return the updated object from Redmine
* because the server does not provide any XML in response.
*/
private <T extends Identifiable> void updateObject(Class<T> classs, T obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getUpdateURI(obj.getClass(), Integer.toString(obj.getId()));
HttpPut http = new HttpPut(uri);
String xml = RedmineXMLGenerator.toXML(obj);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
}
private <T extends Identifiable> void deleteObject(Class<T> classs, String id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
URI uri = getUpdateURI(classs, id);
HttpDelete http = new HttpDelete(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
}
private URI getCreateURI(Class zz) throws MalformedURLException {
String query =urls.get(zz) + URL_POSTFIX;
return createURI(query);
}
private URI getUpdateURI(Class zz, String id) throws MalformedURLException {
String query = urls.get(zz) + "/" + id + URL_POSTFIX;
return createURI(query);
}
private String sendGet(URI uri) throws NotFoundException, IOException, AuthenticationException, RedmineException {
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
throw new NotFoundException("Server returned '404 not found'. response body:" + response.getBody());
}
return response.getBody();
}
/**
* Sample usage:
* <p>
*
* <pre>
* {@code
* Project project = new Project();
* Long timeStamp = Calendar.getInstance().getTimeInMillis();
* String key = "projkey" + timeStamp;
* String name = "project number " + timeStamp;
* String description = "some description for the project";
* project.setIdentifier(key);
* project.setName(name);
* project.setDescription(description);
*
* Project createdProject = mgr.createProject(project);
* }
* </pre>
*
* @param project
* project to create on the server
*
* @return the newly created Project object.
*
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
*/
public Project createProject(Project project) throws IOException,AuthenticationException, RedmineException {
// see bug http://www.redmine.org/issues/7184
URI uri = createURI("projects.xml", new BasicNameValuePair("include", "trackers"));
HttpPost httpPost = new HttpPost(uri);
String createProjectXML = RedmineXMLGenerator.toXML(project);
// System.out.println("create project:" + createProjectXML);
setEntity(httpPost, createProjectXML);
Response response = sendRequest(httpPost);
Project createdProject = RedmineXMLParser.parseProjectFromXML(response.getBody());
return createdProject;
}
/**
*
* @param project
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException
*/
public void updateProject(Project project) throws IOException,
AuthenticationException, RedmineException, NotFoundException {
updateObject(Project.class, project);
}
/**
* This number of objects (tasks, projects, users) will be requested from Redmine server in 1 request.
*/
public int getObjectsPerPage() {
return objectsPerPage;
}
// TODO add junit test
/**
* This number of objects (tasks, projects, users) will be requested from Redmine server in 1 request.
*/
public void setObjectsPerPage(int pageSize) {
this.objectsPerPage = pageSize;
}
/**
* Load the list of users on the server.
* <p><b>This operation requires "Redmine Administrator" permission.</b>
*
* @return list of User objects
*
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws NotFoundException
* @throws RedmineException
*/
public List<User> getUsers() throws IOException,AuthenticationException, NotFoundException, RedmineException{
return getObjectsList(User.class, new HashSet<NameValuePair>());
}
public User getUserById(Integer userId) throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObject(User.class, userId);
}
public User getCurrentUser() throws IOException, AuthenticationException, RedmineException{
URI uri = createURI("users/current.xml");
HttpGet http = new HttpGet(uri);
Response response = sendRequest(http);
return RedmineXMLParser.parseUserFromXML(response.getBody());
}
public User createUser(User user) throws IOException,AuthenticationException, RedmineException, NotFoundException {
return createObject(User.class, user);
}
/**
* This method cannot return the updated object from Redmine
* because the server does not provide any XML in response.
*
* @param user
* @throws IOException
* @throws AuthenticationException
* invalid or no API access key is used with the server, which
* requires authorization. Check the constructor arguments.
* @throws RedmineException
* @throws NotFoundException some object is not found. e.g. the user with the given id
*/
public void updateUser(User user) throws IOException,
AuthenticationException, RedmineException, NotFoundException {
updateObject(User.class, user);
}
public List<TimeEntry> getTimeEntries() throws IOException,AuthenticationException, NotFoundException, RedmineException{
return getObjectsList(TimeEntry.class, new HashSet<NameValuePair>());
}
/**
* @param id the database Id of the TimeEntry record
*/
public TimeEntry getTimeEntry(Integer id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObject(TimeEntry.class, id);
}
public List<TimeEntry> getTimeEntriesForIssue(Integer issueId) throws IOException,AuthenticationException, NotFoundException, RedmineException{
Set<NameValuePair> params = new HashSet<NameValuePair>();
params.add(new BasicNameValuePair("issue_id", Integer.toString(issueId)));
return getObjectsList(TimeEntry.class, params);
}
public TimeEntry createTimeEntry(TimeEntry obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (!isValidTimeEntry(obj)) {
throw createIllegalTimeEntryException();
}
return createObject(TimeEntry.class, obj);
}
public void updateTimeEntry(TimeEntry obj) throws IOException, AuthenticationException, NotFoundException, RedmineException {
if (!isValidTimeEntry(obj)) {
throw createIllegalTimeEntryException();
}
updateObject(TimeEntry.class, obj);
}
public void deleteTimeEntry(Integer id) throws IOException, AuthenticationException, NotFoundException, RedmineException {
deleteObject(TimeEntry.class, Integer.toString(id));
}
private boolean isValidTimeEntry(TimeEntry obj) {
return obj.getProjectId() != null || obj.getIssueId() != null;
}
private IllegalArgumentException createIllegalTimeEntryException() {
return new IllegalArgumentException("You have to either define a Project or Issue ID for a Time Entry. "
+ "The given Time Entry object has neither defined.");
}
/**
* Get "saved queries" for the given project available to the current user.
*
* <p>This REST API feature was added in Redmine 1.3.0. See http://www.redmine.org/issues/5737
*/
public List<SavedQuery> getSavedQueries(String projectKey) throws IOException, AuthenticationException, NotFoundException, RedmineException {
Set<NameValuePair> params = new HashSet<NameValuePair>();
if ((projectKey != null) && (projectKey.length()>0)) {
params.add(new BasicNameValuePair("project_id", projectKey));
}
return getObjectsList(SavedQuery.class, params);
}
/**
* Get all "saved queries" available to the current user.
*
* <p>This REST API feature was added in Redmine 1.3.0. See http://www.redmine.org/issues/5737
*/
public List<SavedQuery> getSavedQueries() throws IOException, AuthenticationException, NotFoundException, RedmineException {
return getObjectsList(SavedQuery.class, new HashSet<NameValuePair>());
}
private static void debug(String string) {
if (PRINT_DEBUG) {
System.out.println(string);
}
}
public IssueRelation createRelation(String projectKey, Integer issueId, Integer issueToId, String type) throws IOException,AuthenticationException, NotFoundException, RedmineException {
URI uri = createURI("issues/" + issueId + "/relations.xml");
HttpPost http = new HttpPost(uri);
IssueRelation toCreate = new IssueRelation();
toCreate.setIssueId(issueId);
toCreate.setIssueToId(issueToId);
toCreate.setType(type);
String xml = RedmineXMLGenerator.toXML(toCreate);
setEntity((HttpEntityEnclosingRequest)http, xml);
Response response = sendRequest(http);
// if (response.getCode() == HttpStatus.SC_NOT_FOUND) {
// throw new NotFoundException("Project with key '" + projectKey + "' is not found.");
// }
IssueRelation relation = RedmineXMLParser.parseRelationFromXML(response.getBody());
return relation;
}
}
| true | true | private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
throw new AuthenticationException("Forbidden. The API access key you used does not allow this operation. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
| private Response sendRequest(HttpRequest request) throws IOException, AuthenticationException, RedmineException {
debug(request.getRequestLine().toString());
DefaultHttpClient httpclient = HttpUtil.getNewHttpClient();
configureProxy(httpclient);
if (useBasicAuth) {
// replaced because of http://code.google.com/p/redmine-java-api/issues/detail?id=72
// httpclient.getCredentialsProvider().setCredentials(
// new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
// new UsernamePasswordCredentials(login, password));
final String credentials = String.valueOf(Base64Encoder.encode((login + ':' + password).getBytes(CHARSET)));
request.addHeader("Authorization", "Basic: " + credentials);
}
request.addHeader("Accept-Encoding", "gzip,deflate");
HttpResponse httpResponse = httpclient.execute((HttpUriRequest)request);
// System.out.println(httpResponse.getStatusLine());
int responseCode = httpResponse.getStatusLine().getStatusCode();
if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthenticationException("Authorization error. Please check if you provided a valid API access key or Login and Password and REST API service is enabled on the server.");
}
if (responseCode == HttpStatus.SC_FORBIDDEN) {
throw new AuthenticationException("Forbidden. Please check the user has proper permissions.");
}
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
if (responseCode == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
List<String> errors = RedmineXMLParser.parseErrors(responseBody);
throw new RedmineException(errors);
}
/* 422 "invalid"
<?xml version="1.0" encoding="UTF-8"?>
<errors>
<error>Name can't be blank</error>
<error>Identifier has already been taken</error>
</errors>
*/
// have to fill our own object, otherwise there's no guarantee
// that the request body can be retrieved later ("socket closed" exception can occur)
Response r = new Response(responseCode, responseBody);
httpclient.getConnectionManager().shutdown();
// String responseBody = EntityUtils.toString(responseEntity);
return r;
}
|
diff --git a/sonar-checkstyle-plugin/src/main/java/org/sonar/plugins/checkstyle/CheckstyleAuditListener.java b/sonar-checkstyle-plugin/src/main/java/org/sonar/plugins/checkstyle/CheckstyleAuditListener.java
index 81c06ccce..66c53e31a 100644
--- a/sonar-checkstyle-plugin/src/main/java/org/sonar/plugins/checkstyle/CheckstyleAuditListener.java
+++ b/sonar-checkstyle-plugin/src/main/java/org/sonar/plugins/checkstyle/CheckstyleAuditListener.java
@@ -1,149 +1,149 @@
/*
* Sonar Java
* Copyright (C) 2012 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.plugins.checkstyle;
import com.google.common.annotations.VisibleForTesting;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.BatchExtension;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.resources.JavaFile;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.Violation;
/**
* @since 2.3
*/
public class CheckstyleAuditListener implements AuditListener, BatchExtension {
private static final Logger LOG = LoggerFactory.getLogger(CheckstyleAuditListener.class);
private final SensorContext context;
private final Project project;
private final RuleFinder ruleFinder;
private Resource currentResource = null;
public CheckstyleAuditListener(SensorContext context, Project project, RuleFinder ruleFinder) {
this.context = context;
this.project = project;
this.ruleFinder = ruleFinder;
}
public void auditStarted(AuditEvent event) {
// nop
}
public void auditFinished(AuditEvent event) {
// nop
}
public void fileStarted(AuditEvent event) {
// nop
}
public void fileFinished(AuditEvent event) {
currentResource = null;
}
public void addError(AuditEvent event) {
String ruleKey = getRuleKey(event);
if (ruleKey != null) {
String message = getMessage(event);
// In Checkstyle 5.5 exceptions are reported as an events from TreeWalker
if ("com.puppycrawl.tools.checkstyle.TreeWalker".equals(ruleKey)) {
- LOG.warn(message);
+ LOG.warn(event.getFileName() + ": " + message);
}
Rule rule = ruleFinder.findByKey(CheckstyleConstants.REPOSITORY_KEY, ruleKey);
if (rule != null) {
initResource(event);
Violation violation = Violation.create(rule, currentResource)
.setLineId(getLineId(event))
.setMessage(message);
context.saveViolation(violation);
}
}
}
private void initResource(AuditEvent event) {
if (currentResource == null) {
String absoluteFilename = event.getFileName();
currentResource = JavaFile.fromAbsolutePath(absoluteFilename, project.getFileSystem().getSourceDirs(), false);
}
}
@VisibleForTesting
static String getRuleKey(AuditEvent event) {
String key = null;
try {
key = event.getModuleId();
} catch (Exception e) {
// checkstyle throws a NullPointerException if the message is not set
}
if (StringUtils.isBlank(key)) {
try {
key = event.getSourceName();
} catch (Exception e) {
// checkstyle can throw a NullPointerException if the message is not set
}
}
return key;
}
@VisibleForTesting
static String getMessage(AuditEvent event) {
try {
return event.getMessage();
} catch (Exception e) {
// checkstyle can throw a NullPointerException if the message is not set
return null;
}
}
@VisibleForTesting
static Integer getLineId(AuditEvent event) {
try {
int line = event.getLine();
// checkstyle returns 0 if there is no relation to a file content, but we use null
return line == 0 ? null : line;
} catch (Exception e) {
// checkstyle can throw a NullPointerException if the message is not set
return null;
}
}
/**
* Note that this method never invoked from Checkstyle 5.5.
*/
public void addException(AuditEvent event, Throwable throwable) {
// nop
}
Resource getCurrentResource() {
return currentResource;
}
}
| true | true | public void addError(AuditEvent event) {
String ruleKey = getRuleKey(event);
if (ruleKey != null) {
String message = getMessage(event);
// In Checkstyle 5.5 exceptions are reported as an events from TreeWalker
if ("com.puppycrawl.tools.checkstyle.TreeWalker".equals(ruleKey)) {
LOG.warn(message);
}
Rule rule = ruleFinder.findByKey(CheckstyleConstants.REPOSITORY_KEY, ruleKey);
if (rule != null) {
initResource(event);
Violation violation = Violation.create(rule, currentResource)
.setLineId(getLineId(event))
.setMessage(message);
context.saveViolation(violation);
}
}
}
| public void addError(AuditEvent event) {
String ruleKey = getRuleKey(event);
if (ruleKey != null) {
String message = getMessage(event);
// In Checkstyle 5.5 exceptions are reported as an events from TreeWalker
if ("com.puppycrawl.tools.checkstyle.TreeWalker".equals(ruleKey)) {
LOG.warn(event.getFileName() + ": " + message);
}
Rule rule = ruleFinder.findByKey(CheckstyleConstants.REPOSITORY_KEY, ruleKey);
if (rule != null) {
initResource(event);
Violation violation = Violation.create(rule, currentResource)
.setLineId(getLineId(event))
.setMessage(message);
context.saveViolation(violation);
}
}
}
|
diff --git a/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/ca/BeansXmlCompletionProposalComputer.java b/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/ca/BeansXmlCompletionProposalComputer.java
index b6c4f5ac4..3034f2341 100644
--- a/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/ca/BeansXmlCompletionProposalComputer.java
+++ b/cdi/plugins/org.jboss.tools.cdi.ui/src/org/jboss/tools/cdi/ui/ca/BeansXmlCompletionProposalComputer.java
@@ -1,183 +1,183 @@
/*******************************************************************************
* Copyright (c) 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
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.cdi.ui.ca;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.graphics.Image;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
import org.eclipse.wst.sse.ui.contentassist.CompletionProposalInvocationContext;
import org.eclipse.wst.sse.ui.internal.contentassist.ContentAssistUtils;
import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
import org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest;
import org.eclipse.wst.xml.ui.internal.editor.XMLEditorPluginImageHelper;
import org.eclipse.wst.xml.ui.internal.editor.XMLEditorPluginImages;
import org.jboss.tools.cdi.core.CDICoreNature;
import org.jboss.tools.cdi.core.CDIUtil;
import org.jboss.tools.cdi.internal.core.ca.BeansXmlProcessor;
import org.jboss.tools.common.el.core.resolver.ELContext;
import org.jboss.tools.common.text.TextProposal;
import org.jboss.tools.common.ui.CommonUIPlugin;
import org.jboss.tools.jst.jsp.contentassist.AutoContentAssistantProposal;
import org.jboss.tools.jst.jsp.contentassist.computers.XmlTagCompletionProposalComputer;
import org.jboss.tools.jst.web.kb.KbQuery;
import org.jboss.tools.jst.web.kb.KbQuery.Type;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
@SuppressWarnings("restriction")
public class BeansXmlCompletionProposalComputer extends XmlTagCompletionProposalComputer {
@Override
protected void addTagInsertionProposals(
ContentAssistRequest contentAssistRequest, int childPosition,
CompletionProposalInvocationContext context) {
String prefix = getTagPrefix();
String uri = getTagUri();
String query = null;
String nodeText = null;
IndexedRegion treeNode = ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset());
int nodeStartOffset = treeNode == null ? -1 : treeNode.getStartOffset();
int localInvocationOffset = nodeStartOffset == -1 ? -1 : context.getInvocationOffset() - nodeStartOffset;
if (treeNode instanceof Element) {
IStructuredDocumentRegion reg = getStructuredDocumentRegion(context.getInvocationOffset());
ITextRegion firstRegion = reg == null ? null : reg.getFirstRegion();
if (firstRegion == null)
return;
if (firstRegion.getType() != DOMRegionContext.XML_END_TAG_OPEN ) {
return;
}
IndexedRegion prevTreeNode = context.getInvocationOffset() <= 0 ? null : ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset() - 1);
if (prevTreeNode instanceof Text) {
treeNode = prevTreeNode;
localInvocationOffset = ((Text)treeNode).getData() == null ? 0 : ((Text)treeNode).getData().length();
}
} else if (!(treeNode instanceof Text)) {
return;
}
nodeText = treeNode instanceof Text ? ((Text)treeNode).getData() : "";
if (localInvocationOffset > 0 && localInvocationOffset <= nodeText.length()) {
query = nodeText.substring(0, localInvocationOffset);
}
if (query == null)
query = ""; //$NON-NLS-1$
ELContext elContext = getContext();
IProject project = elContext == null || elContext.getResource() == null ? null :
elContext.getResource().getProject();
if (project == null)
return;
// The following code is made due to make sure that the CDI Model and Project is up-to-date
CDICoreNature nature = CDIUtil.getCDINatureWithProgress(project);
if (nature == null)
return;
KbQuery kbQuery = createKbQuery(Type.TAG_BODY, query, query, prefix, uri);
TextProposal[] proposals = BeansXmlProcessor.getInstance().getProposals(kbQuery, project);
String matchString = leftTrim(query);
for (int i = 0; proposals != null && i < proposals.length; i++) {
TextProposal textProposal = proposals[i];
String replacementString = textProposal.getReplacementString();
int replacementOffset = contentAssistRequest.getReplacementBeginPosition() - matchString.length();
int replacementLength = matchString.length();
int cursorPosition = getCursorPositionForProposedText(replacementString);
Image image = CommonUIPlugin.getImageDescriptorRegistry().get(textProposal.getImageDescriptor());
- if (image == null) {
+ if (textProposal.getImageDescriptor() == null) {
image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC);
}
String displayString = textProposal.getLabel();
IContextInformation contextInformation = null;
String additionalProposalInfo = textProposal.getContextInfo();
int relevance = textProposal.getRelevance();
if (relevance == TextProposal.R_NONE) {
relevance = TextProposal.R_TAG_INSERTION;
}
AutoContentAssistantProposal proposal = new AutoContentAssistantProposal(false, replacementString,
replacementOffset, replacementLength, cursorPosition, image, displayString,
contextInformation, additionalProposalInfo, relevance);
contentAssistRequest.addProposal(proposal);
}
}
@Override
protected void addAttributeNameProposals(
ContentAssistRequest contentAssistRequest,
CompletionProposalInvocationContext context) {
// No actions required
}
@Override
protected void addAttributeValueProposals(
ContentAssistRequest contentAssistRequest,
CompletionProposalInvocationContext context) {
// No actions required
}
@Override
protected void addTagNameProposals(
ContentAssistRequest contentAssistRequest, int childPosition,
CompletionProposalInvocationContext context) {
// No actions required
}
@Override
protected void addTagNameProposals(
ContentAssistRequest contentAssistRequest, int childPosition,
boolean insertTagOpenningCharacter,
CompletionProposalInvocationContext context) {
// No actions required
}
@Override
protected void addAttributeValueELProposals(
ContentAssistRequest contentAssistRequest,
CompletionProposalInvocationContext context) {
// No actions required
}
@Override
protected void addTextELProposals(
ContentAssistRequest contentAssistRequest,
CompletionProposalInvocationContext context) {
// No actions required
}
private String leftTrim(String value) {
int len = value.length();
int st = 0;
char[] val = value.toCharArray();
while ((st < len) && (val[st] <= ' ')) {
st++;
}
return (st > 0) ? value.substring(st) : value;
}
}
| true | true | protected void addTagInsertionProposals(
ContentAssistRequest contentAssistRequest, int childPosition,
CompletionProposalInvocationContext context) {
String prefix = getTagPrefix();
String uri = getTagUri();
String query = null;
String nodeText = null;
IndexedRegion treeNode = ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset());
int nodeStartOffset = treeNode == null ? -1 : treeNode.getStartOffset();
int localInvocationOffset = nodeStartOffset == -1 ? -1 : context.getInvocationOffset() - nodeStartOffset;
if (treeNode instanceof Element) {
IStructuredDocumentRegion reg = getStructuredDocumentRegion(context.getInvocationOffset());
ITextRegion firstRegion = reg == null ? null : reg.getFirstRegion();
if (firstRegion == null)
return;
if (firstRegion.getType() != DOMRegionContext.XML_END_TAG_OPEN ) {
return;
}
IndexedRegion prevTreeNode = context.getInvocationOffset() <= 0 ? null : ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset() - 1);
if (prevTreeNode instanceof Text) {
treeNode = prevTreeNode;
localInvocationOffset = ((Text)treeNode).getData() == null ? 0 : ((Text)treeNode).getData().length();
}
} else if (!(treeNode instanceof Text)) {
return;
}
nodeText = treeNode instanceof Text ? ((Text)treeNode).getData() : "";
if (localInvocationOffset > 0 && localInvocationOffset <= nodeText.length()) {
query = nodeText.substring(0, localInvocationOffset);
}
if (query == null)
query = ""; //$NON-NLS-1$
ELContext elContext = getContext();
IProject project = elContext == null || elContext.getResource() == null ? null :
elContext.getResource().getProject();
if (project == null)
return;
// The following code is made due to make sure that the CDI Model and Project is up-to-date
CDICoreNature nature = CDIUtil.getCDINatureWithProgress(project);
if (nature == null)
return;
KbQuery kbQuery = createKbQuery(Type.TAG_BODY, query, query, prefix, uri);
TextProposal[] proposals = BeansXmlProcessor.getInstance().getProposals(kbQuery, project);
String matchString = leftTrim(query);
for (int i = 0; proposals != null && i < proposals.length; i++) {
TextProposal textProposal = proposals[i];
String replacementString = textProposal.getReplacementString();
int replacementOffset = contentAssistRequest.getReplacementBeginPosition() - matchString.length();
int replacementLength = matchString.length();
int cursorPosition = getCursorPositionForProposedText(replacementString);
Image image = CommonUIPlugin.getImageDescriptorRegistry().get(textProposal.getImageDescriptor());
if (image == null) {
image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC);
}
String displayString = textProposal.getLabel();
IContextInformation contextInformation = null;
String additionalProposalInfo = textProposal.getContextInfo();
int relevance = textProposal.getRelevance();
if (relevance == TextProposal.R_NONE) {
relevance = TextProposal.R_TAG_INSERTION;
}
AutoContentAssistantProposal proposal = new AutoContentAssistantProposal(false, replacementString,
replacementOffset, replacementLength, cursorPosition, image, displayString,
contextInformation, additionalProposalInfo, relevance);
contentAssistRequest.addProposal(proposal);
}
}
| protected void addTagInsertionProposals(
ContentAssistRequest contentAssistRequest, int childPosition,
CompletionProposalInvocationContext context) {
String prefix = getTagPrefix();
String uri = getTagUri();
String query = null;
String nodeText = null;
IndexedRegion treeNode = ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset());
int nodeStartOffset = treeNode == null ? -1 : treeNode.getStartOffset();
int localInvocationOffset = nodeStartOffset == -1 ? -1 : context.getInvocationOffset() - nodeStartOffset;
if (treeNode instanceof Element) {
IStructuredDocumentRegion reg = getStructuredDocumentRegion(context.getInvocationOffset());
ITextRegion firstRegion = reg == null ? null : reg.getFirstRegion();
if (firstRegion == null)
return;
if (firstRegion.getType() != DOMRegionContext.XML_END_TAG_OPEN ) {
return;
}
IndexedRegion prevTreeNode = context.getInvocationOffset() <= 0 ? null : ContentAssistUtils.getNodeAt(context.getViewer(), context.getInvocationOffset() - 1);
if (prevTreeNode instanceof Text) {
treeNode = prevTreeNode;
localInvocationOffset = ((Text)treeNode).getData() == null ? 0 : ((Text)treeNode).getData().length();
}
} else if (!(treeNode instanceof Text)) {
return;
}
nodeText = treeNode instanceof Text ? ((Text)treeNode).getData() : "";
if (localInvocationOffset > 0 && localInvocationOffset <= nodeText.length()) {
query = nodeText.substring(0, localInvocationOffset);
}
if (query == null)
query = ""; //$NON-NLS-1$
ELContext elContext = getContext();
IProject project = elContext == null || elContext.getResource() == null ? null :
elContext.getResource().getProject();
if (project == null)
return;
// The following code is made due to make sure that the CDI Model and Project is up-to-date
CDICoreNature nature = CDIUtil.getCDINatureWithProgress(project);
if (nature == null)
return;
KbQuery kbQuery = createKbQuery(Type.TAG_BODY, query, query, prefix, uri);
TextProposal[] proposals = BeansXmlProcessor.getInstance().getProposals(kbQuery, project);
String matchString = leftTrim(query);
for (int i = 0; proposals != null && i < proposals.length; i++) {
TextProposal textProposal = proposals[i];
String replacementString = textProposal.getReplacementString();
int replacementOffset = contentAssistRequest.getReplacementBeginPosition() - matchString.length();
int replacementLength = matchString.length();
int cursorPosition = getCursorPositionForProposedText(replacementString);
Image image = CommonUIPlugin.getImageDescriptorRegistry().get(textProposal.getImageDescriptor());
if (textProposal.getImageDescriptor() == null) {
image = XMLEditorPluginImageHelper.getInstance().getImage(XMLEditorPluginImages.IMG_OBJ_TAG_GENERIC);
}
String displayString = textProposal.getLabel();
IContextInformation contextInformation = null;
String additionalProposalInfo = textProposal.getContextInfo();
int relevance = textProposal.getRelevance();
if (relevance == TextProposal.R_NONE) {
relevance = TextProposal.R_TAG_INSERTION;
}
AutoContentAssistantProposal proposal = new AutoContentAssistantProposal(false, replacementString,
replacementOffset, replacementLength, cursorPosition, image, displayString,
contextInformation, additionalProposalInfo, relevance);
contentAssistRequest.addProposal(proposal);
}
}
|
diff --git a/microemulator/core/src/org/microemu/applet/Main.java b/microemulator/core/src/org/microemu/applet/Main.java
index 4ef9deb4..f15bed74 100644
--- a/microemulator/core/src/org/microemu/applet/Main.java
+++ b/microemulator/core/src/org/microemu/applet/Main.java
@@ -1,328 +1,330 @@
/*
* MicroEmulator
* Copyright (C) 2001 Bartek Teodorczyk <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contributor(s):
* daniel(at)angrymachine.com.ar
*/
package org.microemu.applet;
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Locale;
import java.util.Vector;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.swing.Timer;
import org.microemu.DisplayComponent;
import org.microemu.EmulatorContext;
import org.microemu.MIDletAccess;
import org.microemu.MIDletBridge;
import org.microemu.MicroEmulator;
import org.microemu.RecordStoreManager;
import org.microemu.app.ui.swing.SwingDeviceComponent;
import org.microemu.device.Device;
import org.microemu.device.DeviceDisplay;
import org.microemu.device.DeviceFactory;
import org.microemu.device.FontManager;
import org.microemu.device.InputMethod;
import org.microemu.device.j2se.J2SEDeviceDisplay;
import org.microemu.device.j2se.J2SEFontManager;
import org.microemu.device.j2se.J2SEInputMethod;
import org.microemu.util.JadMidletEntry;
import org.microemu.util.JadProperties;
import org.microemu.util.MemoryRecordStoreManager;
public class Main extends Applet implements MicroEmulator
{
private static final long serialVersionUID = 1L;
private MIDlet midlet = null;
private RecordStoreManager recordStoreManager;
private JadProperties manifest = new JadProperties();
private SwingDeviceComponent devicePanel;
private EmulatorContext emulatorContext = new EmulatorContext()
{
private InputMethod inputMethod = new J2SEInputMethod();
private DeviceDisplay deviceDisplay = new J2SEDeviceDisplay(this);
private FontManager fontManager = new J2SEFontManager();
public DisplayComponent getDisplayComponent()
{
return devicePanel.getDisplayComponent();
}
public InputMethod getDeviceInputMethod()
{
return inputMethod;
}
public DeviceDisplay getDeviceDisplay()
{
return deviceDisplay;
}
public FontManager getDeviceFontManager()
{
return fontManager;
}
};
public Main()
{
devicePanel = new SwingDeviceComponent();
devicePanel.addKeyListener(devicePanel);
}
public void init()
{
if (midlet != null) {
return;
}
MIDletBridge.setMicroEmulator(this);
recordStoreManager = new MemoryRecordStoreManager();
setLayout(new BorderLayout());
add(devicePanel, "Center");
Device device;
String deviceParameter = getParameter("device");
if (deviceParameter == null) {
device = new Device();
+ DeviceFactory.setDevice(device);
+ device.init(emulatorContext);
} else {
try {
Class cl = Class.forName(deviceParameter);
device = (Device) cl.newInstance();
DeviceFactory.setDevice(device);
device.init(emulatorContext);
} catch (ClassNotFoundException ex) {
try {
device = Device.create(
emulatorContext,
Main.class.getClassLoader(),
deviceParameter);
DeviceFactory.setDevice(device);
} catch (IOException ex1) {
System.out.println(ex);
return;
}
} catch (IllegalAccessException ex) {
System.out.println(ex);
return;
} catch (InstantiationException ex) {
System.out.println(ex);
return;
}
}
devicePanel.init();
manifest.clear();
try {
URL url = getClass().getClassLoader().getResource(
"META-INF/MANIFEST.MF");
manifest.load(url.openStream());
if (manifest.getProperty("MIDlet-Name") == null) {
manifest.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
// load jad
String midletClassName = null;
String jadFile = getParameter("jad");
if (jadFile != null) {
InputStream jadInputStream = null;
try {
URL jad = new URL(getCodeBase(), jadFile);
jadInputStream = jad.openStream();
manifest.load(jadInputStream);
Vector entries = manifest.getMidletEntries();
// only load the first (no midlet suite support anyway)
if (entries.size() > 0) {
JadMidletEntry entry = (JadMidletEntry) entries.elementAt(0);
midletClassName = entry.getClassName();
}
} catch (IOException e) {
} finally {
if (jadInputStream != null) {
try {
jadInputStream.close();
} catch (IOException e1) {
}
}
}
}
if (midletClassName == null) {
midletClassName = getParameter("midlet");
if (midletClassName == null) {
System.out.println("There is no midlet parameter");
return;
}
}
Class midletClass;
try {
midletClass = Class.forName(midletClassName);
} catch (ClassNotFoundException ex) {
System.out.println("Cannot find " + midletClassName + " MIDlet class");
return;
}
try {
midlet = (MIDlet) midletClass.newInstance();
} catch (Exception ex) {
System.out.println("Cannot initialize " + midletClass + " MIDlet class");
System.out.println(ex);
ex.printStackTrace();
return;
}
Image tmpImg = DeviceFactory.getDevice().getNormalImage();
resize(tmpImg.getWidth(), tmpImg.getHeight());
return;
}
public void start() {
devicePanel.requestFocus();
new Thread("midlet_starter") {
public void run() {
try {
MIDletBridge.getMIDletAccess(midlet).startApp();
} catch (MIDletStateChangeException ex) {
System.err.println(ex);
}
}
}.start();
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
devicePanel.requestFocus();
}
});
timer.setRepeats(false);
timer.start();
}
public void stop()
{
MIDletBridge.getMIDletAccess(midlet).pauseApp();
}
public void destroy()
{
try {
MIDletBridge.getMIDletAccess(midlet).destroyApp(true);
} catch (MIDletStateChangeException ex) {
System.err.println(ex);
}
}
public RecordStoreManager getRecordStoreManager()
{
return recordStoreManager;
}
public String getAppProperty(String key)
{
if (key.equals("applet")) {
return "yes";
}
String value = null;
if (key.equals("microedition.platform")) {
value = "MicroEmulator";
} else if (key.equals("microedition.profile")) {
value = "MIDP-1.0";
} else if (key.equals("microedition.configuration")) {
value = "CLDC-1.0";
} else if (key.equals("microedition.locale")) {
value = Locale.getDefault().getLanguage();
} else if (key.equals("microedition.encoding")) {
value = System.getProperty("file.encoding");
} else if (getParameter(key) != null) {
value = getParameter(key);
} else {
value = manifest.getProperty(key);
}
return value;
}
public boolean platformRequest(String url)
{
try {
getAppletContext().showDocument(new URL(url), "mini");
} catch (Exception e) {
}
return false;
}
public void notifyDestroyed(MIDletAccess previousMidletAccess)
{
}
public String getAppletInfo()
{
return "Title: MicroEmulator \nAuthor: Bartek Teodorczyk, 2001";
}
public String[][] getParameterInfo()
{
String[][] info = {
{ "midlet", "MIDlet class name", "The MIDlet class name. This field is mandatory." },
};
return info;
}
}
| true | true | public void init()
{
if (midlet != null) {
return;
}
MIDletBridge.setMicroEmulator(this);
recordStoreManager = new MemoryRecordStoreManager();
setLayout(new BorderLayout());
add(devicePanel, "Center");
Device device;
String deviceParameter = getParameter("device");
if (deviceParameter == null) {
device = new Device();
} else {
try {
Class cl = Class.forName(deviceParameter);
device = (Device) cl.newInstance();
DeviceFactory.setDevice(device);
device.init(emulatorContext);
} catch (ClassNotFoundException ex) {
try {
device = Device.create(
emulatorContext,
Main.class.getClassLoader(),
deviceParameter);
DeviceFactory.setDevice(device);
} catch (IOException ex1) {
System.out.println(ex);
return;
}
} catch (IllegalAccessException ex) {
System.out.println(ex);
return;
} catch (InstantiationException ex) {
System.out.println(ex);
return;
}
}
devicePanel.init();
manifest.clear();
try {
URL url = getClass().getClassLoader().getResource(
"META-INF/MANIFEST.MF");
manifest.load(url.openStream());
if (manifest.getProperty("MIDlet-Name") == null) {
manifest.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
// load jad
String midletClassName = null;
String jadFile = getParameter("jad");
if (jadFile != null) {
InputStream jadInputStream = null;
try {
URL jad = new URL(getCodeBase(), jadFile);
jadInputStream = jad.openStream();
manifest.load(jadInputStream);
Vector entries = manifest.getMidletEntries();
// only load the first (no midlet suite support anyway)
if (entries.size() > 0) {
JadMidletEntry entry = (JadMidletEntry) entries.elementAt(0);
midletClassName = entry.getClassName();
}
} catch (IOException e) {
} finally {
if (jadInputStream != null) {
try {
jadInputStream.close();
} catch (IOException e1) {
}
}
}
}
if (midletClassName == null) {
midletClassName = getParameter("midlet");
if (midletClassName == null) {
System.out.println("There is no midlet parameter");
return;
}
}
Class midletClass;
try {
midletClass = Class.forName(midletClassName);
} catch (ClassNotFoundException ex) {
System.out.println("Cannot find " + midletClassName + " MIDlet class");
return;
}
try {
midlet = (MIDlet) midletClass.newInstance();
} catch (Exception ex) {
System.out.println("Cannot initialize " + midletClass + " MIDlet class");
System.out.println(ex);
ex.printStackTrace();
return;
}
Image tmpImg = DeviceFactory.getDevice().getNormalImage();
resize(tmpImg.getWidth(), tmpImg.getHeight());
return;
}
| public void init()
{
if (midlet != null) {
return;
}
MIDletBridge.setMicroEmulator(this);
recordStoreManager = new MemoryRecordStoreManager();
setLayout(new BorderLayout());
add(devicePanel, "Center");
Device device;
String deviceParameter = getParameter("device");
if (deviceParameter == null) {
device = new Device();
DeviceFactory.setDevice(device);
device.init(emulatorContext);
} else {
try {
Class cl = Class.forName(deviceParameter);
device = (Device) cl.newInstance();
DeviceFactory.setDevice(device);
device.init(emulatorContext);
} catch (ClassNotFoundException ex) {
try {
device = Device.create(
emulatorContext,
Main.class.getClassLoader(),
deviceParameter);
DeviceFactory.setDevice(device);
} catch (IOException ex1) {
System.out.println(ex);
return;
}
} catch (IllegalAccessException ex) {
System.out.println(ex);
return;
} catch (InstantiationException ex) {
System.out.println(ex);
return;
}
}
devicePanel.init();
manifest.clear();
try {
URL url = getClass().getClassLoader().getResource(
"META-INF/MANIFEST.MF");
manifest.load(url.openStream());
if (manifest.getProperty("MIDlet-Name") == null) {
manifest.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
// load jad
String midletClassName = null;
String jadFile = getParameter("jad");
if (jadFile != null) {
InputStream jadInputStream = null;
try {
URL jad = new URL(getCodeBase(), jadFile);
jadInputStream = jad.openStream();
manifest.load(jadInputStream);
Vector entries = manifest.getMidletEntries();
// only load the first (no midlet suite support anyway)
if (entries.size() > 0) {
JadMidletEntry entry = (JadMidletEntry) entries.elementAt(0);
midletClassName = entry.getClassName();
}
} catch (IOException e) {
} finally {
if (jadInputStream != null) {
try {
jadInputStream.close();
} catch (IOException e1) {
}
}
}
}
if (midletClassName == null) {
midletClassName = getParameter("midlet");
if (midletClassName == null) {
System.out.println("There is no midlet parameter");
return;
}
}
Class midletClass;
try {
midletClass = Class.forName(midletClassName);
} catch (ClassNotFoundException ex) {
System.out.println("Cannot find " + midletClassName + " MIDlet class");
return;
}
try {
midlet = (MIDlet) midletClass.newInstance();
} catch (Exception ex) {
System.out.println("Cannot initialize " + midletClass + " MIDlet class");
System.out.println(ex);
ex.printStackTrace();
return;
}
Image tmpImg = DeviceFactory.getDevice().getNormalImage();
resize(tmpImg.getWidth(), tmpImg.getHeight());
return;
}
|
diff --git a/Core/src/java/de/hattrickorganizer/gui/lineup/CopyListener.java b/Core/src/java/de/hattrickorganizer/gui/lineup/CopyListener.java
index 4ef76675..9240179b 100644
--- a/Core/src/java/de/hattrickorganizer/gui/lineup/CopyListener.java
+++ b/Core/src/java/de/hattrickorganizer/gui/lineup/CopyListener.java
@@ -1,109 +1,109 @@
package de.hattrickorganizer.gui.lineup;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import de.hattrickorganizer.model.HOVerwaltung;
import de.hattrickorganizer.tools.HOLogger;
/**
* Listener for the "copy ratings to clipboard" feature at the lineup screen.
*
* @author aik
*/
public class CopyListener implements ActionListener {
private AufstellungsRatingPanel lineup;
private static String LF = System.getProperty("line.separator", "\n");
private JMenuItem miPlaintext = new JMenuItem(HOVerwaltung.instance().getLanguageString("Lineup.CopyRatings.PlainText"));
private JMenuItem miHattickML = new JMenuItem(HOVerwaltung.instance().getLanguageString("Lineup.CopyRatings.HattrickML"));
final JPopupMenu menu = new JPopupMenu();
/**
* Create the CopyListener and initialize the gui components.
*/
public CopyListener(AufstellungsRatingPanel lineup) {
this.lineup = lineup;
miPlaintext.addActionListener(this);
miHattickML.addActionListener(this);
menu.add(miPlaintext);
menu.add(miHattickML);
}
/**
* Handle action events (shop popup menu or copy ratings).
*/
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource().equals(miPlaintext)) {
menu.setVisible(false);
copyToClipboard(getRatingsAsText());
} else if (e != null && e.getSource().equals(miHattickML)) {
copyToClipboard(getRatingsAsHattrickML());
menu.setVisible(false);
} else if (e != null && e.getSource() != null && e.getSource() instanceof Component) {
menu.show((Component)e.getSource(), 1, 1);
}
}
/**
* Copy the giben text into the system clipboard.
*/
public static void copyToClipboard(final String txt) {
try {
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(txt), null);
} catch (Exception e) {
HOLogger.instance().error(CopyListener.class, e);
}
}
/**
* Get ratings as normal text, ordered like in HT.
*/
private String getRatingsAsText() {
StringBuilder sb = new StringBuilder("");
if (lineup != null) {
sb.append(HOVerwaltung.instance().getLanguageString("MatchMittelfeld") + ": " + lineup.getMidfieldRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("rechteAbwehrseite") + ": " + lineup.getRightDefenseRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("Abwehrzentrum") + ": " + lineup.getCentralDefenseRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("linkeAbwehrseite") + ": " + lineup.getLeftDefenseRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("rechteAngriffsseite") + ": " + lineup.getRightAttackRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("Angriffszentrum") + ": " + lineup.getCentralAttackRating() + LF);
sb.append(HOVerwaltung.instance().getLanguageString("linkeAngriffsseite") + ": " + lineup.getLeftAttackRating() + LF);
}
return sb.toString();
}
/**
* Get ratings in a HT-ML style table.
*/
private String getRatingsAsHattrickML() {
StringBuilder sb = new StringBuilder("");
if (lineup != null) {
sb.append("[table]");
sb.append("[tr][th][/th][th]"+HOVerwaltung.instance().getLanguageString("Links"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Mitte"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Rechts")+"[/th][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Attack")+"[/th]");
sb.append("[td]"+lineup.getLeftAttackRating());
sb.append("[/td][td]"+lineup.getCentralAttackRating());
sb.append("[/td][td]"+lineup.getRightAttackRating());
sb.append("[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("MatchMittelfeld")+"[/th]");
- sb.append("[td colspan=\"3\"] "); // TODO: is there a "center" @ HT-ML?
+ sb.append("[td colspan='3' align='center']");
sb.append(lineup.getMidfieldRating()+"[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Verteidigung"));
sb.append("[/th][td]"+lineup.getLeftDefenseRating()+"[/td][td]");
sb.append(lineup.getCentralDefenseRating()+"[/td][td]");
sb.append(lineup.getRightDefenseRating()+"[/td][/tr]" + LF);
sb.append("[/table]");
sb.append(LF);
}
return sb.toString();
}
}
| true | true | private String getRatingsAsHattrickML() {
StringBuilder sb = new StringBuilder("");
if (lineup != null) {
sb.append("[table]");
sb.append("[tr][th][/th][th]"+HOVerwaltung.instance().getLanguageString("Links"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Mitte"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Rechts")+"[/th][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Attack")+"[/th]");
sb.append("[td]"+lineup.getLeftAttackRating());
sb.append("[/td][td]"+lineup.getCentralAttackRating());
sb.append("[/td][td]"+lineup.getRightAttackRating());
sb.append("[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("MatchMittelfeld")+"[/th]");
sb.append("[td colspan=\"3\"] "); // TODO: is there a "center" @ HT-ML?
sb.append(lineup.getMidfieldRating()+"[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Verteidigung"));
sb.append("[/th][td]"+lineup.getLeftDefenseRating()+"[/td][td]");
sb.append(lineup.getCentralDefenseRating()+"[/td][td]");
sb.append(lineup.getRightDefenseRating()+"[/td][/tr]" + LF);
sb.append("[/table]");
sb.append(LF);
}
return sb.toString();
}
| private String getRatingsAsHattrickML() {
StringBuilder sb = new StringBuilder("");
if (lineup != null) {
sb.append("[table]");
sb.append("[tr][th][/th][th]"+HOVerwaltung.instance().getLanguageString("Links"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Mitte"));
sb.append("[/th][th]"+HOVerwaltung.instance().getLanguageString("Rechts")+"[/th][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Attack")+"[/th]");
sb.append("[td]"+lineup.getLeftAttackRating());
sb.append("[/td][td]"+lineup.getCentralAttackRating());
sb.append("[/td][td]"+lineup.getRightAttackRating());
sb.append("[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("MatchMittelfeld")+"[/th]");
sb.append("[td colspan='3' align='center']");
sb.append(lineup.getMidfieldRating()+"[/td][/tr]" + LF);
sb.append("[tr][th]"+HOVerwaltung.instance().getLanguageString("Verteidigung"));
sb.append("[/th][td]"+lineup.getLeftDefenseRating()+"[/td][td]");
sb.append(lineup.getCentralDefenseRating()+"[/td][td]");
sb.append(lineup.getRightDefenseRating()+"[/td][/tr]" + LF);
sb.append("[/table]");
sb.append(LF);
}
return sb.toString();
}
|
diff --git a/src/main/java/com/mareksebera/simpledilbert/preferences/DilbertPreferences.java b/src/main/java/com/mareksebera/simpledilbert/preferences/DilbertPreferences.java
index c874f97..dff03cb 100644
--- a/src/main/java/com/mareksebera/simpledilbert/preferences/DilbertPreferences.java
+++ b/src/main/java/com/mareksebera/simpledilbert/preferences/DilbertPreferences.java
@@ -1,295 +1,291 @@
package com.mareksebera.simpledilbert.preferences;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.mareksebera.simpledilbert.R;
import com.mareksebera.simpledilbert.favorites.FavoritedItem;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
public final class DilbertPreferences {
private final SharedPreferences preferences;
private final SharedPreferences.Editor editor;
private static final String PREF_CURRENT_DATE = "dilbert_current_date";
private static final String PREF_CURRENT_URL = "dilbert_current_url";
private static final String PREF_HIGH_QUALITY_ENABLED = "dilbert_use_high_quality";
private static final String PREF_DARK_LAYOUT = "dilbert_dark_layout";
private static final String PREF_DARK_WIDGET_LAYOUT = "dilbert_dark_layout_widget";
private static final String PREF_FORCE_LANDSCAPE = "dilbert_force_landscape";
private static final String PREF_HIDE_TOOLBARS = "dilbert_hide_toolbars";
private static final String PREF_DOWNLOAD_TARGET = "dilbert_download_target_folder";
private static final String PREF_SHARE_IMAGE = "dilbert_share_with_image";
private static final String PREF_MOBILE_NETWORK = "dilbert_using_slow_network";
private static final String TAG = "DilbertPreferences";
public static final DateTimeZone TIME_ZONE = DateTimeZone
.forID("America/Chicago");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat
.forPattern("yyyy-MM-dd");
@SuppressLint("CommitPrefEdits")
public DilbertPreferences(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = preferences.edit();
}
public LocalDate getCurrentDate() {
String savedDate = preferences.getString(PREF_CURRENT_DATE, null);
if (savedDate == null) {
return LocalDate.now(DilbertPreferences.TIME_ZONE);
} else {
return LocalDate.parse(savedDate, DATE_FORMATTER);
}
}
public boolean saveCurrentDate(LocalDate currentDate) {
editor.putString(PREF_CURRENT_DATE,
currentDate.toString(DilbertPreferences.DATE_FORMATTER));
return editor.commit();
}
public boolean isHighQualityOn() {
return preferences.getBoolean(PREF_HIGH_QUALITY_ENABLED, true);
}
public boolean saveCurrentUrl(String date, String s) {
editor.putString(PREF_CURRENT_URL, s);
editor.putString(date, s);
return editor.commit();
}
public String getCachedUrl(LocalDate dateKey) {
return getCachedUrl(dateKey.toString(DATE_FORMATTER));
}
String getCachedUrl(String dateKey) {
return preferences.getString(dateKey, null);
}
public boolean removeCache(LocalDate currentDate) {
return editor.remove(
currentDate.toString(DilbertPreferences.DATE_FORMATTER))
.commit();
}
public boolean isFavorited(LocalDate currentDay) {
return preferences.getBoolean(toFavoritedKey(currentDay), false);
}
public boolean toggleIsFavorited(LocalDate currentDay) {
boolean newState = !isFavorited(currentDay);
editor.putBoolean(toFavoritedKey(currentDay), newState).commit();
return newState;
}
private String toFavoritedKey(LocalDate currentDay) {
return "favorite_"
+ currentDay.toString(DilbertPreferences.DATE_FORMATTER);
}
public List<FavoritedItem> getFavoritedItems() {
List<FavoritedItem> favorites = new ArrayList<FavoritedItem>();
Map<String, ?> allPreferences = preferences.getAll();
if (allPreferences != null) {
for (String key : allPreferences.keySet()) {
if (key.startsWith("favorite_")
&& (Boolean) allPreferences.get(key)) {
String date = key.replace("favorite_", "");
favorites.add(new FavoritedItem(LocalDate.parse(date,
DATE_FORMATTER)));
}
}
}
Collections.sort(favorites, new Comparator<FavoritedItem>() {
@Override
public int compare(FavoritedItem lhs, FavoritedItem rhs) {
return lhs.getDate().compareTo(rhs.getDate());
}
});
return favorites;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void downloadImageViaManager(final Activity activity,
final String downloadUrl, LocalDate stripDate) {
try {
DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
String url = toHighQuality(downloadUrl);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationUri(Uri.withAppendedPath(
Uri.parse("file://" + getDownloadTarget()),
DATE_FORMATTER.print(stripDate) + ".gif"));
request.setVisibleInDownloadsUi(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}else{
request.setShowRunningNotification(true);
}
dm.enqueue(request);
- } catch (Exception e) {
- Log.e(TAG, "Should not happen", e);
- Toast.makeText(activity, R.string.download_manager_unsupported,
- Toast.LENGTH_LONG).show();
- } catch (Error e) {
- Log.e(TAG, "Should not happen", e);
+ } catch (Throwable t) {
+ Log.e(TAG, "Should not happen", t);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
}
}
public String toHighQuality(String url) {
if (url == null)
return null;
return url.replace(".gif", ".zoom.gif").replace("zoom.zoom", "zoom");
}
public String toLowQuality(LocalDate date, String url) {
if (url == null)
return null;
if (date.getDayOfWeek() == DateTimeConstants.SUNDAY) {
return url.replace(".zoom.gif", ".sunday.gif").replace("zoom.zoom",
"zoom");
}
return url.replace(".zoom.gif", ".gif").replace("zoom.zoom", "zoom");
}
public boolean saveDateForWidgetId(int appWidgetId, LocalDate date) {
date = validateDate(date);
return editor.putString("widget_" + appWidgetId,
date.toString(DATE_FORMATTER)).commit();
}
public LocalDate getDateForWidgetId(int appWidgetId) {
String savedDate = preferences.getString("widget_" + appWidgetId, null);
if (savedDate == null)
return LocalDate.now();
else
return LocalDate.parse(savedDate, DATE_FORMATTER);
}
public static LocalDate getRandomDate() {
Random random = new Random();
LocalDate now = LocalDate.now();
int year = 1989 + random.nextInt(now.getYear() - 1989);
int month = 1 + random.nextInt(12);
int day = random.nextInt(31);
return LocalDate.parse(
String.format(new Locale("en"), "%d-%d-1", year, month))
.plusDays(day);
}
/**
* First strip was published on 16.4.1989
*
* @see <a href="http://en.wikipedia.org/wiki/Dilbert">Wikipedia</a>
*/
public static LocalDate getFirstStripDate() {
return LocalDate.parse("1989-04-16",
DilbertPreferences.DATE_FORMATTER);
}
public boolean deleteDateForWidgetId(int widgetId) {
return editor.remove("widget_" + widgetId).commit();
}
private static LocalDate validateDate(LocalDate selDate) {
if (selDate.isAfter(LocalDate.now())) {
selDate = LocalDate.now();
}
if (selDate.isBefore(DilbertPreferences.getFirstStripDate())) {
selDate = DilbertPreferences.getFirstStripDate();
}
return selDate;
}
public boolean isForceLandscape() {
return preferences.getBoolean(PREF_FORCE_LANDSCAPE, false);
}
public boolean setIsForceLandscape(boolean force) {
return editor.putBoolean(PREF_FORCE_LANDSCAPE, force).commit();
}
public boolean isDarkLayoutEnabled() {
return preferences.getBoolean(PREF_DARK_LAYOUT, false);
}
public boolean setIsDarkLayoutEnabled(boolean dark) {
return editor.putBoolean(PREF_DARK_LAYOUT, dark).commit();
}
public boolean isToolbarsHidden() {
return preferences.getBoolean(PREF_HIDE_TOOLBARS, false);
}
public boolean setIsToolbarsHidden(boolean hidden) {
return editor.putBoolean(PREF_HIDE_TOOLBARS, hidden).commit();
}
public boolean setIsHighQualityOn(boolean enabled) {
return editor.putBoolean(PREF_HIGH_QUALITY_ENABLED, enabled).commit();
}
public boolean isDarkWidgetLayoutEnabled() {
return preferences.getBoolean(PREF_DARK_WIDGET_LAYOUT, false);
}
public boolean setIsDarkWidgetLayoutEnabled(boolean dark) {
return editor.putBoolean(PREF_DARK_WIDGET_LAYOUT, dark).commit();
}
public String getDownloadTarget() {
return preferences.getString(
PREF_DOWNLOAD_TARGET,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
}
public boolean setDownloadTarget(String absolutePath) {
return absolutePath != null && editor.putString(PREF_DOWNLOAD_TARGET, absolutePath).commit();
}
public boolean isSharingImage() {
return preferences.getBoolean(PREF_SHARE_IMAGE, true);
}
public boolean setIsSharingImage(boolean shouldShareImage) {
return editor.putBoolean(PREF_SHARE_IMAGE, shouldShareImage).commit();
}
public boolean setIsSlowNetwork(boolean isSlowNetwork) {
return editor.putBoolean(PREF_MOBILE_NETWORK, isSlowNetwork).commit();
}
public boolean isSlowNetwork() {
return preferences.getBoolean(PREF_MOBILE_NETWORK, true);
}
}
| true | true | public void downloadImageViaManager(final Activity activity,
final String downloadUrl, LocalDate stripDate) {
try {
DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
String url = toHighQuality(downloadUrl);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationUri(Uri.withAppendedPath(
Uri.parse("file://" + getDownloadTarget()),
DATE_FORMATTER.print(stripDate) + ".gif"));
request.setVisibleInDownloadsUi(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}else{
request.setShowRunningNotification(true);
}
dm.enqueue(request);
} catch (Exception e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
} catch (Error e) {
Log.e(TAG, "Should not happen", e);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
}
}
| public void downloadImageViaManager(final Activity activity,
final String downloadUrl, LocalDate stripDate) {
try {
DownloadManager dm = (DownloadManager) activity
.getSystemService(Context.DOWNLOAD_SERVICE);
String url = toHighQuality(downloadUrl);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.setDestinationUri(Uri.withAppendedPath(
Uri.parse("file://" + getDownloadTarget()),
DATE_FORMATTER.print(stripDate) + ".gif"));
request.setVisibleInDownloadsUi(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}else{
request.setShowRunningNotification(true);
}
dm.enqueue(request);
} catch (Throwable t) {
Log.e(TAG, "Should not happen", t);
Toast.makeText(activity, R.string.download_manager_unsupported,
Toast.LENGTH_LONG).show();
}
}
|
diff --git a/src/com/reelfx/view/Interface.java b/src/com/reelfx/view/Interface.java
index e3a46b9..8dfc9fb 100644
--- a/src/com/reelfx/view/Interface.java
+++ b/src/com/reelfx/view/Interface.java
@@ -1,457 +1,453 @@
package com.reelfx.view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.io.File;
import java.sql.Time;
import java.util.Calendar;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JWindow;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import com.reelfx.Applet;
import com.reelfx.controller.ApplicationController;
import com.reelfx.model.ScreenRecorder;
public class Interface extends JFrame implements MouseListener, MouseMotionListener, WindowListener, ActionListener, ComponentListener {
private static final long serialVersionUID = 4803377343174867777L;
public final static int READY = 0;
public final static int READY_WITH_OPTIONS = 1;
public final static int PRE_RECORDING = 5;
public final static int RECORDING = 2;
public final static int THINKING = 3;
public final static int FATAL = 4;
public JButton recordBtn, previewBtn, saveBtn, insightBtn, deleteBtn;
public AudioSelectBox audioSelect;
public JPanel recordingOptionsPanel, statusPanel, postRecordingOptionsPanel;
private JLabel status, message;
//private JTextArea message;
private Timer timer;
private ApplicationController controller;
private JFileChooser fileSelect = new JFileChooser();
private Color backgroundColor = new Color(34, 34, 34);
private Color statusColor = new Color(255, 102, 102);
private Color messageColor = new Color(255, 255, 153);
private int currentState = READY, timerCount = 0;
private Dimension screen;
private CountDown countdown = new CountDown();
public Interface(ApplicationController controller) {
super();
this.controller = controller;
Toolkit tk = Toolkit.getDefaultToolkit();
screen = tk.getScreenSize();
// From Docs: Gets the size of the screen. On systems with multiple displays, the primary display is used. Multi-screen aware display dimensions are available from GraphicsConfiguration and GraphicsDevice
// ------- setup the JFrame -------
setTitle("Review for "+Applet.SCREEN_CAPTURE_NAME);
setResizable(false);
setDefaultCloseOperation(HIDE_ON_CLOSE);
//setBackground(backgroundColor); // same as Flex review tool
//setPreferredSize(dim); // full screen
//setPreferredSize(new Dimension(500, 50)); // will auto fit to the size needed, but if you want to specify a size
setLocation((int)(screen.width*0.75), screen.height/6);
//setLayout(new BorderLayout(0, 3));
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
setAlwaysOnTop(true);
addMouseListener(this);
addMouseMotionListener(this);
addWindowListener(this);
addComponentListener(this);
/*if (AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSPARENT)) {
System.out.println("Transparency supported!");
}*/
// ------- setup recording options -------
recordingOptionsPanel = new JPanel();
//recordingOptionsPanel.setMaximumSize(new Dimension(180,1000));
recordingOptionsPanel.setOpaque(false);
recordBtn = new JButton("Record");
recordBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(recordBtn.getText().equals("Record")) {
prepareForRecording();
}
else if(recordBtn.getText().equals("Stop")) {
stopRecording();
}
}
});
recordingOptionsPanel.add(recordBtn);
audioSelect = new AudioSelectBox();
recordingOptionsPanel.add(audioSelect);
add(recordingOptionsPanel); //,BorderLayout.NORTH);
// ------- setup status bar -------
status = new JLabel();
//status.setBackground(statusColor);
//status.setPreferredSize(new Dimension(50, 40));
status.setFont(new java.awt.Font("Arial", 1, 13));
//status.setForeground(Color.WHITE);
status.setOpaque(true);
status.setHorizontalAlignment(SwingConstants.CENTER);
statusPanel = new JPanel();
statusPanel.setOpaque(false);
statusPanel.add(status);
add(statusPanel); //,BorderLayout.CENTER);
// ------- setup post recording options -------
postRecordingOptionsPanel = new JPanel();
//postRecordingOptionsPanel.setBackground(messageColor);
//postRecordingOptionsPanel.setMaximumSize(new Dimension(180,1000));
//postRecordingOptionsPanel.setBorder(javax.swing.BorderFactory.createLineBorder(backgroundColor, 8));
postRecordingOptionsPanel.setLayout(new BoxLayout(postRecordingOptionsPanel, BoxLayout.Y_AXIS));
postRecordingOptionsPanel.add(new JSeparator());
/*
message = new JTextArea();
message.setFont(new java.awt.Font("Arial", 0, 13));
message.setMinimumSize(new Dimension(200,20));
message.setOpaque(false);
message.setLineWrap(true);
message.setBorder(javax.swing.BorderFactory.createLineBorder(messageColor, 5));
//message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
message.setText("You have a review for \"Shot 2000-0300\" from 04/03/2010");
message.setAlignmentX(0.5F);
/* */
message = new JLabel();
message.setFont(new java.awt.Font("Arial", 0, 13));
message.setOpaque(false);
message.setMaximumSize(new Dimension(180,1000));
message.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
message.setAlignmentX(0.5F);
/* */
postRecordingOptionsPanel.add(message);
previewBtn = new JButton("Preview It");
previewBtn.setFont(new java.awt.Font("Arial", 0, 13));
previewBtn.setAlignmentX(0.5F);
previewBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
previewRecording();
}
});
postRecordingOptionsPanel.add(previewBtn);
saveBtn = new JButton("Save to My Computer");
saveBtn.setFont(new java.awt.Font("Arial", 0, 13));
saveBtn.setAlignmentX(0.5F);
saveBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveRecording();
}
});
postRecordingOptionsPanel.add(saveBtn);
insightBtn = new JButton("Post to Insight");
insightBtn.setFont(new java.awt.Font("Arial", 0, 13));
insightBtn.setAlignmentX(0.5F);
insightBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
postRecording();
}
});
postRecordingOptionsPanel.add(insightBtn);
deleteBtn = new JButton("Delete It");
deleteBtn.setFont(new java.awt.Font("Arial", 0, 13));
deleteBtn.setAlignmentX(0.5F);
deleteBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
deleteRecording();
}
});
postRecordingOptionsPanel.add(deleteBtn);
add(postRecordingOptionsPanel); //,BorderLayout.SOUTH);
System.out.println("Interface initialized...");
}
public void changeState(int state) {
changeState(state, null);
}
public void changeState(int state, String statusText) {
switch(state) {
case READY:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
- postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
- case READY_WITH_OPTIONS:
+ case READY_WITH_OPTIONS:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
if(!controller.getOptionsMessage().isEmpty()) {
message.setText("<html><body><table cellpadding='5' width='100%'><tr><td align='center'>"+controller.getOptionsMessage()+"</td></tr></table></body></html>");
}
- postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(true);
break;
case PRE_RECORDING:
if(currentState == READY_WITH_OPTIONS && !deleteRecording())
break;
recordBtn.setEnabled(false);
audioSelect.setVisible(false);
status.setEnabled(true);
status.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
- postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
case RECORDING:
recordBtn.setEnabled(true);
recordBtn.setText("Stop");
audioSelect.setVisible(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
case FATAL:
case THINKING:
recordBtn.setEnabled(false);
audioSelect.setEnabled(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
- postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
}
currentState = state; // needs to be at end
pack();
}
public void prepareForRecording() {
changeState(PRE_RECORDING,"Ready");
controller.prepareForRecording();
if(timer == null) {
timer = new Timer(1000, this);
timer.start(); // calls actionPerformed
}
else
timer.restart(); // calls actionPerformed
/*
countdown.setVisible(true);
countdown.pack();
*/
}
@Override
public void actionPerformed(ActionEvent e) { // for the timer
if(status.getText().equals("Ready")) {
changeState(PRE_RECORDING,"Set");
} else if(status.getText().equals("Set")) {
changeState(RECORDING,"Go!");
startRecording();
} else {
status.setText((timerCount/60 < 10 ? "0" : "")+timerCount/60+":"+(timerCount%60 < 10 ? "0" : "")+timerCount%60);
timerCount++;
}
}
private void startRecording() {
controller.startRecording(audioSelect.getSelectedMixer(),audioSelect.getSelectedIndex());
}
public void stopRecording() {
timer.stop();
timerCount = 0;
controller.stopRecording();
changeState(READY_WITH_OPTIONS);
}
public void previewRecording() {
controller.previewRecording();
}
public void saveRecording() {
setAlwaysOnTop(false);
int returnVal = fileSelect.showSaveDialog(this);
setAlwaysOnTop(true);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileSelect.getSelectedFile();
controller.saveRecording(file);
}
}
public void postRecording() {
controller.postRecording();
}
/**
* @return boolean that says whether to continue with whatever action called this or not
*/
public boolean deleteRecording() {
int n = JOptionPane.showConfirmDialog(this,
"This will delete the last review you recorded. Are you sure?",
"Are you sure?",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
controller.deleteRecording();
return true;
} else {
return false;
}
}
// ----- listener methods till EOF ------
private Point mouseOffset = null;
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
mouseOffset = new Point(e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e) {
mouseOffset = null;
}
public void mouseDragged(MouseEvent e) {
Point p = e.getLocationOnScreen();
p.x -= mouseOffset.x;
p.y -= mouseOffset.y;
p.x = Math.min(Math.max(p.x, 0), screen.width-this.getWidth());
p.y = Math.min(Math.max(p.y, 0), screen.height-this.getHeight());
setLocation(p);
}
public void mouseMoved(MouseEvent e) {}
@Override
public void windowActivated(WindowEvent e) { // gains focus or returned from minimize
//System.out.println("Window activated.");
}
@Override
public void windowClosing(WindowEvent e) {
//System.out.println("Window closing");
}
@Override
public void windowDeactivated(WindowEvent e) { // lose focus or minimized
//System.out.println("Window deactivated");
}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowOpened(WindowEvent e) {}
@Override
public void windowClosed(WindowEvent e) {} // not called with close operation set to HIDE_FRAME
@Override
public void componentHidden(ComponentEvent e) {}
@Override
public void componentMoved(ComponentEvent e) { // temporary until I return to a JWindow and not a JFrame
Point p = this.getLocation();
p.x = Math.min(Math.max(p.x, 0), screen.width-this.getWidth());
p.y = Math.min(Math.max(p.y, 0), screen.height-this.getHeight());
setLocation(p);
}
@Override
public void componentResized(ComponentEvent e) {}
@Override
public void componentShown(ComponentEvent e) {}
}
| false | true | public void changeState(int state, String statusText) {
switch(state) {
case READY:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
case READY_WITH_OPTIONS:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
if(!controller.getOptionsMessage().isEmpty()) {
message.setText("<html><body><table cellpadding='5' width='100%'><tr><td align='center'>"+controller.getOptionsMessage()+"</td></tr></table></body></html>");
}
postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(true);
break;
case PRE_RECORDING:
if(currentState == READY_WITH_OPTIONS && !deleteRecording())
break;
recordBtn.setEnabled(false);
audioSelect.setVisible(false);
status.setEnabled(true);
status.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
case RECORDING:
recordBtn.setEnabled(true);
recordBtn.setText("Stop");
audioSelect.setVisible(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
case FATAL:
case THINKING:
recordBtn.setEnabled(false);
audioSelect.setEnabled(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setEnabled(true);
postRecordingOptionsPanel.setVisible(false);
break;
}
currentState = state; // needs to be at end
pack();
}
| public void changeState(int state, String statusText) {
switch(state) {
case READY:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
case READY_WITH_OPTIONS:
recordBtn.setEnabled(true);
recordBtn.setText("Record");
audioSelect.setEnabled(true);
audioSelect.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
if(!controller.getOptionsMessage().isEmpty()) {
message.setText("<html><body><table cellpadding='5' width='100%'><tr><td align='center'>"+controller.getOptionsMessage()+"</td></tr></table></body></html>");
}
postRecordingOptionsPanel.setVisible(true);
break;
case PRE_RECORDING:
if(currentState == READY_WITH_OPTIONS && !deleteRecording())
break;
recordBtn.setEnabled(false);
audioSelect.setVisible(false);
status.setEnabled(true);
status.setVisible(true);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
case RECORDING:
recordBtn.setEnabled(true);
recordBtn.setText("Stop");
audioSelect.setVisible(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
case FATAL:
case THINKING:
recordBtn.setEnabled(false);
audioSelect.setEnabled(false);
if(statusText != null) {
status.setText(statusText);
statusPanel.setVisible(true);
} else {
status.setText("");
statusPanel.setVisible(false);
}
postRecordingOptionsPanel.setVisible(false);
break;
}
currentState = state; // needs to be at end
pack();
}
|
diff --git a/src/main/java/org/mvel2/ast/BinaryOperation.java b/src/main/java/org/mvel2/ast/BinaryOperation.java
index f473644e..fae3e0f3 100644
--- a/src/main/java/org/mvel2/ast/BinaryOperation.java
+++ b/src/main/java/org/mvel2/ast/BinaryOperation.java
@@ -1,161 +1,163 @@
/**
* MVEL 2.0
* Copyright (C) 2007 The Codehaus
* Mike Brock, Dhanji Prasanna, John Graham, Mark Proctor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvel2.ast;
import org.mvel2.CompileException;
import org.mvel2.Operator;
import org.mvel2.ParserContext;
import org.mvel2.ScriptRuntimeException;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.util.NullType;
import org.mvel2.util.ParseTools;
import static org.mvel2.DataConversion.canConvert;
import static org.mvel2.DataConversion.convert;
import static org.mvel2.Operator.PTABLE;
import static org.mvel2.debug.DebugTools.getOperatorSymbol;
import static org.mvel2.math.MathProcessor.doOperations;
import static org.mvel2.util.CompilerTools.getReturnTypeFromOp;
import static org.mvel2.util.ParseTools.boxPrimitive;
public class BinaryOperation extends BooleanNode {
private final int operation;
private int lType = -1;
private int rType = -1;
public BinaryOperation(int operation, ParserContext ctx) {
super(ctx);
this.operation = operation;
}
public BinaryOperation(int operation, ASTNode left, ASTNode right, ParserContext ctx) {
super(ctx);
this.operation = operation;
if ((this.left = left) == null) {
throw new ScriptRuntimeException("not a statement");
}
if ((this.right = right) == null) {
throw new ScriptRuntimeException("not a statement");
}
// if (ctx.isStrongTyping()) {
switch (operation) {
case Operator.ADD:
/**
* In the special case of Strings, the return type may leftward propogate.
*/
if (left.getEgressType() == String.class || right.getEgressType() == String.class) {
egressType = String.class;
lType = ParseTools.__resolveType(left.egressType);
rType = ParseTools.__resolveType(right.egressType);
return;
}
default:
if (!ctx.isStrongTyping()) break;
if (!left.getEgressType().isAssignableFrom(right.getEgressType()) && !right.getEgressType().isAssignableFrom(left.getEgressType())) {
if (right.isLiteral() && canConvert(left.getEgressType(), right.getEgressType())) {
this.right = new LiteralNode(convert(right.getReducedValueAccelerated(null, null, null), left.getEgressType()), pCtx);
} else if (!left.getEgressType().equals(NullType.class)
&& !right.getEgressType().equals(NullType.class)
&& !(Number.class.isAssignableFrom(right.getEgressType())
&& Number.class.isAssignableFrom(left.getEgressType()))
&& ((!right.getEgressType().isPrimitive() && !left.getEgressType().isPrimitive())
|| (!canConvert(boxPrimitive(left.getEgressType()), boxPrimitive(right.getEgressType()))))) {
throw new CompileException("incompatible types in statement: " + right.getEgressType()
- + " (compared from: " + left.getEgressType() + ")", left.getExpr(), left.getStart());
+ + " (compared from: " + left.getEgressType() + ")",
+ left.getExpr() != null ? left.getExpr() : right.getExpr(),
+ left.getExpr() != null ? left.getStart() : right.getStart());
}
}
}
// }
if (this.left.isLiteral() && this.right.isLiteral()) {
if (this.left.egressType == this.right.egressType) {
lType = rType = ParseTools.__resolveType(left.egressType);
} else {
lType = ParseTools.__resolveType(this.left.egressType);
rType = ParseTools.__resolveType(this.right.egressType);
}
}
egressType = getReturnTypeFromOp(operation, this.left.egressType, this.right.egressType);
}
public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) {
return doOperations(lType, left.getReducedValueAccelerated(ctx, thisValue, factory), operation, rType,
right.getReducedValueAccelerated(ctx, thisValue, factory));
}
public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) {
throw new RuntimeException("unsupported AST operation");
}
public int getOperation() {
return operation;
}
public BinaryOperation getRightBinary() {
return right != null && right instanceof BinaryOperation ? (BinaryOperation) right : null;
}
public void setRightMost(ASTNode right) {
BinaryOperation n = this;
while (n.right != null && n.right instanceof BinaryOperation) {
n = (BinaryOperation) n.right;
}
n.right = right;
if (n == this) {
if ((rType = ParseTools.__resolveType(n.right.getEgressType())) == 0) rType = -1;
}
}
public ASTNode getRightMost() {
BinaryOperation n = this;
while (n.right != null && n.right instanceof BinaryOperation) {
n = (BinaryOperation) n.right;
}
return n.right;
}
public int getPrecedence() {
return PTABLE[operation];
}
public boolean isGreaterPrecedence(BinaryOperation o) {
return o.getPrecedence() > PTABLE[operation];
}
@Override
public boolean isLiteral() {
return false;
}
public String toString() {
return "(" + left + " " + getOperatorSymbol(operation) + " " + right + ")";
}
}
| true | true | public BinaryOperation(int operation, ASTNode left, ASTNode right, ParserContext ctx) {
super(ctx);
this.operation = operation;
if ((this.left = left) == null) {
throw new ScriptRuntimeException("not a statement");
}
if ((this.right = right) == null) {
throw new ScriptRuntimeException("not a statement");
}
// if (ctx.isStrongTyping()) {
switch (operation) {
case Operator.ADD:
/**
* In the special case of Strings, the return type may leftward propogate.
*/
if (left.getEgressType() == String.class || right.getEgressType() == String.class) {
egressType = String.class;
lType = ParseTools.__resolveType(left.egressType);
rType = ParseTools.__resolveType(right.egressType);
return;
}
default:
if (!ctx.isStrongTyping()) break;
if (!left.getEgressType().isAssignableFrom(right.getEgressType()) && !right.getEgressType().isAssignableFrom(left.getEgressType())) {
if (right.isLiteral() && canConvert(left.getEgressType(), right.getEgressType())) {
this.right = new LiteralNode(convert(right.getReducedValueAccelerated(null, null, null), left.getEgressType()), pCtx);
} else if (!left.getEgressType().equals(NullType.class)
&& !right.getEgressType().equals(NullType.class)
&& !(Number.class.isAssignableFrom(right.getEgressType())
&& Number.class.isAssignableFrom(left.getEgressType()))
&& ((!right.getEgressType().isPrimitive() && !left.getEgressType().isPrimitive())
|| (!canConvert(boxPrimitive(left.getEgressType()), boxPrimitive(right.getEgressType()))))) {
throw new CompileException("incompatible types in statement: " + right.getEgressType()
+ " (compared from: " + left.getEgressType() + ")", left.getExpr(), left.getStart());
}
}
}
// }
if (this.left.isLiteral() && this.right.isLiteral()) {
if (this.left.egressType == this.right.egressType) {
lType = rType = ParseTools.__resolveType(left.egressType);
} else {
lType = ParseTools.__resolveType(this.left.egressType);
rType = ParseTools.__resolveType(this.right.egressType);
}
}
egressType = getReturnTypeFromOp(operation, this.left.egressType, this.right.egressType);
}
| public BinaryOperation(int operation, ASTNode left, ASTNode right, ParserContext ctx) {
super(ctx);
this.operation = operation;
if ((this.left = left) == null) {
throw new ScriptRuntimeException("not a statement");
}
if ((this.right = right) == null) {
throw new ScriptRuntimeException("not a statement");
}
// if (ctx.isStrongTyping()) {
switch (operation) {
case Operator.ADD:
/**
* In the special case of Strings, the return type may leftward propogate.
*/
if (left.getEgressType() == String.class || right.getEgressType() == String.class) {
egressType = String.class;
lType = ParseTools.__resolveType(left.egressType);
rType = ParseTools.__resolveType(right.egressType);
return;
}
default:
if (!ctx.isStrongTyping()) break;
if (!left.getEgressType().isAssignableFrom(right.getEgressType()) && !right.getEgressType().isAssignableFrom(left.getEgressType())) {
if (right.isLiteral() && canConvert(left.getEgressType(), right.getEgressType())) {
this.right = new LiteralNode(convert(right.getReducedValueAccelerated(null, null, null), left.getEgressType()), pCtx);
} else if (!left.getEgressType().equals(NullType.class)
&& !right.getEgressType().equals(NullType.class)
&& !(Number.class.isAssignableFrom(right.getEgressType())
&& Number.class.isAssignableFrom(left.getEgressType()))
&& ((!right.getEgressType().isPrimitive() && !left.getEgressType().isPrimitive())
|| (!canConvert(boxPrimitive(left.getEgressType()), boxPrimitive(right.getEgressType()))))) {
throw new CompileException("incompatible types in statement: " + right.getEgressType()
+ " (compared from: " + left.getEgressType() + ")",
left.getExpr() != null ? left.getExpr() : right.getExpr(),
left.getExpr() != null ? left.getStart() : right.getStart());
}
}
}
// }
if (this.left.isLiteral() && this.right.isLiteral()) {
if (this.left.egressType == this.right.egressType) {
lType = rType = ParseTools.__resolveType(left.egressType);
} else {
lType = ParseTools.__resolveType(this.left.egressType);
rType = ParseTools.__resolveType(this.right.egressType);
}
}
egressType = getReturnTypeFromOp(operation, this.left.egressType, this.right.egressType);
}
|
diff --git a/src/javax/sip/SipFactory.java b/src/javax/sip/SipFactory.java
index 1d7e9a57..e5a57d5d 100755
--- a/src/javax/sip/SipFactory.java
+++ b/src/javax/sip/SipFactory.java
@@ -1,355 +1,355 @@
/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Unpublished - rights reserved under the Copyright Laws of the United States.
* Copyright � 2003 Sun Microsystems, Inc. All rights reserved.
* Copyright � 2005 BEA Systems, Inc. All rights reserved.
*
* Use is subject to license terms.
*
* This distribution may include materials developed by third parties.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Module Name : JSIP Specification
* File Name : SipFactory.java
* Author : Phelim O'Doherty
*
* HISTORY
* Version Date Author Comments
* 1.1 08/10/2002 Phelim O'Doherty
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
package javax.sip;
import javax.sip.address.AddressFactory;
import javax.sip.message.MessageFactory;
import javax.sip.header.HeaderFactory;
import java.util.*;
import java.lang.reflect.Constructor;
/**
* The SipFactory is a singleton class which applications can use a single
* access point to obtain proprietary implementations of this specification. As
* the SipFactory is a singleton class there will only ever be one instance of
* the SipFactory. The single instance of the SipFactory can be obtained using
* the {@link SipFactory#getInstance()} method. If an instance of the SipFactory
* already exists it will be returned to the application, otherwise a new
* instance will be created. A peer implementation object can be obtained from
* the SipFactory by invoking the appropriate create method on the SipFactory
* e.g. to create a peer SipStack, an application would invoke the
* {@link SipFactory#createSipStack(Properties)} method.
* <p>
* <b>Naming Convention</b><br>
* Note that the SipFactory utilises a naming convention defined by this
* specification to identify the location of proprietary objects that implement
* this specification. The naming convention is defined as follows:
* <ul>
* <li>The <b>upper-level package structure</b> referred to by the SipFactory
* with the attribute <var>pathname</var> can be used to differentiate between
* proprietary implementations from different SIP stack vendors. The
* <var>pathname</var> used by each SIP vendor <B>must be</B> the domain name
* assigned to that vendor in reverse order. For example, the pathname used by
* Sun Microsystem's would be <code>com.sun</code>.
* <li>The <b>lower-level package structure and classname</b> of a peer object
* is also mandated by this specification. The lowel-level package must be
* identical to the package structure defined by this specification and the
* classname is mandated to the interface name appended with the
* <code>Impl</code> post-fix. For example, the lower-level package structure
* and classname of a proprietary implementation of the
* <code>javax.sip.SipStack</code> interface <B>must</B> be
* <code>javax.sip.SipStackImpl</code>.
* </ul>
*
* Using this naming convention the SipFactory can locate a vendor's
* implementation of this specification without requiring an application to
* supply a user defined string to each create method in the SipFactory. Instead
* an application merely needs to identify the vendors SIP implementation it
* would like to use by setting the pathname of that vendors implementation.
* <p>
* It follows that a proprietary implementation of a peer object of this
* specification can be located at:
* <p>
* <code>'pathname'.'lower-level package structure and classname'.</code>
* <p>
* For example an application can use the SipFactory to instantiate a Sun
* Microsystems's peer SipStack object by setting the pathname to
* <code>com.sun</code> and calling the createSipStack method. The SipFactory
* would return a new instance of the SipStack object at the following location:
* <code>com.sun.javax.sip.SipStackImpl.java</code> Because the space of
* domain names is managed, this scheme ensures that collisions between two
* different vendor's implementations will not happen. For example: a different
* vendor with a domain name 'foo.com' would have their peer SipStack object
* located at <code>com.foo.javax.sip.SipStackImpl.java</code>.
* <p>
* <b>Default Namespace:</b><br>
* This specification defines a default namespace for the SipFactory, this
* namespace is the location of the Reference Implementation. The default
* namespace is <code>gov.nist</code> the author of the Reference
* Implementation, therefore the <var>pathname</var> will have the initial
* value of <code>gov.nist</code> for a new instance of the SipFactory. An
* application must set the <var>pathname</var> of the SipFactory on retrieval
* of a new instance of the factory in order to use a different vendors SIP
* stack from that of the Reference Implementation. An application can not mix
* different vendor's peer implementation objects.
*
* @author BEA Systems, Inc.
* @author NIST
* @version 1.2
*/
public class SipFactory {
/**
* Returns an instance of a SipFactory. This is a singleton class so this
* method is the global access point for the SipFactory.
*
* @return the single instance of this singleton SipFactory
*/
public synchronized static SipFactory getInstance() {
if (myFactory == null) {
myFactory = new SipFactory();
}
return myFactory;
}
/**
* Creates an instance of a SipStack implementation based on the
* configuration properties object passed to this method. If a
* "javax.sip.IP_ADDRESS" is supplied, this method ensures that only one
* instance of a SipStack is returned to the application per IP Address, no
* matter how often this method is called for the same IP Address. Different
* SipStack instances are returned for each different IP address. If an
* "javax.sip.IP_ADDRESS" property is not specified, then the
* "javax.sip.STACK_NAME" uniquely identifies the stack. See
* {@link SipStack} for the expected format of the <code>properties</code>
* argument. Note that as of v1.2 the IP address is no longer a mandatory
* argument when creating the SIP stack.
*
* @throws PeerUnavailableException
* if the peer class could not be found
*/
- public SipStack createSipStack(Properties properties)
+ public synchronized SipStack createSipStack(Properties properties)
throws PeerUnavailableException {
String ipAddress = properties.getProperty("javax.sip.IP_ADDRESS");
String name = properties.getProperty("javax.sip.STACK_NAME");
if (name == null ) throw new PeerUnavailableException("Missing javax.sip.STACK_NAME property");
// IP address was not specified in the properties.
// this means that the architecture supports a single sip stack
// instance per stack name
// and each listening point is assinged its own IP address.
if ( ipAddress == null) {
SipStack mySipStack = (SipStack) this.sipStackByName.get(name);
if (mySipStack == null) {
mySipStack = createStack(properties);
}
return mySipStack;
} else {
// Check to see if a stack with that IP Address is already
// created, if so select it to be returned. In this case
// the Name is not used.
int i = 0;
for (i = 0; i < sipStackList.size(); i++) {
if (((SipStack) sipStackList.get(i)).getIPAddress().equals( ipAddress )) {
return (SipStack) sipStackList.get(i);
}
}
return createStack(properties);
}
}
/**
* Creates an instance of the MessageFactory implementation. This method
* ensures that only one instance of a MessageFactory is returned to the
* application, no matter how often this method is called.
*
* @throws PeerUnavailableException
* if peer class could not be found
*/
public MessageFactory createMessageFactory()
throws PeerUnavailableException {
if (messageFactory == null) {
messageFactory = (MessageFactory) createSipFactory("javax.sip.message.MessageFactoryImpl");
}
return messageFactory;
}
/**
* Creates an instance of the HeaderFactory implementation. This method
* ensures that only one instance of a HeaderFactory is returned to the
* application, no matter how often this method is called.
*
* @throws PeerUnavailableException
* if peer class could not be found
*/
public HeaderFactory createHeaderFactory() throws PeerUnavailableException {
if (headerFactory == null) {
headerFactory = (HeaderFactory) createSipFactory("javax.sip.header.HeaderFactoryImpl");
}
return headerFactory;
}
/**
* Creates an instance of the AddressFactory implementation. This method
* ensures that only one instance of an AddressFactory is returned to the
* application, no matter how often this method is called.
*
* @throws PeerUnavailableException
* if peer class could not be found
*/
public AddressFactory createAddressFactory()
throws PeerUnavailableException {
if (addressFactory == null) {
addressFactory = (AddressFactory) createSipFactory("javax.sip.address.AddressFactoryImpl");
}
return addressFactory;
}
/**
* Sets the <var>pathname</var> that identifies the location of a
* particular vendor's implementation of this specification. The
* <var>pathname</var> must be the reverse domain name assigned to the
* vendor providing the implementation. An application must call
* {@link SipFactory#resetFactory()} before changing between different
* implementations of this specification.
*
* @param pathName -
* the reverse domain name of the vendor, e.g. Sun Microsystem's
* would be 'com.sun'
*/
public void setPathName(String pathName) {
this.pathName = pathName;
}
/**
* Returns the current <var>pathname</var> of the SipFactory. The
* <var>pathname</var> identifies the location of a particular vendor's
* implementation of this specification as defined the naming convention.
* The pathname must be the reverse domain name assigned to the vendor
* providing this implementation. This value is defaulted to
* <code>gov.nist</code> the location of the Reference Implementation.
*
* @return the string identifying the current vendor implementation.
*/
public String getPathName() {
return pathName;
}
/**
* This method reset's the SipFactory's references to the object's it has
* created. It allows these objects to be garbage collected assuming the
* application no longer holds references to them. This method must be
* called to reset the factories references to a specific vendors
* implementation of this specification before it creates another vendors
* implementation of this specification by changing the <var>pathname</var>
* of the SipFactory.
*
* @since v1.1
*/
public void resetFactory() {
sipStackList.clear();
messageFactory = null;
headerFactory = null;
addressFactory = null;
sipStackByName = new Hashtable();
pathName = "gov.nist";
}
/**
* Private Utility method used by all create methods to return an instance
* of the supplied object.
*/
private Object createSipFactory(String objectClassName)
throws PeerUnavailableException {
// If the stackClassName is null, then throw an exception
if (objectClassName == null) {
throw new NullPointerException();
}
try {
Class peerObjectClass = Class.forName(getPathName() + "."
+ objectClassName);
// Creates a new instance of the class represented by this Class
// object.
Object newPeerObject = peerObjectClass.newInstance();
return (newPeerObject);
} catch (Exception e) {
String errmsg = "The Peer Factory: "
+ getPathName()
+ "."
+ objectClassName
+ " could not be instantiated. Ensure the Path Name has been set.";
throw new PeerUnavailableException(errmsg, e);
}
}
/**
* Private Utility method used to create a new SIP Stack instance.
*/
private SipStack createStack(Properties properties)
throws PeerUnavailableException {
try {
// create parameters argument to identify constructor
Class[] paramTypes = new Class[1];
paramTypes[0] = Class.forName("java.util.Properties");
// get constructor of SipSatck in order to instantiate
Constructor sipStackConstructor = Class.forName(
getPathName() + ".javax.sip.SipStackImpl").getConstructor(
paramTypes);
// Wrap properties object in order to pass to constructor of
// SipSatck
Object[] conArgs = new Object[1];
conArgs[0] = properties;
// Creates a new instance of SipStack Class with the supplied
// properties.
SipStack sipStack = (SipStack) sipStackConstructor.newInstance(conArgs);
sipStackList.add(sipStack);
String name = properties.getProperty("javax.sip.STACK_NAME");
this.sipStackByName.put(name, sipStack);
return sipStack;
} catch (Exception e) {
String errmsg = "The Peer SIP Stack: "
+ getPathName()
+ ".javax.sip.SipStackImpl"
+ " could not be instantiated. Ensure the Path Name has been set.";
throw new PeerUnavailableException(errmsg, e);
}
}
/**
* Constructor for SipFactory class. This is private because applications
* are not permitted to create an instance of the SipFactory using "new".
*/
private SipFactory() {
this.sipStackByName = new Hashtable();
}
// default domain to locate Reference Implementation
private String pathName = "gov.nist";
// My sip stack. The implementation will allow only a single
// sip stack in future versions of this specification.
private Hashtable sipStackByName;
// intrenal variable to ensure SipFactory only returns a single instance
// of the other Factories and SipStack
private MessageFactory messageFactory = null;
private HeaderFactory headerFactory = null;
private AddressFactory addressFactory = null;
private static SipFactory myFactory = null;
// This is for backwards compatibility with
// version 1.1
private final LinkedList sipStackList = new LinkedList();
}
| true | true | public SipStack createSipStack(Properties properties)
throws PeerUnavailableException {
String ipAddress = properties.getProperty("javax.sip.IP_ADDRESS");
String name = properties.getProperty("javax.sip.STACK_NAME");
if (name == null ) throw new PeerUnavailableException("Missing javax.sip.STACK_NAME property");
// IP address was not specified in the properties.
// this means that the architecture supports a single sip stack
// instance per stack name
// and each listening point is assinged its own IP address.
if ( ipAddress == null) {
SipStack mySipStack = (SipStack) this.sipStackByName.get(name);
if (mySipStack == null) {
mySipStack = createStack(properties);
}
return mySipStack;
} else {
// Check to see if a stack with that IP Address is already
// created, if so select it to be returned. In this case
// the Name is not used.
int i = 0;
for (i = 0; i < sipStackList.size(); i++) {
if (((SipStack) sipStackList.get(i)).getIPAddress().equals( ipAddress )) {
return (SipStack) sipStackList.get(i);
}
}
return createStack(properties);
}
}
| public synchronized SipStack createSipStack(Properties properties)
throws PeerUnavailableException {
String ipAddress = properties.getProperty("javax.sip.IP_ADDRESS");
String name = properties.getProperty("javax.sip.STACK_NAME");
if (name == null ) throw new PeerUnavailableException("Missing javax.sip.STACK_NAME property");
// IP address was not specified in the properties.
// this means that the architecture supports a single sip stack
// instance per stack name
// and each listening point is assinged its own IP address.
if ( ipAddress == null) {
SipStack mySipStack = (SipStack) this.sipStackByName.get(name);
if (mySipStack == null) {
mySipStack = createStack(properties);
}
return mySipStack;
} else {
// Check to see if a stack with that IP Address is already
// created, if so select it to be returned. In this case
// the Name is not used.
int i = 0;
for (i = 0; i < sipStackList.size(); i++) {
if (((SipStack) sipStackList.get(i)).getIPAddress().equals( ipAddress )) {
return (SipStack) sipStackList.get(i);
}
}
return createStack(properties);
}
}
|
diff --git a/swows/src/main/java/org/swows/xmlinrdf/DomDecoder.java b/swows/src/main/java/org/swows/xmlinrdf/DomDecoder.java
index e423ba3..53e3373 100644
--- a/swows/src/main/java/org/swows/xmlinrdf/DomDecoder.java
+++ b/swows/src/main/java/org/swows/xmlinrdf/DomDecoder.java
@@ -1,1584 +1,1585 @@
/*
* Copyright (c) 2011 Miguel Ceriani
* [email protected]
* This file is part of Semantic Web Open datatafloW System (SWOWS).
* SWOWS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* SWOWS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General
* Public License along with SWOWS. If not, see <http://www.gnu.org/licenses/>.
*/
package org.swows.xmlinrdf;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.swows.graph.events.DynamicGraph;
import org.swows.graph.events.GraphUpdate;
import org.swows.graph.events.Listener;
import org.swows.runnable.RunnableContext;
import org.swows.util.GraphUtils;
import org.swows.util.Utils;
import org.swows.vocabulary.SWI;
import org.swows.vocabulary.XML;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.sparql.util.NodeComparator;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
public class DomDecoder implements Listener, RunnableContext, EventListener {
private static String VOID_NAMESPACE = "http://www.swows.org/xml/no-namespace";
private static final Logger logger = Logger.getLogger(DomDecoder.class);
private static final Comparator<Node> nodeComparator = new NodeComparator();
private static final String specialXmlNamespacesSeparator = "#";
private static final Set<String> specialXmlNamespaces = new HashSet<>(2);
static {
specialXmlNamespaces.add("http://www.w3.org/1999/xhtml");
specialXmlNamespaces.add("http://www.w3.org/2000/svg");
}
// private static String specialNamespace(String )
private DocumentReceiver docReceiver;
private DOMImplementation domImplementation;
private DynamicGraph graph;
// private Set<DomEventListener> domEventListeners;
private Map<String, Set<DomEventListener>> domEventListeners;
private Document document;
private RunnableContext updatesContext;
private Map<Node, Set<org.w3c.dom.Node>> graph2domNodeMapping = new HashMap<Node, Set<org.w3c.dom.Node>>();
private Map<org.w3c.dom.Node, Node> dom2graphNodeMapping = new HashMap<org.w3c.dom.Node, Node>();
private Node docRootNode;
private Map<Element,NavigableMap<Node, Vector<org.w3c.dom.Node>>> dom2orderedByKeyChildren = new HashMap<Element, NavigableMap<Node,Vector<org.w3c.dom.Node>>>();
private Map<Element,Map<org.w3c.dom.Node, Node>> dom2childrenKeys = new HashMap<Element, Map<org.w3c.dom.Node, Node>>();
private Set<Element> dom2descendingOrder = new HashSet<Element>();
private Map<Element, Node> dom2childrenOrderProperty = new HashMap<Element, Node>();
private static EventManager DEFAULT_EVENT_MANAGER =
new EventManager() {
public void removeEventListener(
Node targetNode,
org.w3c.dom.Node target, String type,
EventListener listener, boolean useCapture) {
if (target instanceof EventTarget)
((EventTarget) target).removeEventListener(type, listener, useCapture);
}
public void addEventListener(
Node targetNode,
org.w3c.dom.Node target, String type,
EventListener listener, boolean useCapture) {
if (target instanceof EventTarget)
((EventTarget) target).addEventListener(type, listener, useCapture);
}
};
private EventManager eventManager;// = DEFAULT_EVENT_MANAGER;
// private Map<String, Set<Element>> eventType2elements = new HashMap<String, Set<Element>>();
// private Map<Element, Set<String>> element2eventTypes = new HashMap<Element, Set<String>>();
public void addDomEventListener(String eventType, DomEventListener l) {
synchronized(this) {
if (domEventListeners == null)
domEventListeners = new HashMap<String, Set<DomEventListener>>();
}
synchronized(domEventListeners) {
Set<DomEventListener> domEventListenersForType = domEventListeners.get(eventType);
if (domEventListenersForType == null) {
domEventListenersForType = new HashSet<DomEventListener>();
domEventListeners.put(eventType, domEventListenersForType);
}
domEventListenersForType.add(l);
}
}
public void removeDomEventListener(String eventType, DomEventListener l) {
if (domEventListeners != null) {
synchronized(domEventListeners) {
domEventListeners.remove(l);
}
}
}
public synchronized void handleEvent(Event evt) {
logger.debug("In DOM decoder handling event " + evt + " of type " + evt.getType());
// System.out.println("In DOM decoder handling event " + evt + " of type " + evt.getType());
org.w3c.dom.Node eventCurrentTargetDomNode = (org.w3c.dom.Node) evt.getCurrentTarget();
Node eventCurrentTargetGraphNode = dom2graphNodeMapping.get(eventCurrentTargetDomNode);
org.w3c.dom.Node eventTargetDomNode = (org.w3c.dom.Node) evt.getTarget();
Node eventTargetGraphNode = dom2graphNodeMapping.get(eventTargetDomNode);
if (domEventListeners != null) {
synchronized (domEventListeners) {
Set<DomEventListener> domEventListenersForType = domEventListeners.get(evt.getType());
for (DomEventListener l : domEventListenersForType) {
logger.debug("Sending to " + l + " the event " + evt);
l.handleEvent(evt, eventCurrentTargetGraphNode, eventTargetGraphNode);
}
}
}
}
public static Document decode(DynamicGraph graph, Node docRootNode) {
try {
return decode(graph, docRootNode, DOMImplementationRegistry.newInstance().getDOMImplementation("XML 1.0"));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
}
public static Document decodeOne(DynamicGraph graph) {
return decodeAll(graph).next();
}
public static ExtendedIterator<Document> decodeAll(final DynamicGraph graph) {
return graph
.find(Node.ANY, RDF.type.asNode(), XML.Document.asNode())
.mapWith(new Map1<Triple, Document>() {
public Document map1(Triple triple) {
return decode(graph, triple.getSubject());
}
});
}
private static String qNameElement(final Graph graph, final Node elementNode) {
return
GraphUtils
.getSingleValueProperty(
graph,
GraphUtils.getSingleValueProperty(graph, elementNode, RDF.type.asNode()),
XML.nodeName.asNode() )
.getLiteralLexicalForm();
}
private static String namespaceElement(final Graph graph, final Node elementNode) {
try {
return
graph.find(
GraphUtils.getSingleValueProperty(graph, elementNode, RDF.type.asNode()),
XML.namespace.asNode(),
Node.ANY)
.next().getObject().getURI();
} catch (NoSuchElementException e) {
return null;
}
}
private static String qNameAttr(final Graph graph, final Node elementNode) {
return
GraphUtils
.getSingleValueProperty(
graph,
elementNode,
XML.nodeName.asNode() )
.getLiteralLexicalForm();
}
private static String namespaceAttr(final Graph graph, final Node elementNode) {
try {
return
graph.find(
elementNode,
XML.namespace.asNode(),
Node.ANY)
.next().getObject().getURI();
} catch (NoSuchElementException e) {
return null;
}
}
private static String value(final Graph graph, final Node elementNode) {
try {
return
graph.find(elementNode, XML.nodeValue.asNode(), Node.ANY)
.next().getObject().getLiteralLexicalForm();
} catch (NoSuchElementException e) {
return null;
}
}
private Text decodeText(Graph graph, Node elementNode) {
return document.createTextNode(value(graph, elementNode));
}
@SuppressWarnings("unused")
private Comment decodeComment(Graph graph, Node elementNode) {
return document.createComment(value(graph, elementNode));
}
@SuppressWarnings("unused")
private ProcessingInstruction decodeProcessingInstruction(Graph graph, Node elementNode) {
return document.createProcessingInstruction(
qNameElement(graph, elementNode),
value(graph, elementNode) );
}
private Attr decodeAttr(Node elementNode) {
String nsUri = namespaceAttr(graph, elementNode);
if (nsUri == null)
throw new RuntimeException("Namespace not found for attribute " + elementNode + " in graph " + graph);
return
(nsUri.equals(VOID_NAMESPACE))
? document.createAttribute( qNameAttr(graph, elementNode) )
: document.createAttributeNS(
namespaceAttr(graph, elementNode),
qNameAttr(graph, elementNode) );
}
private void removeAttr(Element element, Node elementNode) {
String nsUri = namespaceAttr(graph, elementNode);
if (nsUri == null)
throw new RuntimeException("Namespace not found for attribute " + elementNode + " in graph " + graph);
if (nsUri.equals(VOID_NAMESPACE))
element.removeAttribute( qNameAttr(graph, elementNode) );
else
element.removeAttributeNS(
namespaceAttr(graph, elementNode),
qNameAttr(graph, elementNode) );
}
public String md5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
private void reorder(
// Set<org.w3c.dom.Node> noKeyChildren,
boolean ascendingOrder,
Element element,
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren ) {
// if (ascendingOrder) {
// for (org.w3c.dom.Node child : noKeyChildren) {
// element.appendChild(child);
// }
// }
for (Node orderKeyNode : ascendingOrder ? orderedByKeyChildren.keySet() : orderedByKeyChildren.descendingKeySet() ) {
for (org.w3c.dom.Node child : orderedByKeyChildren.get(orderKeyNode)) {
element.appendChild(child);
}
}
// if (!ascendingOrder) {
// for (org.w3c.dom.Node child : noKeyChildren) {
// element.appendChild(child);
// }
// }
}
private int elementCount = 0;
private synchronized String newElementId() {
return "n_" + Integer.toHexString(elementCount++);
}
private void putChildByKey(Element parent, org.w3c.dom.Node node, Node orderKeyNode) {
Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent);
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent);
Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode);
if (sameKeyBag == null) {
sameKeyBag = new Vector<org.w3c.dom.Node>();
orderedByKeyChildren.put(orderKeyNode, sameKeyBag);
}
sameKeyBag.add(node);
childrenKeys.put(node, orderKeyNode);
}
private void removeChildByKey(Element parent, org.w3c.dom.Node node) {
Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent);
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent);
Node prevOrderKeyNode = childrenKeys.get(node);
if (prevOrderKeyNode != null) {
Vector<org.w3c.dom.Node> oldKeyBag = orderedByKeyChildren.get(prevOrderKeyNode);
oldKeyBag.remove(node);
if (oldKeyBag.isEmpty())
orderedByKeyChildren.remove(prevOrderKeyNode);
}
childrenKeys.remove(node);
}
private void updateChildByKey(Element parent, org.w3c.dom.Node node, Node orderKeyNode) {
Map<org.w3c.dom.Node, Node> childrenKeys = dom2childrenKeys.get(parent);
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren = dom2orderedByKeyChildren.get(parent);
Node prevOrderKeyNode = childrenKeys.get(node);
if (prevOrderKeyNode != null) {
Vector<org.w3c.dom.Node> oldKeyBag = orderedByKeyChildren.get(prevOrderKeyNode);
oldKeyBag.remove(node);
if (oldKeyBag.isEmpty())
orderedByKeyChildren.remove(prevOrderKeyNode);
}
Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode);
if (sameKeyBag == null) {
sameKeyBag = new Vector<org.w3c.dom.Node>();
orderedByKeyChildren.put(orderKeyNode, sameKeyBag);
}
sameKeyBag.add(node);
childrenKeys.put(node, orderKeyNode);
}
private void setupElementChildren(Node elementNode, Element element) {
Node childrenOrderProperty =
GraphUtils.getSingleValueOptProperty(graph, elementNode, XML.childrenOrderedBy.asNode());
if (childrenOrderProperty != null)
dom2childrenOrderProperty.put(element, childrenOrderProperty);
boolean ascendingOrder =
!graph.contains(elementNode, XML.childrenOrderType.asNode(), XML.Descending.asNode());
if (!ascendingOrder)
dom2descendingOrder.add(element);
ExtendedIterator<Node> children = GraphUtils.getPropertyValues(graph, elementNode, XML.hasChild.asNode());
{
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
new TreeMap<Node, Vector<org.w3c.dom.Node>>(nodeComparator);
Map<org.w3c.dom.Node, Node> childrenKeys =
new HashMap<org.w3c.dom.Node, Node>();
dom2orderedByKeyChildren.put(element, orderedByKeyChildren);
dom2childrenKeys.put(element, childrenKeys);
}
// Set<org.w3c.dom.Node> noKeyChildren = new HashSet<org.w3c.dom.Node>();
while (children.hasNext()) {
Node child = children.next();
// if (!orderedChildren.contains(child)) {
org.w3c.dom.Node domChild = decodeNode(child);
if (domChild != null) {
addNodeMapping(child, domChild);
Node orderKeyNode =
( childrenOrderProperty != null ) ?
GraphUtils.getSingleValueOptProperty(graph, child, childrenOrderProperty) :
GraphUtils.getSingleValueOptProperty(graph, child, XML.orderKey.asNode());
// if (orderKeyNode == null) {
//// noKeyChildren.add(domChild);
// orderKeyNode = Node.NULL;
// } //else {
updateChildByKey(element, domChild, orderKeyNode);
// Vector<org.w3c.dom.Node> sameKeyBag = orderedByKeyChildren.get(orderKeyNode);
// if (sameKeyBag == null) {
// sameKeyBag = new Vector<org.w3c.dom.Node>();
// orderedByKeyChildren.put(orderKeyNode, sameKeyBag);
// }
// sameKeyBag.add(domChild);
// }
}
// }
}
reorder(/*noKeyChildren, */ascendingOrder, element, dom2orderedByKeyChildren.get(element));
}
private void decodeElementAttrsAndChildren(final Element element, final Node elementNode) {
ExtendedIterator<Triple> triples =
graph.find(elementNode, Node.ANY, Node.ANY);
while (triples.hasNext()) {
Triple t = triples.next();
if ( graph.contains(
t.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode())) {
Attr attr = decodeAttr(t.getPredicate());
attr.setValue(t.getObject().getLiteralLexicalForm());
element.setAttributeNodeNS(attr);
}
}
if (elementNode.isURI()) {
element.setAttribute("resource", elementNode.getURI());
if (!element.hasAttribute("id"))
element.setAttribute("id", newElementId());
// element.setAttribute("id", elementNode.getURI());
}
// Set<Node> orderedChildren = new HashSet<Node>();
// {
// Node child = GraphUtils.getSingleValueOptProperty(graph, elementNode, XML.firstChild.asNode());
// while (child != null) {
// orderedChildren.add(child);
// org.w3c.dom.Node newChild = decodeNode(graph, child);
// if (newChild != null) {
// addNodeMapping(child, newChild);
// element.appendChild(newChild);
// }
// child = GraphUtils.getSingleValueOptProperty(graph, child, XML.nextSibling.asNode());
// }
// }
// System.out.println("Looking for eventListeners in element " + element + " (" + elementNode + ")");
Iterator<Node> eventTypeNodes = GraphUtils.getPropertyValues(graph, elementNode, XML.listenedEventType.asNode());
while (eventTypeNodes.hasNext()) {
Node eventTypeNode = eventTypeNodes.next();
if (eventTypeNode.isLiteral()) {
String eventType = eventTypeNode.getLiteralLexicalForm();
// System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")");
// ((EventTarget) element).addEventListener(eventType, this, false);
logger.trace("Calling addEventListener() for new node");
eventManager.addEventListener(elementNode, element, eventType, this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// if (elemsForEventType == null) {
// elemsForEventType = new HashSet<Element>();
// eventType2elements.put(eventType, elemsForEventType);
// ((EventTarget) document).addEventListener(eventType, this, false);
// }
// elemsForEventType.add(element);
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// if (eventTypesForElement == null) {
// eventTypesForElement = new HashSet<String>();
// element2eventTypes.put(element, eventTypesForElement);
// }
// eventTypesForElement.add(eventType);
}
}
setupElementChildren(elementNode, element);
}
private Element decodeElement(final Node elementNode) {
Element element =
document.createElementNS(
namespaceElement(graph, elementNode),
qNameElement(graph, elementNode) );
addNodeMapping(elementNode, element);
decodeElementAttrsAndChildren(element, elementNode);
return element;
}
private org.w3c.dom.Node decodeNode(Node elementNode) {
try {
Node nodeType = GraphUtils.getSingleValueProperty(graph, elementNode, RDF.type.asNode());
if ( graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) )
return decodeElement(elementNode);
if ( nodeType.equals( XML.Text.asNode() ) )
return decodeText(graph, elementNode);
throw new RuntimeException("Type not recognised for node " + elementNode);
} catch(NoSuchElementException e) {
throw new RuntimeException("Type not found for node " + elementNode);
}
}
private void decodeDocument(Node docRootNode) {
Iterator<Node> possibleDocs =
GraphUtils.getPropertyValues(graph, docRootNode, XML.hasChild.asNode());
while (possibleDocs.hasNext()) {
// try {
Node elementNode = possibleDocs.next();
document =
domImplementation.createDocument(
namespaceElement(graph, elementNode),
qNameElement(graph, elementNode),
null);
if (docRootNode.isURI())
document.setDocumentURI(docRootNode.getURI());
Element docElement = document.getDocumentElement();
addNodeMapping(docRootNode, document);
addNodeMapping(elementNode, docElement);
decodeElementAttrsAndChildren( docElement, elementNode );
// } catch(RuntimeException e) { }
}
}
private void redecodeDocument(Node docRootNode) {
graph2domNodeMapping = new HashMap<Node, Set<org.w3c.dom.Node>>();
dom2graphNodeMapping = new HashMap<org.w3c.dom.Node, Node>();
// eventType2elements = new HashMap<String, Set<Element>>();
// element2eventTypes = new HashMap<Element, Set<String>>();
decodeDocument(docRootNode);
if (docReceiver != null)
docReceiver.sendDocument(document);
}
private void redecodeDocument() {
redecodeDocument(
graph
.find(SWI.GraphRoot.asNode(), XML.document.asNode(), Node.ANY)
.mapWith( new Map1<Triple, Node>() {
public Node map1(Triple t) {
return t.getObject();
}
})
.andThen(
graph
.find(Node.ANY, RDF.type.asNode(), XML.Document.asNode())
.mapWith( new Map1<Triple, Node>() {
public Node map1(Triple t) {
return t.getSubject();
}
}) ).next());
}
private void decodeWorker(DynamicGraph graph, Node docRootNode) {
logger.debug("decoding document from " + Utils.standardStr(graph) + " ...");
decodeDocument(docRootNode);
logger.debug("registering as listener of " + Utils.standardStr(graph) + " ...");
graph.getEventManager2().register(this);
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl) {
return (new DomDecoder(graph, docRootNode, domImpl)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
EventManager eventManager) {
return (new DomDecoder(graph, docRootNode, domImpl, eventManager)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext) {
return (new DomDecoder(graph, docRootNode, domImpl, updatesContext)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
EventManager eventManager) {
return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, eventManager)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, DocumentReceiver docReceiver) {
return (new DomDecoder(graph, docRootNode, domImpl, docReceiver)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, DocumentReceiver docReceiver,
EventManager eventManager) {
return (new DomDecoder(graph, docRootNode, domImpl, docReceiver, eventManager)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
DocumentReceiver docReceiver) {
return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
DocumentReceiver docReceiver,
EventManager eventManager) {
return (new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver, eventManager)).getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, eventManager);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, eventManager);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, docReceiver);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, docReceiver, eventManager);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decode(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl, RunnableContext updatesContext,
DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
DomDecoder domDecoder = new DomDecoder(graph, docRootNode, domImpl, updatesContext, docReceiver, eventManager);
if (domEventListeners != null)
for (String eventType : domEventListeners.keySet())
for (DomEventListener listener : domEventListeners.get(eventType))
domDecoder.addDomEventListener(eventType, listener);
return domDecoder.getDocument();
}
public static Document decodeOne(DynamicGraph graph, DOMImplementation domImpl) {
return decodeAll(graph, domImpl).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
EventManager eventManager) {
return decodeAll(graph, domImpl, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext) {
return decodeAll(graph, domImpl, updatesContext).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
DocumentReceiver docReceiver) {
return decodeAll(graph, domImpl, docReceiver).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
DocumentReceiver docReceiver,
EventManager eventManager) {
return decodeAll(graph, domImpl, docReceiver, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext, DocumentReceiver docReceiver) {
return decodeAll(graph, domImpl, updatesContext, docReceiver).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext, DocumentReceiver docReceiver,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, domEventListeners).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, domEventListeners, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, updatesContext, domEventListeners).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, domEventListeners, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, docReceiver, domEventListeners).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, docReceiver, domEventListeners, eventManager).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext, DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners).next();
}
public static Document decodeOne(
DynamicGraph graph, DOMImplementation domImpl,
RunnableContext updatesContext, DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners, eventManager).next();
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl) {
return decodeAll(graph, domImpl, (RunnableContext) null);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
EventManager eventManager) {
return decodeAll(graph, domImpl, (RunnableContext) null, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final DocumentReceiver docReceiver) {
return decodeAll(graph, domImpl, null, docReceiver);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final DocumentReceiver docReceiver,
EventManager eventManager) {
return decodeAll(graph, domImpl, null, docReceiver, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext) {
return decodeAll(graph, domImpl, updatesContext, (DocumentReceiver) null);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, (DocumentReceiver) null, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext, final DocumentReceiver docReceiver) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, (EventManager) null);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext, final DocumentReceiver docReceiver,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, null, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, (RunnableContext) null, domEventListeners);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, (RunnableContext) null, domEventListeners, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, null, docReceiver, domEventListeners);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final DocumentReceiver docReceiver,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, null, docReceiver, domEventListeners, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, updatesContext, null, domEventListeners);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext,
Map<String,Set<DomEventListener>> domEventListeners,
EventManager eventManager) {
return decodeAll(graph, domImpl, updatesContext, null, domEventListeners, eventManager);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext, final DocumentReceiver docReceiver,
final Map<String,Set<DomEventListener>> domEventListeners) {
return decodeAll(graph, domImpl, updatesContext, docReceiver, domEventListeners, null);
}
public static ExtendedIterator<Document> decodeAll(
final DynamicGraph graph, final DOMImplementation domImpl,
final RunnableContext updatesContext, final DocumentReceiver docReceiver,
final Map<String,Set<DomEventListener>> domEventListeners,
final EventManager eventManager) {
return
graph
.find(SWI.GraphRoot.asNode(), XML.document.asNode(), Node.ANY)
.mapWith( new Map1<Triple, Node>() {
public Node map1(Triple t) {
return t.getObject();
}
})
.andThen(
graph
.find(Node.ANY, RDF.type.asNode(), XML.Document.asNode())
.mapWith( new Map1<Triple, Node>() {
public Node map1(Triple t) {
return t.getSubject();
}
}))
.mapWith( new Map1<Node, Document>() {
public Document map1(Node node) {
return decode(graph, node, domImpl, updatesContext, docReceiver, domEventListeners, eventManager);
}
} );
}
private void addNodeMapping(Node graphNode, org.w3c.dom.Node domNode) {
// System.out.println(this + ": adding mapping ( " + graphNode + " -> " + domNode + " )");
Set<org.w3c.dom.Node> domeNodeSet = graph2domNodeMapping.get(graphNode);
if (domeNodeSet == null) {
domeNodeSet = new HashSet<org.w3c.dom.Node>();
graph2domNodeMapping.put(graphNode, domeNodeSet);
}
domeNodeSet.add(domNode);
dom2graphNodeMapping.put(domNode, graphNode);
}
private void removeNodeMapping(org.w3c.dom.Node domNode) {
Node graphNode = dom2graphNodeMapping.get(domNode);
if (graphNode != null) {
dom2graphNodeMapping.remove(domNode);
Set<org.w3c.dom.Node> domeNodeSet = graph2domNodeMapping.get(graphNode);
domeNodeSet.remove(domNode);
if (domeNodeSet.isEmpty())
graph2domNodeMapping.remove(graphNode);
}
dom2orderedByKeyChildren.remove(domNode);
dom2childrenOrderProperty.remove(domNode);
dom2descendingOrder.remove(domNode);
}
private void removeSubtreeMapping(org.w3c.dom.Node domNode) {
// System.out.println(this + ": removing subtree mapping of " + domNode );
removeNodeMapping(domNode);
NamedNodeMap attrMap = domNode.getAttributes();
if (attrMap != null) {
for (int i = 0; i < attrMap.getLength(); i++) {
removeSubtreeMapping(attrMap.item(i));
}
}
NodeList children = domNode.getChildNodes();
if (children != null) {
for (int i = 0; i < children.getLength(); i++) {
removeSubtreeMapping(children.item(i));
}
}
// if (domNode instanceof Element) {
// Element element = (Element) domNode;
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// if (eventTypesForElement != null) {
// for (String eventType : eventTypesForElement) {
// Set<Element> elementsForEventType = eventType2elements.get(eventType);
// elementsForEventType.remove(element);
// if (elementsForEventType.isEmpty()) {
// eventType2elements.remove(eventType);
// ((EventTarget) document).removeEventListener(eventType, DomDecoder2.this, false);
// }
// }
// element2eventTypes.remove(element);
// }
// }
}
// private DomDecoder(DynamicGraph graph) {
// this.graph = graph;
// this.updatesContext = this;
// }
//
private DomDecoder(DomDecoder domDecoder) {
this.graph = domDecoder.graph;
this.elementCount = domDecoder.elementCount;
this.docRootNode = domDecoder.docRootNode;
this.domImplementation = domDecoder.domImplementation;
this.dom2childrenKeys = domDecoder.dom2childrenKeys;
this.dom2childrenOrderProperty = domDecoder.dom2childrenOrderProperty;
this.dom2descendingOrder = domDecoder.dom2descendingOrder;
this.dom2graphNodeMapping = domDecoder.dom2graphNodeMapping;
this.dom2orderedByKeyChildren = domDecoder.dom2orderedByKeyChildren;
this.eventManager = domDecoder.eventManager;
this.updatesContext = this;
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl) {
this(graph, docRootNode, domImpl, (DocumentReceiver) null);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
EventManager eventManager) {
this(graph, docRootNode, domImpl, (DocumentReceiver) null, eventManager);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
DocumentReceiver docReceiver) {
this(graph, docRootNode, domImpl, null, docReceiver);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
DocumentReceiver docReceiver,
EventManager eventManager) {
this(graph, docRootNode, domImpl, null, docReceiver, eventManager);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
RunnableContext updatesContext) {
this(graph, docRootNode, domImpl, updatesContext,DEFAULT_EVENT_MANAGER);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
RunnableContext updatesContext,
EventManager eventManager) {
this(graph, docRootNode, domImpl, updatesContext, null, eventManager);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
RunnableContext updatesContext,
DocumentReceiver docReceiver) {
this(graph, docRootNode, domImpl, updatesContext, docReceiver, DEFAULT_EVENT_MANAGER);
}
private DomDecoder(
DynamicGraph graph, Node docRootNode,
DOMImplementation domImpl,
RunnableContext updatesContext,
DocumentReceiver docReceiver,
EventManager eventManager) {
this.graph = graph;
this.domImplementation = domImpl;
this.updatesContext = ( updatesContext == null ? this : updatesContext );
this.docReceiver = docReceiver;
this.eventManager = eventManager;
this.docRootNode = docRootNode;
decodeWorker(graph, docRootNode);
}
public void run(Runnable runnable) {
runnable.run();
}
private Document getDocument() {
return document;
}
private void orderChild(org.w3c.dom.Node node, Element parent, Node orderKeyNode) {
putChildByKey(parent, node, orderKeyNode);
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(parent);
if (!dom2descendingOrder.contains(parent)) {
Entry<Node, Vector<org.w3c.dom.Node>> nextEntry =
orderedByKeyChildren.higherEntry(orderKeyNode);
if (nextEntry == null) {
parent.appendChild(node);
} else {
parent.insertBefore(node, nextEntry.getValue().firstElement());
}
} else {
Entry<Node, Vector<org.w3c.dom.Node>> nextEntry =
orderedByKeyChildren.lowerEntry(orderKeyNode);
if (nextEntry == null) {
parent.appendChild(node);
} else {
parent.insertBefore(node, nextEntry.getValue().firstElement());
}
}
}
private void reorderChild(org.w3c.dom.Node node, Element parent, Node orderKeyNode) {
orderChild(node, parent, orderKeyNode);
}
private void insertChildInOrder(org.w3c.dom.Node child, Node childNode, Element parent) {
Node childrenOrderProperty = dom2childrenOrderProperty.get(parent);
Node orderKeyNode =
( childrenOrderProperty != null ) ?
GraphUtils.getSingleValueOptProperty(graph, childNode, childrenOrderProperty) :
GraphUtils.getSingleValueOptProperty(graph, childNode, XML.orderKey.asNode());
orderChild(child, parent, orderKeyNode);
}
private void removeChild(org.w3c.dom.Node node, Element parent) {
removeChildByKey(parent, node);
parent.removeChild(node);
}
private boolean mustReorderAllChildrenOf(Element parent, GraphUpdate update) {
Node parentNode = dom2graphNodeMapping.get(parent);
return
update.getAddedGraph().contains(parentNode, XML.childrenOrderedBy.asNode(), Node.ANY)
|| update.getAddedGraph().contains(parentNode, XML.childrenOrderType.asNode(), Node.ANY)
|| update.getDeletedGraph().contains(parentNode, XML.childrenOrderedBy.asNode(), Node.ANY)
|| update.getDeletedGraph().contains(parentNode, XML.childrenOrderType.asNode(), Node.ANY);
}
public synchronized void notifyUpdate(final Graph sourceGraph, final GraphUpdate update) {
logger.debug("Begin of Notify Update in DOM Decoder");
if (!update.getAddedGraph().isEmpty() || !update.getDeletedGraph().isEmpty()) {
updatesContext.run(
new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
ExtendedIterator<Triple> addEventsIter =
update.getAddedGraph().find(Node.ANY, Node.ANY, Node.ANY);
DomDecoder newDom = new DomDecoder(DomDecoder.this);
newDom.dom2graphNodeMapping =
(Map<org.w3c.dom.Node, Node>) ((HashMap<org.w3c.dom.Node, Node>) dom2graphNodeMapping).clone();
// newDom.graph2domNodeMapping = (Map<Node, Set<org.w3c.dom.Node>>) ((HashMap<Node, Set<org.w3c.dom.Node>>) graph2domNodeMapping).clone();
for (Node key : graph2domNodeMapping.keySet()) {
newDom.graph2domNodeMapping.put(key, (Set<org.w3c.dom.Node>) ((HashSet<org.w3c.dom.Node>) graph2domNodeMapping.get(key)).clone());
}
newDom.document = document;
// newDom.document = (Document) document.cloneNode(true);
while (addEventsIter.hasNext()) {
final Triple newTriple = addEventsIter.next();
// org.w3c.dom.Node xmlSubj = nodeMapping.get(newTriple.getSubject());
//System.out.println("Checking add event " + newTriple);
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(newTriple.getSubject());
// if (domSubjs == null)
// logger.warn(this + ": managing add event " + newTriple + ", domSubjs is null");
if (domSubjs != null) {
logger.trace("Managing add event " + newTriple + " for domSubjs " + domSubjs);
Set<org.w3c.dom.Node> domSubjsTemp = new HashSet<org.w3c.dom.Node>();
domSubjsTemp.addAll(domSubjs);
Iterator<org.w3c.dom.Node> domSubjIter = domSubjsTemp.iterator();
// Basic properties: DOM node must be recreated
if (newTriple.getPredicate().equals(RDF.type.asNode())
|| newTriple.getPredicate().equals(XML.nodeName.asNode())) {
//org.w3c.dom.Node parentNode = null;
Node nodeType = newTriple.getObject();
if ( nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
org.w3c.dom.Node newNode = newDom.decodeNode(newTriple.getSubject());
parentNode.replaceChild(newNode, domSubj);
newDom.removeSubtreeMapping(domSubj);
newDom.addNodeMapping(newTriple.getSubject(), newNode);
}
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is a DOM Attribute
} else if (
graph.contains(
newTriple.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode() ) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
Attr newAttr = newDom.decodeAttr(newTriple.getPredicate());
// newDom.addNodeMapping(newTriple.getPredicate(), newAttr);
newAttr.setValue(newTriple.getObject().getLiteralLexicalForm());
element.setAttributeNodeNS(newAttr);
}
// Predicate is xml:hasChild
} else if ( newTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
Node nodeType =
graph
.find(newTriple.getSubject(), XML.nodeType.asNode(), Node.ANY)
.next().getObject();
logger.trace("Managing add hasChild (" + newTriple + ") for domSubjs " + domSubjs + " and node type " + nodeType);
if (nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
org.w3c.dom.Node newChild = newDom.decodeNode(newTriple.getObject());
newDom.addNodeMapping(newTriple.getObject(), newChild);
// element.appendChild(newChild);
insertChildInOrder(newChild, newTriple.getObject(), element);
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is xml:nodeValue
} else if ( newTriple.getPredicate().equals(XML.nodeValue.asNode()) ) {
logger.trace("Managing add nodeValue (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
node.setNodeValue(newTriple.getObject().getLiteralLexicalForm());
}
// Predicate is orderKey
} else if ( newTriple.getPredicate().equals(XML.orderKey.asNode()) ) {
logger.trace("Managing add orderKey (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
newTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& newTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(newTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)) {
logger.trace("Managing add childrenOrderType (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (!dom2descendingOrder.contains(node)) {
dom2descendingOrder.add((Element) node);
reorder(false, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if ( newTriple.getPredicate().equals(XML.childrenOrderedBy.asNode()) ) {
logger.trace("Managing add childrenOrderedBy (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(newTriple.getSubject(), (Element) node);
}
// Predicate is xml:listenedEventType
} else if ( newTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = newTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
logger.trace("On add, registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element /*+ " (" + elementNode + ")"*/);
// ((EventTarget) element).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.addEventListener(
newTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// if (elemsForEventType == null) {
// elemsForEventType = new HashSet<Element>();
// eventType2elements.put(eventType, elemsForEventType);
// ((EventTarget) document).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
// elemsForEventType.add(element);
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// if (eventTypesForElement == null) {
// eventTypesForElement = new HashSet<String>();
// element2eventTypes.put(element, eventTypesForElement);
// }
// eventTypesForElement.add(eventType);
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(newTriple.getPredicate())
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing add predicate is the childrenOrderedBy for some parent (" + newTriple + ")");
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
}
}
ExtendedIterator<Triple> deleteEventsIter =
update.getDeletedGraph().find(Node.ANY, Node.ANY, Node.ANY);
while (deleteEventsIter.hasNext()) {
Triple oldTriple = deleteEventsIter.next();
//org.w3c.dom.Node xmlSubj = nodeMapping.get(oldTriple.getSubject());
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(oldTriple.getSubject());
//System.out.println("Checking for " + oldTriple.getSubject() + " contained in " + sourceGraph);
if (domSubjs != null && graph.contains(oldTriple.getSubject(), RDF.type.asNode(), Node.ANY)) {
//System.out.println("Found " + oldTriple.getSubject() + " contained in " + sourceGraph);
//System.out.println("Managing " + oldTriple.getPredicate() + "/" + oldTriple.getObject());
Iterator<org.w3c.dom.Node> domSubjIter = domSubjs.iterator();
if ( ( oldTriple.getPredicate().equals(XML.nodeName.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeName.asNode(), Node.ANY) )
|| ( oldTriple.getPredicate().equals(XML.nodeType.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeType.asNode(), Node.ANY) ) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
switch (domSubj.getNodeType()) {
case org.w3c.dom.Node.ATTRIBUTE_NODE:
Attr oldAttr = (Attr) domSubj;
Element ownerElement = oldAttr.getOwnerElement();
ownerElement.removeAttributeNode(oldAttr);
newDom.removeSubtreeMapping(oldAttr);
break;
case org.w3c.dom.Node.DOCUMENT_NODE:
if ( oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
break;
default:
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
parentNode.removeChild(domSubj);
newDom.removeSubtreeMapping(domSubj);
}
}
}
} else if (
oldTriple.getPredicate().equals(XML.nodeValue.asNode())
&& !graph.contains(oldTriple.getSubject(), XML.nodeValue.asNode(), Node.ANY)) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
domSubj.setNodeValue("");
}
} else if (
graph.contains(
oldTriple.getPredicate(),
RDFS.subClassOf.asNode(),
- XML.Attr.asNode() ) ) {
+ XML.Attr.asNode() )
+ && !update.getAddedGraph().contains(oldTriple.getSubject(), oldTriple.getPredicate(), Node.ANY) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
newDom.removeAttr(element, oldTriple.getPredicate());
}
// Set<org.w3c.dom.Node> domObjsOrig = graph2domNodeMapping.get(oldTriple.getObject());
// if (domObjsOrig != null) {
// Set<org.w3c.dom.Node> domObjs = new HashSet<org.w3c.dom.Node>();
// domObjs.addAll(domObjsOrig);
// while (domSubjIter.hasNext()) {
// Element element = (Element) domSubjIter.next();
// Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
// while (domObjsIter.hasNext()) {
// try {
// Attr oldAttr = (Attr) domObjsIter.next();
// if ( oldAttr.getNamespaceURI() == null
// ? element.hasAttribute(oldAttr.getName())
// : element.hasAttributeNS(oldAttr.getNamespaceURI(), oldAttr.getLocalName()))
// element.removeAttributeNode(oldAttr);
// newDom.removeSubtreeMapping(oldAttr);
// } catch(DOMException e) {
// if (!e.equals(DOMException.NOT_FOUND_ERR))
// throw e;
// }
// }
// }
// }
} else if ( oldTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
if ( domSubj.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE && oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
Set<org.w3c.dom.Node> domObjs = graph2domNodeMapping.get(oldTriple.getObject());
if (domObjs != null) {
Element element = (Element) domSubj;
Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
while (domObjsIter.hasNext()) {
try {
org.w3c.dom.Node domObj = domObjsIter.next();
removeChild(domObj, element);
newDom.removeSubtreeMapping(domObj);
} catch(DOMException e) {
if (!e.equals(DOMException.NOT_FOUND_ERR))
throw e;
}
}
}
}
// Predicate is orderKey
} else if (
oldTriple.getPredicate().equals(XML.orderKey.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.orderKey.asNode(), Node.ANY) ) {
logger.trace("Managing delete orderKey (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = oldTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& oldTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)
&& !update.getDeletedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderType (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (dom2descendingOrder.contains(node)) {
dom2descendingOrder.remove((Element) node);
reorder(true, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderedBy.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderedBy (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(oldTriple.getSubject(), (Element) node);
}
} else if ( oldTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = oldTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
// System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")");
// ((EventTarget) element).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.removeEventListener(
oldTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// elemsForEventType.remove(element);
// if (elemsForEventType.isEmpty()) {
// eventType2elements.remove(eventType);
// ((EventTarget) document).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// eventTypesForElement.remove(eventType);
// if (eventTypesForElement.isEmpty()) {
// element2eventTypes.remove(element);
// }
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(oldTriple.getPredicate())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), childrenOrderProperty, Node.ANY)
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing delete predicate that is the childrenOrderedBy for some parent (" + oldTriple + ")");
reorderChild(node, (Element) parent, null);
}
}
}
}
// System.out.println("End of notifyEvents() in " + this);
}
dom2graphNodeMapping = newDom.dom2graphNodeMapping;
graph2domNodeMapping = newDom.graph2domNodeMapping;
// document = newDom.document;
}
});
}
logger.debug("End of Notify Update in DOM Decoder");
}
}
| true | true | public synchronized void notifyUpdate(final Graph sourceGraph, final GraphUpdate update) {
logger.debug("Begin of Notify Update in DOM Decoder");
if (!update.getAddedGraph().isEmpty() || !update.getDeletedGraph().isEmpty()) {
updatesContext.run(
new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
ExtendedIterator<Triple> addEventsIter =
update.getAddedGraph().find(Node.ANY, Node.ANY, Node.ANY);
DomDecoder newDom = new DomDecoder(DomDecoder.this);
newDom.dom2graphNodeMapping =
(Map<org.w3c.dom.Node, Node>) ((HashMap<org.w3c.dom.Node, Node>) dom2graphNodeMapping).clone();
// newDom.graph2domNodeMapping = (Map<Node, Set<org.w3c.dom.Node>>) ((HashMap<Node, Set<org.w3c.dom.Node>>) graph2domNodeMapping).clone();
for (Node key : graph2domNodeMapping.keySet()) {
newDom.graph2domNodeMapping.put(key, (Set<org.w3c.dom.Node>) ((HashSet<org.w3c.dom.Node>) graph2domNodeMapping.get(key)).clone());
}
newDom.document = document;
// newDom.document = (Document) document.cloneNode(true);
while (addEventsIter.hasNext()) {
final Triple newTriple = addEventsIter.next();
// org.w3c.dom.Node xmlSubj = nodeMapping.get(newTriple.getSubject());
//System.out.println("Checking add event " + newTriple);
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(newTriple.getSubject());
// if (domSubjs == null)
// logger.warn(this + ": managing add event " + newTriple + ", domSubjs is null");
if (domSubjs != null) {
logger.trace("Managing add event " + newTriple + " for domSubjs " + domSubjs);
Set<org.w3c.dom.Node> domSubjsTemp = new HashSet<org.w3c.dom.Node>();
domSubjsTemp.addAll(domSubjs);
Iterator<org.w3c.dom.Node> domSubjIter = domSubjsTemp.iterator();
// Basic properties: DOM node must be recreated
if (newTriple.getPredicate().equals(RDF.type.asNode())
|| newTriple.getPredicate().equals(XML.nodeName.asNode())) {
//org.w3c.dom.Node parentNode = null;
Node nodeType = newTriple.getObject();
if ( nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
org.w3c.dom.Node newNode = newDom.decodeNode(newTriple.getSubject());
parentNode.replaceChild(newNode, domSubj);
newDom.removeSubtreeMapping(domSubj);
newDom.addNodeMapping(newTriple.getSubject(), newNode);
}
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is a DOM Attribute
} else if (
graph.contains(
newTriple.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode() ) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
Attr newAttr = newDom.decodeAttr(newTriple.getPredicate());
// newDom.addNodeMapping(newTriple.getPredicate(), newAttr);
newAttr.setValue(newTriple.getObject().getLiteralLexicalForm());
element.setAttributeNodeNS(newAttr);
}
// Predicate is xml:hasChild
} else if ( newTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
Node nodeType =
graph
.find(newTriple.getSubject(), XML.nodeType.asNode(), Node.ANY)
.next().getObject();
logger.trace("Managing add hasChild (" + newTriple + ") for domSubjs " + domSubjs + " and node type " + nodeType);
if (nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
org.w3c.dom.Node newChild = newDom.decodeNode(newTriple.getObject());
newDom.addNodeMapping(newTriple.getObject(), newChild);
// element.appendChild(newChild);
insertChildInOrder(newChild, newTriple.getObject(), element);
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is xml:nodeValue
} else if ( newTriple.getPredicate().equals(XML.nodeValue.asNode()) ) {
logger.trace("Managing add nodeValue (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
node.setNodeValue(newTriple.getObject().getLiteralLexicalForm());
}
// Predicate is orderKey
} else if ( newTriple.getPredicate().equals(XML.orderKey.asNode()) ) {
logger.trace("Managing add orderKey (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
newTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& newTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(newTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)) {
logger.trace("Managing add childrenOrderType (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (!dom2descendingOrder.contains(node)) {
dom2descendingOrder.add((Element) node);
reorder(false, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if ( newTriple.getPredicate().equals(XML.childrenOrderedBy.asNode()) ) {
logger.trace("Managing add childrenOrderedBy (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(newTriple.getSubject(), (Element) node);
}
// Predicate is xml:listenedEventType
} else if ( newTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = newTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
logger.trace("On add, registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element /*+ " (" + elementNode + ")"*/);
// ((EventTarget) element).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.addEventListener(
newTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// if (elemsForEventType == null) {
// elemsForEventType = new HashSet<Element>();
// eventType2elements.put(eventType, elemsForEventType);
// ((EventTarget) document).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
// elemsForEventType.add(element);
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// if (eventTypesForElement == null) {
// eventTypesForElement = new HashSet<String>();
// element2eventTypes.put(element, eventTypesForElement);
// }
// eventTypesForElement.add(eventType);
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(newTriple.getPredicate())
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing add predicate is the childrenOrderedBy for some parent (" + newTriple + ")");
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
}
}
ExtendedIterator<Triple> deleteEventsIter =
update.getDeletedGraph().find(Node.ANY, Node.ANY, Node.ANY);
while (deleteEventsIter.hasNext()) {
Triple oldTriple = deleteEventsIter.next();
//org.w3c.dom.Node xmlSubj = nodeMapping.get(oldTriple.getSubject());
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(oldTriple.getSubject());
//System.out.println("Checking for " + oldTriple.getSubject() + " contained in " + sourceGraph);
if (domSubjs != null && graph.contains(oldTriple.getSubject(), RDF.type.asNode(), Node.ANY)) {
//System.out.println("Found " + oldTriple.getSubject() + " contained in " + sourceGraph);
//System.out.println("Managing " + oldTriple.getPredicate() + "/" + oldTriple.getObject());
Iterator<org.w3c.dom.Node> domSubjIter = domSubjs.iterator();
if ( ( oldTriple.getPredicate().equals(XML.nodeName.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeName.asNode(), Node.ANY) )
|| ( oldTriple.getPredicate().equals(XML.nodeType.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeType.asNode(), Node.ANY) ) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
switch (domSubj.getNodeType()) {
case org.w3c.dom.Node.ATTRIBUTE_NODE:
Attr oldAttr = (Attr) domSubj;
Element ownerElement = oldAttr.getOwnerElement();
ownerElement.removeAttributeNode(oldAttr);
newDom.removeSubtreeMapping(oldAttr);
break;
case org.w3c.dom.Node.DOCUMENT_NODE:
if ( oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
break;
default:
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
parentNode.removeChild(domSubj);
newDom.removeSubtreeMapping(domSubj);
}
}
}
} else if (
oldTriple.getPredicate().equals(XML.nodeValue.asNode())
&& !graph.contains(oldTriple.getSubject(), XML.nodeValue.asNode(), Node.ANY)) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
domSubj.setNodeValue("");
}
} else if (
graph.contains(
oldTriple.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode() ) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
newDom.removeAttr(element, oldTriple.getPredicate());
}
// Set<org.w3c.dom.Node> domObjsOrig = graph2domNodeMapping.get(oldTriple.getObject());
// if (domObjsOrig != null) {
// Set<org.w3c.dom.Node> domObjs = new HashSet<org.w3c.dom.Node>();
// domObjs.addAll(domObjsOrig);
// while (domSubjIter.hasNext()) {
// Element element = (Element) domSubjIter.next();
// Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
// while (domObjsIter.hasNext()) {
// try {
// Attr oldAttr = (Attr) domObjsIter.next();
// if ( oldAttr.getNamespaceURI() == null
// ? element.hasAttribute(oldAttr.getName())
// : element.hasAttributeNS(oldAttr.getNamespaceURI(), oldAttr.getLocalName()))
// element.removeAttributeNode(oldAttr);
// newDom.removeSubtreeMapping(oldAttr);
// } catch(DOMException e) {
// if (!e.equals(DOMException.NOT_FOUND_ERR))
// throw e;
// }
// }
// }
// }
} else if ( oldTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
if ( domSubj.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE && oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
Set<org.w3c.dom.Node> domObjs = graph2domNodeMapping.get(oldTriple.getObject());
if (domObjs != null) {
Element element = (Element) domSubj;
Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
while (domObjsIter.hasNext()) {
try {
org.w3c.dom.Node domObj = domObjsIter.next();
removeChild(domObj, element);
newDom.removeSubtreeMapping(domObj);
} catch(DOMException e) {
if (!e.equals(DOMException.NOT_FOUND_ERR))
throw e;
}
}
}
}
// Predicate is orderKey
} else if (
oldTriple.getPredicate().equals(XML.orderKey.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.orderKey.asNode(), Node.ANY) ) {
logger.trace("Managing delete orderKey (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = oldTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& oldTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)
&& !update.getDeletedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderType (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (dom2descendingOrder.contains(node)) {
dom2descendingOrder.remove((Element) node);
reorder(true, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderedBy.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderedBy (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(oldTriple.getSubject(), (Element) node);
}
} else if ( oldTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = oldTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
// System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")");
// ((EventTarget) element).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.removeEventListener(
oldTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// elemsForEventType.remove(element);
// if (elemsForEventType.isEmpty()) {
// eventType2elements.remove(eventType);
// ((EventTarget) document).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// eventTypesForElement.remove(eventType);
// if (eventTypesForElement.isEmpty()) {
// element2eventTypes.remove(element);
// }
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(oldTriple.getPredicate())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), childrenOrderProperty, Node.ANY)
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing delete predicate that is the childrenOrderedBy for some parent (" + oldTriple + ")");
reorderChild(node, (Element) parent, null);
}
}
}
}
// System.out.println("End of notifyEvents() in " + this);
}
dom2graphNodeMapping = newDom.dom2graphNodeMapping;
graph2domNodeMapping = newDom.graph2domNodeMapping;
// document = newDom.document;
}
});
}
logger.debug("End of Notify Update in DOM Decoder");
}
| public synchronized void notifyUpdate(final Graph sourceGraph, final GraphUpdate update) {
logger.debug("Begin of Notify Update in DOM Decoder");
if (!update.getAddedGraph().isEmpty() || !update.getDeletedGraph().isEmpty()) {
updatesContext.run(
new Runnable() {
@SuppressWarnings("unchecked")
public void run() {
ExtendedIterator<Triple> addEventsIter =
update.getAddedGraph().find(Node.ANY, Node.ANY, Node.ANY);
DomDecoder newDom = new DomDecoder(DomDecoder.this);
newDom.dom2graphNodeMapping =
(Map<org.w3c.dom.Node, Node>) ((HashMap<org.w3c.dom.Node, Node>) dom2graphNodeMapping).clone();
// newDom.graph2domNodeMapping = (Map<Node, Set<org.w3c.dom.Node>>) ((HashMap<Node, Set<org.w3c.dom.Node>>) graph2domNodeMapping).clone();
for (Node key : graph2domNodeMapping.keySet()) {
newDom.graph2domNodeMapping.put(key, (Set<org.w3c.dom.Node>) ((HashSet<org.w3c.dom.Node>) graph2domNodeMapping.get(key)).clone());
}
newDom.document = document;
// newDom.document = (Document) document.cloneNode(true);
while (addEventsIter.hasNext()) {
final Triple newTriple = addEventsIter.next();
// org.w3c.dom.Node xmlSubj = nodeMapping.get(newTriple.getSubject());
//System.out.println("Checking add event " + newTriple);
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(newTriple.getSubject());
// if (domSubjs == null)
// logger.warn(this + ": managing add event " + newTriple + ", domSubjs is null");
if (domSubjs != null) {
logger.trace("Managing add event " + newTriple + " for domSubjs " + domSubjs);
Set<org.w3c.dom.Node> domSubjsTemp = new HashSet<org.w3c.dom.Node>();
domSubjsTemp.addAll(domSubjs);
Iterator<org.w3c.dom.Node> domSubjIter = domSubjsTemp.iterator();
// Basic properties: DOM node must be recreated
if (newTriple.getPredicate().equals(RDF.type.asNode())
|| newTriple.getPredicate().equals(XML.nodeName.asNode())) {
//org.w3c.dom.Node parentNode = null;
Node nodeType = newTriple.getObject();
if ( nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
org.w3c.dom.Node newNode = newDom.decodeNode(newTriple.getSubject());
parentNode.replaceChild(newNode, domSubj);
newDom.removeSubtreeMapping(domSubj);
newDom.addNodeMapping(newTriple.getSubject(), newNode);
}
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is a DOM Attribute
} else if (
graph.contains(
newTriple.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode() ) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
Attr newAttr = newDom.decodeAttr(newTriple.getPredicate());
// newDom.addNodeMapping(newTriple.getPredicate(), newAttr);
newAttr.setValue(newTriple.getObject().getLiteralLexicalForm());
element.setAttributeNodeNS(newAttr);
}
// Predicate is xml:hasChild
} else if ( newTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
Node nodeType =
graph
.find(newTriple.getSubject(), XML.nodeType.asNode(), Node.ANY)
.next().getObject();
logger.trace("Managing add hasChild (" + newTriple + ") for domSubjs " + domSubjs + " and node type " + nodeType);
if (nodeType.equals(XML.Element.asNode()) || graph.contains(nodeType, RDFS.subClassOf.asNode(), XML.Element.asNode()) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
org.w3c.dom.Node newChild = newDom.decodeNode(newTriple.getObject());
newDom.addNodeMapping(newTriple.getObject(), newChild);
// element.appendChild(newChild);
insertChildInOrder(newChild, newTriple.getObject(), element);
}
} else if (
nodeType.equals(XML.Document.asNode())
&& graph.contains(SWI.GraphRoot.asNode(), XML.document.asNode(), newTriple.getSubject())) {
redecodeDocument(newTriple.getSubject());
return;
}
// Predicate is xml:nodeValue
} else if ( newTriple.getPredicate().equals(XML.nodeValue.asNode()) ) {
logger.trace("Managing add nodeValue (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
node.setNodeValue(newTriple.getObject().getLiteralLexicalForm());
}
// Predicate is orderKey
} else if ( newTriple.getPredicate().equals(XML.orderKey.asNode()) ) {
logger.trace("Managing add orderKey (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
newTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& newTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(newTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)) {
logger.trace("Managing add childrenOrderType (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (!dom2descendingOrder.contains(node)) {
dom2descendingOrder.add((Element) node);
reorder(false, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if ( newTriple.getPredicate().equals(XML.childrenOrderedBy.asNode()) ) {
logger.trace("Managing add childrenOrderedBy (" + newTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(newTriple.getSubject(), (Element) node);
}
// Predicate is xml:listenedEventType
} else if ( newTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = newTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
logger.trace("On add, registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element /*+ " (" + elementNode + ")"*/);
// ((EventTarget) element).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.addEventListener(
newTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// if (elemsForEventType == null) {
// elemsForEventType = new HashSet<Element>();
// eventType2elements.put(eventType, elemsForEventType);
// ((EventTarget) document).addEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
// elemsForEventType.add(element);
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// if (eventTypesForElement == null) {
// eventTypesForElement = new HashSet<String>();
// element2eventTypes.put(element, eventTypesForElement);
// }
// eventTypesForElement.add(eventType);
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(newTriple.getPredicate())
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing add predicate is the childrenOrderedBy for some parent (" + newTriple + ")");
Node orderKeyNode = newTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
}
}
ExtendedIterator<Triple> deleteEventsIter =
update.getDeletedGraph().find(Node.ANY, Node.ANY, Node.ANY);
while (deleteEventsIter.hasNext()) {
Triple oldTriple = deleteEventsIter.next();
//org.w3c.dom.Node xmlSubj = nodeMapping.get(oldTriple.getSubject());
Set<org.w3c.dom.Node> domSubjs = graph2domNodeMapping.get(oldTriple.getSubject());
//System.out.println("Checking for " + oldTriple.getSubject() + " contained in " + sourceGraph);
if (domSubjs != null && graph.contains(oldTriple.getSubject(), RDF.type.asNode(), Node.ANY)) {
//System.out.println("Found " + oldTriple.getSubject() + " contained in " + sourceGraph);
//System.out.println("Managing " + oldTriple.getPredicate() + "/" + oldTriple.getObject());
Iterator<org.w3c.dom.Node> domSubjIter = domSubjs.iterator();
if ( ( oldTriple.getPredicate().equals(XML.nodeName.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeName.asNode(), Node.ANY) )
|| ( oldTriple.getPredicate().equals(XML.nodeType.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.nodeType.asNode(), Node.ANY) ) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
switch (domSubj.getNodeType()) {
case org.w3c.dom.Node.ATTRIBUTE_NODE:
Attr oldAttr = (Attr) domSubj;
Element ownerElement = oldAttr.getOwnerElement();
ownerElement.removeAttributeNode(oldAttr);
newDom.removeSubtreeMapping(oldAttr);
break;
case org.w3c.dom.Node.DOCUMENT_NODE:
if ( oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
break;
default:
org.w3c.dom.Node parentNode = domSubj.getParentNode();
if (parentNode != null) {
parentNode.removeChild(domSubj);
newDom.removeSubtreeMapping(domSubj);
}
}
}
} else if (
oldTriple.getPredicate().equals(XML.nodeValue.asNode())
&& !graph.contains(oldTriple.getSubject(), XML.nodeValue.asNode(), Node.ANY)) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
domSubj.setNodeValue("");
}
} else if (
graph.contains(
oldTriple.getPredicate(),
RDFS.subClassOf.asNode(),
XML.Attr.asNode() )
&& !update.getAddedGraph().contains(oldTriple.getSubject(), oldTriple.getPredicate(), Node.ANY) ) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
newDom.removeAttr(element, oldTriple.getPredicate());
}
// Set<org.w3c.dom.Node> domObjsOrig = graph2domNodeMapping.get(oldTriple.getObject());
// if (domObjsOrig != null) {
// Set<org.w3c.dom.Node> domObjs = new HashSet<org.w3c.dom.Node>();
// domObjs.addAll(domObjsOrig);
// while (domSubjIter.hasNext()) {
// Element element = (Element) domSubjIter.next();
// Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
// while (domObjsIter.hasNext()) {
// try {
// Attr oldAttr = (Attr) domObjsIter.next();
// if ( oldAttr.getNamespaceURI() == null
// ? element.hasAttribute(oldAttr.getName())
// : element.hasAttributeNS(oldAttr.getNamespaceURI(), oldAttr.getLocalName()))
// element.removeAttributeNode(oldAttr);
// newDom.removeSubtreeMapping(oldAttr);
// } catch(DOMException e) {
// if (!e.equals(DOMException.NOT_FOUND_ERR))
// throw e;
// }
// }
// }
// }
} else if ( oldTriple.getPredicate().equals(XML.hasChild.asNode()) ) {
while (domSubjIter.hasNext()) {
org.w3c.dom.Node domSubj = domSubjIter.next();
if ( domSubj.getNodeType() == org.w3c.dom.Node.DOCUMENT_NODE && oldTriple.getSubject().equals(docRootNode) ) {
redecodeDocument();
return;
}
Set<org.w3c.dom.Node> domObjs = graph2domNodeMapping.get(oldTriple.getObject());
if (domObjs != null) {
Element element = (Element) domSubj;
Iterator<org.w3c.dom.Node> domObjsIter = domObjs.iterator();
while (domObjsIter.hasNext()) {
try {
org.w3c.dom.Node domObj = domObjsIter.next();
removeChild(domObj, element);
newDom.removeSubtreeMapping(domObj);
} catch(DOMException e) {
if (!e.equals(DOMException.NOT_FOUND_ERR))
throw e;
}
}
}
}
// Predicate is orderKey
} else if (
oldTriple.getPredicate().equals(XML.orderKey.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.orderKey.asNode(), Node.ANY) ) {
logger.trace("Managing delete orderKey (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty == null || childrenOrderProperty.equals(XML.orderKey.asNode()) ) {
Node orderKeyNode = oldTriple.getObject();
reorderChild(node, (Element) parent, orderKeyNode);
}
}
}
// Predicate xml:childrenOrderType and object xml:Descending
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderType.asNode())
&& oldTriple.getObject().equals(XML.Descending)
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY)
&& !update.getDeletedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderType (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element) {
NavigableMap<Node, Vector<org.w3c.dom.Node>> orderedByKeyChildren =
dom2orderedByKeyChildren.get(node);
if (dom2descendingOrder.contains(node)) {
dom2descendingOrder.remove((Element) node);
reorder(true, (Element) node, orderedByKeyChildren);
}
}
}
// Predicate xml:childrenOrderedBy
} else if (
oldTriple.getPredicate().equals(XML.childrenOrderedBy.asNode())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), XML.childrenOrderedBy.asNode(), Node.ANY) ) {
logger.trace("Managing delete childrenOrderedBy (" + oldTriple + ") for domSubjs " + domSubjs);
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
if (node instanceof Element)
setupElementChildren(oldTriple.getSubject(), (Element) node);
}
} else if ( oldTriple.getPredicate().equals(XML.listenedEventType.asNode()) ) {
Node eventTypeNode = oldTriple.getObject();
if (eventTypeNode.isLiteral()) {
while (domSubjIter.hasNext()) {
Element element = (Element) domSubjIter.next();
// System.out.println("Registering eventListener for type " + eventTypeNode.getLiteralLexicalForm() + " in element " + element + " (" + elementNode + ")");
// ((EventTarget) element).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
eventManager.removeEventListener(
oldTriple.getSubject(),
element,
eventTypeNode.getLiteralLexicalForm(),
DomDecoder.this, false);
// Set<Element> elemsForEventType = eventType2elements.get(eventType);
// elemsForEventType.remove(element);
// if (elemsForEventType.isEmpty()) {
// eventType2elements.remove(eventType);
// ((EventTarget) document).removeEventListener(eventTypeNode.getLiteralLexicalForm(), DomDecoder2.this, false);
// }
//
// Set<String> eventTypesForElement = element2eventTypes.get(element);
// eventTypesForElement.remove(eventType);
// if (eventTypesForElement.isEmpty()) {
// element2eventTypes.remove(element);
// }
}
}
}
// Predicate is the childrenOrderedBy for some parent
while (domSubjIter.hasNext()) {
org.w3c.dom.Node node = domSubjIter.next();
org.w3c.dom.Node parent = node.getParentNode();
if ( parent != null
&& parent instanceof Element ) {
Node childrenOrderProperty = dom2childrenOrderProperty.get((Element) parent);
if ( childrenOrderProperty != null
&& childrenOrderProperty.equals(oldTriple.getPredicate())
&& !update.getAddedGraph().contains(oldTriple.getSubject(), childrenOrderProperty, Node.ANY)
&& !mustReorderAllChildrenOf((Element) parent, update) ) {
logger.trace("Managing delete predicate that is the childrenOrderedBy for some parent (" + oldTriple + ")");
reorderChild(node, (Element) parent, null);
}
}
}
}
// System.out.println("End of notifyEvents() in " + this);
}
dom2graphNodeMapping = newDom.dom2graphNodeMapping;
graph2domNodeMapping = newDom.graph2domNodeMapping;
// document = newDom.document;
}
});
}
logger.debug("End of Notify Update in DOM Decoder");
}
|
diff --git a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditView.java b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditView.java
index eef819a..f1e2943 100644
--- a/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditView.java
+++ b/de.uni_koeln.ub.drc.ui/src/de/uni_koeln/ub/drc/ui/views/EditView.java
@@ -1,176 +1,176 @@
/**************************************************************************************************
* Copyright (c) 2010 Fabian Steeg. All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
* <p/>
* Contributors: Fabian Steeg - initial API and implementation
*************************************************************************************************/
package de.uni_koeln.ub.drc.ui.views;
import java.io.IOException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.e4.core.commands.ECommandService;
import org.eclipse.e4.core.commands.EHandlerService;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.Persist;
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import scala.collection.mutable.Stack;
import de.uni_koeln.ub.drc.data.Modification;
import de.uni_koeln.ub.drc.data.Page;
import de.uni_koeln.ub.drc.data.User;
import de.uni_koeln.ub.drc.data.Word;
import de.uni_koeln.ub.drc.ui.DrcUiActivator;
import de.uni_koeln.ub.drc.ui.Messages;
/**
* A view that the area to edit the text. Marks the section in the image file that corresponds to
* the word in focus (in {@link CheckView}).
* @author Fabian Steeg (fsteeg)
*/
public final class EditView {
@Inject
private EHandlerService handlerService;
@Inject
private ECommandService commandService;
@Inject
IEclipseContext context;
final MDirtyable dirtyable;
final EditComposite editComposite;
Label label;
ScrolledComposite sc;
@PostConstruct
public void setContext() {
editComposite.context = context; // FIXME this can't be right
focusLatestWord();
}
private void focusLatestWord() {
if (editComposite != null && editComposite.getWords() != null) {
Text text = editComposite.getWords()
.get(DrcUiActivator.instance().currentUser().latestWord());
text.setFocus();
sc.showControl(text);
}
}
@Inject
public EditView(final Composite parent, final MDirtyable dirtyable) {
this.dirtyable = dirtyable;
sc = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
label = new Label(parent, SWT.CENTER | SWT.WRAP);
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
editComposite = new EditComposite(this, SWT.NONE);
sc.setContent(editComposite);
sc.setExpandVertical(true);
sc.setExpandHorizontal(true);
sc.setMinSize(editComposite.computeSize(SWT.DEFAULT, SWT.MAX));
editComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayoutFactory.fillDefaults().generateLayout(parent);
}
@Inject
public void setSelection(
@Optional @Named( IServiceConstants.ACTIVE_SELECTION ) final List<Page> pages) {
if (pages != null && pages.size() > 0) {
Page page = pages.get(0);
if (dirtyable.isDirty()) {
MessageDialog dialog = new MessageDialog(editComposite.getShell(), Messages.SavePage, null,
Messages.CurrentPageModified, MessageDialog.CONFIRM,
new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL }, 0);
dialog.create();
if (dialog.open() == Window.OK) {
try {
doSave(null);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
editComposite.update(page);
} else {
return;
}
dirtyable.setDirty(false);
}
@Persist
public void doSave(@Optional final IProgressMonitor m) throws IOException, InterruptedException {
final IProgressMonitor monitor = m == null ? new NullProgressMonitor() : m;
final Page page = editComposite.getPage();
monitor.beginTask(Messages.SavingPage, page.words().size());
final List<Text> words = editComposite.getWords();
editComposite.getDisplay().syncExec(new Runnable() {
@Override
public void run() {
for (int i = 0; i < words.size(); i++) {
Text text = words.get(i);
resetWarningColor(text);
addToHistory(text);
monitor.worked(1);
}
saveToXml(page);
}
private void addToHistory(Text text) {
String newText = text.getText();
Word word = (Word) text.getData(Word.class.toString());
Stack<Modification> history = word.history();
Modification oldMod = history.top();
if (!newText.equals(oldMod.form()) && !word.original().trim().equals(Page.ParagraphMarker())) {
User user = DrcUiActivator.instance().currentUser();
- if (!oldMod.author().equals(user.id())) {
+ if (!oldMod.author().equals(user.id()) && !oldMod.voters().contains(user.id())) {
oldMod.downvote(user.id());
User.withId(DrcUiActivator.instance().userDb(), oldMod.author()).wasDownvoted();
}
history.push(new Modification(newText, user.id()));
user.hasEdited();
user.save(DrcUiActivator.instance().userDb());
text.setFocus();
}
}
private void resetWarningColor(Text text) {
if (text.getForeground().equals(text.getDisplay().getSystemColor(EditComposite.DUBIOUS))) {
text.setForeground(text.getDisplay().getSystemColor(EditComposite.DEFAULT));
label.setText(""); //$NON-NLS-1$
}
}
});
dirtyable.setDirty(false);
}
public boolean isSaveOnCloseNeeded() {
return true;
}
private void saveToXml(final Page page) {
System.out.println("Saving page: " + page); //$NON-NLS-1$
page.saveToDb(DrcUiActivator.instance().db());
}
}
| true | true | public void doSave(@Optional final IProgressMonitor m) throws IOException, InterruptedException {
final IProgressMonitor monitor = m == null ? new NullProgressMonitor() : m;
final Page page = editComposite.getPage();
monitor.beginTask(Messages.SavingPage, page.words().size());
final List<Text> words = editComposite.getWords();
editComposite.getDisplay().syncExec(new Runnable() {
@Override
public void run() {
for (int i = 0; i < words.size(); i++) {
Text text = words.get(i);
resetWarningColor(text);
addToHistory(text);
monitor.worked(1);
}
saveToXml(page);
}
private void addToHistory(Text text) {
String newText = text.getText();
Word word = (Word) text.getData(Word.class.toString());
Stack<Modification> history = word.history();
Modification oldMod = history.top();
if (!newText.equals(oldMod.form()) && !word.original().trim().equals(Page.ParagraphMarker())) {
User user = DrcUiActivator.instance().currentUser();
if (!oldMod.author().equals(user.id())) {
oldMod.downvote(user.id());
User.withId(DrcUiActivator.instance().userDb(), oldMod.author()).wasDownvoted();
}
history.push(new Modification(newText, user.id()));
user.hasEdited();
user.save(DrcUiActivator.instance().userDb());
text.setFocus();
}
}
private void resetWarningColor(Text text) {
if (text.getForeground().equals(text.getDisplay().getSystemColor(EditComposite.DUBIOUS))) {
text.setForeground(text.getDisplay().getSystemColor(EditComposite.DEFAULT));
label.setText(""); //$NON-NLS-1$
}
}
});
dirtyable.setDirty(false);
}
| public void doSave(@Optional final IProgressMonitor m) throws IOException, InterruptedException {
final IProgressMonitor monitor = m == null ? new NullProgressMonitor() : m;
final Page page = editComposite.getPage();
monitor.beginTask(Messages.SavingPage, page.words().size());
final List<Text> words = editComposite.getWords();
editComposite.getDisplay().syncExec(new Runnable() {
@Override
public void run() {
for (int i = 0; i < words.size(); i++) {
Text text = words.get(i);
resetWarningColor(text);
addToHistory(text);
monitor.worked(1);
}
saveToXml(page);
}
private void addToHistory(Text text) {
String newText = text.getText();
Word word = (Word) text.getData(Word.class.toString());
Stack<Modification> history = word.history();
Modification oldMod = history.top();
if (!newText.equals(oldMod.form()) && !word.original().trim().equals(Page.ParagraphMarker())) {
User user = DrcUiActivator.instance().currentUser();
if (!oldMod.author().equals(user.id()) && !oldMod.voters().contains(user.id())) {
oldMod.downvote(user.id());
User.withId(DrcUiActivator.instance().userDb(), oldMod.author()).wasDownvoted();
}
history.push(new Modification(newText, user.id()));
user.hasEdited();
user.save(DrcUiActivator.instance().userDb());
text.setFocus();
}
}
private void resetWarningColor(Text text) {
if (text.getForeground().equals(text.getDisplay().getSystemColor(EditComposite.DUBIOUS))) {
text.setForeground(text.getDisplay().getSystemColor(EditComposite.DEFAULT));
label.setText(""); //$NON-NLS-1$
}
}
});
dirtyable.setDirty(false);
}
|
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/tta/architecture/util/ArchitectureBuilder.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/tta/architecture/util/ArchitectureBuilder.java
index b1aa6d871..f29f01d8a 100644
--- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/tta/architecture/util/ArchitectureBuilder.java
+++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/llvm/tta/architecture/util/ArchitectureBuilder.java
@@ -1,310 +1,310 @@
package net.sf.orcc.backends.llvm.tta.architecture.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.dftools.graph.Vertex;
import net.sf.orcc.OrccRuntimeException;
import net.sf.orcc.backends.llvm.tta.architecture.AddressSpace;
import net.sf.orcc.backends.llvm.tta.architecture.ArchitectureFactory;
import net.sf.orcc.backends.llvm.tta.architecture.Buffer;
import net.sf.orcc.backends.llvm.tta.architecture.Component;
import net.sf.orcc.backends.llvm.tta.architecture.Design;
import net.sf.orcc.backends.llvm.tta.architecture.DesignConfiguration;
import net.sf.orcc.backends.llvm.tta.architecture.FunctionUnit;
import net.sf.orcc.backends.llvm.tta.architecture.Port;
import net.sf.orcc.backends.llvm.tta.architecture.Processor;
import net.sf.orcc.backends.llvm.tta.architecture.ProcessorConfiguration;
import net.sf.orcc.backends.llvm.tta.architecture.Signal;
import net.sf.orcc.backends.util.Mapping;
import net.sf.orcc.df.Action;
import net.sf.orcc.df.Actor;
import net.sf.orcc.df.Argument;
import net.sf.orcc.df.Broadcast;
import net.sf.orcc.df.Connection;
import net.sf.orcc.df.Instance;
import net.sf.orcc.df.Network;
import net.sf.orcc.df.util.DfSwitch;
import net.sf.orcc.ir.Type;
import net.sf.orcc.ir.TypeList;
import net.sf.orcc.ir.Var;
public class ArchitectureBuilder extends DfSwitch<Design> {
private Map<Component, Map<Component, Buffer>> bufferMap;
private Map<Vertex, Component> componentMap;
@SuppressWarnings("unused")
private DesignConfiguration conf;
private Design design;
private ArchitectureFactory factory = ArchitectureFactory.eINSTANCE;
@SuppressWarnings("unused")
private Mapping mapping;
private List<String> optimizedActors;
private int bufferId = 0;
public ArchitectureBuilder(DesignConfiguration conf) {
design = factory.createDesign();
componentMap = new HashMap<Vertex, Component>();
bufferMap = new HashMap<Component, Map<Component, Buffer>>();
optimizedActors = new ArrayList<String>();
optimizedActors.add("decoder_texture_IQ");
optimizedActors.add("Merger");
optimizedActors.add("decoder_motion_interpolation");
optimizedActors.add("decoder_motion_add");
optimizedActors.add("decoder_texture_idct2d");
optimizedActors.add("decoder_motion_framebuf");
}
public ArchitectureBuilder(DesignConfiguration conf, Mapping mapping) {
this.conf = conf;
this.mapping = mapping;
}
private FunctionUnit addBuffer(Processor processor, Buffer buffer) {
int i = processor.getData().size();
AddressSpace buf = factory.createAddressSpace("buf_" + i, i, 8, 0,
buffer.getDepth() * 4);
FunctionUnit lsu = factory.createLSU("LSU_buf_" + i, processor, buf);
processor.getData().add(buf);
processor.getFunctionUnits().add(lsu);
return lsu;
}
private Buffer createBuffer(Vertex source, Vertex target) {
Buffer buffer = factory.createBuffer(bufferId++, source, target);
Port sourcePort = addBuffer((Processor) source, buffer);
Port targetPort = addBuffer((Processor) target, buffer);
buffer.setSourcePort(sourcePort);
buffer.setTargetPort(targetPort);
design.add(buffer);
return buffer;
}
private void addSignal(Connection connection) {
Vertex source = componentMap.get(connection.getSource());
Vertex target = componentMap.get(connection.getTarget());
Port sourcePort = null;
Port targetPort = null;
int size;
if (source == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getSource());
design.addInput(port);
source = port;
} else {
if (source instanceof Processor) {
Processor processor = (Processor) source;
FunctionUnit fu = factory.createOutputSignalUnit(processor,
connection.getSourcePort().getName());
processor.getFunctionUnits().add(fu);
sourcePort = fu;
} else {
Component component = (Component) source;
sourcePort = factory.createPort(connection.getSourcePort());
- component.addInput(sourcePort);
+ component.addOutput(sourcePort);
}
}
if (target == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getTarget());
design.addOutput(port);
size = port.getSize();
target = port;
} else {
if (target instanceof Processor) {
throw new OrccRuntimeException("Unsupported input signal.");
} else {
Component component = (Component) target;
targetPort = factory.createPort(connection.getTargetPort());
component.addInput(targetPort);
size = targetPort.getSize();
}
}
Signal signal = factory.createSignal(connection.getAttribute("id")
.getValue().toString(), size, source, target, sourcePort,
targetPort);
design.add(signal);
}
private void mapToBuffer(Connection connection) {
Component source = componentMap.get(connection.getSource());
Component target = componentMap.get(connection.getTarget());
Map<Component, Buffer> tgtToBufferMap;
if (bufferMap.containsKey(source)) {
tgtToBufferMap = bufferMap.get(source);
} else {
tgtToBufferMap = new HashMap<Component, Buffer>();
bufferMap.put(source, tgtToBufferMap);
}
Buffer buffer;
if (tgtToBufferMap.containsKey(target)) {
buffer = tgtToBufferMap.get(target);
} else {
buffer = createBuffer(source, target);
tgtToBufferMap.put(target, buffer);
}
buffer.getMappedConnections().add(connection);
}
@Override
public Design caseBroadcast(Broadcast broadcast) {
ProcessorConfiguration conf = ProcessorConfiguration.STANDARD;
Processor processor = factory.createProcessor(
"processor_" + broadcast.getName(), conf, 512);
processor.getMappedActors().add(broadcast);
design.add(processor);
componentMap.put(broadcast, processor);
return null;
}
@Override
public Design caseConnection(Connection connection) {
if (isNative(connection)) {
addSignal(connection);
} else {
mapToBuffer(connection);
}
return null;
}
@Override
public Design caseInstance(Instance instance) {
Actor actor = instance.getActor();
Component component;
if (actor.isNative()) {
component = factory.createComponent(instance.getActor()
.getSimpleName());
for (Argument arg : instance.getArguments()) {
component.setAttribute(arg.getVariable().getName(),
arg.getValue());
}
} else {
int memorySize = computeNeededMemorySize(instance);
// ProcessorConfiguration conf = optimizedActors.contains(instance
// .getName()) ? ProcessorConfiguration.CUSTOM
// : ProcessorConfiguration.STANDARD;
ProcessorConfiguration conf = ProcessorConfiguration.STANDARD;
Processor processor = factory.createProcessor("processor_"
+ instance.getName(), conf, memorySize);
component = processor;
processor.getMappedActors().add(instance);
}
design.add(component);
componentMap.put(instance, component);
return null;
}
@Override
public Design caseNetwork(Network network) {
design = factory.createDesign();
for (Vertex entity : network.getEntities()) {
doSwitch(entity);
}
for (Instance instance : network.getInstances()) {
doSwitch(instance);
}
for (Connection connection : network.getConnections()) {
doSwitch(connection);
}
for (Buffer buffer : design.getBuffers()) {
buffer.update();
}
return design;
}
private int computeNeededMemorySize(Action action) {
int neededMemorySize = 0;
neededMemorySize += computeNeededMemorySize(action.getBody()
.getLocals());
neededMemorySize += computeNeededMemorySize(action.getInputPattern()
.getVariables());
neededMemorySize += computeNeededMemorySize(action.getScheduler()
.getLocals());
neededMemorySize += computeNeededMemorySize(action.getPeekPattern()
.getVariables());
return neededMemorySize;
}
/**
* Returns the memory size needed by the given actor in bits. This size
* corresponds to the sum of state variable size (only assignable variables
* or constant arrays) plus the maximum of the sum of local arrays per each
* action.
*
* @param instance
* the given instance
* @return the memory size needed by the given actor
*/
private int computeNeededMemorySize(Instance instance) {
int neededMemorySize = 0;
// Compute memory size needed by state variable
for (Var var : instance.getActor().getStateVars()) {
if (var.isAssignable() || var.getType().isList()) {
neededMemorySize += getSize(var.getType());
}
}
// Compute memory size needed by the actions
for (Action action : instance.getActor().getActions()) {
neededMemorySize += computeNeededMemorySize(action) * 1.3;
}
return neededMemorySize;
}
/**
* Return the memory size needed by the given variables. That corresponds to
* the total size of the contained arrays.
*
* @param vars
* the list procedure
* @return the memory size needed by the given procedure
*/
private int computeNeededMemorySize(List<Var> localVars) {
int neededMemorySize = 0;
// Compute memory size needed by local arrays
for (Var var : localVars) {
if (var.getType().isList()) {
neededMemorySize += getSize(var.getType());
}
}
return neededMemorySize;
}
private int getSize(Type type) {
int size;
if (type.isList()) {
size = getSize(((TypeList) type).getInnermostType());
for (int dim : type.getDimensions()) {
size *= dim;
}
} else if (type.isBool()) {
size = 8;
} else {
size = type.getSizeInBits();
}
return size;
}
private boolean isNative(Connection connection) {
net.sf.orcc.df.Port source = connection.getSourcePort();
net.sf.orcc.df.Port target = connection.getTargetPort();
return (source != null && source.isNative())
|| (target != null && target.isNative());
}
}
| true | true | private void addSignal(Connection connection) {
Vertex source = componentMap.get(connection.getSource());
Vertex target = componentMap.get(connection.getTarget());
Port sourcePort = null;
Port targetPort = null;
int size;
if (source == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getSource());
design.addInput(port);
source = port;
} else {
if (source instanceof Processor) {
Processor processor = (Processor) source;
FunctionUnit fu = factory.createOutputSignalUnit(processor,
connection.getSourcePort().getName());
processor.getFunctionUnits().add(fu);
sourcePort = fu;
} else {
Component component = (Component) source;
sourcePort = factory.createPort(connection.getSourcePort());
component.addInput(sourcePort);
}
}
if (target == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getTarget());
design.addOutput(port);
size = port.getSize();
target = port;
} else {
if (target instanceof Processor) {
throw new OrccRuntimeException("Unsupported input signal.");
} else {
Component component = (Component) target;
targetPort = factory.createPort(connection.getTargetPort());
component.addInput(targetPort);
size = targetPort.getSize();
}
}
Signal signal = factory.createSignal(connection.getAttribute("id")
.getValue().toString(), size, source, target, sourcePort,
targetPort);
design.add(signal);
}
| private void addSignal(Connection connection) {
Vertex source = componentMap.get(connection.getSource());
Vertex target = componentMap.get(connection.getTarget());
Port sourcePort = null;
Port targetPort = null;
int size;
if (source == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getSource());
design.addInput(port);
source = port;
} else {
if (source instanceof Processor) {
Processor processor = (Processor) source;
FunctionUnit fu = factory.createOutputSignalUnit(processor,
connection.getSourcePort().getName());
processor.getFunctionUnits().add(fu);
sourcePort = fu;
} else {
Component component = (Component) source;
sourcePort = factory.createPort(connection.getSourcePort());
component.addOutput(sourcePort);
}
}
if (target == null) {
Port port = factory.createPort((net.sf.orcc.df.Port) connection
.getTarget());
design.addOutput(port);
size = port.getSize();
target = port;
} else {
if (target instanceof Processor) {
throw new OrccRuntimeException("Unsupported input signal.");
} else {
Component component = (Component) target;
targetPort = factory.createPort(connection.getTargetPort());
component.addInput(targetPort);
size = targetPort.getSize();
}
}
Signal signal = factory.createSignal(connection.getAttribute("id")
.getValue().toString(), size, source, target, sourcePort,
targetPort);
design.add(signal);
}
|
diff --git a/src/java-server-framework/org/xins/server/APIServlet.java b/src/java-server-framework/org/xins/server/APIServlet.java
index d9430c119..1e67e4da6 100644
--- a/src/java-server-framework/org/xins/server/APIServlet.java
+++ b/src/java-server-framework/org/xins/server/APIServlet.java
@@ -1,155 +1,155 @@
/*
* $Id$
*/
package org.xins.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.util.servlet.ServletUtils;
import org.znerd.xmlenc.XMLOutputter;
/**
* Servlet that forwards request to an <code>API</code>.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public final class APIServlet
extends HttpServlet {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>APIServlet</code> object.
*/
public APIServlet() {
// empty
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The API that this servlet forwards requests to.
*/
private API _api;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
public void init(ServletConfig config)
throws ServletException {
String apiClass = config.getInitParameter("api.class");
if (apiClass == null || apiClass.equals("")) {
throw new ServletException("Unable to initialize servlet \"" + config.getServletName() + "\", API class should be set in init parameter \"api.class\".");
}
// TODO: Better error handling
try {
_api = (API) Class.forName(apiClass).newInstance();
} catch (Exception e) {
throw new ServletException("Unable to initialize servlet \"" + config.getServletName() + "\", unable to instantiate an object of type " + apiClass + ", or unable to convert it to an API instance.");
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handleRequest(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
handleRequest(req, resp);
}
private void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO: Be less memory-intensive
// Set the content output type to XML
resp.setContentType("text/xml");
// Reset the XMLOutputter
StringWriter stringWriter = new StringWriter();
XMLOutputter xmlOutputter = new XMLOutputter(stringWriter, "UTF-8");
// Stick all parameters in a map
Map map = new HashMap();
Enumeration names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = req.getParameter(name);
map.put(name, value);
}
// Create a new call context
CallContext context = new CallContext(xmlOutputter, map);
// Forward the call
PrintWriter out = resp.getWriter();
boolean succeeded = false;
try {
_api.handleCall(context);
succeeded = true;
} catch (Throwable exception) {
xmlOutputter.reset(out, "UTF-8");
xmlOutputter.startTag("result");
xmlOutputter.attribute("success", "false");
xmlOutputter.attribute("code", "InternalError");
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.class");
xmlOutputter.pcdata(exception.getClass().getName());
String message = exception.getMessage();
if (message != null && message.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.message");
xmlOutputter.pcdata(message);
}
StringWriter stWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stWriter);
exception.printStackTrace(printWriter);
String stackTrace = stWriter.toString();
- if (stackTrace != null && message.length() > 0) {
+ if (stackTrace != null && stackTrace.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.stacktrace");
xmlOutputter.pcdata(stackTrace);
}
xmlOutputter.close();
}
if (succeeded) {
out.print(stringWriter.toString());
}
out.flush();
}
}
| true | true | private void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO: Be less memory-intensive
// Set the content output type to XML
resp.setContentType("text/xml");
// Reset the XMLOutputter
StringWriter stringWriter = new StringWriter();
XMLOutputter xmlOutputter = new XMLOutputter(stringWriter, "UTF-8");
// Stick all parameters in a map
Map map = new HashMap();
Enumeration names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = req.getParameter(name);
map.put(name, value);
}
// Create a new call context
CallContext context = new CallContext(xmlOutputter, map);
// Forward the call
PrintWriter out = resp.getWriter();
boolean succeeded = false;
try {
_api.handleCall(context);
succeeded = true;
} catch (Throwable exception) {
xmlOutputter.reset(out, "UTF-8");
xmlOutputter.startTag("result");
xmlOutputter.attribute("success", "false");
xmlOutputter.attribute("code", "InternalError");
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.class");
xmlOutputter.pcdata(exception.getClass().getName());
String message = exception.getMessage();
if (message != null && message.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.message");
xmlOutputter.pcdata(message);
}
StringWriter stWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stWriter);
exception.printStackTrace(printWriter);
String stackTrace = stWriter.toString();
if (stackTrace != null && message.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.stacktrace");
xmlOutputter.pcdata(stackTrace);
}
xmlOutputter.close();
}
if (succeeded) {
out.print(stringWriter.toString());
}
out.flush();
}
| private void handleRequest(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO: Be less memory-intensive
// Set the content output type to XML
resp.setContentType("text/xml");
// Reset the XMLOutputter
StringWriter stringWriter = new StringWriter();
XMLOutputter xmlOutputter = new XMLOutputter(stringWriter, "UTF-8");
// Stick all parameters in a map
Map map = new HashMap();
Enumeration names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = req.getParameter(name);
map.put(name, value);
}
// Create a new call context
CallContext context = new CallContext(xmlOutputter, map);
// Forward the call
PrintWriter out = resp.getWriter();
boolean succeeded = false;
try {
_api.handleCall(context);
succeeded = true;
} catch (Throwable exception) {
xmlOutputter.reset(out, "UTF-8");
xmlOutputter.startTag("result");
xmlOutputter.attribute("success", "false");
xmlOutputter.attribute("code", "InternalError");
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.class");
xmlOutputter.pcdata(exception.getClass().getName());
String message = exception.getMessage();
if (message != null && message.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.message");
xmlOutputter.pcdata(message);
}
StringWriter stWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stWriter);
exception.printStackTrace(printWriter);
String stackTrace = stWriter.toString();
if (stackTrace != null && stackTrace.length() > 0) {
xmlOutputter.endTag();
xmlOutputter.startTag("param");
xmlOutputter.attribute("name", "_exception.stacktrace");
xmlOutputter.pcdata(stackTrace);
}
xmlOutputter.close();
}
if (succeeded) {
out.print(stringWriter.toString());
}
out.flush();
}
|
diff --git a/src/org/servalproject/messages/ShowConversationActivity.java b/src/org/servalproject/messages/ShowConversationActivity.java
index 829340bc..d1dfafa5 100644
--- a/src/org/servalproject/messages/ShowConversationActivity.java
+++ b/src/org/servalproject/messages/ShowConversationActivity.java
@@ -1,466 +1,465 @@
/*
* Copyright (C) 2012 The Serval Project
*
* This file is part of Serval Software (http://www.servalproject.org)
*
* Serval Software 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 source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.servalproject.messages;
import org.servalproject.R;
import org.servalproject.ServalBatPhoneApplication;
import org.servalproject.account.AccountService;
import org.servalproject.meshms.IncomingMeshMS;
import org.servalproject.meshms.OutgoingMeshMS;
import org.servalproject.meshms.SimpleMeshMS;
import org.servalproject.provider.MessagesContract;
import org.servalproject.servald.Identities;
import org.servalproject.servald.Peer;
import org.servalproject.servald.PeerListService;
import org.servalproject.servald.SubscriberId;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* activity to show a conversation thread
*
*/
public class ShowConversationActivity extends ListActivity {
/*
* private class level constants
*/
private final boolean V_LOG = true;
private final String TAG = "ShowConversationActivity";
private ShowConversationListAdapter mDataAdapter;
/*
* private class level variables
*/
private int threadId = -1;
private Peer recipient;
private Cursor cursor;
protected final static int DIALOG_RECIPIENT_INVALID = 1;
private final static int DIALOG_CONTENT_EMPTY = 2;
private InputMethodManager imm;
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(IncomingMeshMS.NEW_MESSAGES)) {
populateList();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
if (V_LOG) {
Log.v(TAG, "on create called");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.show_conversation);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// get the thread id from the intent
Intent mIntent = getIntent();
String did = null;
SubscriberId recipientSid = null;
if (Intent.ACTION_SENDTO.equals(mIntent.getAction())) {
Uri uri = mIntent.getData();
Log.v(TAG, "Received " + mIntent.getAction() + " " + uri.toString());
if (uri != null) {
if (uri.getScheme().equals("sms")
|| uri.getScheme().equals("smsto")) {
did = uri.getSchemeSpecificPart();
did = did.trim();
if (did.endsWith(","))
did = did.substring(0, did.length() - 1).trim();
if (did.indexOf("<") > 0)
did = did.substring(did.indexOf("<") + 1,
did.indexOf(">")).trim();
Log.v(TAG, "Parsed did " + did);
}
}
}
threadId = mIntent.getIntExtra("threadId", -1);
try {
{
String recipientSidString = mIntent.getStringExtra("recipient");
if (recipientSidString != null)
recipientSid = new SubscriberId(recipientSidString);
}
if (recipientSid == null && did != null) {
// lookup the sid from the contacts database
long contactId = AccountService.getContactId(
getContentResolver(), did);
if (contactId >= 0)
recipientSid = AccountService.getContactSid(
getContentResolver(),
contactId);
if (recipientSid == null) {
// TODO scan the network first and only complain when you
// attempt to send?
throw new UnsupportedOperationException(
"Subscriber id not found for phone number " + did);
}
}
if (recipientSid == null)
throw new UnsupportedOperationException(
"No Subscriber id found");
retrieveRecipient(getContentResolver(), recipientSid);
if (threadId == -1) {
// see if there is an existing conversation thread for this
// recipient
- threadId = MessageUtils.getThreadId(
- Identities.getCurrentIdentity(), recipientSid,
+ threadId = MessageUtils.getThreadId(recipientSid,
getContentResolver());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
finish();
}
Button sendButton = (Button) findViewById(R.id.show_message_ui_btn_send_message);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView message = (TextView) findViewById(R.id.show_conversation_ui_txt_content);
if (recipient == null || recipient.sid == null) {
showDialog(DIALOG_RECIPIENT_INVALID);
} else if (message.getText() == null
|| "".equals(message.getText())) {
showDialog(DIALOG_CONTENT_EMPTY);
} else {
sendMessage(recipient, message);
}
}
});
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(
ShowConversationActivity.this);
b.setMessage("Do you want to delete this entire thread?");
b.setNegativeButton("Cancel", null);
b.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
MessageUtils
.deleteThread(
ShowConversationActivity.this,
threadId);
ShowConversationActivity.this.finish();
} catch (Exception e) {
Log.e("BatPhone", e.getMessage(), e);
ServalBatPhoneApplication.context
.displayToastMessage(e.getMessage());
}
}
});
b.show();
}
});
}
protected void retrieveRecipient(final ContentResolver resolver,
final SubscriberId recipientSid) {
recipient = PeerListService.getPeer(getContentResolver(),
recipientSid);
final TextView recipientView = (TextView) findViewById(R.id.show_conversation_ui_recipient);
recipientView.setText(recipient.toString());
if (recipient.cacheUntil < SystemClock.elapsedRealtime()) {
new AsyncTask<Void, Peer, Void>() {
@Override
protected void onPostExecute(Void result) {
recipientView.setText(recipient.toString());
}
@Override
protected Void doInBackground(Void... params) {
Log.v("BatPhone", "Resolving recipient");
PeerListService.resolve(recipient);
return null;
}
}.execute();
}
}
private void sendMessage(Peer recipient, final TextView text) {
// send the message
try {
SimpleMeshMS message = new SimpleMeshMS(
Identities.getCurrentIdentity(),
recipient.sid,
Identities.getCurrentDid(),
recipient.did,
System.currentTimeMillis(),
text.getText().toString()
);
OutgoingMeshMS.processSimpleMessage(message);
saveMessage(message);
// refresh the message list
runOnUiThread(new Runnable() {
@Override
public void run() {
imm.hideSoftInputFromWindow(text.getWindowToken(), 0);
text.setText("");
populateList();
}
});
} catch (Exception e) {
Log.e("BatPhone", e.getMessage(), e);
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
}
}
// save the message
private void saveMessage(SimpleMeshMS message) {
ContentResolver contentResolver = getContentResolver();
// save the message
int[] result = MessageUtils.saveSentMessage(message, contentResolver,
threadId);
threadId = result[0];
int messageId = result[1];
int toastMessageId;
if (messageId != -1) {
Log.i(TAG, "New message saved with messageId '" + messageId
+ "', threadId '" + threadId + "'");
toastMessageId = R.string.new_message_ui_toast_sent_successfully;
} else {
Log.e(TAG, "unable to save new message");
toastMessageId = R.string.new_message_ui_toast_sent_unsuccessfully;
}
// keep the user informed
Toast.makeText(getApplicationContext(),
toastMessageId,
Toast.LENGTH_LONG).show();
}
/*
* get the required data and populate the cursor
*/
private void populateList() {
if (V_LOG) {
Log.v(TAG, "get cursor called, current threadID = " + threadId);
}
Cursor oldCursor = cursor;
// get a content resolver
ContentResolver mContentResolver = getApplicationContext()
.getContentResolver();
MessageUtils.markThreadRead(mContentResolver, threadId);
Uri mUri = MessagesContract.CONTENT_URI;
String mSelection = MessagesContract.Table.THREAD_ID + " = ?";
String[] mSelectionArgs = new String[1];
mSelectionArgs[0] = Integer.toString(threadId);
String mOrderBy = MessagesContract.Table.RECEIVED_TIME + " DESC";
cursor = mContentResolver.query(
mUri,
null,
mSelection,
mSelectionArgs,
mOrderBy);
// zero length arrays required by list adapter constructor,
// manual matching to views & columns will occur in the bindView
// method
String[] mColumnNames = new String[0];
int[] mLayoutElements = new int[0];
mDataAdapter = new ShowConversationListAdapter(
this,
R.layout.show_conversation_item_us,
cursor,
mColumnNames,
mLayoutElements);
// swap the adapters before closing the old cursor
setListAdapter(mDataAdapter);
if (oldCursor != null)
oldCursor.close();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
public void onPause() {
if (V_LOG) {
Log.v(TAG, "on pause called");
}
this.unregisterReceiver(receiver);
if (cursor != null) {
cursor.close();
cursor = null;
}
super.onPause();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
public void onResume() {
if (V_LOG) {
Log.v(TAG, "on resume called");
}
IntentFilter filter = new IntentFilter();
filter.addAction(IncomingMeshMS.NEW_MESSAGES);
this.registerReceiver(receiver, filter);
// get the data
populateList();
super.onResume();
}
/*
* (non-Javadoc)
*
* @see android.app.ListActivity#onDestroy()
*/
@Override
public void onDestroy() {
if (V_LOG) {
Log.v(TAG, "on destroy called");
}
super.onDestroy();
}
/*
* dialog related methods
*/
/*
* callback method used to construct the required dialog (non-Javadoc)
*
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
// create the required alert dialog
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
AlertDialog mDialog = null;
switch (id) {
case DIALOG_RECIPIENT_INVALID:
mBuilder.setMessage(
R.string.new_message_ui_dialog_recipient_invalid)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
mDialog = mBuilder.create();
break;
case DIALOG_CONTENT_EMPTY:
mBuilder.setMessage(R.string.new_message_ui_dialog_content_empty)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
mDialog = mBuilder.create();
break;
default:
mDialog = null;
}
return mDialog;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
if (V_LOG) {
Log.v(TAG, "on create called");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.show_conversation);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// get the thread id from the intent
Intent mIntent = getIntent();
String did = null;
SubscriberId recipientSid = null;
if (Intent.ACTION_SENDTO.equals(mIntent.getAction())) {
Uri uri = mIntent.getData();
Log.v(TAG, "Received " + mIntent.getAction() + " " + uri.toString());
if (uri != null) {
if (uri.getScheme().equals("sms")
|| uri.getScheme().equals("smsto")) {
did = uri.getSchemeSpecificPart();
did = did.trim();
if (did.endsWith(","))
did = did.substring(0, did.length() - 1).trim();
if (did.indexOf("<") > 0)
did = did.substring(did.indexOf("<") + 1,
did.indexOf(">")).trim();
Log.v(TAG, "Parsed did " + did);
}
}
}
threadId = mIntent.getIntExtra("threadId", -1);
try {
{
String recipientSidString = mIntent.getStringExtra("recipient");
if (recipientSidString != null)
recipientSid = new SubscriberId(recipientSidString);
}
if (recipientSid == null && did != null) {
// lookup the sid from the contacts database
long contactId = AccountService.getContactId(
getContentResolver(), did);
if (contactId >= 0)
recipientSid = AccountService.getContactSid(
getContentResolver(),
contactId);
if (recipientSid == null) {
// TODO scan the network first and only complain when you
// attempt to send?
throw new UnsupportedOperationException(
"Subscriber id not found for phone number " + did);
}
}
if (recipientSid == null)
throw new UnsupportedOperationException(
"No Subscriber id found");
retrieveRecipient(getContentResolver(), recipientSid);
if (threadId == -1) {
// see if there is an existing conversation thread for this
// recipient
threadId = MessageUtils.getThreadId(
Identities.getCurrentIdentity(), recipientSid,
getContentResolver());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
finish();
}
Button sendButton = (Button) findViewById(R.id.show_message_ui_btn_send_message);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView message = (TextView) findViewById(R.id.show_conversation_ui_txt_content);
if (recipient == null || recipient.sid == null) {
showDialog(DIALOG_RECIPIENT_INVALID);
} else if (message.getText() == null
|| "".equals(message.getText())) {
showDialog(DIALOG_CONTENT_EMPTY);
} else {
sendMessage(recipient, message);
}
}
});
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(
ShowConversationActivity.this);
b.setMessage("Do you want to delete this entire thread?");
b.setNegativeButton("Cancel", null);
b.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
MessageUtils
.deleteThread(
ShowConversationActivity.this,
threadId);
ShowConversationActivity.this.finish();
} catch (Exception e) {
Log.e("BatPhone", e.getMessage(), e);
ServalBatPhoneApplication.context
.displayToastMessage(e.getMessage());
}
}
});
b.show();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
if (V_LOG) {
Log.v(TAG, "on create called");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.show_conversation);
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// get the thread id from the intent
Intent mIntent = getIntent();
String did = null;
SubscriberId recipientSid = null;
if (Intent.ACTION_SENDTO.equals(mIntent.getAction())) {
Uri uri = mIntent.getData();
Log.v(TAG, "Received " + mIntent.getAction() + " " + uri.toString());
if (uri != null) {
if (uri.getScheme().equals("sms")
|| uri.getScheme().equals("smsto")) {
did = uri.getSchemeSpecificPart();
did = did.trim();
if (did.endsWith(","))
did = did.substring(0, did.length() - 1).trim();
if (did.indexOf("<") > 0)
did = did.substring(did.indexOf("<") + 1,
did.indexOf(">")).trim();
Log.v(TAG, "Parsed did " + did);
}
}
}
threadId = mIntent.getIntExtra("threadId", -1);
try {
{
String recipientSidString = mIntent.getStringExtra("recipient");
if (recipientSidString != null)
recipientSid = new SubscriberId(recipientSidString);
}
if (recipientSid == null && did != null) {
// lookup the sid from the contacts database
long contactId = AccountService.getContactId(
getContentResolver(), did);
if (contactId >= 0)
recipientSid = AccountService.getContactSid(
getContentResolver(),
contactId);
if (recipientSid == null) {
// TODO scan the network first and only complain when you
// attempt to send?
throw new UnsupportedOperationException(
"Subscriber id not found for phone number " + did);
}
}
if (recipientSid == null)
throw new UnsupportedOperationException(
"No Subscriber id found");
retrieveRecipient(getContentResolver(), recipientSid);
if (threadId == -1) {
// see if there is an existing conversation thread for this
// recipient
threadId = MessageUtils.getThreadId(recipientSid,
getContentResolver());
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
ServalBatPhoneApplication.context.displayToastMessage(e
.getMessage());
finish();
}
Button sendButton = (Button) findViewById(R.id.show_message_ui_btn_send_message);
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
TextView message = (TextView) findViewById(R.id.show_conversation_ui_txt_content);
if (recipient == null || recipient.sid == null) {
showDialog(DIALOG_RECIPIENT_INVALID);
} else if (message.getText() == null
|| "".equals(message.getText())) {
showDialog(DIALOG_CONTENT_EMPTY);
} else {
sendMessage(recipient, message);
}
}
});
Button deleteButton = (Button) findViewById(R.id.delete);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(
ShowConversationActivity.this);
b.setMessage("Do you want to delete this entire thread?");
b.setNegativeButton("Cancel", null);
b.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
MessageUtils
.deleteThread(
ShowConversationActivity.this,
threadId);
ShowConversationActivity.this.finish();
} catch (Exception e) {
Log.e("BatPhone", e.getMessage(), e);
ServalBatPhoneApplication.context
.displayToastMessage(e.getMessage());
}
}
});
b.show();
}
});
}
|
diff --git a/core/http/server-spring/src/main/java/org/openrdf/http/server/repository/namespaces/NamespaceController.java b/core/http/server-spring/src/main/java/org/openrdf/http/server/repository/namespaces/NamespaceController.java
index 7ac4c4f19..4eb09be2e 100644
--- a/core/http/server-spring/src/main/java/org/openrdf/http/server/repository/namespaces/NamespaceController.java
+++ b/core/http/server-spring/src/main/java/org/openrdf/http/server/repository/namespaces/NamespaceController.java
@@ -1,133 +1,133 @@
/*
* Copyright Aduna (http://www.aduna-software.com/) (c) 2007.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.http.server.repository.namespaces;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import info.aduna.io.IOUtil;
import info.aduna.webapp.views.EmptySuccessView;
import info.aduna.webapp.views.SimpleResponseView;
import org.openrdf.http.server.ClientHTTPException;
import org.openrdf.http.server.ServerHTTPException;
import org.openrdf.http.server.repository.RepositoryInterceptor;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
/**
* Handles requests for manipulating a specific namespace definition in a
* repository.
*
* @author Herko ter Horst
* @author Arjohn Kampman
*/
public class NamespaceController extends AbstractController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public NamespaceController()
throws ApplicationContextException
{
setSupportedMethods(new String[] { METHOD_GET, "PUT", "DELETE" });
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
String pathInfoStr = request.getPathInfo();
String[] pathInfo = pathInfoStr.substring(1).split("/");
String prefix = pathInfo[pathInfo.length - 1];
RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
String reqMethod = request.getMethod();
if (METHOD_GET.equals(reqMethod)) {
- logger.info("GET namespace for prefix {}" + prefix);
+ logger.info("GET namespace for prefix {}", prefix);
return getExportNamespaceResult(repositoryCon, prefix);
}
else if ("PUT".equals(reqMethod)) {
logger.info("PUT prefix {}", prefix);
return getUpdateNamespaceResult(repositoryCon, prefix, request);
}
else if ("DELETE".equals(reqMethod)) {
logger.info("DELETE prefix {}", prefix);
return getRemoveNamespaceResult(repositoryCon, prefix);
}
else {
throw new ServerHTTPException("Unexpected request method: " + reqMethod);
}
}
private ModelAndView getExportNamespaceResult(RepositoryConnection repositoryCon, String prefix)
throws ServerHTTPException, ClientHTTPException
{
try {
String namespace = repositoryCon.getNamespace(prefix);
if (namespace == null) {
throw new ClientHTTPException(SC_NOT_FOUND, "Undefined prefix: " + prefix);
}
Map<String, Object> model = new HashMap<String, Object>();
model.put(SimpleResponseView.CONTENT_KEY, namespace);
return new ModelAndView(SimpleResponseView.getInstance(), model);
}
catch (RepositoryException e) {
throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
}
}
private ModelAndView getUpdateNamespaceResult(RepositoryConnection repositoryCon, String prefix,
HttpServletRequest request)
throws IOException, ClientHTTPException, ServerHTTPException
{
String namespace = IOUtil.readString(request.getReader());
namespace = namespace.trim();
if (namespace.length() == 0) {
throw new ClientHTTPException(SC_BAD_REQUEST, "No namespace name found in request body");
}
// FIXME: perform some sanity checks on the namespace string
try {
repositoryCon.setNamespace(prefix, namespace);
}
catch (RepositoryException e) {
throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
}
return new ModelAndView(EmptySuccessView.getInstance());
}
private ModelAndView getRemoveNamespaceResult(RepositoryConnection repositoryCon, String prefix)
throws ServerHTTPException
{
try {
repositoryCon.removeNamespace(prefix);
}
catch (RepositoryException e) {
throw new ServerHTTPException("Repository error: " + e.getMessage(), e);
}
return new ModelAndView(EmptySuccessView.getInstance());
}
}
| true | true | protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
String pathInfoStr = request.getPathInfo();
String[] pathInfo = pathInfoStr.substring(1).split("/");
String prefix = pathInfo[pathInfo.length - 1];
RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
String reqMethod = request.getMethod();
if (METHOD_GET.equals(reqMethod)) {
logger.info("GET namespace for prefix {}" + prefix);
return getExportNamespaceResult(repositoryCon, prefix);
}
else if ("PUT".equals(reqMethod)) {
logger.info("PUT prefix {}", prefix);
return getUpdateNamespaceResult(repositoryCon, prefix, request);
}
else if ("DELETE".equals(reqMethod)) {
logger.info("DELETE prefix {}", prefix);
return getRemoveNamespaceResult(repositoryCon, prefix);
}
else {
throw new ServerHTTPException("Unexpected request method: " + reqMethod);
}
}
| protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
String pathInfoStr = request.getPathInfo();
String[] pathInfo = pathInfoStr.substring(1).split("/");
String prefix = pathInfo[pathInfo.length - 1];
RepositoryConnection repositoryCon = RepositoryInterceptor.getRepositoryConnection(request);
String reqMethod = request.getMethod();
if (METHOD_GET.equals(reqMethod)) {
logger.info("GET namespace for prefix {}", prefix);
return getExportNamespaceResult(repositoryCon, prefix);
}
else if ("PUT".equals(reqMethod)) {
logger.info("PUT prefix {}", prefix);
return getUpdateNamespaceResult(repositoryCon, prefix, request);
}
else if ("DELETE".equals(reqMethod)) {
logger.info("DELETE prefix {}", prefix);
return getRemoveNamespaceResult(repositoryCon, prefix);
}
else {
throw new ServerHTTPException("Unexpected request method: " + reqMethod);
}
}
|
diff --git a/src/com/example/AndroidContactViewer/ContactListActivity.java b/src/com/example/AndroidContactViewer/ContactListActivity.java
index d90491c..2cbc0cd 100644
--- a/src/com/example/AndroidContactViewer/ContactListActivity.java
+++ b/src/com/example/AndroidContactViewer/ContactListActivity.java
@@ -1,185 +1,186 @@
package com.example.AndroidContactViewer;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View.OnClickListener;
import com.example.AndroidContactViewer.datastore.ContactDataSource;
public class ContactListActivity extends ListActivity implements OnClickListener {
private boolean filtered = false;
private ContactListActivity _activity = null;
protected ContactAdapter contact_adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this;
setContentView(R.layout.contact_list);
ToolbarConfig toolbar = new ToolbarConfig(this, "Contacts");
// setup the about button
Button button = toolbar.getToolbarRightButton();
button.setText("New Contact");
button.setOnClickListener(this);
toolbar.hideLeftButton();
// initialize the list view
ContactDataSource datasource = new ContactDataSource(this);
datasource.open();
contact_adapter = new ContactAdapter(this, R.layout.contact_list_item, datasource.all());
setListAdapter(contact_adapter);
datasource.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
_activity.closeContextMenu();
return false;
}
});
// setup context menu
registerForContextMenu(lv);
//Setup Search
EditText search_box = (EditText)findViewById(R.id.search_box);
search_box.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
ContactListActivity.this.contact_adapter.getFilter().filter(charSequence);
+ filtered = true;
}
@Override
public void afterTextChanged(Editable editable) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.call:
Toast.makeText(this, "Call", 5).show();
return true;
case R.id.message:
Toast.makeText(this, "Message", 5).show();
return true;
case R.id.email:
Toast.makeText(this, "email", 5).show();
return true;
case R.id.profile:
Intent myIntent = new Intent(getBaseContext(), ContactViewActivity.class);
myIntent.putExtra("ContactID", ((ContactAdapter)getListAdapter()).getItem(info.position).getContactId());
startActivity(myIntent);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
this.openContextMenu(v);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.toolbar_right_button:
Intent myIntent = new Intent(getBaseContext(), ContactEditActivity.class);
myIntent.putExtra("ContactID", 0);
startActivity(myIntent);
break;
default:
Toast.makeText(
ContactListActivity.this,
"Unknown click",
Toast.LENGTH_SHORT).show();
break;
}
}
public boolean onSearchRequested() {
EditText search_box = (EditText)findViewById(R.id.search_box);
search_box.requestFocus();
// Return false so that Android doesn't try to run an actual search dialog.
return false;
}
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*/
@Override
public void onBackPressed() {
if(filtered){
ContactListActivity.this.contact_adapter.getFilter().filter("");
EditText search_box = (EditText)findViewById(R.id.search_box);
search_box.setText("");
filtered = false;
} else{
super.onBackPressed();
}
}
/*
* We need to provide a custom adapter in order to use a custom list item
* view.
*/
private class ContactAdapter extends ArrayAdapter<Contact> {
public ContactAdapter(Context context, int textViewResourceId,
List<Contact> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View item = inflater.inflate(R.layout.contact_list_item, parent, false);
Contact contact = getItem(position);
((TextView) item.findViewById(R.id.item_name)).setText(contact
.getName());
((TextView) item.findViewById(R.id.item_title)).setText(contact
.getTitle());
((TextView) item.findViewById(R.id.item_phone)).setText(contact
.getDefaultContactPhone());
return item;
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this;
setContentView(R.layout.contact_list);
ToolbarConfig toolbar = new ToolbarConfig(this, "Contacts");
// setup the about button
Button button = toolbar.getToolbarRightButton();
button.setText("New Contact");
button.setOnClickListener(this);
toolbar.hideLeftButton();
// initialize the list view
ContactDataSource datasource = new ContactDataSource(this);
datasource.open();
contact_adapter = new ContactAdapter(this, R.layout.contact_list_item, datasource.all());
setListAdapter(contact_adapter);
datasource.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
_activity.closeContextMenu();
return false;
}
});
// setup context menu
registerForContextMenu(lv);
//Setup Search
EditText search_box = (EditText)findViewById(R.id.search_box);
search_box.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
ContactListActivity.this.contact_adapter.getFilter().filter(charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this;
setContentView(R.layout.contact_list);
ToolbarConfig toolbar = new ToolbarConfig(this, "Contacts");
// setup the about button
Button button = toolbar.getToolbarRightButton();
button.setText("New Contact");
button.setOnClickListener(this);
toolbar.hideLeftButton();
// initialize the list view
ContactDataSource datasource = new ContactDataSource(this);
datasource.open();
contact_adapter = new ContactAdapter(this, R.layout.contact_list_item, datasource.all());
setListAdapter(contact_adapter);
datasource.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
_activity.closeContextMenu();
return false;
}
});
// setup context menu
registerForContextMenu(lv);
//Setup Search
EditText search_box = (EditText)findViewById(R.id.search_box);
search_box.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
ContactListActivity.this.contact_adapter.getFilter().filter(charSequence);
filtered = true;
}
@Override
public void afterTextChanged(Editable editable) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
}
|
diff --git a/h2/src/main/org/h2/mvstore/WriteBuffer.java b/h2/src/main/org/h2/mvstore/WriteBuffer.java
index 7d873e258..0da1d9274 100644
--- a/h2/src/main/org/h2/mvstore/WriteBuffer.java
+++ b/h2/src/main/org/h2/mvstore/WriteBuffer.java
@@ -1,324 +1,324 @@
/*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.mvstore;
import java.nio.ByteBuffer;
/**
* An auto-resize buffer to write data into a ByteBuffer.
*/
public class WriteBuffer {
private static final int MAX_REUSE_CAPACITY = 4 * 1024 * 1024;
/**
* The minimum number of bytes to grow a buffer at a time.
*/
private static final int MIN_GROW = 1024 * 1024;
private ByteBuffer reuse = ByteBuffer.allocate(MIN_GROW);
private ByteBuffer buff = reuse;
/**
* Write a variable size integer.
*
* @param x the value
* @return this
*/
public WriteBuffer putVarInt(int x) {
DataUtils.writeVarInt(ensureCapacity(5), x);
return this;
}
/**
* Write a variable size long.
*
* @param x the value
* @return this
*/
public WriteBuffer putVarLong(long x) {
DataUtils.writeVarLong(ensureCapacity(10), x);
return this;
}
/**
* Write the characters of a string in a format similar to UTF-8.
*
* @param s the string
* @param len the number of characters to write
* @return this
*/
public WriteBuffer putStringData(String s, int len) {
ByteBuffer b = ensureCapacity(3 * len);
for (int i = 0; i < len; i++) {
int c = s.charAt(i);
if (c < 0x80) {
b.put((byte) c);
} else if (c >= 0x800) {
b.put((byte) (0xe0 | (c >> 12)));
b.put((byte) (((c >> 6) & 0x3f)));
b.put((byte) (c & 0x3f));
} else {
b.put((byte) (0xc0 | (c >> 6)));
b.put((byte) (c & 0x3f));
}
}
return this;
}
/**
* Put a byte.
*
* @param x the value
* @return this
*/
public WriteBuffer put(byte x) {
ensureCapacity(1).put(x);
return this;
}
/**
* Put a character.
*
* @param x the value
* @return this
*/
public WriteBuffer putChar(char x) {
ensureCapacity(2).putChar(x);
return this;
}
/**
* Put a short.
*
* @param x the value
* @return this
*/
public WriteBuffer putShort(short x) {
ensureCapacity(2).putShort(x);
return this;
}
/**
* Put an integer.
*
* @param x the value
* @return this
*/
public WriteBuffer putInt(int x) {
ensureCapacity(4).putInt(x);
return this;
}
/**
* Put a long.
*
* @param x the value
* @return this
*/
public WriteBuffer putLong(long x) {
ensureCapacity(8).putLong(x);
return this;
}
/**
* Put a float.
*
* @param x the value
* @return this
*/
public WriteBuffer putFloat(float x) {
ensureCapacity(4).putFloat(x);
return this;
}
/**
* Put a double.
*
* @param x the value
* @return this
*/
public WriteBuffer putDouble(double x) {
ensureCapacity(8).putDouble(x);
return this;
}
/**
* Put a byte array.
*
* @param bytes the value
* @return this
*/
public WriteBuffer put(byte[] bytes) {
ensureCapacity(bytes.length).put(bytes);
return this;
}
/**
* Put a byte array.
*
* @param bytes the value
* @param offset the source offset
* @param length the number of bytes
* @return this
*/
public WriteBuffer put(byte[] bytes, int offset, int length) {
ensureCapacity(length).put(bytes, offset, length);
return this;
}
/**
* Put the contents of a byte buffer.
*
* @param src the source buffer
* @return this
*/
public WriteBuffer put(ByteBuffer src) {
ensureCapacity(buff.remaining()).put(src);
return this;
}
/**
* Set the limit, possibly growing the buffer.
*
* @param newLimit the new limit
* @return this
*/
public WriteBuffer limit(int newLimit) {
ensureCapacity(newLimit - buff.position()).limit(newLimit);
return this;
}
/**
* Get the capacity.
*
* @return the capacity
*/
public int capacity() {
return buff.capacity();
}
/**
* Set the position.
*
* @param newPosition the new position
* @return the new position
*/
public WriteBuffer position(int newPosition) {
buff.position(newPosition);
return this;
}
/**
* Get the limit.
*
* @return the limit
*/
public int limit() {
return buff.limit();
}
/**
* Get the current position.
*
* @return the position
*/
public int position() {
return buff.position();
}
/**
* Copy the data into the destination array.
*
* @param dst the destination array
* @return this
*/
public WriteBuffer get(byte[] dst) {
buff.get(dst);
return this;
}
/**
* Update an integer at the given index.
*
* @param index the index
* @param value the value
* @return this
*/
public WriteBuffer putInt(int index, int value) {
buff.putInt(index, value);
return this;
}
/**
* Update a short at the given index.
*
* @param index the index
* @param value the value
* @return this
*/
public WriteBuffer putShort(int index, short value) {
buff.putShort(index, value);
return this;
}
/**
* Clear the buffer after use.
*
* @return this
*/
public WriteBuffer clear() {
if (buff.limit() > MAX_REUSE_CAPACITY) {
buff = reuse;
} else if (buff != reuse) {
reuse = buff;
}
buff.clear();
return this;
}
/**
* Get the byte buffer.
*
* @return the byte buffer
*/
public ByteBuffer getBuffer() {
return buff;
}
private ByteBuffer ensureCapacity(int len) {
if (buff.remaining() < len) {
grow(len);
}
return buff;
}
private void grow(int additional) {
ByteBuffer temp = buff;
int needed = additional - temp.remaining();
// grow at least MIN_GROW
long grow = Math.max(needed, MIN_GROW);
// grow at least 50% of the current size
grow = Math.max(temp.capacity() / 2, grow);
- // the new capacity is at least Integer.MAX_VALUE
+ // the new capacity is at most Integer.MAX_VALUE
int newCapacity = (int) Math.min(Integer.MAX_VALUE, temp.capacity() + grow);
if (newCapacity < needed) {
throw new OutOfMemoryError("Capacity: " + newCapacity + " needed: " + needed);
}
try {
buff = ByteBuffer.allocate(newCapacity);
} catch (OutOfMemoryError e) {
throw new OutOfMemoryError("Capacity: " + newCapacity);
}
temp.flip();
buff.put(temp);
if (newCapacity <= MAX_REUSE_CAPACITY) {
reuse = buff;
}
}
}
| true | true | private void grow(int additional) {
ByteBuffer temp = buff;
int needed = additional - temp.remaining();
// grow at least MIN_GROW
long grow = Math.max(needed, MIN_GROW);
// grow at least 50% of the current size
grow = Math.max(temp.capacity() / 2, grow);
// the new capacity is at least Integer.MAX_VALUE
int newCapacity = (int) Math.min(Integer.MAX_VALUE, temp.capacity() + grow);
if (newCapacity < needed) {
throw new OutOfMemoryError("Capacity: " + newCapacity + " needed: " + needed);
}
try {
buff = ByteBuffer.allocate(newCapacity);
} catch (OutOfMemoryError e) {
throw new OutOfMemoryError("Capacity: " + newCapacity);
}
temp.flip();
buff.put(temp);
if (newCapacity <= MAX_REUSE_CAPACITY) {
reuse = buff;
}
}
| private void grow(int additional) {
ByteBuffer temp = buff;
int needed = additional - temp.remaining();
// grow at least MIN_GROW
long grow = Math.max(needed, MIN_GROW);
// grow at least 50% of the current size
grow = Math.max(temp.capacity() / 2, grow);
// the new capacity is at most Integer.MAX_VALUE
int newCapacity = (int) Math.min(Integer.MAX_VALUE, temp.capacity() + grow);
if (newCapacity < needed) {
throw new OutOfMemoryError("Capacity: " + newCapacity + " needed: " + needed);
}
try {
buff = ByteBuffer.allocate(newCapacity);
} catch (OutOfMemoryError e) {
throw new OutOfMemoryError("Capacity: " + newCapacity);
}
temp.flip();
buff.put(temp);
if (newCapacity <= MAX_REUSE_CAPACITY) {
reuse = buff;
}
}
|
diff --git a/src/plugin/Stalemate.java b/src/plugin/Stalemate.java
index 7221c3e..8e999c0 100644
--- a/src/plugin/Stalemate.java
+++ b/src/plugin/Stalemate.java
@@ -1,842 +1,842 @@
package plugin;
import java.io.*;
import static util.ColorParser.parseColors;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import net.minecraft.server.v1_5_R3.Block;
import net.minecraft.server.v1_5_R3.Item;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import amendedclasses.LoggerOutputStream;
import controllers.RoundController;
import defense.PlayerAI;
import defense.Team;
import serial.MapArea;
import serial.RoundConfiguration;
import serial.SerializableItemStack;
import soldier.SoldierClass;
import java.util.*;
public class Stalemate extends JavaPlugin implements Listener {
private Map<String, List<ItemStack>> itempacks = new ConcurrentHashMap<String, List<ItemStack>>();
public Map<String, String> settings = new ConcurrentHashMap<String, String>();
private static Stalemate instance;
public final Map<String, PlayerAI> aiMap = new ConcurrentHashMap<String, PlayerAI>();
private List<RoundController> rounds = new Vector<RoundController>();
private Map<String, CommandCallback> cmdMap = new ConcurrentHashMap<String, CommandCallback>();
private Map<String, String> helpMap = new ConcurrentHashMap<String, String>();
private Map<String, TrapCallback> trapMap = new ConcurrentHashMap<String, TrapCallback>();
public final Map<Location, String> placedTraps = new ConcurrentHashMap<Location, String>();
public String getSetting(String key, String def)
{
String val = settings.get(key);
if (val == null) val = def;
return val;
}
private static TrapCallback createCallbackFromXML(Element e)
{
final List<TrapCallback> tasks = new Vector<TrapCallback>();
NodeList stuff = e.getChildNodes();
for (int i = 0; i < stuff.getLength(); i++)
{
Node n = stuff.item(i);
if (!(n instanceof Element))
continue;
Element task = (Element) n;
String name = task.getNodeName();
switch (name.toLowerCase()) {
case "explosion":
tasks.add(new ExplosiveTrapCallback(task));
break;
case "kill":
tasks.add(new KillPlayerCallback(task));
break;
case "sleep":
tasks.add(new SleepTrapCallback(task));
break;
case "command":
tasks.add(new CommandTrapCallback(task));
break;
default:
System.out.println("Trap Callbacks: Unrecognized tag: "+name);
}
}
String reusables = e.getAttribute("reusable");
boolean reusable = true;
if (!reusables.equals("true"))
{
reusable = false;
}
final boolean reusableF = reusable;
return new TrapCallback() {
@Override
public void onTriggered(Player p, Location loc, RoundController rnd) {
for (TrapCallback c : tasks)
try {
c.onTriggered(p, loc, rnd);
} catch (Throwable e) {
RuntimeException e1 = new RuntimeException(Stalemate.getInstance().getSetting("trap_exc_msg", "Exception when triggering trap."));
e1.initCause(e);
throw e1;
}
}
@Override
public boolean isReusable() {
return reusableF;
}
};
}
public static Stalemate getInstance()
{
return instance;
}
private static class AsyncTask {
public long timeToWait;
public long lastTimeUpdated;
public final Callable<?> call;
public AsyncTask(long t, Callable<?> c) {
timeToWait = t;
call = c;
lastTimeUpdated = System.nanoTime()/1000000;
}
}
public Map<String, TrapCallback> getTrapCallbacks()
{
return trapMap;
}
private List<AsyncTask> tasks = new Vector<AsyncTask>();
private Thread asyncUpdateThread = new Thread() {
public void run() {
while (Stalemate.getInstance().isEnabled())
{
for (AsyncTask t : tasks)
{
t.timeToWait += -(t.lastTimeUpdated-(t.lastTimeUpdated = System.nanoTime()/1000000));
if (t.timeToWait <= 0)
{
tasks.remove(t);
try {
t.call.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public void setTimeout(long timeToWait, Callable<?> callback)
{
tasks.add(new AsyncTask(timeToWait, callback));
}
public Stalemate()
{
instance = this;
}
private void join(Team t, Player p)
{
for (Team tt : Team.list())
{
if (Arrays.asList(tt.getPlayers()).contains(p.getName().toUpperCase()))
tt.removePlayer(p.getName().toUpperCase());
}
t.addPlayer(p.getName());
for (RoundController rc : rounds)
{
if (rc.getConfig().getParticipatingTeams().contains(t))
{
p.teleport(rc.getConfig().getArea().randomLoc());
}
}
}
private void initRound(RoundController rnd)
{
rounds.add(rnd);
rnd.startRound();
}
private void placeTrap(String type, Location loc)
{
for (RoundController rc : rounds)
{
MapArea a = rc.getConfig().getArea();
if (a.contains(loc))
{
rc.placeTrap(type, loc);
break;
}
}
}
private Set<String> noChange = new HashSet<String>();
private Map<String, List<ItemStack>> itemsAccountableMap = new ConcurrentHashMap<String, List<ItemStack>>();
public void onEnable()
{
// TODO: Implement all commands
registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
for (String key : helpMap.keySet())
{
sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key+" - "+synColor(ChatColor.AQUA)+helpMap.get(key));
}
}
});
registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command.")));
return;
}
// TODO: Finish
}
});
registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /"+args[0]+" <teamname>")));
return;
}
Team t = Team.getTeam(args[1]);
Team yours = null;
for (Team te : Team.list())
{
if (te.containsPlayer(sender.getName().toUpperCase()))
{
yours = te;
}
}
if (yours == null)
{
sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>")));
return;
}
if (!sender.getName().equalsIgnoreCase(yours.getOwner()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
for (RoundController rc : rounds)
{
if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable())
{
rc.getConfig().addTeam(yours);
}
}
}
});
registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() {
@Override
public void onCommand(final CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("war_perm", "stalemate.start")))
{
sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>"));
return;
}
RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){
@Override
public Object call() throws Exception {
for (RoundController r : rounds) {
if (r.getPlayers().contains(sender.getName().toUpperCase()))
{
for (String p : r.getPlayers())
{
List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase());
Player pl = Stalemate.this.getServer().getPlayer(p);
Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0]));
acct.clear();
acct.addAll(failed.values());
noChange.remove(p.toUpperCase());
}
break;
}
}
return null;
}});
initRound(rnd);
Team yours = null;
for (Team t : Team.list())
{
if (t.containsPlayer(sender.getName()))
{
yours = t;
break;
}
}
if (!yours.getOwner().equalsIgnoreCase(sender.getName()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
rnd.getConfig().addTeam(yours);
}
});
registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap or removes one if already here."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
assert(args.length > 0);
if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
if (args.length < 6)
{
sender.sendMessage(getSetting("syntax_trap_console_msg", "Syntax: "+args[0]+" <world> <x> <y> <z>"));
return;
}
World w;
int x, y, z;
String trapName;
try {
w = getServer().getWorld(args[1]);
if (w == null) {
sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World."));
return;
}
x = Integer.parseInt(args[2]);
y = Integer.parseInt(args[3]);
z = Integer.parseInt(args[4]);
trapName = args[5];
} catch (NumberFormatException e) {
sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z."));
return;
}
placeTrap(trapName, new Location(w, x, y, z));
sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed."));
} else {
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /"+args[0]+" <trap_type>")));
return;
}
Player p = (Player) sender;
String trapName = args[1];
placeTrap(trapName, p.getLocation());
sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed.")));
}
}
});
registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_perm", "stalemate.join")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (args.length < 2) {
sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>")));
Team yours = null;
for (Team tt : Team.list())
{
if (tt.containsPlayer(sender.getName()))
{
yours = tt;
break;
}
}
sender.sendMessage("Your current team is: "+yours.getName());
return;
}
Player target = getServer().getPlayer(args[1]);
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command."));
return;
}
for (Team t : Team.list())
{
// TODO: Use linear search or hashing
if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0)
{
join(t, (Player) sender);
sender.sendMessage(parseColors(getSetting("join_success_msg", "Success.")));
return;
}
}
Team x = new Team(args[1]);
join(x, (Player) sender);
}
});
registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this feature."));
return;
}
for (RoundController rc : rounds)
{
if (rc.getPlayers().contains(sender.getName().toUpperCase()))
{
List<Team> teams = rc.getConfig().getParticipatingTeams();
for (Team t : teams)
if (t.removePlayer(sender.getName())) break;
}
}
}
});
registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this command."));
return;
}
if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple"))
{
sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it.")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /"+args[0]+" <classname>")));
return;
}
SoldierClass s = SoldierClass.fromName(args[1]);
if (!sender.hasPermission(s.getPermission()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class.")));
return;
}
ItemStack[] give = s.getItems();
List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account;
for (ItemStack i : give)
account.add(i.clone());
Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give);
account.removeAll(failed.values());
}
});
try {
onEnable0();
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate.");
- e.printStackTrace(new PrintWriter(new LoggerOutputStream(getLogger(), Level.SEVERE)));
+ e.printStackTrace();
}
asyncUpdateThread.start();
getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!");
}
protected static boolean isInRound(Player sender) {
// TODO Auto-generated method stub
return false;
}
public CommandCallback registerCommand(String name, String desc, CommandCallback onCommand)
{
CommandCallback c = cmdMap.put(name.toUpperCase(), onCommand);
helpMap.put(name.toUpperCase(), desc);
return c;
}
public void onDisable()
{
getLogger().info("Peace! AAAAH!");
Map<String, List<SerializableItemStack>> saveAccount = new HashMap<String, List<SerializableItemStack>>();
for (String s : itemsAccountableMap.keySet()) {
List<SerializableItemStack> l = SerializableItemStack.fromList(itemsAccountableMap.get(s));
saveAccount.put(s, l);
}
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(getDataFolder(), "items.dat")));
oos.writeObject(saveAccount);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String synColor(ChatColor c)
{
return ChatColor.COLOR_CHAR+""+c.getChar();
}
public boolean onCommand(CommandSender sender, Command cmd, String lbl, String args[])
{
if (!cmd.getName().equalsIgnoreCase("stalemate")) return false;
if (!sender.hasPermission("stalemate.basic"))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission.</font></xml>")));
return true;
}
if (args.length == 0)
{
args = new String[] {"help"};
}
String name = args[0];
CommandCallback cb = cmdMap.get(name);
if (cb == null)
{
sender.sendMessage(parseColors(getSetting("invalid_cmd_msg", "Invalid Command. Please type /stalemate "+getSetting("help_cmd", "help")+" for help.")));
return false;
}
cb.onCommand(sender, Arrays.asList(name, args).toArray(new String[0]));
return true;
}
private void generateConfig(File f) throws IOException
{
// Writing lines to translate CRLF -> LF and LF -> CRLF
PrintWriter writer = new PrintWriter(new FileOutputStream(f));
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("config.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String ln;
while ((ln = br.readLine()) != null)
writer.println(ln);
writer.close();
br.close();
}
public void onEnable0() throws Throwable
{
File config = new File(this.getDataFolder(), "config.xml");
if (!config.exists())
{
generateConfig(config);
}
if (!config.isFile())
{
boolean success = config.delete();
if (!success)
{
config.deleteOnExit();
throw new RuntimeException("Failed to create config.");
} else {
generateConfig(config);
}
}
FileInputStream stream = new FileInputStream(config);
// Buffer the file in memory
ByteArrayOutputStream b = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = stream.read(buf)) != -1)
{
b.write(buf, 0, bytesRead);
}
stream.close();
buf = null;
byte[] bytes = b.toByteArray();
b.close();
// Begin parsing
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc;
try {
doc = builder.parse(new ByteArrayInputStream(bytes));
} catch (Throwable t)
{
Throwable exc = new RuntimeException("Config Error: Invalid XML File: config.xml");
exc.initCause(t);
throw exc;
}
Element root = doc.getDocumentElement();
NodeList classes = root.getElementsByTagName("soldiers");
for (int i = 0; i < classes.getLength(); i++)
{
Node nn = classes.item(i);
if (!(nn instanceof Element)) continue;
Element section = (Element) nn;
// Load item packs
NodeList nodes = section.getElementsByTagName("itempack");
for (int j = 0; j < nodes.getLength(); j++)
{
Node nnn = nodes.item(j);
if (!(nnn instanceof Element)) continue;
Element pack = (Element) nnn;
NodeList items = pack.getElementsByTagName("item");
List<ItemStack> packItems = new Vector<ItemStack>();
for (int k = 0; k < items.getLength(); k++)
{
Node nnnn = items.item(k);
if (!(nnnn instanceof Element)) continue;
Element item = (Element) nnnn;
String idStr = item.getAttribute("id");
int id = -1;
if (idStr.equals(""))
{
// Fetch according to name attribute
String name = item.getAttribute("name");
for (Block block : Block.byId)
{
if (block.getName().equalsIgnoreCase(name))
{
id = block.id;
break;
}
}
if (id == -1) {
for (Item mcItem : Item.byId)
{
if (mcItem.getName().equalsIgnoreCase(name))
{
id = mcItem.id;
break;
}
}
if (id == -1)
throw new RuntimeException("Config Error: Non-existent name: "+name);
}
} else {
String name = item.getAttribute("name");
if (!name.equals("")) throw new RuntimeException("Both name and ID specified. Specify one or the other. Name: "+name+" ID: "+idStr);
try {
id = Integer.parseInt(idStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: Expected a number for item ID. Got: "+idStr);
}
}
String dmgStr = item.getAttribute("dmg");
int dmg;
if (dmgStr.equals("")) {
dmg = 0;
} else {
try {
dmg = Integer.parseInt(dmgStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: Expected an integer (-2147483648 -> 2147483647) for item damage. Got: "+dmgStr);
}
}
int num;
String numStr = item.getAttribute("num");
if (numStr.equals("")) {
num = 1;
} else {
try {
num = Integer.parseInt(numStr);
if (num <= 0) throw new NumberFormatException("break");
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: Expected a positive integer for item number. Got: "+numStr);
}
}
ItemStack stack = new ItemStack(id, num, (short) dmg);
packItems.add(stack);
}
if (pack.getAttribute("name").equals("")) throw new RuntimeException("Config Error: Item packs require a name attribute.");
itempacks.put(pack.getAttribute("name").toUpperCase(), packItems);
}
NodeList classList = section.getElementsByTagName("sclass");
for (int j = 0; j < classList.getLength(); j++)
{
Element classElement = (Element) classList.item(j);
String name = classElement.getAttribute("name");
String permission = classElement.getAttribute("permission");
NodeList itemList = classElement.getElementsByTagName("item");
List<ItemStack> classItems = new Vector<ItemStack>();
for (int k = 0; k < itemList.getLength(); k++)
{
Element item = (Element) itemList.item(k);
String n = item.getAttribute("name");
String isPackStr = item.getAttribute("isPack").toLowerCase();
boolean isPack;
if (isPackStr.equals(""))
{
isPack = false;
} else {
try {
isPack = Boolean.parseBoolean(isPackStr);
} catch (RuntimeException e) {
throw new RuntimeException("Config Error: Expected a true/false value for attribute isPack. Got: "+isPackStr);
}
}
if (n.equals("") || !isPack)
{
// Normal Item Processing
String idStr = item.getAttribute("id");
int id = -1;
if (!n.equals(""))
{
if (!idStr.equals(""))
throw new RuntimeException("Config Error: Name and ID specified. Please specify one or the other. Name: "+n+" ID: "+idStr);
for (Block b1 : Block.byId)
{
if (b1.getName().equalsIgnoreCase(n))
{
id = b1.id;
break;
}
}
if (id == -1)
throw new RuntimeException("Config Error: Non-existent name: "+n);
} else {
try {
id = Integer.parseInt(idStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: ID must be a valid integer. Got: "+idStr);
}
}
int num;
String numStr = item.getAttribute("num");
if (numStr.equals(""))
{
num = 1;
} else {
try {
num = Integer.parseInt(numStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: Expected an integer for item amount. Got: "+numStr);
}
}
int dmg;
String dmgStr = item.getAttribute("dmg");
if (dmgStr.equals(""))
{
dmg = 0;
} else {
try {
dmg = Integer.parseInt(dmgStr);
} catch (NumberFormatException e) {
throw new RuntimeException("Config Error: Expected an integer (-32768 -> 32767) for item damage. Got: "+dmgStr);
}
}
ItemStack stack = new ItemStack(id, num, (short) dmg);
classItems.add(stack);
} else {
// Fetch item pack and add in.
if (!itempacks.containsKey(n.toUpperCase()))
throw new RuntimeException("Config Error: Non-existent item pack: "+n);
classItems.addAll(itempacks.get(n.toUpperCase()));
}
}
new SoldierClass(name, classItems.toArray(new ItemStack[0]), permission);
}
}
// Load Settings
NodeList settings = root.getElementsByTagName("settings");
for (int i = 0; i < settings.getLength(); i++)
{
Node nnnn = settings.item(i);
Element section = (Element) nnnn;
NodeList tags = section.getElementsByTagName("setting");
for (int j = 0; j < tags.getLength(); j++)
{
Element setting = (Element) tags.item(j);
String name = setting.getAttribute("name");
String value = setting.getAttribute("value");
if (name.equals(""))
throw new RuntimeException("Please include a name attribute for all setting tags in config.xml");
this.settings.put(name, value);
}
}
// Load Traps
NodeList traps = root.getElementsByTagName("traps");
for (int i = 0; i < traps.getLength(); i++)
{
Element section = (Element) settings.item(i);
NodeList trapList = section.getElementsByTagName("trap");
for (int j = 0; j < trapList.getLength(); j++)
{
Element trap = (Element) trapList.item(j);
String name = trap.getAttribute("name");
if (name.equals("")) throw new RuntimeException("All traps must have a name.");
TrapCallback call = createCallbackFromXML(trap);
trapMap.put(name.toUpperCase(), call);
}
}
// Load accounts
File accountsFile = new File(getDataFolder(), "items.dat");
if (accountsFile.isDirectory())
accountsFile.delete();
if (!accountsFile.exists())
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile));
out.writeObject(new HashMap<String, List<SerializableItemStack>>());
out.close();
}
try {
// TODO: Fix race condition, so that checking and opening is atomic
ObjectInputStream in = new ObjectInputStream(new FileInputStream(accountsFile));
@SuppressWarnings("unchecked")
Map<String, List<SerializableItemStack>> read = (Map<String, List<SerializableItemStack>>) in.readObject();
in.close();
// Begin translation
for (String s : read.keySet())
{
itemsAccountableMap.put(s, SerializableItemStack.toList(read.get(s)));
}
} catch (Throwable t) {
accountsFile.delete();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile));
out.writeObject(new HashMap<String, List<SerializableItemStack>>());
out.close();
System.err.println("Please restart the server. A data file has been corrupted.");
throw new RuntimeException(t);
}
}
}
| true | true | public void onEnable()
{
// TODO: Implement all commands
registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
for (String key : helpMap.keySet())
{
sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key+" - "+synColor(ChatColor.AQUA)+helpMap.get(key));
}
}
});
registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command.")));
return;
}
// TODO: Finish
}
});
registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /"+args[0]+" <teamname>")));
return;
}
Team t = Team.getTeam(args[1]);
Team yours = null;
for (Team te : Team.list())
{
if (te.containsPlayer(sender.getName().toUpperCase()))
{
yours = te;
}
}
if (yours == null)
{
sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>")));
return;
}
if (!sender.getName().equalsIgnoreCase(yours.getOwner()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
for (RoundController rc : rounds)
{
if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable())
{
rc.getConfig().addTeam(yours);
}
}
}
});
registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() {
@Override
public void onCommand(final CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("war_perm", "stalemate.start")))
{
sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>"));
return;
}
RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){
@Override
public Object call() throws Exception {
for (RoundController r : rounds) {
if (r.getPlayers().contains(sender.getName().toUpperCase()))
{
for (String p : r.getPlayers())
{
List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase());
Player pl = Stalemate.this.getServer().getPlayer(p);
Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0]));
acct.clear();
acct.addAll(failed.values());
noChange.remove(p.toUpperCase());
}
break;
}
}
return null;
}});
initRound(rnd);
Team yours = null;
for (Team t : Team.list())
{
if (t.containsPlayer(sender.getName()))
{
yours = t;
break;
}
}
if (!yours.getOwner().equalsIgnoreCase(sender.getName()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
rnd.getConfig().addTeam(yours);
}
});
registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap or removes one if already here."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
assert(args.length > 0);
if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
if (args.length < 6)
{
sender.sendMessage(getSetting("syntax_trap_console_msg", "Syntax: "+args[0]+" <world> <x> <y> <z>"));
return;
}
World w;
int x, y, z;
String trapName;
try {
w = getServer().getWorld(args[1]);
if (w == null) {
sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World."));
return;
}
x = Integer.parseInt(args[2]);
y = Integer.parseInt(args[3]);
z = Integer.parseInt(args[4]);
trapName = args[5];
} catch (NumberFormatException e) {
sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z."));
return;
}
placeTrap(trapName, new Location(w, x, y, z));
sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed."));
} else {
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /"+args[0]+" <trap_type>")));
return;
}
Player p = (Player) sender;
String trapName = args[1];
placeTrap(trapName, p.getLocation());
sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed.")));
}
}
});
registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_perm", "stalemate.join")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (args.length < 2) {
sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>")));
Team yours = null;
for (Team tt : Team.list())
{
if (tt.containsPlayer(sender.getName()))
{
yours = tt;
break;
}
}
sender.sendMessage("Your current team is: "+yours.getName());
return;
}
Player target = getServer().getPlayer(args[1]);
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command."));
return;
}
for (Team t : Team.list())
{
// TODO: Use linear search or hashing
if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0)
{
join(t, (Player) sender);
sender.sendMessage(parseColors(getSetting("join_success_msg", "Success.")));
return;
}
}
Team x = new Team(args[1]);
join(x, (Player) sender);
}
});
registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this feature."));
return;
}
for (RoundController rc : rounds)
{
if (rc.getPlayers().contains(sender.getName().toUpperCase()))
{
List<Team> teams = rc.getConfig().getParticipatingTeams();
for (Team t : teams)
if (t.removePlayer(sender.getName())) break;
}
}
}
});
registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this command."));
return;
}
if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple"))
{
sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it.")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /"+args[0]+" <classname>")));
return;
}
SoldierClass s = SoldierClass.fromName(args[1]);
if (!sender.hasPermission(s.getPermission()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class.")));
return;
}
ItemStack[] give = s.getItems();
List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account;
for (ItemStack i : give)
account.add(i.clone());
Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give);
account.removeAll(failed.values());
}
});
try {
onEnable0();
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate.");
e.printStackTrace(new PrintWriter(new LoggerOutputStream(getLogger(), Level.SEVERE)));
}
asyncUpdateThread.start();
getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!");
}
| public void onEnable()
{
// TODO: Implement all commands
registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
for (String key : helpMap.keySet())
{
sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key+" - "+synColor(ChatColor.AQUA)+helpMap.get(key));
}
}
});
registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command.")));
return;
}
// TODO: Finish
}
});
registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /"+args[0]+" <teamname>")));
return;
}
Team t = Team.getTeam(args[1]);
Team yours = null;
for (Team te : Team.list())
{
if (te.containsPlayer(sender.getName().toUpperCase()))
{
yours = te;
}
}
if (yours == null)
{
sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>")));
return;
}
if (!sender.getName().equalsIgnoreCase(yours.getOwner()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
for (RoundController rc : rounds)
{
if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable())
{
rc.getConfig().addTeam(yours);
}
}
}
});
registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() {
@Override
public void onCommand(final CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("war_perm", "stalemate.start")))
{
sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>"));
return;
}
RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){
@Override
public Object call() throws Exception {
for (RoundController r : rounds) {
if (r.getPlayers().contains(sender.getName().toUpperCase()))
{
for (String p : r.getPlayers())
{
List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase());
Player pl = Stalemate.this.getServer().getPlayer(p);
Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0]));
acct.clear();
acct.addAll(failed.values());
noChange.remove(p.toUpperCase());
}
break;
}
}
return null;
}});
initRound(rnd);
Team yours = null;
for (Team t : Team.list())
{
if (t.containsPlayer(sender.getName()))
{
yours = t;
break;
}
}
if (!yours.getOwner().equalsIgnoreCase(sender.getName()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
rnd.getConfig().addTeam(yours);
}
});
registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap or removes one if already here."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
assert(args.length > 0);
if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
if (args.length < 6)
{
sender.sendMessage(getSetting("syntax_trap_console_msg", "Syntax: "+args[0]+" <world> <x> <y> <z>"));
return;
}
World w;
int x, y, z;
String trapName;
try {
w = getServer().getWorld(args[1]);
if (w == null) {
sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World."));
return;
}
x = Integer.parseInt(args[2]);
y = Integer.parseInt(args[3]);
z = Integer.parseInt(args[4]);
trapName = args[5];
} catch (NumberFormatException e) {
sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z."));
return;
}
placeTrap(trapName, new Location(w, x, y, z));
sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed."));
} else {
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /"+args[0]+" <trap_type>")));
return;
}
Player p = (Player) sender;
String trapName = args[1];
placeTrap(trapName, p.getLocation());
sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed.")));
}
}
});
registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("join_perm", "stalemate.join")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (args.length < 2) {
sender.sendMessage(parseColors(getSetting("syntax_join_msg", "/stalemate "+args[0]+" <player> or to create a team: /stalemate "+args[0]+" <teamname>")));
Team yours = null;
for (Team tt : Team.list())
{
if (tt.containsPlayer(sender.getName()))
{
yours = tt;
break;
}
}
sender.sendMessage("Your current team is: "+yours.getName());
return;
}
Player target = getServer().getPlayer(args[1]);
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command."));
return;
}
for (Team t : Team.list())
{
// TODO: Use linear search or hashing
if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0)
{
join(t, (Player) sender);
sender.sendMessage(parseColors(getSetting("join_success_msg", "Success.")));
return;
}
}
Team x = new Team(args[1]);
join(x, (Player) sender);
}
});
registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this feature."));
return;
}
for (RoundController rc : rounds)
{
if (rc.getPlayers().contains(sender.getName().toUpperCase()))
{
List<Team> teams = rc.getConfig().getParticipatingTeams();
for (Team t : teams)
if (t.removePlayer(sender.getName())) break;
}
}
}
});
registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() {
@Override
public void onCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player))
{
sender.sendMessage(getSetting("players_only_msg", "Only players may use this command."));
return;
}
if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass")))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>")));
return;
}
if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple"))
{
sender.sendMessage(parseColors(getSetting("class_nochange", "You may not change your class once you have selected it.")));
return;
}
if (args.length < 2)
{
sender.sendMessage(parseColors(getSetting("class_syntax", "Syntax: /"+args[0]+" <classname>")));
return;
}
SoldierClass s = SoldierClass.fromName(args[1]);
if (!sender.hasPermission(s.getPermission()))
{
sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class.")));
return;
}
ItemStack[] give = s.getItems();
List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account;
for (ItemStack i : give)
account.add(i.clone());
Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give);
account.removeAll(failed.values());
}
});
try {
onEnable0();
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate.");
e.printStackTrace();
}
asyncUpdateThread.start();
getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!");
}
|
diff --git a/src/main/java/net/sf/webdav/methods/DoLock.java b/src/main/java/net/sf/webdav/methods/DoLock.java
index 0bdd90e..1bd2f2d 100644
--- a/src/main/java/net/sf/webdav/methods/DoLock.java
+++ b/src/main/java/net/sf/webdav/methods/DoLock.java
@@ -1,593 +1,594 @@
/*
* Copyright 1999,2004 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 net.sf.webdav.methods;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import net.sf.webdav.ITransaction;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.exceptions.LockFailedException;
import net.sf.webdav.exceptions.WebdavException;
import net.sf.webdav.fromcatalina.XMLWriter;
import net.sf.webdav.locking.IResourceLocks;
import net.sf.webdav.locking.LockedObject;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class DoLock extends AbstractMethod {
private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory
.getLogger(DoLock.class);
private IWebdavStore _store;
private IResourceLocks _resourceLocks;
private boolean _readOnly;
private boolean _macLockRequest = false;
private boolean _exclusive = false;
private String _type = null;
private String _lockOwner = null;
private String _path = null;
private String _parentPath = null;
private String _userAgent = null;
public DoLock(IWebdavStore store, IResourceLocks resourceLocks,
boolean readOnly) {
_store = store;
_resourceLocks = resourceLocks;
_readOnly = readOnly;
}
public void execute(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
LOG.trace("-- " + this.getClass().getName());
if (_readOnly) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
return;
} else {
_path = getRelativePath(req);
_parentPath = getParentPath(getCleanPath(_path));
Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
if (!checkLocks(transaction, req, resp, _resourceLocks, _path)) {
errorList.put(_path, WebdavStatus.SC_LOCKED);
sendReport(req, resp, errorList);
return; // resource is locked
}
if (!checkLocks(transaction, req, resp, _resourceLocks, _parentPath)) {
errorList.put(_parentPath, WebdavStatus.SC_LOCKED);
sendReport(req, resp, errorList);
return; // parent is locked
}
// Mac OS Finder (whether 10.4.x or 10.5) can't store files
// because executing a LOCK without lock information causes a
// SC_BAD_REQUEST
_userAgent = req.getHeader("User-Agent");
if (_userAgent != null && _userAgent.indexOf("Darwin") != -1) {
_macLockRequest = true;
String timeString = new Long(System.currentTimeMillis())
.toString();
_lockOwner = _userAgent.concat(timeString);
}
String tempLockOwner = "doLock" + System.currentTimeMillis()
+ req.toString();
if (_resourceLocks.lock(transaction, _path, tempLockOwner, false,
0, TEMP_TIMEOUT, TEMPORARY)) {
try {
if (req.getHeader("If") != null) {
doRefreshLock(transaction, req, resp);
} else {
doLock(transaction, req, resp);
}
} catch (LockFailedException e) {
resp.sendError(WebdavStatus.SC_LOCKED);
e.printStackTrace();
} finally {
_resourceLocks.unlockTemporaryLockedObjects(transaction,
_path, tempLockOwner);
}
}
}
}
private void doLock(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
StoredObject so = _store.getStoredObject(transaction, _path);
if (so != null) {
doLocking(transaction, req, resp);
} else {
// resource doesn't exist, null-resource lock
doNullResourceLock(transaction, req, resp);
}
so = null;
_exclusive = false;
_type = null;
_lockOwner = null;
}
private void doLocking(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException {
// Tests if LockObject on requested path exists, and if so, tests
// exclusivity
LockedObject lo = _resourceLocks.getLockedObjectByPath(transaction,
_path);
if (lo != null) {
if (lo.isExclusive()) {
sendLockFailError(transaction, req, resp);
return;
}
}
try {
// Thats the locking itself
executeLock(transaction, req, resp);
} catch (ServletException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
LOG.trace(e.toString());
} catch (LockFailedException e) {
sendLockFailError(transaction, req, resp);
} finally {
lo = null;
}
}
private void doNullResourceLock(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws IOException {
StoredObject parentSo, nullSo = null;
try {
parentSo = _store.getStoredObject(transaction, _parentPath);
if (_parentPath != null && parentSo == null) {
_store.createFolder(transaction, _parentPath);
} else if (_parentPath != null && parentSo != null
&& parentSo.isResource()) {
resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
return;
}
nullSo = _store.getStoredObject(transaction, _path);
if (nullSo == null) {
// resource doesn't exist
_store.createResource(transaction, _path);
// Transmit expects 204 response-code, not 201
if (_userAgent != null && _userAgent.indexOf("Transmit") != -1) {
LOG
.trace("DoLock.execute() : do workaround for user agent '"
+ _userAgent + "'");
resp.setStatus(WebdavStatus.SC_NO_CONTENT);
} else {
resp.setStatus(WebdavStatus.SC_CREATED);
}
} else {
// resource already exists, could not execute null-resource lock
sendLockFailError(transaction, req, resp);
return;
}
nullSo = _store.getStoredObject(transaction, _path);
// define the newly created resource as null-resource
nullSo.setNullResource(true);
// Thats the locking itself
executeLock(transaction, req, resp);
} catch (LockFailedException e) {
sendLockFailError(transaction, req, resp);
} catch (WebdavException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
} catch (ServletException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
} finally {
parentSo = null;
nullSo = null;
}
}
private void doRefreshLock(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws IOException, LockFailedException {
String[] lockTokens = getLockIdFromIfHeader(req);
String lockToken = null;
if (lockTokens != null)
lockToken = lockTokens[0];
if (lockToken != null) {
// Getting LockObject of specified lockToken in If header
LockedObject refreshLo = _resourceLocks.getLockedObjectByID(
transaction, lockToken);
if (refreshLo != null) {
int timeout = getTimeout(transaction, req);
refreshLo.refreshTimeout(timeout);
// sending success response
generateXMLReport(transaction, resp, refreshLo);
refreshLo = null;
} else {
// no LockObject to given lockToken
resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
}
} else {
resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED);
}
}
// ------------------------------------------------- helper methods
/**
* Executes the LOCK
*/
private void executeLock(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws LockFailedException, IOException,
ServletException {
// Mac OS lock request workaround
if (_macLockRequest) {
LOG.trace("DoLock.execute() : do workaround for user agent '"
+ _userAgent + "'");
doMacLockRequestWorkaround(transaction, req, resp);
} else {
// Getting LockInformation from request
if (getLockInformation(transaction, req, resp)) {
int depth = getDepth(req);
int lockDuration = getTimeout(transaction, req);
boolean lockSuccess = false;
if (_exclusive) {
lockSuccess = _resourceLocks.exclusiveLock(transaction,
_path, _lockOwner, depth, lockDuration);
} else {
lockSuccess = _resourceLocks.sharedLock(transaction, _path,
_lockOwner, depth, lockDuration);
}
if (lockSuccess) {
// Locks successfully placed - return information about
LockedObject lo = _resourceLocks.getLockedObjectByPath(
transaction, _path);
if (lo != null) {
generateXMLReport(transaction, resp, lo);
} else {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
}
} else {
sendLockFailError(transaction, req, resp);
throw new LockFailedException();
}
} else {
// information for LOCK could not be read successfully
resp.setContentType("text/xml; charset=UTF-8");
resp.sendError(WebdavStatus.SC_BAD_REQUEST);
}
}
}
/**
* Tries to get the LockInformation from LOCK request
*/
private boolean getLockInformation(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Node lockInfoNode = null;
DocumentBuilder documentBuilder = null;
documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder.parse(new InputSource(req
.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
lockInfoNode = rootElement;
if (lockInfoNode != null) {
NodeList childList = lockInfoNode.getChildNodes();
Node lockScopeNode = null;
Node lockTypeNode = null;
Node lockOwnerNode = null;
Node currentNode = null;
String nodeName = null;
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE
|| currentNode.getNodeType() == Node.TEXT_NODE) {
nodeName = currentNode.getNodeName();
if (nodeName.endsWith("locktype")) {
lockTypeNode = currentNode;
}
if (nodeName.endsWith("lockscope")) {
lockScopeNode = currentNode;
}
if (nodeName.endsWith("owner")) {
lockOwnerNode = currentNode;
}
} else {
return false;
}
}
if (lockScopeNode != null) {
String scope = null;
childList = lockScopeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
scope = currentNode.getNodeName();
if (scope.endsWith("exclusive")) {
_exclusive = true;
} else if (scope.equals("shared")) {
_exclusive = false;
}
}
}
if (scope == null) {
return false;
}
} else {
return false;
}
if (lockTypeNode != null) {
childList = lockTypeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
_type = currentNode.getNodeName();
if (_type.endsWith("write")) {
_type = "write";
} else if (_type.equals("read")) {
_type = "read";
}
}
}
if (_type == null) {
return false;
}
} else {
return false;
}
if (lockOwnerNode != null) {
childList = lockOwnerNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
- _lockOwner = currentNode.getNodeValue();
+ _lockOwner = currentNode.getFirstChild()
+ .getNodeValue();
}
}
}
if (_lockOwner == null) {
return false;
}
} else {
return false;
}
} catch (DOMException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
} catch (SAXException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
}
return true;
}
/**
* Ties to read the timeout from request
*/
private int getTimeout(ITransaction transaction, HttpServletRequest req) {
int lockDuration = DEFAULT_TIMEOUT;
String lockDurationStr = req.getHeader("Timeout");
if (lockDurationStr == null) {
lockDuration = DEFAULT_TIMEOUT;
} else {
int commaPos = lockDurationStr.indexOf(',');
// if multiple timeouts, just use the first one
if (commaPos != -1) {
lockDurationStr = lockDurationStr.substring(0, commaPos);
}
if (lockDurationStr.startsWith("Second-")) {
lockDuration = new Integer(lockDurationStr.substring(7))
.intValue();
} else {
if (lockDurationStr.equalsIgnoreCase("infinity")) {
lockDuration = MAX_TIMEOUT;
} else {
try {
lockDuration = new Integer(lockDurationStr).intValue();
} catch (NumberFormatException e) {
lockDuration = MAX_TIMEOUT;
}
}
}
if (lockDuration <= 0) {
lockDuration = DEFAULT_TIMEOUT;
}
if (lockDuration > MAX_TIMEOUT) {
lockDuration = MAX_TIMEOUT;
}
}
return lockDuration;
}
/**
* Generates the response XML with all lock information
*/
private void generateXMLReport(ITransaction transaction,
HttpServletResponse resp, LockedObject lo) throws IOException {
HashMap<String, String> namespaces = new HashMap<String, String>();
namespaces.put("DAV:", "D");
resp.setStatus(WebdavStatus.SC_OK);
resp.setContentType("text/xml; charset=UTF-8");
XMLWriter generatedXML = new XMLWriter(resp.getWriter(), namespaces);
generatedXML.writeXMLHeader();
generatedXML.writeElement("DAV::prop", XMLWriter.OPENING);
generatedXML.writeElement("DAV::lockdiscovery", XMLWriter.OPENING);
generatedXML.writeElement("DAV::activelock", XMLWriter.OPENING);
generatedXML.writeElement("DAV::locktype", XMLWriter.OPENING);
generatedXML.writeProperty("DAV::" + _type);
generatedXML.writeElement("DAV::locktype", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::lockscope", XMLWriter.OPENING);
if (_exclusive) {
generatedXML.writeProperty("DAV::exclusive");
} else {
generatedXML.writeProperty("DAV::shared");
}
generatedXML.writeElement("DAV::lockscope", XMLWriter.CLOSING);
int depth = lo.getLockDepth();
generatedXML.writeElement("DAV::depth", XMLWriter.OPENING);
if (depth == INFINITY) {
generatedXML.writeText("Infinity");
} else {
generatedXML.writeText(String.valueOf(depth));
}
generatedXML.writeElement("DAV::depth", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::owner", XMLWriter.OPENING);
generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
generatedXML.writeText(_lockOwner);
generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::owner", XMLWriter.CLOSING);
long timeout = lo.getTimeoutMillis();
generatedXML.writeElement("DAV::timeout", XMLWriter.OPENING);
generatedXML.writeText("Second-" + timeout / 1000);
generatedXML.writeElement("DAV::timeout", XMLWriter.CLOSING);
String lockToken = lo.getID();
generatedXML.writeElement("DAV::locktoken", XMLWriter.OPENING);
generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
generatedXML.writeText("opaquelocktoken:" + lockToken);
generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::locktoken", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::activelock", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::lockdiscovery", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::prop", XMLWriter.CLOSING);
resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">");
generatedXML.sendData();
}
/**
* Executes the lock for a Mac OS Finder client
*/
private void doMacLockRequestWorkaround(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws LockFailedException, IOException {
LockedObject lo;
int depth = getDepth(req);
int lockDuration = getTimeout(transaction, req);
if (lockDuration < 0 || lockDuration > MAX_TIMEOUT)
lockDuration = DEFAULT_TIMEOUT;
boolean lockSuccess = false;
lockSuccess = _resourceLocks.exclusiveLock(transaction, _path,
_lockOwner, depth, lockDuration);
if (lockSuccess) {
// Locks successfully placed - return information about
lo = _resourceLocks.getLockedObjectByPath(transaction, _path);
if (lo != null) {
generateXMLReport(transaction, resp, lo);
} else {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
}
} else {
// Locking was not successful
sendLockFailError(transaction, req, resp);
}
}
/**
* Sends an error report to the client
*/
private void sendLockFailError(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
errorList.put(_path, WebdavStatus.SC_LOCKED);
sendReport(req, resp, errorList);
}
}
| true | true | private boolean getLockInformation(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Node lockInfoNode = null;
DocumentBuilder documentBuilder = null;
documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder.parse(new InputSource(req
.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
lockInfoNode = rootElement;
if (lockInfoNode != null) {
NodeList childList = lockInfoNode.getChildNodes();
Node lockScopeNode = null;
Node lockTypeNode = null;
Node lockOwnerNode = null;
Node currentNode = null;
String nodeName = null;
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE
|| currentNode.getNodeType() == Node.TEXT_NODE) {
nodeName = currentNode.getNodeName();
if (nodeName.endsWith("locktype")) {
lockTypeNode = currentNode;
}
if (nodeName.endsWith("lockscope")) {
lockScopeNode = currentNode;
}
if (nodeName.endsWith("owner")) {
lockOwnerNode = currentNode;
}
} else {
return false;
}
}
if (lockScopeNode != null) {
String scope = null;
childList = lockScopeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
scope = currentNode.getNodeName();
if (scope.endsWith("exclusive")) {
_exclusive = true;
} else if (scope.equals("shared")) {
_exclusive = false;
}
}
}
if (scope == null) {
return false;
}
} else {
return false;
}
if (lockTypeNode != null) {
childList = lockTypeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
_type = currentNode.getNodeName();
if (_type.endsWith("write")) {
_type = "write";
} else if (_type.equals("read")) {
_type = "read";
}
}
}
if (_type == null) {
return false;
}
} else {
return false;
}
if (lockOwnerNode != null) {
childList = lockOwnerNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
_lockOwner = currentNode.getNodeValue();
}
}
}
if (_lockOwner == null) {
return false;
}
} else {
return false;
}
} catch (DOMException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
} catch (SAXException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
}
return true;
}
| private boolean getLockInformation(ITransaction transaction,
HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Node lockInfoNode = null;
DocumentBuilder documentBuilder = null;
documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder.parse(new InputSource(req
.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
lockInfoNode = rootElement;
if (lockInfoNode != null) {
NodeList childList = lockInfoNode.getChildNodes();
Node lockScopeNode = null;
Node lockTypeNode = null;
Node lockOwnerNode = null;
Node currentNode = null;
String nodeName = null;
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE
|| currentNode.getNodeType() == Node.TEXT_NODE) {
nodeName = currentNode.getNodeName();
if (nodeName.endsWith("locktype")) {
lockTypeNode = currentNode;
}
if (nodeName.endsWith("lockscope")) {
lockScopeNode = currentNode;
}
if (nodeName.endsWith("owner")) {
lockOwnerNode = currentNode;
}
} else {
return false;
}
}
if (lockScopeNode != null) {
String scope = null;
childList = lockScopeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
scope = currentNode.getNodeName();
if (scope.endsWith("exclusive")) {
_exclusive = true;
} else if (scope.equals("shared")) {
_exclusive = false;
}
}
}
if (scope == null) {
return false;
}
} else {
return false;
}
if (lockTypeNode != null) {
childList = lockTypeNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
_type = currentNode.getNodeName();
if (_type.endsWith("write")) {
_type = "write";
} else if (_type.equals("read")) {
_type = "read";
}
}
}
if (_type == null) {
return false;
}
} else {
return false;
}
if (lockOwnerNode != null) {
childList = lockOwnerNode.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
currentNode = childList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
_lockOwner = currentNode.getFirstChild()
.getNodeValue();
}
}
}
if (_lockOwner == null) {
return false;
}
} else {
return false;
}
} catch (DOMException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
} catch (SAXException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
e.printStackTrace();
return false;
}
return true;
}
|
diff --git a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/dnd/QueryBuilder.java b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/dnd/QueryBuilder.java
index dcd02d33..5ba3d8ba 100644
--- a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/dnd/QueryBuilder.java
+++ b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/dnd/QueryBuilder.java
@@ -1,230 +1,230 @@
/*
* License (BSD Style License):
* Copyright (c) 2010
* Author MalteV
* Software Engineering
* Department of Computer Science
* Technische Universit�t Darmstadt
* 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 Software Engineering Group or Technische
* Universit�t Darmstadt 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 de.tud.cs.st.vespucci.diagram.dnd;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import de.tud.cs.st.vespucci.diagram.dnd.JavaType.Resolver;
/**
* A Class which provides static tools for supporting DnD
*
* @author MalteV
* @author BenjaminL
*/
public class QueryBuilder {
// constants for the querybuilder
public final static String PACKAGE = "package";
public final static String CLASS_WITH_MEMBERS = "class_with_members";
public final static String CLASS = "class";
public final static String METHOD = "method";
public final static String FIELD = "field";
private static final String QUERY_DELIMITER = " or ";
private static final String DERIVED = "derived";
private static final String STANDARD_SHAPENAME = "A dynamic name";
/**
* creates a new Query from the data of a drop event
*
* @param map
* data of the drop event
* @return new query
* @author BenjaminL
*/
public static String createQueryForAMapOfIResource(Map<String, Object> map) {
return createQueryForAMapOfIResource(map, "");
}
/**
* creates a new Query from the data of the drop event under consideration
* of the old Query
*
* @param map
* data of the drop event
* @param oldQuery
* old Query of the model element
* @return new query
* @author BenjaminL
*/
public static String createQueryForAMapOfIResource(Map<String, Object> map,
String oldQuery) {
if (oldQuery == null || (oldQuery.equals("empty") && map.size() > 0))
oldQuery = "";
else if (oldQuery.trim().toLowerCase().equals(DERIVED))
return oldQuery;
else if (oldQuery.length() > 0)
oldQuery += QUERY_DELIMITER;
String res = oldQuery;
// translate all DND objects to query
List<String> queries = createQueryFromDNDobjects(map);
// extending the old Query
if (queries != null) {
for (String s : queries) {
res = res + s + "\n" + QUERY_DELIMITER;
}
} else {
}
if (res.endsWith(QUERY_DELIMITER)) // length() >=
// QUERY_DELIMITER.length())
res = res.substring(0, res.length() - QUERY_DELIMITER.length() - 1);
if (res.equals(""))
return res;
else
return res + "\n";
}
/**
* Creates a List that contains for all Java Files in map an entry: e.g.:
* package: package(<PACKAGENAME>) class:
* class_with_members(<PACKAGENAME>,<PACKAGENAME>.<CLASSNAME>) method:
* method(<PACKAGENAME>,<PACKAGENAME>.<CLASSNAME>,'<init>' OR
* <METHODNAME>,<RETURNTYPES>,<PARAMETERTYPES>) field:
* field(<PACKAGENAME>,<PACKAGENAME>.<CLASSNAME>,<FIELDNAME>,<FIELDTYPE>)
*
* @param map
* @return query list
* @author BenjaminL
*/
private static List<String> createQueryFromDNDobjects(
Map<String, Object> map) {
LinkedList<String> list = new LinkedList<String>();
for (String key : map.keySet()) {
Object o = map.get(key);
// package...
if (o instanceof IPackageFragment) {
key = PACKAGE + "('"
+ Resolver.getFQPackageNameFromIxxx(o, key) + "')";
list.add(key);
} else if (o instanceof ICompilationUnit) {
// CLASS
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IMethod) {
// METHOD
IMethod method = (IMethod) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
String methodname = Resolver.getMethodnameFromMethod(method);
List<String> para = Resolver
.getParameterTypesFromMethod(method);
StringBuffer sbPara = new StringBuffer();
String returntype = Resolver.getReturnTypeFromIxxx(method, key);
sbPara.append("[");
for (String s : para) {
sbPara.append("'" + s + "'");
}
sbPara.replace(sbPara.length(), sbPara.length(), "]");
key = METHOD + "('" + packagename + "','" + classname + "','"
+ methodname + "','" + returntype + "',"
+ sbPara.toString() + ")";
list.add(key);
} else if (o instanceof IType) {
// IType
IType type = (IType) o;
ICompilationUnit cU = type.getCompilationUnit();
String packagename = Resolver.getFQPackageNameFromIxxx(cU, key);
String classname = Resolver.getFQClassnamefromIxxx(cU, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IField) {
// FIELD
IField field = (IField) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
- String classname = Resolver.getFQClassnamefromIxxx(o, key);
+ String classname = field.getParent().getElementName();
String fieldname = field.getElementName();
String type = Resolver.getFQFieldTypeName(field);
key = FIELD + "('" + packagename + "','" + classname + "','"
+ fieldname + "','" + type + "')";
list.add(key);
} else if (o instanceof IPackageFragmentRoot) {
List<String> packages = Resolver
.getPackagesFromPFR((IPackageFragmentRoot) o);
for (String s : packages) {
key = PACKAGE + "('" + s + "')";
list.add(key);
}
}
}
return list;
}
/**
* getting the first known object name - else return "A dynamic name"
*
* @param extendedData
* @return name as string
* @author BenjaminL
*/
public static Object createNameforNewEnsemble(Map<?, ?> extendedData) {
// getting the first known object name
for (Object key : extendedData.keySet()) {
Object o = extendedData.get(key);
String tmp = Resolver.getElementNameFromObject(o);
if (!tmp.equals(""))
return tmp;
}
return STANDARD_SHAPENAME;
}
public static boolean isProcessable(Map<String, Object> extendedData) {
return Resolver.isProcessable(extendedData);
}
}
| true | true | private static List<String> createQueryFromDNDobjects(
Map<String, Object> map) {
LinkedList<String> list = new LinkedList<String>();
for (String key : map.keySet()) {
Object o = map.get(key);
// package...
if (o instanceof IPackageFragment) {
key = PACKAGE + "('"
+ Resolver.getFQPackageNameFromIxxx(o, key) + "')";
list.add(key);
} else if (o instanceof ICompilationUnit) {
// CLASS
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IMethod) {
// METHOD
IMethod method = (IMethod) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
String methodname = Resolver.getMethodnameFromMethod(method);
List<String> para = Resolver
.getParameterTypesFromMethod(method);
StringBuffer sbPara = new StringBuffer();
String returntype = Resolver.getReturnTypeFromIxxx(method, key);
sbPara.append("[");
for (String s : para) {
sbPara.append("'" + s + "'");
}
sbPara.replace(sbPara.length(), sbPara.length(), "]");
key = METHOD + "('" + packagename + "','" + classname + "','"
+ methodname + "','" + returntype + "',"
+ sbPara.toString() + ")";
list.add(key);
} else if (o instanceof IType) {
// IType
IType type = (IType) o;
ICompilationUnit cU = type.getCompilationUnit();
String packagename = Resolver.getFQPackageNameFromIxxx(cU, key);
String classname = Resolver.getFQClassnamefromIxxx(cU, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IField) {
// FIELD
IField field = (IField) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
String fieldname = field.getElementName();
String type = Resolver.getFQFieldTypeName(field);
key = FIELD + "('" + packagename + "','" + classname + "','"
+ fieldname + "','" + type + "')";
list.add(key);
} else if (o instanceof IPackageFragmentRoot) {
List<String> packages = Resolver
.getPackagesFromPFR((IPackageFragmentRoot) o);
for (String s : packages) {
key = PACKAGE + "('" + s + "')";
list.add(key);
}
}
}
return list;
}
| private static List<String> createQueryFromDNDobjects(
Map<String, Object> map) {
LinkedList<String> list = new LinkedList<String>();
for (String key : map.keySet()) {
Object o = map.get(key);
// package...
if (o instanceof IPackageFragment) {
key = PACKAGE + "('"
+ Resolver.getFQPackageNameFromIxxx(o, key) + "')";
list.add(key);
} else if (o instanceof ICompilationUnit) {
// CLASS
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IMethod) {
// METHOD
IMethod method = (IMethod) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = Resolver.getFQClassnamefromIxxx(o, key);
String methodname = Resolver.getMethodnameFromMethod(method);
List<String> para = Resolver
.getParameterTypesFromMethod(method);
StringBuffer sbPara = new StringBuffer();
String returntype = Resolver.getReturnTypeFromIxxx(method, key);
sbPara.append("[");
for (String s : para) {
sbPara.append("'" + s + "'");
}
sbPara.replace(sbPara.length(), sbPara.length(), "]");
key = METHOD + "('" + packagename + "','" + classname + "','"
+ methodname + "','" + returntype + "',"
+ sbPara.toString() + ")";
list.add(key);
} else if (o instanceof IType) {
// IType
IType type = (IType) o;
ICompilationUnit cU = type.getCompilationUnit();
String packagename = Resolver.getFQPackageNameFromIxxx(cU, key);
String classname = Resolver.getFQClassnamefromIxxx(cU, key);
key = CLASS_WITH_MEMBERS + "('" + packagename + "','"
+ classname + "')";
list.add(key);
} else if (o instanceof IField) {
// FIELD
IField field = (IField) o;
String packagename = Resolver.getFQPackageNameFromIxxx(o, key);
String classname = field.getParent().getElementName();
String fieldname = field.getElementName();
String type = Resolver.getFQFieldTypeName(field);
key = FIELD + "('" + packagename + "','" + classname + "','"
+ fieldname + "','" + type + "')";
list.add(key);
} else if (o instanceof IPackageFragmentRoot) {
List<String> packages = Resolver
.getPackagesFromPFR((IPackageFragmentRoot) o);
for (String s : packages) {
key = PACKAGE + "('" + s + "')";
list.add(key);
}
}
}
return list;
}
|
diff --git a/rdt/org.eclipse.ptp.rdt.core/src/org/eclipse/ptp/internal/rdt/core/navigation/RemoteNavigationService.java b/rdt/org.eclipse.ptp.rdt.core/src/org/eclipse/ptp/internal/rdt/core/navigation/RemoteNavigationService.java
index ad4261096..73b95099a 100644
--- a/rdt/org.eclipse.ptp.rdt.core/src/org/eclipse/ptp/internal/rdt/core/navigation/RemoteNavigationService.java
+++ b/rdt/org.eclipse.ptp.rdt.core/src/org/eclipse/ptp/internal/rdt/core/navigation/RemoteNavigationService.java
@@ -1,50 +1,57 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM - Initial API and implementation
*******************************************************************************/
package org.eclipse.ptp.internal.rdt.core.navigation;
import java.util.List;
import org.eclipse.cdt.core.dom.IName;
import org.eclipse.cdt.core.model.ITranslationUnit;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ptp.internal.rdt.core.RemoteScannerInfoProviderFactory;
import org.eclipse.ptp.internal.rdt.core.model.Scope;
import org.eclipse.ptp.internal.rdt.core.model.TranslationUnit;
import org.eclipse.ptp.internal.rdt.core.serviceproviders.AbstractRemoteService;
import org.eclipse.ptp.internal.rdt.core.subsystems.ICIndexSubsystem;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.core.subsystems.IConnectorService;
/**
* @author Mike Kucera
*
*/
public class RemoteNavigationService extends AbstractRemoteService implements INavigationService {
public RemoteNavigationService(IHost host, IConnectorService connectorService) {
super(host, connectorService);
}
public OpenDeclarationResult openDeclaration(Scope scope, ITranslationUnit unit, String selectedText, int selectionStart, int selectionLength, IProgressMonitor monitor) {
// go to the subsystem
ICIndexSubsystem subsystem = getSubSystem();
if(unit instanceof TranslationUnit) {
- IScannerInfo scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getResource());
+ IScannerInfo scannerInfo = null;
+ if(unit.getResource() == null) {
+ // external translation unit... get scanner info from the context?
+ scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getCProject().getProject());
+ }
+ else {
+ scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getResource());
+ }
((TranslationUnit)unit).setASTContext(scannerInfo);
}
return subsystem.openDeclaration(scope, unit, selectedText, selectionStart, selectionLength, monitor);
}
}
| true | true | public OpenDeclarationResult openDeclaration(Scope scope, ITranslationUnit unit, String selectedText, int selectionStart, int selectionLength, IProgressMonitor monitor) {
// go to the subsystem
ICIndexSubsystem subsystem = getSubSystem();
if(unit instanceof TranslationUnit) {
IScannerInfo scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getResource());
((TranslationUnit)unit).setASTContext(scannerInfo);
}
return subsystem.openDeclaration(scope, unit, selectedText, selectionStart, selectionLength, monitor);
}
| public OpenDeclarationResult openDeclaration(Scope scope, ITranslationUnit unit, String selectedText, int selectionStart, int selectionLength, IProgressMonitor monitor) {
// go to the subsystem
ICIndexSubsystem subsystem = getSubSystem();
if(unit instanceof TranslationUnit) {
IScannerInfo scannerInfo = null;
if(unit.getResource() == null) {
// external translation unit... get scanner info from the context?
scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getCProject().getProject());
}
else {
scannerInfo = RemoteScannerInfoProviderFactory.getScannerInfo(unit.getResource());
}
((TranslationUnit)unit).setASTContext(scannerInfo);
}
return subsystem.openDeclaration(scope, unit, selectedText, selectionStart, selectionLength, monitor);
}
|
diff --git a/src/main/java/hudson/plugins/svn_tag/SvnTagPlugin.java b/src/main/java/hudson/plugins/svn_tag/SvnTagPlugin.java
index 9ddb283..3a51a2a 100644
--- a/src/main/java/hudson/plugins/svn_tag/SvnTagPlugin.java
+++ b/src/main/java/hudson/plugins/svn_tag/SvnTagPlugin.java
@@ -1,310 +1,312 @@
package hudson.plugins.svn_tag;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.scm.SubversionSCM;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.tmatesoft.svn.core.SVNCommitInfo;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.wc.SVNCommitClient;
import org.tmatesoft.svn.core.wc.SVNCopyClient;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
/**
* Consolidates the work common in Publisher and MavenReporter.
*
* @author Kenji Nakamura
*/
@SuppressWarnings({"UtilityClass", "ImplicitCallToSuper", "MethodReturnOfConcreteClass", "MethodParameterOfConcreteClass", "InstanceofInterfaces", "unchecked"})
public class SvnTagPlugin {
/**
* Description appeared in configuration screen.
*/
public static final String DESCRIPTION =
"Perform Subversion tagging on successful build";
/**
* The prefix to identify jelly variables for this plugin.
*/
public static final String CONFIG_PREFIX = "svntag.";
/**
* Creates a new SvnTagPlugin object.
*/
private SvnTagPlugin() {
}
/**
* Returns the root project value.
*
* @param project the given project value.
* @return the root project value.
*/
@SuppressWarnings({"MethodParameterOfConcreteClass"})
private static AbstractProject getRootProject(AbstractProject project) {
//noinspection InstanceofInterfaces
if (project.getParent() instanceof Hudson) {
return project;
} else {
//noinspection CastToConcreteClass
return getRootProject((AbstractProject) project.getParent());
}
}
/**
* True if the operation was successful.
*
* @param abstractBuild build
* @param launcher launcher
* @param buildListener build listener
* @param tagBaseURLStr tag base URL string
* @param tagComment tag comment
* @return true if the operation was successful
*/
@SuppressWarnings({"FeatureEnvy", "UnusedDeclaration", "TypeMayBeWeakened", "LocalVariableOfConcreteClass"})
public static boolean perform(AbstractBuild abstractBuild,
Launcher launcher,
BuildListener buildListener,
String tagBaseURLStr, String tagComment) {
PrintStream logger = buildListener.getLogger();
if (!Result.SUCCESS.equals(abstractBuild.getResult())) {
logger.println("No Subversion tagging for unsuccessful build. ");
return true;
}
AbstractProject<?, ?> rootProject =
getRootProject(abstractBuild.getProject());
Map<String, String> env;
if (!(rootProject.getScm() instanceof SubversionSCM)) {
logger.println("SvnTag plugin doesn't support tagging for SCM " +
rootProject.getScm().toString() + ".");
return true;
}
SubversionSCM scm = SubversionSCM.class.cast(rootProject.getScm());
env = abstractBuild.getEnvVars();
// Let SubversionSCM fill revision number.
// It is guaranteed for getBuilds() return the latest build (i.e.
// current build) at first
// The passed in abstractBuild may be the sub maven module and not
// have revision.txt holding Svn revision information, so need to use
// the build associated with the root level project.
scm.buildEnvVars(rootProject.getBuilds().get(0), env);
SubversionSCM.ModuleLocation[] moduleLocations = scm.getLocations();
// environment variable "SVN_REVISION" doesn't contain revision number when multiple modules are
// specified. Instead, parse revision.txt and obtain the corresponding revision numbers.
Map<String, Long> revisions;
try {
revisions = parseRevisionFile(abstractBuild);
} catch (IOException e) {
logger.println("Failed to parse revision.txt. " + e.getLocalizedMessage());
return false;
}
ISVNAuthenticationProvider sap = scm.getDescriptor().createAuthenticationProvider();
if (sap == null) {
logger.println("Subversion authentication info is not set.");
return false;
}
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(sap);
String emptyDirName = System.getProperty("java.io.tmpdir") + "/hudson/svn_tag/emptyDir";
File emptyDir = new File(emptyDirName);
try {
if (emptyDir.exists()) {
FileUtils.forceDelete(emptyDir);
}
FileUtils.forceMkdir(emptyDir);
FileUtils.forceDeleteOnExit(emptyDir);
} catch (IOException e) {
logger.println("Failed to create an empty directory used to create intermediate directories." + e.getLocalizedMessage());
return false;
}
SVNCommitClient commitClient = new SVNCommitClient(sam, null);
for (SubversionSCM.ModuleLocation ml : moduleLocations) {
logger.println("moduleLocation: Remote ->" + ml.remote);
List locationPathElements = Arrays.asList(StringUtils.split(ml.remote, "/"));
String evaledTagBaseURLStr = evalGroovyExpression(env, tagBaseURLStr, locationPathElements);
URI repoURI;
try {
repoURI = new URI(ml.remote);
} catch (URISyntaxException e) {
logger.println("Failed to parse SVN repo URL. " + e.getLocalizedMessage());
return false;
}
SVNURL parsedTagBaseURL = null;
+ SVNURL parsedTagBaseParentURL = null;
try {
parsedTagBaseURL = SVNURL.parseURIEncoded(repoURI.resolve(evaledTagBaseURLStr).toString());
+ parsedTagBaseParentURL = SVNURL.parseURIEncoded(repoURI.resolve(evaledTagBaseURLStr + "/..").toString());
logger.println("Tag Base URL: '" + parsedTagBaseURL.toString() + "'.");
} catch (SVNException e) {
logger.println("Failed to parse tag base URL '" + evaledTagBaseURLStr + "'. " + e.getLocalizedMessage());
}
try {
SVNCommitInfo deleteInfo =
commitClient.doDelete(new SVNURL[]{parsedTagBaseURL},
"Delete old tag by SvnTag Hudson plugin.");
SVNErrorMessage deleteErrMsg = deleteInfo.getErrorMessage();
if (null != deleteErrMsg) {
logger.println(deleteErrMsg.getMessage());
} else {
logger.println("Delete old tag " + evaledTagBaseURLStr + ".");
}
} catch (SVNException e) {
logger.println("There was no old tag at " + evaledTagBaseURLStr + ".");
}
SVNCommitInfo mkdirInfo = null;
try {
// commtClient.doMkDir doesn't support "-parent" option available in svn command.
// Import an empty directory to create intermediate directories.
// mkdirInfo = commitClient.doMkDir(new SVNURL[]{parsedTagBaseURL},
// "Created by SvnTag Hudson plugin.");
- mkdirInfo = commitClient.doImport(emptyDir, parsedTagBaseURL, "Created by SvnTag Hudson plugin.", false);
+ mkdirInfo = commitClient.doImport(emptyDir, parsedTagBaseParentURL, "Created by SvnTag Hudson plugin.", false);
} catch (SVNException e) {
- logger.println("Failed to create a directory '" + parsedTagBaseURL.toString() + "'.");
+ logger.println("Failed to create a directory '" + parsedTagBaseParentURL.toString() + "'.");
return false;
}
SVNErrorMessage mkdirErrMsg = mkdirInfo.getErrorMessage();
if (null != mkdirErrMsg) {
logger.println(mkdirErrMsg.getMessage());
return false;
}
SVNCopyClient copyClient = new SVNCopyClient(sam, null);
try {
String evalComment = evalGroovyExpression((Map<String, String>) abstractBuild.getEnvVars(), tagComment, locationPathElements);
SVNCommitInfo commitInfo =
copyClient.doCopy(SVNURL.parseURIEncoded(ml.remote),
SVNRevision.create(Long.valueOf(revisions.get(ml.remote))),
parsedTagBaseURL, false,
false, evalComment);
SVNErrorMessage errorMsg = commitInfo.getErrorMessage();
if (null != errorMsg) {
logger.println(errorMsg.getFullMessage());
return false;
} else {
logger.println("Tagged as Revision " +
commitInfo.getNewRevision());
}
} catch (SVNException e) {
logger.println("Subversion copy failed. " +
e.getLocalizedMessage());
return false;
}
}
return true;
}
@SuppressWarnings({"StaticMethodOnlyUsedInOneClass", "TypeMayBeWeakened"})
static String evalGroovyExpression(Map<String, String> env, String evalText, List locationPathElements) {
Binding binding = new Binding();
binding.setVariable("env", env);
binding.setVariable("sys", System.getProperties());
if (locationPathElements == null) {
binding.setVariable("repoURL", Arrays.asList(StringUtils.split("http://svn.example.com/path1/path2/path3/path4/path5/path6/path7/path8/path9/path10"), "/"));
} else {
binding.setVariable("repoURL", locationPathElements);
}
CompilerConfiguration config = new CompilerConfiguration();
GroovyShell shell = new GroovyShell(binding, config);
Object result = shell.evaluate("return \"" + evalText + "\"");
if (result == null) {
return "";
} else {
return result.toString().trim();
}
}
/**
* Reads the revision file of the specified build.
*
* @param build build object
* @return map from Subversion URL to its revision.
* @throws java.io.IOException thrown when operation failed
*/
/*package*/
@SuppressWarnings({"NestedAssignment"})
static Map<String, Long> parseRevisionFile(AbstractBuild build) throws IOException {
Map<String, Long> revisions = new HashMap<String, Long>(); // module -> revision
// read the revision file of the last build
File file = SubversionSCM.getRevisionFile(build);
if (!file.exists()) // nothing to compare against
{
return revisions;
}
BufferedReader br = new BufferedReader(new FileReader(file));
try {
String line;
while ((line = br.readLine()) != null) {
int index = line.lastIndexOf('/');
if (index < 0) {
continue; // invalid line?
}
try {
revisions.put(line.substring(0, index), Long.parseLong(line.substring(index + 1)));
} catch (NumberFormatException e) {
// perhaps a corrupted line. ignore
}
}
} finally {
br.close();
}
return revisions;
}
}
| false | true | public static boolean perform(AbstractBuild abstractBuild,
Launcher launcher,
BuildListener buildListener,
String tagBaseURLStr, String tagComment) {
PrintStream logger = buildListener.getLogger();
if (!Result.SUCCESS.equals(abstractBuild.getResult())) {
logger.println("No Subversion tagging for unsuccessful build. ");
return true;
}
AbstractProject<?, ?> rootProject =
getRootProject(abstractBuild.getProject());
Map<String, String> env;
if (!(rootProject.getScm() instanceof SubversionSCM)) {
logger.println("SvnTag plugin doesn't support tagging for SCM " +
rootProject.getScm().toString() + ".");
return true;
}
SubversionSCM scm = SubversionSCM.class.cast(rootProject.getScm());
env = abstractBuild.getEnvVars();
// Let SubversionSCM fill revision number.
// It is guaranteed for getBuilds() return the latest build (i.e.
// current build) at first
// The passed in abstractBuild may be the sub maven module and not
// have revision.txt holding Svn revision information, so need to use
// the build associated with the root level project.
scm.buildEnvVars(rootProject.getBuilds().get(0), env);
SubversionSCM.ModuleLocation[] moduleLocations = scm.getLocations();
// environment variable "SVN_REVISION" doesn't contain revision number when multiple modules are
// specified. Instead, parse revision.txt and obtain the corresponding revision numbers.
Map<String, Long> revisions;
try {
revisions = parseRevisionFile(abstractBuild);
} catch (IOException e) {
logger.println("Failed to parse revision.txt. " + e.getLocalizedMessage());
return false;
}
ISVNAuthenticationProvider sap = scm.getDescriptor().createAuthenticationProvider();
if (sap == null) {
logger.println("Subversion authentication info is not set.");
return false;
}
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(sap);
String emptyDirName = System.getProperty("java.io.tmpdir") + "/hudson/svn_tag/emptyDir";
File emptyDir = new File(emptyDirName);
try {
if (emptyDir.exists()) {
FileUtils.forceDelete(emptyDir);
}
FileUtils.forceMkdir(emptyDir);
FileUtils.forceDeleteOnExit(emptyDir);
} catch (IOException e) {
logger.println("Failed to create an empty directory used to create intermediate directories." + e.getLocalizedMessage());
return false;
}
SVNCommitClient commitClient = new SVNCommitClient(sam, null);
for (SubversionSCM.ModuleLocation ml : moduleLocations) {
logger.println("moduleLocation: Remote ->" + ml.remote);
List locationPathElements = Arrays.asList(StringUtils.split(ml.remote, "/"));
String evaledTagBaseURLStr = evalGroovyExpression(env, tagBaseURLStr, locationPathElements);
URI repoURI;
try {
repoURI = new URI(ml.remote);
} catch (URISyntaxException e) {
logger.println("Failed to parse SVN repo URL. " + e.getLocalizedMessage());
return false;
}
SVNURL parsedTagBaseURL = null;
try {
parsedTagBaseURL = SVNURL.parseURIEncoded(repoURI.resolve(evaledTagBaseURLStr).toString());
logger.println("Tag Base URL: '" + parsedTagBaseURL.toString() + "'.");
} catch (SVNException e) {
logger.println("Failed to parse tag base URL '" + evaledTagBaseURLStr + "'. " + e.getLocalizedMessage());
}
try {
SVNCommitInfo deleteInfo =
commitClient.doDelete(new SVNURL[]{parsedTagBaseURL},
"Delete old tag by SvnTag Hudson plugin.");
SVNErrorMessage deleteErrMsg = deleteInfo.getErrorMessage();
if (null != deleteErrMsg) {
logger.println(deleteErrMsg.getMessage());
} else {
logger.println("Delete old tag " + evaledTagBaseURLStr + ".");
}
} catch (SVNException e) {
logger.println("There was no old tag at " + evaledTagBaseURLStr + ".");
}
SVNCommitInfo mkdirInfo = null;
try {
// commtClient.doMkDir doesn't support "-parent" option available in svn command.
// Import an empty directory to create intermediate directories.
// mkdirInfo = commitClient.doMkDir(new SVNURL[]{parsedTagBaseURL},
// "Created by SvnTag Hudson plugin.");
mkdirInfo = commitClient.doImport(emptyDir, parsedTagBaseURL, "Created by SvnTag Hudson plugin.", false);
} catch (SVNException e) {
logger.println("Failed to create a directory '" + parsedTagBaseURL.toString() + "'.");
return false;
}
SVNErrorMessage mkdirErrMsg = mkdirInfo.getErrorMessage();
if (null != mkdirErrMsg) {
logger.println(mkdirErrMsg.getMessage());
return false;
}
SVNCopyClient copyClient = new SVNCopyClient(sam, null);
try {
String evalComment = evalGroovyExpression((Map<String, String>) abstractBuild.getEnvVars(), tagComment, locationPathElements);
SVNCommitInfo commitInfo =
copyClient.doCopy(SVNURL.parseURIEncoded(ml.remote),
SVNRevision.create(Long.valueOf(revisions.get(ml.remote))),
parsedTagBaseURL, false,
false, evalComment);
SVNErrorMessage errorMsg = commitInfo.getErrorMessage();
if (null != errorMsg) {
logger.println(errorMsg.getFullMessage());
return false;
} else {
logger.println("Tagged as Revision " +
commitInfo.getNewRevision());
}
} catch (SVNException e) {
logger.println("Subversion copy failed. " +
e.getLocalizedMessage());
return false;
}
}
return true;
}
| public static boolean perform(AbstractBuild abstractBuild,
Launcher launcher,
BuildListener buildListener,
String tagBaseURLStr, String tagComment) {
PrintStream logger = buildListener.getLogger();
if (!Result.SUCCESS.equals(abstractBuild.getResult())) {
logger.println("No Subversion tagging for unsuccessful build. ");
return true;
}
AbstractProject<?, ?> rootProject =
getRootProject(abstractBuild.getProject());
Map<String, String> env;
if (!(rootProject.getScm() instanceof SubversionSCM)) {
logger.println("SvnTag plugin doesn't support tagging for SCM " +
rootProject.getScm().toString() + ".");
return true;
}
SubversionSCM scm = SubversionSCM.class.cast(rootProject.getScm());
env = abstractBuild.getEnvVars();
// Let SubversionSCM fill revision number.
// It is guaranteed for getBuilds() return the latest build (i.e.
// current build) at first
// The passed in abstractBuild may be the sub maven module and not
// have revision.txt holding Svn revision information, so need to use
// the build associated with the root level project.
scm.buildEnvVars(rootProject.getBuilds().get(0), env);
SubversionSCM.ModuleLocation[] moduleLocations = scm.getLocations();
// environment variable "SVN_REVISION" doesn't contain revision number when multiple modules are
// specified. Instead, parse revision.txt and obtain the corresponding revision numbers.
Map<String, Long> revisions;
try {
revisions = parseRevisionFile(abstractBuild);
} catch (IOException e) {
logger.println("Failed to parse revision.txt. " + e.getLocalizedMessage());
return false;
}
ISVNAuthenticationProvider sap = scm.getDescriptor().createAuthenticationProvider();
if (sap == null) {
logger.println("Subversion authentication info is not set.");
return false;
}
ISVNAuthenticationManager sam = SVNWCUtil.createDefaultAuthenticationManager();
sam.setAuthenticationProvider(sap);
String emptyDirName = System.getProperty("java.io.tmpdir") + "/hudson/svn_tag/emptyDir";
File emptyDir = new File(emptyDirName);
try {
if (emptyDir.exists()) {
FileUtils.forceDelete(emptyDir);
}
FileUtils.forceMkdir(emptyDir);
FileUtils.forceDeleteOnExit(emptyDir);
} catch (IOException e) {
logger.println("Failed to create an empty directory used to create intermediate directories." + e.getLocalizedMessage());
return false;
}
SVNCommitClient commitClient = new SVNCommitClient(sam, null);
for (SubversionSCM.ModuleLocation ml : moduleLocations) {
logger.println("moduleLocation: Remote ->" + ml.remote);
List locationPathElements = Arrays.asList(StringUtils.split(ml.remote, "/"));
String evaledTagBaseURLStr = evalGroovyExpression(env, tagBaseURLStr, locationPathElements);
URI repoURI;
try {
repoURI = new URI(ml.remote);
} catch (URISyntaxException e) {
logger.println("Failed to parse SVN repo URL. " + e.getLocalizedMessage());
return false;
}
SVNURL parsedTagBaseURL = null;
SVNURL parsedTagBaseParentURL = null;
try {
parsedTagBaseURL = SVNURL.parseURIEncoded(repoURI.resolve(evaledTagBaseURLStr).toString());
parsedTagBaseParentURL = SVNURL.parseURIEncoded(repoURI.resolve(evaledTagBaseURLStr + "/..").toString());
logger.println("Tag Base URL: '" + parsedTagBaseURL.toString() + "'.");
} catch (SVNException e) {
logger.println("Failed to parse tag base URL '" + evaledTagBaseURLStr + "'. " + e.getLocalizedMessage());
}
try {
SVNCommitInfo deleteInfo =
commitClient.doDelete(new SVNURL[]{parsedTagBaseURL},
"Delete old tag by SvnTag Hudson plugin.");
SVNErrorMessage deleteErrMsg = deleteInfo.getErrorMessage();
if (null != deleteErrMsg) {
logger.println(deleteErrMsg.getMessage());
} else {
logger.println("Delete old tag " + evaledTagBaseURLStr + ".");
}
} catch (SVNException e) {
logger.println("There was no old tag at " + evaledTagBaseURLStr + ".");
}
SVNCommitInfo mkdirInfo = null;
try {
// commtClient.doMkDir doesn't support "-parent" option available in svn command.
// Import an empty directory to create intermediate directories.
// mkdirInfo = commitClient.doMkDir(new SVNURL[]{parsedTagBaseURL},
// "Created by SvnTag Hudson plugin.");
mkdirInfo = commitClient.doImport(emptyDir, parsedTagBaseParentURL, "Created by SvnTag Hudson plugin.", false);
} catch (SVNException e) {
logger.println("Failed to create a directory '" + parsedTagBaseParentURL.toString() + "'.");
return false;
}
SVNErrorMessage mkdirErrMsg = mkdirInfo.getErrorMessage();
if (null != mkdirErrMsg) {
logger.println(mkdirErrMsg.getMessage());
return false;
}
SVNCopyClient copyClient = new SVNCopyClient(sam, null);
try {
String evalComment = evalGroovyExpression((Map<String, String>) abstractBuild.getEnvVars(), tagComment, locationPathElements);
SVNCommitInfo commitInfo =
copyClient.doCopy(SVNURL.parseURIEncoded(ml.remote),
SVNRevision.create(Long.valueOf(revisions.get(ml.remote))),
parsedTagBaseURL, false,
false, evalComment);
SVNErrorMessage errorMsg = commitInfo.getErrorMessage();
if (null != errorMsg) {
logger.println(errorMsg.getFullMessage());
return false;
} else {
logger.println("Tagged as Revision " +
commitInfo.getNewRevision());
}
} catch (SVNException e) {
logger.println("Subversion copy failed. " +
e.getLocalizedMessage());
return false;
}
}
return true;
}
|
diff --git a/src/com/fsck/k9/Account.java b/src/com/fsck/k9/Account.java
index 5038307e..c43c2d33 100644
--- a/src/com/fsck/k9/Account.java
+++ b/src/com/fsck/k9/Account.java
@@ -1,1275 +1,1279 @@
package com.fsck.k9;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Account stores all of the settings for a single account defined by the user. It is able to save
* and delete itself given a Preferences to work with. Each account is defined by a UUID.
*/
public class Account implements BaseAccount
{
public static final String EXPUNGE_IMMEDIATELY = "EXPUNGE_IMMEDIATELY";
public static final String EXPUNGE_MANUALLY = "EXPUNGE_MANUALLY";
public static final String EXPUNGE_ON_POLL = "EXPUNGE_ON_POLL";
public static final int DELETE_POLICY_NEVER = 0;
public static final int DELETE_POLICY_7DAYS = 1;
public static final int DELETE_POLICY_ON_DELETE = 2;
public static final int DELETE_POLICY_MARK_AS_READ = 3;
public static final String TYPE_WIFI = "WIFI";
public static final String TYPE_MOBILE = "MOBILE";
public static final String TYPE_OTHER = "OTHER";
private static String[] networkTypes = { TYPE_WIFI, TYPE_MOBILE, TYPE_OTHER };
/**
* <pre>
* 0 - Never (DELETE_POLICY_NEVER)
* 1 - After 7 days (DELETE_POLICY_7DAYS)
* 2 - When I delete from inbox (DELETE_POLICY_ON_DELETE)
* 3 - Mark as read (DELETE_POLICY_MARK_AS_READ)
* </pre>
*/
private int mDeletePolicy;
private String mUuid;
private String mStoreUri;
private String mLocalStoreUri;
private String mTransportUri;
private String mDescription;
private String mAlwaysBcc;
private int mAutomaticCheckIntervalMinutes;
private int mDisplayCount;
private int mChipColor;
private int mLedColor;
private long mLastAutomaticCheckTime;
private boolean mNotifyNewMail;
private boolean mNotifySelfNewMail;
private String mDraftsFolderName;
private String mSentFolderName;
private String mTrashFolderName;
private String mOutboxFolderName;
private String mAutoExpandFolderName;
private FolderMode mFolderDisplayMode;
private FolderMode mFolderSyncMode;
private FolderMode mFolderPushMode;
private FolderMode mFolderTargetMode;
private int mAccountNumber;
private boolean mVibrate;
private boolean mRing;
private boolean mSaveAllHeaders;
private boolean mPushPollOnConnect;
private String mRingtoneUri;
private boolean mNotifySync;
private HideButtons mHideMessageViewButtons;
private boolean mIsSignatureBeforeQuotedText;
private String mExpungePolicy = EXPUNGE_IMMEDIATELY;
private int mMaxPushFolders;
private int mIdleRefreshMinutes;
private boolean goToUnreadMessageSearch;
private Map<String, Boolean> compressionMap = new ConcurrentHashMap<String, Boolean>();
private Searchable searchableFolders;
private boolean subscribedFoldersOnly;
private int maximumPolledMessageAge;
// Tracks if we have sent a notification for this account for
// current set of fetched messages
private boolean mRingNotified;
private List<Identity> identities;
public enum FolderMode
{
NONE, ALL, FIRST_CLASS, FIRST_AND_SECOND_CLASS, NOT_SECOND_CLASS;
}
public enum HideButtons
{
NEVER, ALWAYS, KEYBOARD_AVAILABLE;
}
public enum Searchable
{
ALL, DISPLAYABLE, NONE
}
protected Account(Context context)
{
// TODO Change local store path to something readable / recognizable
mUuid = UUID.randomUUID().toString();
mLocalStoreUri = "local://localhost/" + context.getDatabasePath(mUuid + ".db");
mAutomaticCheckIntervalMinutes = -1;
mIdleRefreshMinutes = 24;
mSaveAllHeaders = false;
mPushPollOnConnect = true;
mDisplayCount = -1;
mAccountNumber = -1;
mNotifyNewMail = true;
mNotifySync = true;
mVibrate = false;
mRing = true;
mNotifySelfNewMail = true;
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
mFolderSyncMode = FolderMode.FIRST_CLASS;
mFolderPushMode = FolderMode.FIRST_CLASS;
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
mHideMessageViewButtons = HideButtons.NEVER;
mRingtoneUri = "content://settings/system/notification_sound";
mIsSignatureBeforeQuotedText = false;
mExpungePolicy = EXPUNGE_IMMEDIATELY;
mAutoExpandFolderName = "INBOX";
mMaxPushFolders = 10;
mChipColor = (new Random()).nextInt(0xffffff) + 0xff000000;
mLedColor = mChipColor;
goToUnreadMessageSearch = false;
subscribedFoldersOnly = false;
maximumPolledMessageAge = 10;
searchableFolders = Searchable.ALL;
identities = new ArrayList<Identity>();
Identity identity = new Identity();
identity.setSignatureUse(true);
identity.setSignature(context.getString(R.string.default_signature));
identity.setDescription(context.getString(R.string.default_identity_description));
identities.add(identity);
}
protected Account(Preferences preferences, String uuid)
{
this.mUuid = uuid;
loadAccount(preferences);
}
/**
* Load stored settings for this account.
*/
private synchronized void loadAccount(Preferences preferences)
{
mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".storeUri", null));
mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null);
mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".transportUri", null));
mDescription = preferences.getPreferences().getString(mUuid + ".description", null);
mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid
+ ".automaticCheckIntervalMinutes", -1);
mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid
+ ".idleRefreshMinutes", 24);
mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid
+ ".saveAllHeaders", false);
mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid
+ ".pushPollOnConnect", true);
mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT);
+ if (mDisplayCount < 0)
+ {
+ mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
+ }
mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid
+ ".lastAutomaticCheckTime", 0);
mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail",
false);
mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail",
true);
mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck",
false);
mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0);
mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName",
"Drafts");
mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName",
"Sent");
mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName",
"Trash");
mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName",
"Outbox");
mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY);
mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10);
goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch",
false);
subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly",
false);
maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid
+ ".maximumPolledMessageAge", -1);
for (String type : networkTypes)
{
Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type,
true);
compressionMap.put(type, useCompression);
}
// Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were
// opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code
// should be deleted sometime soon
if (mDraftsFolderName == null || mDraftsFolderName.equals(""))
{
mDraftsFolderName = "Drafts";
}
if (mSentFolderName == null || mSentFolderName.equals(""))
{
mSentFolderName = "Sent";
}
if (mTrashFolderName == null || mTrashFolderName.equals(""))
{
mTrashFolderName = "Trash";
}
if (mOutboxFolderName == null || mOutboxFolderName.equals(""))
{
mOutboxFolderName = "Outbox";
}
// End of 0.103 repair
mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName",
"INBOX");
mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0);
Random random = new Random((long)mAccountNumber+4);
mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor",
(random.nextInt(0x70)) +
(random.nextInt(0x70) * 0xff) +
(random.nextInt(0x70) * 0xffff) +
0xff000000);
mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor);
mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false);
mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true);
try
{
mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum",
HideButtons.NEVER.name()));
}
catch (Exception e)
{
mHideMessageViewButtons = HideButtons.NEVER;
}
mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone",
"content://settings/system/notification_sound");
try
{
mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderSyncMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderPushMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders",
Searchable.ALL.name()));
}
catch (Exception e)
{
searchableFolders = Searchable.ALL;
}
mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(preferences.getPreferences());
}
protected synchronized void delete(Preferences preferences)
{
String[] uuids = preferences.getPreferences().getString("accountUuids", "").split(",");
StringBuffer sb = new StringBuffer();
for (int i = 0, length = uuids.length; i < length; i++)
{
if (!uuids[i].equals(mUuid))
{
if (sb.length() > 0)
{
sb.append(',');
}
sb.append(uuids[i]);
}
}
String accountUuids = sb.toString();
SharedPreferences.Editor editor = preferences.getPreferences().edit();
editor.putString("accountUuids", accountUuids);
editor.remove(mUuid + ".storeUri");
editor.remove(mUuid + ".localStoreUri");
editor.remove(mUuid + ".transportUri");
editor.remove(mUuid + ".description");
editor.remove(mUuid + ".name");
editor.remove(mUuid + ".email");
editor.remove(mUuid + ".alwaysBcc");
editor.remove(mUuid + ".automaticCheckIntervalMinutes");
editor.remove(mUuid + ".pushPollOnConnect");
editor.remove(mUuid + ".saveAllHeaders");
editor.remove(mUuid + ".idleRefreshMinutes");
editor.remove(mUuid + ".lastAutomaticCheckTime");
editor.remove(mUuid + ".notifyNewMail");
editor.remove(mUuid + ".notifySelfNewMail");
editor.remove(mUuid + ".deletePolicy");
editor.remove(mUuid + ".draftsFolderName");
editor.remove(mUuid + ".sentFolderName");
editor.remove(mUuid + ".trashFolderName");
editor.remove(mUuid + ".outboxFolderName");
editor.remove(mUuid + ".autoExpandFolderName");
editor.remove(mUuid + ".accountNumber");
editor.remove(mUuid + ".vibrate");
editor.remove(mUuid + ".ring");
editor.remove(mUuid + ".ringtone");
editor.remove(mUuid + ".lastFullSync");
editor.remove(mUuid + ".folderDisplayMode");
editor.remove(mUuid + ".folderSyncMode");
editor.remove(mUuid + ".folderPushMode");
editor.remove(mUuid + ".folderTargetMode");
editor.remove(mUuid + ".hideButtonsEnum");
editor.remove(mUuid + ".signatureBeforeQuotedText");
editor.remove(mUuid + ".expungePolicy");
editor.remove(mUuid + ".maxPushFolders");
editor.remove(mUuid + ".searchableFolders");
editor.remove(mUuid + ".chipColor");
editor.remove(mUuid + ".ledColor");
editor.remove(mUuid + ".goToUnreadMessageSearch");
editor.remove(mUuid + ".subscribedFoldersOnly");
editor.remove(mUuid + ".maximumPolledMessageAge");
for (String type : networkTypes)
{
editor.remove(mUuid + ".useCompression." + type);
}
deleteIdentities(preferences.getPreferences(), editor);
editor.commit();
}
public synchronized void save(Preferences preferences)
{
SharedPreferences.Editor editor = preferences.getPreferences().edit();
if (!preferences.getPreferences().getString("accountUuids", "").contains(mUuid))
{
/*
* When the account is first created we assign it a unique account number. The
* account number will be unique to that account for the lifetime of the account.
* So, we get all the existing account numbers, sort them ascending, loop through
* the list and check if the number is greater than 1 + the previous number. If so
* we use the previous number + 1 as the account number. This refills gaps.
* mAccountNumber starts as -1 on a newly created account. It must be -1 for this
* algorithm to work.
*
* I bet there is a much smarter way to do this. Anyone like to suggest it?
*/
Account[] accounts = preferences.getAccounts();
int[] accountNumbers = new int[accounts.length];
for (int i = 0; i < accounts.length; i++)
{
accountNumbers[i] = accounts[i].getAccountNumber();
}
Arrays.sort(accountNumbers);
for (int accountNumber : accountNumbers)
{
if (accountNumber > mAccountNumber + 1)
{
break;
}
mAccountNumber = accountNumber;
}
mAccountNumber++;
String accountUuids = preferences.getPreferences().getString("accountUuids", "");
accountUuids += (accountUuids.length() != 0 ? "," : "") + mUuid;
editor.putString("accountUuids", accountUuids);
}
editor.putString(mUuid + ".storeUri", Utility.base64Encode(mStoreUri));
editor.putString(mUuid + ".localStoreUri", mLocalStoreUri);
editor.putString(mUuid + ".transportUri", Utility.base64Encode(mTransportUri));
editor.putString(mUuid + ".description", mDescription);
editor.putString(mUuid + ".alwaysBcc", mAlwaysBcc);
editor.putInt(mUuid + ".automaticCheckIntervalMinutes", mAutomaticCheckIntervalMinutes);
editor.putInt(mUuid + ".idleRefreshMinutes", mIdleRefreshMinutes);
editor.putBoolean(mUuid + ".saveAllHeaders", mSaveAllHeaders);
editor.putBoolean(mUuid + ".pushPollOnConnect", mPushPollOnConnect);
editor.putInt(mUuid + ".displayCount", mDisplayCount);
editor.putLong(mUuid + ".lastAutomaticCheckTime", mLastAutomaticCheckTime);
editor.putBoolean(mUuid + ".notifyNewMail", mNotifyNewMail);
editor.putBoolean(mUuid + ".notifySelfNewMail", mNotifySelfNewMail);
editor.putBoolean(mUuid + ".notifyMailCheck", mNotifySync);
editor.putInt(mUuid + ".deletePolicy", mDeletePolicy);
editor.putString(mUuid + ".draftsFolderName", mDraftsFolderName);
editor.putString(mUuid + ".sentFolderName", mSentFolderName);
editor.putString(mUuid + ".trashFolderName", mTrashFolderName);
editor.putString(mUuid + ".outboxFolderName", mOutboxFolderName);
editor.putString(mUuid + ".autoExpandFolderName", mAutoExpandFolderName);
editor.putInt(mUuid + ".accountNumber", mAccountNumber);
editor.putBoolean(mUuid + ".vibrate", mVibrate);
editor.putBoolean(mUuid + ".ring", mRing);
editor.putString(mUuid + ".hideButtonsEnum", mHideMessageViewButtons.name());
editor.putString(mUuid + ".ringtone", mRingtoneUri);
editor.putString(mUuid + ".folderDisplayMode", mFolderDisplayMode.name());
editor.putString(mUuid + ".folderSyncMode", mFolderSyncMode.name());
editor.putString(mUuid + ".folderPushMode", mFolderPushMode.name());
editor.putString(mUuid + ".folderTargetMode", mFolderTargetMode.name());
editor.putBoolean(mUuid + ".signatureBeforeQuotedText", this.mIsSignatureBeforeQuotedText);
editor.putString(mUuid + ".expungePolicy", mExpungePolicy);
editor.putInt(mUuid + ".maxPushFolders", mMaxPushFolders);
editor.putString(mUuid + ".searchableFolders", searchableFolders.name());
editor.putInt(mUuid + ".chipColor", mChipColor);
editor.putInt(mUuid + ".ledColor", mLedColor);
editor.putBoolean(mUuid + ".goToUnreadMessageSearch", goToUnreadMessageSearch);
editor.putBoolean(mUuid + ".subscribedFoldersOnly", subscribedFoldersOnly);
editor.putInt(mUuid + ".maximumPolledMessageAge", maximumPolledMessageAge);
for (String type : networkTypes)
{
Boolean useCompression = compressionMap.get(type);
if (useCompression != null)
{
editor.putBoolean(mUuid + ".useCompression." + type, useCompression);
}
}
saveIdentities(preferences.getPreferences(), editor);
editor.commit();
}
//TODO: Shouldn't this live in MessagingController?
// Why should everything be in MessagingController? This is an Account-specific operation. --danapple0
public AccountStats getStats(Context context) throws MessagingException
{
long startTime = System.currentTimeMillis();
AccountStats stats = new AccountStats();
int unreadMessageCount = 0;
int flaggedMessageCount = 0;
LocalStore localStore = getLocalStore();
if (K9.measureAccounts())
{
stats.size = localStore.getSize();
}
Account.FolderMode aMode = getFolderDisplayMode();
Preferences prefs = Preferences.getPreferences(context);
long folderLoadStart = System.currentTimeMillis();
List<? extends Folder> folders = localStore.getPersonalNamespaces(false);
long folderLoadEnd = System.currentTimeMillis();
long folderEvalStart = folderLoadEnd;
for (Folder folder : folders)
{
LocalFolder localFolder = (LocalFolder)folder;
//folder.refresh(prefs);
Folder.FolderClass fMode = localFolder.getDisplayClass(prefs);
if (folder.getName().equals(getTrashFolderName()) == false &&
folder.getName().equals(getDraftsFolderName()) == false &&
folder.getName().equals(getOutboxFolderName()) == false &&
folder.getName().equals(getSentFolderName()) == false &&
folder.getName().equals(getErrorFolderName()) == false)
{
if (aMode == Account.FolderMode.NONE)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS &&
fMode != Folder.FolderClass.FIRST_CLASS &&
fMode != Folder.FolderClass.SECOND_CLASS)
{
continue;
}
if (aMode == Account.FolderMode.NOT_SECOND_CLASS &&
fMode == Folder.FolderClass.SECOND_CLASS)
{
continue;
}
unreadMessageCount += folder.getUnreadMessageCount();
flaggedMessageCount += folder.getFlaggedMessageCount();
}
}
long folderEvalEnd = System.currentTimeMillis();
stats.unreadMessageCount = unreadMessageCount;
stats.flaggedMessageCount = flaggedMessageCount;
long endTime = System.currentTimeMillis();
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "Account.getStats() on " + getDescription() + " took " + (endTime - startTime) + " ms;"
+ " loading " + folders.size() + " took " + (folderLoadEnd - folderLoadStart) + " ms;"
+ " evaluating took " + (folderEvalEnd - folderEvalStart) + " ms");
return stats;
}
public void setChipColor(int color)
{
mChipColor = color;
}
public int getChipColor()
{
return mChipColor;
}
public void setLedColor(int color)
{
mLedColor = color;
}
public int getLedColor()
{
return mLedColor;
}
public String getUuid()
{
return mUuid;
}
public Uri getContentUri()
{
return Uri.parse("content://accounts/" + getUuid());
}
public synchronized String getStoreUri()
{
return mStoreUri;
}
public synchronized void setStoreUri(String storeUri)
{
this.mStoreUri = storeUri;
}
public synchronized String getTransportUri()
{
return mTransportUri;
}
public synchronized void setTransportUri(String transportUri)
{
this.mTransportUri = transportUri;
}
public synchronized String getDescription()
{
return mDescription;
}
public synchronized void setDescription(String description)
{
this.mDescription = description;
}
public synchronized String getName()
{
return identities.get(0).getName();
}
public synchronized void setName(String name)
{
identities.get(0).setName(name);
}
public synchronized boolean getSignatureUse()
{
return identities.get(0).getSignatureUse();
}
public synchronized void setSignatureUse(boolean signatureUse)
{
identities.get(0).setSignatureUse(signatureUse);
}
public synchronized String getSignature()
{
return identities.get(0).getSignature();
}
public synchronized void setSignature(String signature)
{
identities.get(0).setSignature(signature);
}
public synchronized String getEmail()
{
return identities.get(0).getEmail();
}
public synchronized void setEmail(String email)
{
identities.get(0).setEmail(email);
}
public synchronized String getAlwaysBcc()
{
return mAlwaysBcc;
}
public synchronized void setAlwaysBcc(String alwaysBcc)
{
this.mAlwaysBcc = alwaysBcc;
}
public synchronized boolean isVibrate()
{
return mVibrate;
}
public synchronized void setVibrate(boolean vibrate)
{
mVibrate = vibrate;
}
/* Have we sent a new mail notification on this account */
public boolean isRingNotified()
{
return mRingNotified;
}
public void setRingNotified(boolean ringNotified)
{
mRingNotified = ringNotified;
}
public synchronized String getRingtone()
{
return mRingtoneUri;
}
public synchronized void setRingtone(String ringtoneUri)
{
mRingtoneUri = ringtoneUri;
}
public synchronized String getLocalStoreUri()
{
return mLocalStoreUri;
}
public synchronized void setLocalStoreUri(String localStoreUri)
{
this.mLocalStoreUri = localStoreUri;
}
/**
* Returns -1 for never.
*/
public synchronized int getAutomaticCheckIntervalMinutes()
{
return mAutomaticCheckIntervalMinutes;
}
/**
* @param automaticCheckIntervalMinutes or -1 for never.
*/
public synchronized boolean setAutomaticCheckIntervalMinutes(int automaticCheckIntervalMinutes)
{
int oldInterval = this.mAutomaticCheckIntervalMinutes;
int newInterval = automaticCheckIntervalMinutes;
this.mAutomaticCheckIntervalMinutes = automaticCheckIntervalMinutes;
return (oldInterval != newInterval);
}
public synchronized int getDisplayCount()
{
return mDisplayCount;
}
public synchronized void setDisplayCount(int displayCount)
{
if (displayCount != -1)
{
this.mDisplayCount = displayCount;
}
else
{
this.mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
}
public synchronized long getLastAutomaticCheckTime()
{
return mLastAutomaticCheckTime;
}
public synchronized void setLastAutomaticCheckTime(long lastAutomaticCheckTime)
{
this.mLastAutomaticCheckTime = lastAutomaticCheckTime;
}
public synchronized boolean isNotifyNewMail()
{
return mNotifyNewMail;
}
public synchronized void setNotifyNewMail(boolean notifyNewMail)
{
this.mNotifyNewMail = notifyNewMail;
}
public synchronized int getDeletePolicy()
{
return mDeletePolicy;
}
public synchronized void setDeletePolicy(int deletePolicy)
{
this.mDeletePolicy = deletePolicy;
}
public synchronized String getDraftsFolderName()
{
return mDraftsFolderName;
}
public synchronized void setDraftsFolderName(String draftsFolderName)
{
mDraftsFolderName = draftsFolderName;
}
public synchronized String getSentFolderName()
{
return mSentFolderName;
}
public synchronized String getErrorFolderName()
{
return K9.ERROR_FOLDER_NAME;
}
public synchronized void setSentFolderName(String sentFolderName)
{
mSentFolderName = sentFolderName;
}
public synchronized String getTrashFolderName()
{
return mTrashFolderName;
}
public synchronized void setTrashFolderName(String trashFolderName)
{
mTrashFolderName = trashFolderName;
}
public synchronized String getOutboxFolderName()
{
return mOutboxFolderName;
}
public synchronized void setOutboxFolderName(String outboxFolderName)
{
mOutboxFolderName = outboxFolderName;
}
public synchronized String getAutoExpandFolderName()
{
return mAutoExpandFolderName;
}
public synchronized void setAutoExpandFolderName(String autoExpandFolderName)
{
mAutoExpandFolderName = autoExpandFolderName;
}
public synchronized int getAccountNumber()
{
return mAccountNumber;
}
public synchronized FolderMode getFolderDisplayMode()
{
return mFolderDisplayMode;
}
public synchronized boolean setFolderDisplayMode(FolderMode displayMode)
{
FolderMode oldDisplayMode = mFolderDisplayMode;
mFolderDisplayMode = displayMode;
return oldDisplayMode != displayMode;
}
public synchronized FolderMode getFolderSyncMode()
{
return mFolderSyncMode;
}
public synchronized boolean setFolderSyncMode(FolderMode syncMode)
{
FolderMode oldSyncMode = mFolderSyncMode;
mFolderSyncMode = syncMode;
if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE)
{
return true;
}
if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE)
{
return true;
}
return false;
}
public synchronized FolderMode getFolderPushMode()
{
return mFolderPushMode;
}
public synchronized boolean setFolderPushMode(FolderMode pushMode)
{
FolderMode oldPushMode = mFolderPushMode;
mFolderPushMode = pushMode;
return pushMode != oldPushMode;
}
public synchronized boolean isShowOngoing()
{
return mNotifySync;
}
public synchronized void setShowOngoing(boolean showOngoing)
{
this.mNotifySync = showOngoing;
}
public synchronized HideButtons getHideMessageViewButtons()
{
return mHideMessageViewButtons;
}
public synchronized void setHideMessageViewButtons(HideButtons hideMessageViewButtons)
{
mHideMessageViewButtons = hideMessageViewButtons;
}
public synchronized FolderMode getFolderTargetMode()
{
return mFolderTargetMode;
}
public synchronized void setFolderTargetMode(FolderMode folderTargetMode)
{
mFolderTargetMode = folderTargetMode;
}
public synchronized boolean isSignatureBeforeQuotedText()
{
return mIsSignatureBeforeQuotedText;
}
public synchronized void setSignatureBeforeQuotedText(boolean mIsSignatureBeforeQuotedText)
{
this.mIsSignatureBeforeQuotedText = mIsSignatureBeforeQuotedText;
}
public synchronized boolean isNotifySelfNewMail()
{
return mNotifySelfNewMail;
}
public synchronized void setNotifySelfNewMail(boolean notifySelfNewMail)
{
mNotifySelfNewMail = notifySelfNewMail;
}
public synchronized String getExpungePolicy()
{
return mExpungePolicy;
}
public synchronized void setExpungePolicy(String expungePolicy)
{
mExpungePolicy = expungePolicy;
}
public synchronized int getMaxPushFolders()
{
return mMaxPushFolders;
}
public synchronized boolean setMaxPushFolders(int maxPushFolders)
{
int oldMaxPushFolders = mMaxPushFolders;
mMaxPushFolders = maxPushFolders;
return oldMaxPushFolders != maxPushFolders;
}
public synchronized boolean isRing()
{
return mRing;
}
public synchronized void setRing(boolean ring)
{
mRing = ring;
}
public LocalStore getLocalStore() throws MessagingException
{
return Store.getLocalInstance(this, K9.app);
}
public Store getRemoteStore() throws MessagingException
{
return Store.getRemoteInstance(this);
}
@Override
public synchronized String toString()
{
return mDescription;
}
public void setCompression(String networkType, boolean useCompression)
{
compressionMap.put(networkType, useCompression);
}
public boolean useCompression(String networkType)
{
Boolean useCompression = compressionMap.get(networkType);
if (useCompression == null)
{
return true;
}
else
{
return useCompression;
}
}
public boolean useCompression(int type)
{
String networkType = TYPE_OTHER;
switch (type)
{
case ConnectivityManager.TYPE_MOBILE:
networkType = TYPE_MOBILE;
break;
case ConnectivityManager.TYPE_WIFI:
networkType = TYPE_WIFI;
break;
}
return useCompression(networkType);
}
@Override
public boolean equals(Object o)
{
if (o instanceof Account)
{
return ((Account)o).mUuid.equals(mUuid);
}
return super.equals(o);
}
@Override
public int hashCode()
{
return mUuid.hashCode();
}
private synchronized List<Identity> loadIdentities(SharedPreferences prefs)
{
List<Identity> newIdentities = new ArrayList<Identity>();
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String name = prefs.getString(mUuid + ".name." + ident, null);
String email = prefs.getString(mUuid + ".email." + ident, null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse." + ident, true);
String signature = prefs.getString(mUuid + ".signature." + ident, null);
String description = prefs.getString(mUuid + ".description." + ident, null);
if (email != null)
{
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(description);
newIdentities.add(identity);
gotOne = true;
}
ident++;
}
while (gotOne);
if (newIdentities.size() == 0)
{
String name = prefs.getString(mUuid + ".name", null);
String email = prefs.getString(mUuid + ".email", null);
boolean signatureUse = prefs.getBoolean(mUuid + ".signatureUse", true);
String signature = prefs.getString(mUuid + ".signature", null);
Identity identity = new Identity();
identity.setName(name);
identity.setEmail(email);
identity.setSignatureUse(signatureUse);
identity.setSignature(signature);
identity.setDescription(email);
newIdentities.add(identity);
}
return newIdentities;
}
private synchronized void deleteIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
int ident = 0;
boolean gotOne = false;
do
{
gotOne = false;
String email = prefs.getString(mUuid + ".email." + ident, null);
if (email != null)
{
editor.remove(mUuid + ".name." + ident);
editor.remove(mUuid + ".email." + ident);
editor.remove(mUuid + ".signatureUse." + ident);
editor.remove(mUuid + ".signature." + ident);
editor.remove(mUuid + ".description." + ident);
gotOne = true;
}
ident++;
}
while (gotOne);
}
private synchronized void saveIdentities(SharedPreferences prefs, SharedPreferences.Editor editor)
{
deleteIdentities(prefs, editor);
int ident = 0;
for (Identity identity : identities)
{
editor.putString(mUuid + ".name." + ident, identity.getName());
editor.putString(mUuid + ".email." + ident, identity.getEmail());
editor.putBoolean(mUuid + ".signatureUse." + ident, identity.getSignatureUse());
editor.putString(mUuid + ".signature." + ident, identity.getSignature());
editor.putString(mUuid + ".description." + ident, identity.getDescription());
ident++;
}
}
public synchronized List<Identity> getIdentities()
{
return identities;
}
public synchronized void setIdentities(List<Identity> newIdentities)
{
identities = new ArrayList<Identity>(newIdentities);
}
public synchronized Identity getIdentity(int i)
{
if (i < identities.size())
{
return identities.get(i);
}
return null;
}
public boolean isAnIdentity(Address[] addrs)
{
if (addrs == null)
{
return false;
}
for (Address addr : addrs)
{
if (findIdentity(addr) != null)
{
return true;
}
}
return false;
}
public boolean isAnIdentity(Address addr)
{
return findIdentity(addr) != null;
}
public synchronized Identity findIdentity(Address addr)
{
for (Identity identity : identities)
{
String email = identity.getEmail();
if (email != null && email.equalsIgnoreCase(addr.getAddress()))
{
return identity;
}
}
return null;
}
public Searchable getSearchableFolders()
{
return searchableFolders;
}
public void setSearchableFolders(Searchable searchableFolders)
{
this.searchableFolders = searchableFolders;
}
public int getIdleRefreshMinutes()
{
return mIdleRefreshMinutes;
}
public void setIdleRefreshMinutes(int idleRefreshMinutes)
{
mIdleRefreshMinutes = idleRefreshMinutes;
}
public boolean isPushPollOnConnect()
{
return mPushPollOnConnect;
}
public void setPushPollOnConnect(boolean pushPollOnConnect)
{
mPushPollOnConnect = pushPollOnConnect;
}
public boolean isSaveAllHeaders()
{
return mSaveAllHeaders;
}
public void setSaveAllHeaders(boolean saveAllHeaders)
{
mSaveAllHeaders = saveAllHeaders;
}
public boolean goToUnreadMessageSearch()
{
return goToUnreadMessageSearch;
}
public void setGoToUnreadMessageSearch(boolean goToUnreadMessageSearch)
{
this.goToUnreadMessageSearch = goToUnreadMessageSearch;
}
public boolean subscribedFoldersOnly()
{
return subscribedFoldersOnly;
}
public void setSubscribedFoldersOnly(boolean subscribedFoldersOnly)
{
this.subscribedFoldersOnly = subscribedFoldersOnly;
}
public int getMaximumPolledMessageAge()
{
return maximumPolledMessageAge;
}
public void setMaximumPolledMessageAge(int maximumPolledMessageAge)
{
this.maximumPolledMessageAge = maximumPolledMessageAge;
}
public Date getEarliestPollDate()
{
int age = getMaximumPolledMessageAge();
if (age < 0 == false)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
if (age < 28)
{
now.add(Calendar.DATE, age * -1);
}
else switch (age)
{
case 28:
now.add(Calendar.MONTH, -1);
break;
case 56:
now.add(Calendar.MONTH, -2);
break;
case 84:
now.add(Calendar.MONTH, -3);
break;
case 168:
now.add(Calendar.MONTH, -6);
break;
case 365:
now.add(Calendar.YEAR, -1);
break;
}
return now.getTime();
}
else
{
return null;
}
}
}
| true | true | private synchronized void loadAccount(Preferences preferences)
{
mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".storeUri", null));
mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null);
mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".transportUri", null));
mDescription = preferences.getPreferences().getString(mUuid + ".description", null);
mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid
+ ".automaticCheckIntervalMinutes", -1);
mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid
+ ".idleRefreshMinutes", 24);
mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid
+ ".saveAllHeaders", false);
mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid
+ ".pushPollOnConnect", true);
mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT);
mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid
+ ".lastAutomaticCheckTime", 0);
mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail",
false);
mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail",
true);
mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck",
false);
mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0);
mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName",
"Drafts");
mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName",
"Sent");
mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName",
"Trash");
mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName",
"Outbox");
mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY);
mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10);
goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch",
false);
subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly",
false);
maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid
+ ".maximumPolledMessageAge", -1);
for (String type : networkTypes)
{
Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type,
true);
compressionMap.put(type, useCompression);
}
// Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were
// opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code
// should be deleted sometime soon
if (mDraftsFolderName == null || mDraftsFolderName.equals(""))
{
mDraftsFolderName = "Drafts";
}
if (mSentFolderName == null || mSentFolderName.equals(""))
{
mSentFolderName = "Sent";
}
if (mTrashFolderName == null || mTrashFolderName.equals(""))
{
mTrashFolderName = "Trash";
}
if (mOutboxFolderName == null || mOutboxFolderName.equals(""))
{
mOutboxFolderName = "Outbox";
}
// End of 0.103 repair
mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName",
"INBOX");
mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0);
Random random = new Random((long)mAccountNumber+4);
mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor",
(random.nextInt(0x70)) +
(random.nextInt(0x70) * 0xff) +
(random.nextInt(0x70) * 0xffff) +
0xff000000);
mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor);
mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false);
mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true);
try
{
mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum",
HideButtons.NEVER.name()));
}
catch (Exception e)
{
mHideMessageViewButtons = HideButtons.NEVER;
}
mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone",
"content://settings/system/notification_sound");
try
{
mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderSyncMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderPushMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders",
Searchable.ALL.name()));
}
catch (Exception e)
{
searchableFolders = Searchable.ALL;
}
mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(preferences.getPreferences());
}
| private synchronized void loadAccount(Preferences preferences)
{
mStoreUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".storeUri", null));
mLocalStoreUri = preferences.getPreferences().getString(mUuid + ".localStoreUri", null);
mTransportUri = Utility.base64Decode(preferences.getPreferences().getString(mUuid
+ ".transportUri", null));
mDescription = preferences.getPreferences().getString(mUuid + ".description", null);
mAlwaysBcc = preferences.getPreferences().getString(mUuid + ".alwaysBcc", mAlwaysBcc);
mAutomaticCheckIntervalMinutes = preferences.getPreferences().getInt(mUuid
+ ".automaticCheckIntervalMinutes", -1);
mIdleRefreshMinutes = preferences.getPreferences().getInt(mUuid
+ ".idleRefreshMinutes", 24);
mSaveAllHeaders = preferences.getPreferences().getBoolean(mUuid
+ ".saveAllHeaders", false);
mPushPollOnConnect = preferences.getPreferences().getBoolean(mUuid
+ ".pushPollOnConnect", true);
mDisplayCount = preferences.getPreferences().getInt(mUuid + ".displayCount", K9.DEFAULT_VISIBLE_LIMIT);
if (mDisplayCount < 0)
{
mDisplayCount = K9.DEFAULT_VISIBLE_LIMIT;
}
mLastAutomaticCheckTime = preferences.getPreferences().getLong(mUuid
+ ".lastAutomaticCheckTime", 0);
mNotifyNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifyNewMail",
false);
mNotifySelfNewMail = preferences.getPreferences().getBoolean(mUuid + ".notifySelfNewMail",
true);
mNotifySync = preferences.getPreferences().getBoolean(mUuid + ".notifyMailCheck",
false);
mDeletePolicy = preferences.getPreferences().getInt(mUuid + ".deletePolicy", 0);
mDraftsFolderName = preferences.getPreferences().getString(mUuid + ".draftsFolderName",
"Drafts");
mSentFolderName = preferences.getPreferences().getString(mUuid + ".sentFolderName",
"Sent");
mTrashFolderName = preferences.getPreferences().getString(mUuid + ".trashFolderName",
"Trash");
mOutboxFolderName = preferences.getPreferences().getString(mUuid + ".outboxFolderName",
"Outbox");
mExpungePolicy = preferences.getPreferences().getString(mUuid + ".expungePolicy", EXPUNGE_IMMEDIATELY);
mMaxPushFolders = preferences.getPreferences().getInt(mUuid + ".maxPushFolders", 10);
goToUnreadMessageSearch = preferences.getPreferences().getBoolean(mUuid + ".goToUnreadMessageSearch",
false);
subscribedFoldersOnly = preferences.getPreferences().getBoolean(mUuid + ".subscribedFoldersOnly",
false);
maximumPolledMessageAge = preferences.getPreferences().getInt(mUuid
+ ".maximumPolledMessageAge", -1);
for (String type : networkTypes)
{
Boolean useCompression = preferences.getPreferences().getBoolean(mUuid + ".useCompression." + type,
true);
compressionMap.put(type, useCompression);
}
// Between r418 and r431 (version 0.103), folder names were set empty if the Incoming settings were
// opened for non-IMAP accounts. 0.103 was never a market release, so perhaps this code
// should be deleted sometime soon
if (mDraftsFolderName == null || mDraftsFolderName.equals(""))
{
mDraftsFolderName = "Drafts";
}
if (mSentFolderName == null || mSentFolderName.equals(""))
{
mSentFolderName = "Sent";
}
if (mTrashFolderName == null || mTrashFolderName.equals(""))
{
mTrashFolderName = "Trash";
}
if (mOutboxFolderName == null || mOutboxFolderName.equals(""))
{
mOutboxFolderName = "Outbox";
}
// End of 0.103 repair
mAutoExpandFolderName = preferences.getPreferences().getString(mUuid + ".autoExpandFolderName",
"INBOX");
mAccountNumber = preferences.getPreferences().getInt(mUuid + ".accountNumber", 0);
Random random = new Random((long)mAccountNumber+4);
mChipColor = preferences.getPreferences().getInt(mUuid+".chipColor",
(random.nextInt(0x70)) +
(random.nextInt(0x70) * 0xff) +
(random.nextInt(0x70) * 0xffff) +
0xff000000);
mLedColor = preferences.getPreferences().getInt(mUuid+".ledColor", mChipColor);
mVibrate = preferences.getPreferences().getBoolean(mUuid + ".vibrate", false);
mRing = preferences.getPreferences().getBoolean(mUuid + ".ring", true);
try
{
mHideMessageViewButtons = HideButtons.valueOf(preferences.getPreferences().getString(mUuid + ".hideButtonsEnum",
HideButtons.NEVER.name()));
}
catch (Exception e)
{
mHideMessageViewButtons = HideButtons.NEVER;
}
mRingtoneUri = preferences.getPreferences().getString(mUuid + ".ringtone",
"content://settings/system/notification_sound");
try
{
mFolderDisplayMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderDisplayMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderDisplayMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
mFolderSyncMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderSyncMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderSyncMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderPushMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderPushMode",
FolderMode.FIRST_CLASS.name()));
}
catch (Exception e)
{
mFolderPushMode = FolderMode.FIRST_CLASS;
}
try
{
mFolderTargetMode = FolderMode.valueOf(preferences.getPreferences().getString(mUuid + ".folderTargetMode",
FolderMode.NOT_SECOND_CLASS.name()));
}
catch (Exception e)
{
mFolderTargetMode = FolderMode.NOT_SECOND_CLASS;
}
try
{
searchableFolders = Searchable.valueOf(preferences.getPreferences().getString(mUuid + ".searchableFolders",
Searchable.ALL.name()));
}
catch (Exception e)
{
searchableFolders = Searchable.ALL;
}
mIsSignatureBeforeQuotedText = preferences.getPreferences().getBoolean(mUuid + ".signatureBeforeQuotedText", false);
identities = loadIdentities(preferences.getPreferences());
}
|
diff --git a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
index 9dd0edc4b..83dea1dea 100644
--- a/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
+++ b/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java
@@ -1,278 +1,278 @@
/*******************************************************************************
* Copyright (c) 2000, 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.core.internal.resources;
import java.util.Hashtable;
import org.eclipse.core.resources.WorkspaceLock;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.internal.utils.*;
//
public class WorkManager implements IManager {
protected int currentOperationId;
// we use a Hashtable for the identifiers to avoid concurrency problems
protected Hashtable identifiers;
protected int nextId;
protected Workspace workspace;
protected WorkspaceLock workspaceLock;
protected Queue operations;
protected Thread currentOperationThread;
class Identifier {
int operationId = OPERATION_EMPTY;
int preparedOperations = 0;
int nestedOperations = 0;
// Indication for running auto build. It is computated based
// on the parameters passed to Workspace.endOperation().
boolean shouldBuild = false;
// Enables or disables a condition based on the shouldBuild field.
boolean avoidAutoBuild = false;
boolean operationCanceled = false;
}
public static final int OPERATION_NONE = -1;
public static final int OPERATION_EMPTY = 0;
public WorkManager(Workspace workspace) {
currentOperationId = OPERATION_NONE;
identifiers = new Hashtable(10);
nextId = 0;
this.workspace = workspace;
operations = new Queue();
}
/**
* Returns null if acquired and a Semaphore object otherwise.
*/
public synchronized Semaphore acquire() {
if (isCurrentOperation())
return null;
if (currentOperationId == OPERATION_NONE && operations.isEmpty()) {
updateCurrentOperation(getOperationId());
return null;
}
return enqueue(new Semaphore(Thread.currentThread()));
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void avoidAutoBuild() {
getIdentifier(currentOperationThread).avoidAutoBuild = true;
}
/**
* An operation calls this method and it only returns when the operation
* is free to run.
*/
public void checkIn() throws CoreException {
try {
- boolean acquired = false;
- while (!acquired) {
+ while (true) {
try {
- acquired = getWorkspaceLock().acquire();
+ if (getWorkspaceLock().acquire())
+ return;
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
/**
* Inform that an operation has finished.
*/
public synchronized void checkOut() throws CoreException {
decrementPreparedOperations();
rebalanceNestedOperations();
// if this is a nested operation, just return
// and do not release the lock
if (getPreparedOperationDepth() > 0)
return;
getWorkspaceLock().release();
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void decrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations--;
}
/**
* If there is another semaphore with the same runnable in the
* queue, the other is returned and the new one is not added.
*/
private synchronized Semaphore enqueue(Semaphore newSemaphore) {
Semaphore semaphore = (Semaphore) operations.get(newSemaphore);
if (semaphore == null) {
operations.add(newSemaphore);
return newSemaphore;
}
return semaphore;
}
public synchronized Thread getCurrentOperationThread() {
return currentOperationThread;
}
private Identifier getIdentifier(Thread key) {
Assert.isNotNull(key, "The thread should never be null.");//$NON-NLS-1$
Identifier identifier = (Identifier) identifiers.get(key);
if (identifier == null) {
identifier = getNewIdentifier();
identifiers.put(key, identifier);
}
return identifier;
}
private Identifier getNewIdentifier() {
Identifier identifier = new Identifier();
identifier.operationId = getNextOperationId();
return identifier;
}
private int getNextOperationId() {
return ++nextId;
}
private int getOperationId() {
return getIdentifier(Thread.currentThread()).operationId;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public int getPreparedOperationDepth() {
return getIdentifier(currentOperationThread).preparedOperations;
}
private WorkspaceLock getWorkspaceLock() throws CoreException {
if (workspaceLock == null)
workspaceLock = workspaceLock = new WorkspaceLock(workspace);
return workspaceLock;
}
/**
* Returns true if the nested operation depth is the same
* as the prepared operation depth, and false otherwise.
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
boolean isBalanced() {
Identifier identifier = getIdentifier(currentOperationThread);
return identifier.nestedOperations == identifier.preparedOperations;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
void incrementNestedOperations() {
getIdentifier(currentOperationThread).nestedOperations++;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void incrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations++;
}
/**
* This method is synchronized with checkIn() and checkOut() that use blocks
* like synchronized (this) { ... }.
*/
public synchronized boolean isCurrentOperation() {
return currentOperationId == getOperationId();
}
public synchronized boolean isNextOperation(Runnable runnable) {
Semaphore next = (Semaphore) operations.peek();
return (next != null) && (next.getRunnable() == runnable);
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void operationCanceled() {
getIdentifier(currentOperationThread).operationCanceled = true;
}
/**
* Used to make things stable again after an operation has failed between
* a workspace.prepareOperation() and workspace.beginOperation().
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void rebalanceNestedOperations() {
Identifier identifier = getIdentifier(currentOperationThread);
identifier.nestedOperations = identifier.preparedOperations;
}
public synchronized void release() {
resetOperationId();
Semaphore next = (Semaphore) operations.peek();
updateCurrentOperation(OPERATION_NONE);
if (next != null)
next.release();
}
private void resetOperationId() {
// ensure the operation cache on this thread is null
identifiers.remove(currentOperationThread);
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public void setBuild(boolean build) {
Identifier identifier = getIdentifier(currentOperationThread);
if (identifier.preparedOperations == identifier.nestedOperations)
identifier.shouldBuild = (identifier.shouldBuild || build);
}
public void setWorkspaceLock(WorkspaceLock lock) {
//if (workspaceLock != null)
//return;
Assert.isNotNull(lock);
workspaceLock = lock;
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public boolean shouldBuild() {
Identifier identifier = getIdentifier(currentOperationThread);
if (!identifier.avoidAutoBuild && identifier.shouldBuild) {
if (identifier.operationCanceled)
return Policy.buildOnCancel;
return true;
}
return false;
}
public void shutdown(IProgressMonitor monitor) {
currentOperationId = OPERATION_NONE;
identifiers = null;
nextId = 0;
}
public void startup(IProgressMonitor monitor) {
}
public synchronized void updateCurrentOperation() {
operations.remove();
updateCurrentOperation(getOperationId());
}
private void updateCurrentOperation(int newID) {
currentOperationId = newID;
if (newID == OPERATION_NONE)
currentOperationThread = null;
else
currentOperationThread = Thread.currentThread();
}
public boolean isTreeLocked() {
return workspace.isTreeLocked();
}
}
| false | true | public void checkIn() throws CoreException {
try {
boolean acquired = false;
while (!acquired) {
try {
acquired = getWorkspaceLock().acquire();
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
| public void checkIn() throws CoreException {
try {
while (true) {
try {
if (getWorkspaceLock().acquire())
return;
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java
index b28f064e..3bc67ce0 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java
@@ -1,1317 +1,1317 @@
package jp.ac.osaka_u.ist.sel.metricstool.main;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.DataManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.ClassMetricsInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.FieldMetricsInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.FileMetricsInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MethodMetricsInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MetricNotRegisteredException;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.CallableUnitInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassTypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExpressionInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalConstructorInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalInnerClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalMethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalParameterInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FileInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.InnerClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.InstanceInitializerInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.JavaPredefinedModifierInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.LocalVariableInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.LocalVariableUsageInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ModifierInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ReferenceTypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.StaticInitializerInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetConstructorInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFile;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFileManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetMethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeParameterInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.VariableDeclarationStatementInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.JavaUnresolvedExternalClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.JavaUnresolvedExternalFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.JavaUnresolvedExternalMethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedConstructorInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedInstanceInitializerInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedMethodInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedStaticInitializerInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVClassMetricsWriter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVFileMetricsWriter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVMethodMetricsWriter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageEvent;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageListener;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePool;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource;
import jp.ac.osaka_u.ist.sel.metricstool.main.parse.asm.JavaByteCodeNameResolver;
import jp.ac.osaka_u.ist.sel.metricstool.main.parse.asm.JavaByteCodeParser;
import jp.ac.osaka_u.ist.sel.metricstool.main.parse.asm.JavaByteCodeUtility;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin.PluginInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.DefaultPluginLauncher;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginLauncher;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.DefaultPluginLoader;
import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.PluginLoadException;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.objectweb.asm.ClassReader;
/**
*
* @author higo
*
* MetricsTool�̃��C���N���X�D ���݂͉������D
*
* since 2006.11.12
*
*/
public class MetricsTool {
/**
*
* @param args �Ώۃt�@�C���̃t�@�C���p�X
*
* ���݉������D �Ώۃt�@�C���̃f�[�^���i�[������C�\����͂��s���D
*/
public static void main(String[] args) {
initSecurityManager();
// ���\���p�̃��X�i���쐬
final MessageListener outListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
final MessageListener errListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
- System.out.print(event.getSource().getMessageSourceName() + " > "
+ System.err.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener);
final Options options = new Options();
{
final Option h = new Option("h", "help", false, "display usage");
h.setRequired(false);
options.addOption(h);
}
{
final Option v = new Option("v", "verbose", false, "output progress verbosely");
v.setRequired(false);
options.addOption(v);
}
{
final Option d = new Option("d", "directores", true,
"specify target directories (separate with comma \',\' if you specify multiple directories");
d.setArgName("directories");
d.setArgs(1);
d.setRequired(false);
options.addOption(d);
}
{
final Option i = new Option(
"i",
"input",
true,
"specify the input that contains the list of target files (separate with comma \',\' if you specify multiple inputs)");
i.setArgName("input");
i.setArgs(1);
i.setRequired(false);
options.addOption(i);
}
{
final Option l = new Option("l", "language", true, "specify programming language");
l.setArgName("input");
l.setArgs(1);
l.setRequired(false);
options.addOption(l);
}
{
final Option m = new Option("m", "metrics", true,
"specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)");
m.setArgName("metrics");
m.setArgs(1);
m.setRequired(false);
options.addOption(m);
}
{
final Option F = new Option("F", "FileMetricsFile", true,
"specify file that measured FILE metrics were stored into");
F.setArgName("file metrics file");
F.setArgs(1);
F.setRequired(false);
options.addOption(F);
}
{
final Option C = new Option("C", "ClassMetricsFile", true,
"specify file that measured CLASS metrics were stored into");
C.setArgName("class metrics file");
C.setArgs(1);
C.setRequired(false);
options.addOption(C);
}
{
final Option M = new Option("M", "MethodMetricsFile", true,
"specify file that measured METHOD metrics were stored into");
M.setArgName("method metrics file");
M.setArgs(1);
M.setRequired(false);
options.addOption(M);
}
{
final Option A = new Option("A", "AttributeMetricsFile", true,
"specify file that measured ATTRIBUTE metrics were stored into");
A.setArgName("attribute metrics file");
A.setArgs(1);
A.setRequired(false);
options.addOption(A);
}
{
final Option s = new Option("s", "AnalyzeStatement", false,
"specify this option if you don't need statement information");
s.setRequired(false);
options.addOption(s);
}
{
final Option b = new Option("b", "libraries", true,
"specify libraries (.jar file or .class file or directory that contains .jar and .class files)");
b.setArgName("libraries");
b.setArgs(1);
b.setRequired(false);
options.addOption(b);
}
{
final Option t = new Option("t", "threads", true,
"specify thread number used for multi-thread processings");
t.setArgName("number");
t.setArgs(1);
t.setRequired(false);
options.addOption(t);
}
final MetricsTool metricsTool = new MetricsTool();
try {
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI��
// ���̂Ƃ��C���̃I�v�V�����͑S�Ė��������
if (cmd.hasOption("h") || (0 == args.length)) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MetricsTool", options, true);
// -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉\����ꗗ��\��
if (!cmd.hasOption("l")) {
err.println("Available languages;");
for (final LANGUAGE language : LANGUAGE.values()) {
err.println("\t" + language.getName() + ": can be specified with term \""
+ language.getIdentifierName() + "\"");
}
// -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�\�ȃ��g���N�X�ꗗ��\��
} else {
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
err.println("Available metrics for "
+ Settings.getInstance().getLanguage().getName());
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager()
.getPlugins()) {
final PluginInfo pluginInfo = plugin.getPluginInfo();
if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) {
err.println("\t" + pluginInfo.getMetricName());
}
}
}
System.exit(0);
}
Settings.getInstance().setVerbose(cmd.hasOption("v"));
if (cmd.hasOption("d")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("d"), ",");
while (tokenizer.hasMoreElements()) {
final String directory = tokenizer.nextToken();
Settings.getInstance().addTargetDirectory(directory);
}
}
if (cmd.hasOption("i")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("i"), ",");
while (tokenizer.hasMoreElements()) {
final String listFile = tokenizer.nextToken();
Settings.getInstance().addListFile(listFile);
}
}
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
if (cmd.hasOption("m")) {
Settings.getInstance().setMetrics(cmd.getOptionValue("m"));
}
if (cmd.hasOption("F")) {
Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F"));
}
if (cmd.hasOption("C")) {
Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C"));
}
if (cmd.hasOption("M")) {
Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M"));
}
if (cmd.hasOption("A")) {
Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A"));
}
Settings.getInstance().setStatement(!cmd.hasOption("s"));
if (cmd.hasOption("b")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("b"), ",");
while (tokenizer.hasMoreElements()) {
final String library = tokenizer.nextToken();
Settings.getInstance().addLibrary(library);
}
}
if (cmd.hasOption("t")) {
Settings.getInstance().setThreadNumber(Integer.parseInt(cmd.getOptionValue("t")));
}
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
// �R�}���h���C�����������������ǂ����`�F�b�N����
{
// -d �� -i �̂ǂ�����w�肳��Ă���͕̂s��
if (!cmd.hasOption("d") && !cmd.hasOption("l")) {
err.println("-d and/or -i must be specified in the analysis mode!");
System.exit(0);
}
// ���ꂪ�w�肳��Ȃ������͕̂s��
if (!cmd.hasOption("l")) {
err.println("-l must be specified for analysis");
System.exit(0);
}
{
// �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& !cmd.hasOption("F")) {
err.println("-F must be specified for file metrics!");
System.exit(0);
}
// �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& !cmd.hasOption("C")) {
err.println("-C must be specified for class metrics!");
System.exit(0);
}
// ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& !cmd.hasOption("M")) {
err.println("-M must be specified for method metrics!");
System.exit(0);
}
// �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& !cmd.hasOption("A")) {
err.println("-A must be specified for field metrics!");
System.exit(0);
}
}
{
// �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& cmd.hasOption("F")) {
err.println("No file metric is specified. -F is ignored.");
}
// �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& cmd.hasOption("C")) {
err.println("No class metric is specified. -C is ignored.");
}
// ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& cmd.hasOption("M")) {
err.println("No method metric is specified. -M is ignored.");
}
// �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& cmd.hasOption("A")) {
err.println("No field metric is specified. -A is ignored.");
}
}
}
} catch (ParseException e) {
System.out.println(e.getMessage());
System.exit(0);
}
final long start = System.nanoTime();
metricsTool.analyzeLibraries();
metricsTool.readTargetFiles();
metricsTool.analyzeTargetFiles();
metricsTool.launchPlugins();
metricsTool.writeMetrics();
out.println("successfully finished.");
final long end = System.nanoTime();
if (Settings.getInstance().isVerbose()) {
out.println("elapsed time: " + (end - start) / 1000000000 + " seconds");
out.println("number of analyzed files: "
+ DataManager.getInstance().getFileInfoManager().getFileInfos().size());
int loc = 0;
for (final FileInfo file : DataManager.getInstance().getFileInfoManager()
.getFileInfos()) {
loc += file.getLOC();
}
out.println("analyzed lines of code: " + loc);
}
MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener);
}
/**
* ���������R���X�g���N�^�D �Z�L�����e�B�}�l�[�W���̏��������s���D
*/
public MetricsTool() {
}
/**
* ���C�u��������͂��C���̏���ExternalClassInfo�Ƃ��ēo�^����D
* readTargetFiles()�̑O�ɌĂяo����Ȃ���Ȃ�Ȃ�
*/
public void analyzeLibraries() {
final Settings settings = Settings.getInstance();
// java����̏ꍇ
if (settings.getLanguage().equals(LANGUAGE.JAVA15)
|| settings.getLanguage().equals(LANGUAGE.JAVA14)
|| settings.getLanguage().equals(LANGUAGE.JAVA13)) {
this.analyzeJavaLibraries();
}
else if (settings.getLanguage().equals(LANGUAGE.CSHARP)) {
}
}
private void analyzeJavaLibraries() {
final Set<JavaUnresolvedExternalClassInfo> unresolvedExternalClasses = new HashSet<JavaUnresolvedExternalClassInfo>();
// �o�C�g�R�[�h����ǂݍ���
for (final String path : Settings.getInstance().getLibraries()) {
readJavaLibraries(new File(path), unresolvedExternalClasses);
}
// �N���X���̂��̂̂ݖ��O�����i�^�͉������Ȃ��j
final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager();
for (final JavaUnresolvedExternalClassInfo unresolvedClassInfo : unresolvedExternalClasses) {
// �����N���X�͖��O�������Ȃ�
if (unresolvedClassInfo.isAnonymous()) {
continue;
}
final String unresolvedName = unresolvedClassInfo.getName();
final String[] name = JavaByteCodeNameResolver.resolveName(unresolvedName);
final Set<String> unresolvedModifiers = unresolvedClassInfo.getModifiers();
final boolean isInterface = unresolvedClassInfo.isInterface();
final Set<ModifierInfo> modifiers = new HashSet<ModifierInfo>();
for (final String unresolvedModifier : unresolvedModifiers) {
modifiers.add(JavaPredefinedModifierInfo.getModifierInfo(unresolvedModifier));
}
final ExternalClassInfo classInfo = unresolvedClassInfo.isInner() ? new ExternalInnerClassInfo(
modifiers, name, isInterface)
: new ExternalClassInfo(modifiers, name, isInterface);
classInfoManager.add(classInfo);
}
// �O���̃N���X����lj�
for (final JavaUnresolvedExternalClassInfo unresolvedClassInfo : unresolvedExternalClasses) {
// �����N���X�͖���
if (unresolvedClassInfo.isAnonymous()) {
continue;
}
// �C���i�[�N���X�łȂ��ꍇ�͖���
if (!unresolvedClassInfo.isInner()) {
continue;
}
final String[] fqName = JavaByteCodeUtility.separateName(unresolvedClassInfo.getName());
final String[] outerFQName = Arrays.copyOf(fqName, fqName.length - 1);
final ClassInfo outerClass = classInfoManager.getClassInfo(outerFQName);
if (null != outerClass) { // outerClass���o�^����Ă��Ȃ���������Ȃ��̂�
final ClassInfo classInfo = classInfoManager.getClassInfo(fqName);
((ExternalInnerClassInfo) classInfo).setOuterUnit(outerClass);
}
}
//�@�^�p�����[�^������
for (final JavaUnresolvedExternalClassInfo unresolvedClassInfo : unresolvedExternalClasses) {
// �����N���X�͖���
if (unresolvedClassInfo.isAnonymous()) {
continue;
}
// �܂��́C�����ς݃I�u�W�F�N�g���擾
final String unresolvedClassName = unresolvedClassInfo.getName();
final String[] className = JavaByteCodeNameResolver.resolveName(unresolvedClassName);
final ExternalClassInfo classInfo = (ExternalClassInfo) classInfoManager
.getClassInfo(className);
// �^�p�����[�^������
final List<String> unresolvedTypeParameters = unresolvedClassInfo.getTypeParameters();
for (int index = 0; index < unresolvedTypeParameters.size(); index++) {
final String unresolvedTypeParameter = unresolvedTypeParameters.get(index);
TypeParameterInfo typeParameter = JavaByteCodeNameResolver.resolveTypeParameter(
unresolvedTypeParameter, index, classInfo);
classInfo.addTypeParameter(typeParameter);
}
}
//�@�e�N���X�ŕ\���Ă���^���������Ă���
for (final JavaUnresolvedExternalClassInfo unresolvedClassInfo : unresolvedExternalClasses) {
// �����N���X�͖��O�������Ȃ�
if (unresolvedClassInfo.isAnonymous()) {
continue;
}
// �܂��́C�����ς݃I�u�W�F�N�g���擾
final String unresolvedClassName = unresolvedClassInfo.getName();
final String[] className = JavaByteCodeNameResolver.resolveName(unresolvedClassName);
final ExternalClassInfo classInfo = (ExternalClassInfo) classInfoManager
.getClassInfo(className);
// �e�N���X,�C���^�[�t�F�[�X������
for (final String unresolvedSuperType : unresolvedClassInfo.getSuperTypes()) {
final TypeInfo superType = JavaByteCodeNameResolver.resolveType(
unresolvedSuperType, null, classInfo);
classInfo.addSuperClass((ClassTypeInfo) superType);
}
// �t�B�[���h�̉���
for (final JavaUnresolvedExternalFieldInfo unresolvedField : unresolvedClassInfo
.getFields()) {
final String fieldName = unresolvedField.getName();
final String unresolvedType = unresolvedField.getType();
final TypeInfo fieldType = JavaByteCodeNameResolver.resolveType(unresolvedType,
null, null);
final Set<String> unresolvedModifiers = unresolvedField.getModifiers();
final boolean isInstance = !unresolvedModifiers
.contains(JavaPredefinedModifierInfo.STATIC_STRING);
final Set<ModifierInfo> modifiers = new HashSet<ModifierInfo>();
for (final String unresolvedModifier : unresolvedModifiers) {
modifiers.add(JavaPredefinedModifierInfo.getModifierInfo(unresolvedModifier));
}
final ExternalFieldInfo field = new ExternalFieldInfo(modifiers, fieldName,
classInfo, isInstance);
field.setType(fieldType);
classInfo.addDefinedField(field);
}
// ���\�b�h�̉���
for (final JavaUnresolvedExternalMethodInfo unresolvedMethod : unresolvedClassInfo
.getMethods()) {
final String name = unresolvedMethod.getName();
final Set<String> unresolvedModifiers = unresolvedMethod.getModifiers();
final boolean isStatic = unresolvedModifiers
.contains(JavaPredefinedModifierInfo.STATIC_STRING);
final Set<ModifierInfo> modifiers = new HashSet<ModifierInfo>();
for (final String unresolvedModifier : unresolvedModifiers) {
modifiers.add(JavaPredefinedModifierInfo.getModifierInfo(unresolvedModifier));
}
// �R���X�g���N�^�̂Ƃ�
if (name.equals("<init>")) {
final ExternalConstructorInfo constructor = new ExternalConstructorInfo(
modifiers);
constructor.setOuterUnit(classInfo);
// �^�p�����[�^�̉���
final List<String> unresolvedTypeParameters = unresolvedMethod
.getTypeParameters();
for (int index = 0; index < unresolvedTypeParameters.size(); index++) {
final String unresolvedTypeParameter = unresolvedTypeParameters.get(index);
TypeParameterInfo typeParameter = (TypeParameterInfo) JavaByteCodeNameResolver
.resolveTypeParameter(unresolvedTypeParameter, index, constructor);
constructor.addTypeParameter(typeParameter);
}
// �����̉���
final List<String> unresolvedParameters = unresolvedMethod.getArgumentTypes();
for (final String unresolvedParameter : unresolvedParameters) {
final TypeInfo parameterType = JavaByteCodeNameResolver.resolveType(
unresolvedParameter, null, constructor);
final ExternalParameterInfo parameter = new ExternalParameterInfo(
parameterType, constructor);
constructor.addParameter(parameter);
}
// �X���[������O�̉���
final List<String> unresolvedThrownExceptions = unresolvedMethod
.getThrownExceptions();
for (final String unresolvedThrownException : unresolvedThrownExceptions) {
final TypeInfo exceptionType = JavaByteCodeNameResolver.resolveType(
unresolvedThrownException, null, constructor);
constructor.addThrownException((ReferenceTypeInfo) exceptionType);
}
classInfo.addDefinedConstructor(constructor);
}
// ���\�b�h�̂Ƃ�
else {
final ExternalMethodInfo method = new ExternalMethodInfo(modifiers, name,
!isStatic);
method.setOuterUnit(classInfo);
// �^�p�����[�^�̉���
final List<String> unresolvedTypeParameters = unresolvedMethod
.getTypeParameters();
for (int index = 0; index < unresolvedTypeParameters.size(); index++) {
final String unresolvedTypeParameter = unresolvedTypeParameters.get(index);
TypeParameterInfo typeParameter = JavaByteCodeNameResolver
.resolveTypeParameter(unresolvedTypeParameter, index, method);
method.addTypeParameter(typeParameter);
}
// �Ԃ�l�̉���
final String unresolvedReturnType = unresolvedMethod.getReturnType();
final TypeInfo returnType = JavaByteCodeNameResolver.resolveType(
unresolvedReturnType, null, method);
method.setReturnType(returnType);
// �����̉���
final List<String> unresolvedParameters = unresolvedMethod.getArgumentTypes();
for (final String unresolvedParameter : unresolvedParameters) {
final TypeInfo parameterType = JavaByteCodeNameResolver.resolveType(
unresolvedParameter, null, method);
final ExternalParameterInfo parameter = new ExternalParameterInfo(
parameterType, method);
method.addParameter(parameter);
}
// �X���[������O�̉���
final List<String> unresolvedThrownExceptions = unresolvedMethod
.getThrownExceptions();
for (final String unresolvedThrownException : unresolvedThrownExceptions) {
final TypeInfo exceptionType = JavaByteCodeNameResolver.resolveType(
unresolvedThrownException, null, method);
method.addThrownException((ReferenceTypeInfo) exceptionType);
}
classInfo.addDefinedMethod(method);
}
}
}
}
private void readJavaLibraries(final File file,
final Set<JavaUnresolvedExternalClassInfo> unresolvedExternalClasses) {
try {
// jar�t�@�C���̏ꍇ
if (file.isFile() && file.getName().endsWith(".jar")) {
final JarFile jar = new JarFile(file);
for (final Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements();) {
final JarEntry entry = entries.nextElement();
if (entry.getName().endsWith(".class")) {
final ClassReader reader = new ClassReader(jar.getInputStream(entry));
final JavaByteCodeParser parser = new JavaByteCodeParser();
reader.accept(parser, ClassReader.SKIP_CODE);
unresolvedExternalClasses.add(parser.getClassInfo());
}
}
}
// class�t�@�C���̏ꍇ
else if (file.isFile() && file.getName().endsWith(".class")) {
final ClassReader reader = new ClassReader(new FileInputStream(file));
final JavaByteCodeParser parser = new JavaByteCodeParser();
reader.accept(parser, ClassReader.SKIP_CODE);
unresolvedExternalClasses.add(parser.getClassInfo());
}
// �f�B���N�g���̏ꍇ
else if (file.isDirectory()) {
for (final File subfile : file.listFiles()) {
if (subfile.isFile()) {
final String name = subfile.getName();
if (name.endsWith(".jar") || name.endsWith(".class")) {
readJavaLibraries(subfile, unresolvedExternalClasses);
}
}
else if (subfile.isDirectory()) {
readJavaLibraries(subfile, unresolvedExternalClasses);
}
}
}
//��L�ȊO�̏ꍇ�͐������Ȃ��t�@�C����Java�̃��C�u�����Ƃ��Ďw�肳��Ă��邱�ƂɂȂ�C�I��
else {
err.println("file <" + file.getAbsolutePath()
+ "> is inappropriate as a Java library.");
System.exit(0);
}
}
// ���C�u�����̓ǂݍ��݂ŗ�O�����������ꍇ�̓v���O�������I��
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
/**
* {@link #readTargetFiles()} �œǂݍ��Ώۃt�@�C���Q����͂���.
*
*/
public void analyzeTargetFiles() {
// �Ώۃt�@�C����AST���疢�����N���X�C�t�B�[���h�C���\�b�h�����擾
out.println("parsing all target files.");
parseTargetFiles();
out.println("resolving definitions and usages.");
if (Settings.getInstance().isVerbose()) {
out.println("STEP1 : resolve definitions.");
}
resolveDefinitions();
if (Settings.getInstance().isVerbose()) {
out.println("STEP2 : resolve types in definitions.");
}
resolveTypes();
if (Settings.getInstance().isVerbose()) {
out.println("STEP3 : resolve method overrides.");
}
addOverrideRelation();
if (Settings.getInstance().isStatement()) {
if (Settings.getInstance().isVerbose()) {
out.println("STEP4 : resolve field and method usages.");
}
addMethodInsideInfomation();
}
// ���@���̂���t�@�C���ꗗ��\��
// err.println("The following files includes incorrect syntax.");
// err.println("Any metrics of them were not measured");
for (final TargetFile targetFile : DataManager.getInstance().getTargetFileManager()) {
if (!targetFile.isCorrectSyntax()) {
err.println("Incorrect syntax file: " + targetFile.getName());
}
}
}
/**
* �v���O�C�������[�h����. �w�肳�ꂽ����C�w�肳�ꂽ���g���N�X�Ɋ֘A����v���O�C���݂̂� {@link PluginManager}�ɓo�^����.
* null ���w�肳�ꂽ�ꍇ�͑Ώی���ɂ����Čv���\�ȑS�Ẵ��g���N�X��o�^����
*
* @param metrics �w�肷�郁�g���N�X�̔z��C�w�肵�Ȃ��ꍇ��null
*/
public void loadPlugins(final String[] metrics) {
final PluginManager pluginManager = DataManager.getInstance().getPluginManager();
final Settings settings = Settings.getInstance();
try {
for (final AbstractPlugin plugin : (new DefaultPluginLoader()).loadPlugins()) {// �v���O�C����S���[�h
final PluginInfo info = plugin.getPluginInfo();
// �Ώی���Ōv���\�łȂ���Γo�^���Ȃ�
if (!info.isMeasurable(settings.getLanguage())) {
continue;
}
if (null != metrics) {
// ���g���N�X���w�肳��Ă���̂ł��̃v���O�C���ƈ�v���邩�`�F�b�N
final String pluginMetricName = info.getMetricName();
for (final String metric : metrics) {
if (metric.equalsIgnoreCase(pluginMetricName)) {
pluginManager.addPlugin(plugin);
break;
}
}
// ���g���N�X���w�肳��Ă��Ȃ��̂łƂ肠�����S���o�^
} else {
pluginManager.addPlugin(plugin);
}
}
} catch (PluginLoadException e) {
err.println(e.getMessage());
System.exit(0);
}
}
/**
* ���[�h�ς݂̃v���O�C�������s����.
*/
public void launchPlugins() {
out.println("calculating metrics.");
PluginLauncher launcher = new DefaultPluginLauncher();
launcher.setMaximumLaunchingNum(1);
launcher.launchAll(DataManager.getInstance().getPluginManager().getPlugins());
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// �C�ɂ��Ȃ�
}
} while (0 < launcher.getCurrentLaunchingNum() + launcher.getLaunchWaitingTaskNum());
launcher.stopLaunching();
}
/**
* {@link Settings}�Ɏw�肳�ꂽ�ꏊ�����͑Ώۃt�@�C����ǂݍ���œo�^����
*/
public void readTargetFiles() {
out.println("building target file list.");
final Settings settings = Settings.getInstance();
// �f�B���N�g������ǂݍ���
for (final String directory : settings.getTargetDirectories()) {
registerFilesFromDirectory(new File(directory));
}
// ���X�g�t�@�C������ǂݍ���
for (final String file : settings.getListFiles()) {
try {
final TargetFileManager targetFiles = DataManager.getInstance()
.getTargetFileManager();
final BufferedReader reader = new BufferedReader(new FileReader(file));
while (reader.ready()) {
final String line = reader.readLine();
final TargetFile targetFile = new TargetFile(line);
targetFiles.add(targetFile);
}
reader.close();
} catch (FileNotFoundException e) {
err.println("\"" + file + "\" is not a valid file!");
System.exit(0);
} catch (IOException e) {
err.println("\"" + file + "\" can\'t read!");
System.exit(0);
}
}
}
/**
* ���g���N�X���� {@link Settings} �Ɏw�肳�ꂽ�t�@�C���ɏo�͂���.
*/
public void writeMetrics() {
final PluginManager pluginManager = DataManager.getInstance().getPluginManager();
final Settings settings = Settings.getInstance();
// �t�@�C�����g���N�X���v������ꍇ
if (0 < pluginManager.getFileMetricPlugins().size()) {
try {
final FileMetricsInfoManager manager = DataManager.getInstance()
.getFileMetricsInfoManager();
manager.checkMetrics();
final String fileName = settings.getFileMetricsFile();
final CSVFileMetricsWriter writer = new CSVFileMetricsWriter(fileName);
writer.write();
} catch (MetricNotRegisteredException e) {
err.println(e.getMessage());
err.println("File metrics can't be output!");
}
}
// �N���X���g���N�X���v������ꍇ
if (0 < pluginManager.getClassMetricPlugins().size()) {
try {
final ClassMetricsInfoManager manager = DataManager.getInstance()
.getClassMetricsInfoManager();
manager.checkMetrics();
final String fileName = settings.getClassMetricsFile();
final CSVClassMetricsWriter writer = new CSVClassMetricsWriter(fileName);
writer.write();
} catch (MetricNotRegisteredException e) {
err.println(e.getMessage());
err.println("Class metrics can't be output!");
}
}
// ���\�b�h���g���N�X���v������ꍇ
if (0 < pluginManager.getMethodMetricPlugins().size()) {
try {
final MethodMetricsInfoManager manager = DataManager.getInstance()
.getMethodMetricsInfoManager();
manager.checkMetrics();
final String fileName = settings.getMethodMetricsFile();
final CSVMethodMetricsWriter writer = new CSVMethodMetricsWriter(fileName);
writer.write();
} catch (MetricNotRegisteredException e) {
err.println(e.getMessage());
err.println("Method metrics can't be output!");
}
}
// �t�B�[���h���g���N�X���v������ꍇ
if (0 < pluginManager.getFieldMetricPlugins().size()) {
try {
final FieldMetricsInfoManager manager = DataManager.getInstance()
.getFieldMetricsInfoManager();
manager.checkMetrics();
final String fileName = settings.getMethodMetricsFile();
final CSVMethodMetricsWriter writer = new CSVMethodMetricsWriter(fileName);
writer.write();
} catch (MetricNotRegisteredException e) {
err.println(e.getMessage());
err.println("Field metrics can't be output!");
}
}
}
/**
* {@link MetricsToolSecurityManager} �̏��������s��. �V�X�e���ɓo�^�ł���C�V�X�e���̃Z�L�����e�B�}�l�[�W���ɂ��o�^����.
*/
private static final void initSecurityManager() {
try {
// MetricsToolSecurityManager�̃V���O���g���C���X�^���X���\�z���C�������ʌ����X���b�h�ɂȂ�
System.setSecurityManager(MetricsToolSecurityManager.getInstance());
} catch (final SecurityException e) {
// ���ɃZ�b�g����Ă���Z�L�����e�B�}�l�[�W���ɂ���āC�V���ȃZ�L�����e�B�}�l�[�W���̓o�^��������Ȃ������D
// �V�X�e���̃Z�L�����e�B�}�l�[�W���Ƃ��Ďg��Ȃ��Ă��C���ʌ����X���b�h�̃A�N�Z�X����͖��Ȃ����삷��̂łƂ肠������������
err
.println("Failed to set system security manager. MetricsToolsecurityManager works only to manage privilege threads.");
}
}
/**
*
* @param file �Ώۃt�@�C���܂��̓f�B���N�g��
*
* �Ώۂ��f�B���N�g���̏ꍇ�́C���̎q�ɑ��čċA�I�ɏ���������D �Ώۂ��t�@�C���̏ꍇ�́C�Ώی���̃\�[�X�t�@�C���ł���C�o�^�������s���D
*/
private void registerFilesFromDirectory(final File file) {
// �f�B���N�g���Ȃ�C�ċA�I�ɏ���
if (file.isDirectory()) {
File[] subfiles = file.listFiles();
for (int i = 0; i < subfiles.length; i++) {
registerFilesFromDirectory(subfiles[i]);
}
// �t�@�C���Ȃ�C�g���q���Ώی���ƈ�v����Γo�^
} else if (file.isFile()) {
final LANGUAGE language = Settings.getInstance().getLanguage();
final String extension = language.getExtension();
final String path = file.getAbsolutePath();
if (path.endsWith(extension)) {
final TargetFileManager targetFiles = DataManager.getInstance()
.getTargetFileManager();
final TargetFile targetFile = new TargetFile(path);
targetFiles.add(targetFile);
}
// �f�B���N�g���ł��t�@�C���ł��Ȃ��ꍇ�͕s��
} else {
err.println("\"" + file.getAbsolutePath() + "\" is not a vaild file!");
System.exit(0);
}
}
/**
* �o�̓��b�Z�[�W�o�͗p�̃v�����^
*/
protected static MessagePrinter out = new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "main";
}
}, MESSAGE_TYPE.OUT);
/**
* �G���[���b�Z�[�W�o�͗p�̃v�����^
*/
protected static MessagePrinter err = new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "main";
}
}, MESSAGE_TYPE.ERROR);
/**
* �Ώۃt�@�C����AST���疢�����N���X�C�t�B�[���h�C���\�b�h�����擾
*/
public void parseTargetFiles() {
final Thread[] threads = new Thread[Settings.getInstance().getThreadNumber()];
final TargetFile[] files = DataManager.getInstance().getTargetFileManager().getFiles()
.toArray(new TargetFile[0]);
final AtomicInteger index = new AtomicInteger();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new TargetFileParser(files, index, out, err));
MetricsToolSecurityManager.getInstance().addPrivilegeThread(threads[i]);
threads[i].start();
}
//�S�ẴX���b�h���I���̂�҂�
for (final Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* �N���X�C���\�b�h�C�t�B�[���h�Ȃǂ̒�`�𖼑O��������DAST �p�[�X�̌�ɌĂяo���Ȃ���Ȃ�Ȃ��D
*/
private void resolveDefinitions() {
// �������N���X���}�l�[�W���C �N���X���}�l�[�W�����擾
final UnresolvedClassInfoManager unresolvedClassManager = DataManager.getInstance()
.getUnresolvedClassInfoManager();
final ClassInfoManager classManager = DataManager.getInstance().getClassInfoManager();
final FieldInfoManager fieldManager = DataManager.getInstance().getFieldInfoManager();
final MethodInfoManager methodManager = DataManager.getInstance().getMethodInfoManager();
// �e�������N���X�ɑ���
for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassManager.getClassInfos()) {
final FileInfo fileInfo = unresolvedClassInfo.getFileInfo();
//�@�N���X��������
final TargetClassInfo classInfo = unresolvedClassInfo.resolve(null, null, classManager,
fieldManager, methodManager);
fileInfo.addDefinedClass(classInfo);
// �������ꂽ�N���X����o�^
classManager.add(classInfo);
}
// �e�������N���X�̊O���̃��j�b�g������
for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassManager.getClassInfos()) {
unresolvedClassInfo.resolveOuterUnit(classManager);
}
}
/**
* �N���X�Ȃǂ̒�`�̒��ŗ��p����Ă���^�𖼑O��������D
* resolveDefinitions�̌�ɌĂяo����Ȃ���Ȃ�Ȃ�
*/
private void resolveTypes() {
// �������N���X���}�l�[�W���C �N���X���}�l�[�W�����擾
final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance()
.getUnresolvedClassInfoManager();
final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager();
// ��� superTyp��������
for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager
.getClassInfos()) {
unresolvedClassInfo.resolveSuperClass(classInfoManager);
}
// �c���Type������
for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager
.getClassInfos()) {
unresolvedClassInfo.resolveTypeParameter(classInfoManager);
for (final UnresolvedMethodInfo unresolvedMethod : unresolvedClassInfo
.getDefinedMethods()) {
unresolvedMethod.resolveParameter(classInfoManager);
unresolvedMethod.resolveReturnType(classInfoManager);
unresolvedMethod.resolveThrownException(classInfoManager);
unresolvedMethod.resolveTypeParameter(classInfoManager);
}
for (final UnresolvedConstructorInfo unresolvedConstructor : unresolvedClassInfo
.getDefinedConstructors()) {
unresolvedConstructor.resolveParameter(classInfoManager);
unresolvedConstructor.resolveThrownException(classInfoManager);
unresolvedConstructor.resolveTypeParameter(classInfoManager);
}
for (final UnresolvedFieldInfo unresolvedField : unresolvedClassInfo.getDefinedFields()) {
unresolvedField.resolveType(classInfoManager);
}
}
}
/**
* ���\�b�h�I�[�o�[���C�h�����eMethodInfo�ɒlj�����DaddInheritanceInfomationToClassInfos �̌� ���� registMethodInfos
* �̌�ɌĂяo���Ȃ���Ȃ�Ȃ�
*/
private void addOverrideRelation() {
// �S�Ă̊O���N���X�ɑ���
for (final ExternalClassInfo classInfo : DataManager.getInstance().getClassInfoManager()
.getExternalClassInfos()) {
addOverrideRelation(classInfo);
}
// �S�Ă̑ΏۃN���X�ɑ���
for (final TargetClassInfo classInfo : DataManager.getInstance().getClassInfoManager()
.getTargetClassInfos()) {
addOverrideRelation(classInfo);
}
}
/**
* ���\�b�h�I�[�o�[���C�h�����eMethodInfo�ɒlj�����D�����Ŏw�肵���N���X�̃��\�b�h�ɂ��ď������s��
*
* @param classInfo �ΏۃN���X
*/
private void addOverrideRelation(final ClassInfo classInfo) {
// �e�e�N���X�ɑ���
for (final ClassInfo superClassInfo : ClassTypeInfo.convert(classInfo.getSuperClasses())) {
// �e�ΏۃN���X�̊e���\�b�h�ɂ��āC�e�N���X�̃��\�b�h���I�[�o�[���C�h���Ă��邩��
for (final MethodInfo methodInfo : classInfo.getDefinedMethods()) {
addOverrideRelation(superClassInfo, methodInfo);
}
}
// �e�C���i�[�N���X�ɑ���
for (InnerClassInfo innerClassInfo : classInfo.getInnerClasses()) {
addOverrideRelation((ClassInfo) innerClassInfo);
}
}
/**
* ���\�b�h�I�[�o�[���C�h����lj�����D�����Ŏw�肳�ꂽ�N���X�Œ�`����Ă��郁�\�b�h�ɑ��đ�����s��.
* AddOverrideInformationToMethodInfos()�̒�����̂Ăяo�����D
*
* @param classInfo �N���X���
* @param overrider �I�[�o�[���C�h�Ώۂ̃��\�b�h
*/
private void addOverrideRelation(final ClassInfo classInfo, final MethodInfo overrider) {
if ((null == classInfo) || (null == overrider)) {
throw new IllegalArgumentException();
}
for (final MethodInfo methodInfo : classInfo.getDefinedMethods()) {
// ���\�b�h�����Ⴄ�ꍇ�̓I�[�o�[���C�h����Ȃ�
if (!methodInfo.getMethodName().equals(overrider.getMethodName())) {
continue;
}
if (0 != methodInfo.compareArgumentsTo(overrider)) {
continue;
}
// �I�[�o�[���C�h�W��o�^����
overrider.addOverridee(methodInfo);
methodInfo.addOverrider(overrider);
// ���ڂ̃I�[�o�[���C�h�W�������o���Ȃ��̂ŁC���̃N���X�̐e�N���X�͒������Ȃ�
return;
}
// �e�N���X�Q�ɑ��čċA�I�ɏ���
for (final ClassInfo superClassInfo : ClassTypeInfo.convert(classInfo.getSuperClasses())) {
addOverrideRelation(superClassInfo, overrider);
}
}
/**
* �G���e�B�e�B�i�t�B�[���h��N���X�j�̑���E�Q�ƁC���\�b�h�̌Ăяo���W��lj�����D
*/
private void addMethodInsideInfomation() {
final UnresolvedClassInfoManager unresolvedClassInfoManager = DataManager.getInstance()
.getUnresolvedClassInfoManager();
final ClassInfoManager classInfoManager = DataManager.getInstance().getClassInfoManager();
final FieldInfoManager fieldInfoManager = DataManager.getInstance().getFieldInfoManager();
final MethodInfoManager methodInfoManager = DataManager.getInstance()
.getMethodInfoManager();
// �e�������N���X��� �ɑ���
for (final UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager
.getClassInfos()) {
final TargetClassInfo classInfo = unresolvedClassInfo.getResolved();
// �������t�B�[���h���ɑ���
for (final UnresolvedFieldInfo unresolvedFieldInfo : unresolvedClassInfo
.getDefinedFields()) {
final TargetFieldInfo fieldInfo = unresolvedFieldInfo.getResolved();
if (null != unresolvedFieldInfo.getInitilizer()) {
final CallableUnitInfo initializerUnit = fieldInfo.isInstanceMember() ? classInfo
.getImplicitInstanceInitializer() : classInfo
.getImplicitStaticInitializer();
final ExpressionInfo initializerExpression = unresolvedFieldInfo
.getInitilizer().resolve(classInfo, initializerUnit, classInfoManager,
fieldInfoManager, methodInfoManager);
fieldInfo.setInitializer(initializerExpression);
// regist as an initializer
// TODO need more SMART way
final LocalVariableInfo fieldInfoAsLocalVariable = new LocalVariableInfo(
fieldInfo.getModifiers(), fieldInfo.getName(), fieldInfo.getType(),
initializerUnit, fieldInfo.getFromLine(), fieldInfo.getFromColumn(),
fieldInfo.getToLine(), fieldInfo.getToColumn());
final LocalVariableUsageInfo fieldUsage = LocalVariableUsageInfo.getInstance(
fieldInfoAsLocalVariable, false, true, initializerUnit,
fieldInfo.getFromLine(), fieldInfo.getFromColumn(),
fieldInfo.getToLine(), fieldInfo.getToColumn());
final VariableDeclarationStatementInfo implicitInitializerStatement = new VariableDeclarationStatementInfo(
initializerUnit, fieldUsage, initializerExpression,
fieldInfo.getFromLine(), fieldInfo.getFromColumn(),
initializerExpression.getToLine(), initializerExpression.getToColumn());
initializerUnit.addStatement(implicitInitializerStatement);
}
}
// �e���������\�b�h���ɑ���
for (final UnresolvedMethodInfo unresolvedMethod : unresolvedClassInfo
.getDefinedMethods()) {
final TargetMethodInfo method = unresolvedMethod.getResolved();
unresolvedMethod.resolveInnerBlock(classInfo, method, classInfoManager,
fieldInfoManager, methodInfoManager);
}
// �e�������R���X�g���N�^���ɑ���
for (final UnresolvedConstructorInfo unresolvedConstructor : unresolvedClassInfo
.getDefinedConstructors()) {
final TargetConstructorInfo constructor = unresolvedConstructor.getResolved();
unresolvedConstructor.resolveInnerBlock(classInfo, constructor, classInfoManager,
fieldInfoManager, methodInfoManager);
}
// resolve UnresolvedInstanceInitializers and register them
for (final UnresolvedInstanceInitializerInfo unresolvedInstanceInitializer : unresolvedClassInfo
.getInstanceInitializers()) {
final InstanceInitializerInfo initializer = unresolvedInstanceInitializer
.getResolved();
unresolvedInstanceInitializer.resolveInnerBlock(classInfo, initializer,
classInfoManager, fieldInfoManager, methodInfoManager);
}
// resolve UnresolvedStaticInitializers and register them
for (final UnresolvedStaticInitializerInfo unresolvedStaticInitializer : unresolvedClassInfo
.getStaticInitializers()) {
final StaticInitializerInfo initializer = unresolvedStaticInitializer.getResolved();
unresolvedStaticInitializer.resolveInnerBlock(classInfo, initializer,
classInfoManager, fieldInfoManager, methodInfoManager);
}
}
}
}
| true | true | public static void main(String[] args) {
initSecurityManager();
// ���\���p�̃��X�i���쐬
final MessageListener outListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
final MessageListener errListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener);
final Options options = new Options();
{
final Option h = new Option("h", "help", false, "display usage");
h.setRequired(false);
options.addOption(h);
}
{
final Option v = new Option("v", "verbose", false, "output progress verbosely");
v.setRequired(false);
options.addOption(v);
}
{
final Option d = new Option("d", "directores", true,
"specify target directories (separate with comma \',\' if you specify multiple directories");
d.setArgName("directories");
d.setArgs(1);
d.setRequired(false);
options.addOption(d);
}
{
final Option i = new Option(
"i",
"input",
true,
"specify the input that contains the list of target files (separate with comma \',\' if you specify multiple inputs)");
i.setArgName("input");
i.setArgs(1);
i.setRequired(false);
options.addOption(i);
}
{
final Option l = new Option("l", "language", true, "specify programming language");
l.setArgName("input");
l.setArgs(1);
l.setRequired(false);
options.addOption(l);
}
{
final Option m = new Option("m", "metrics", true,
"specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)");
m.setArgName("metrics");
m.setArgs(1);
m.setRequired(false);
options.addOption(m);
}
{
final Option F = new Option("F", "FileMetricsFile", true,
"specify file that measured FILE metrics were stored into");
F.setArgName("file metrics file");
F.setArgs(1);
F.setRequired(false);
options.addOption(F);
}
{
final Option C = new Option("C", "ClassMetricsFile", true,
"specify file that measured CLASS metrics were stored into");
C.setArgName("class metrics file");
C.setArgs(1);
C.setRequired(false);
options.addOption(C);
}
{
final Option M = new Option("M", "MethodMetricsFile", true,
"specify file that measured METHOD metrics were stored into");
M.setArgName("method metrics file");
M.setArgs(1);
M.setRequired(false);
options.addOption(M);
}
{
final Option A = new Option("A", "AttributeMetricsFile", true,
"specify file that measured ATTRIBUTE metrics were stored into");
A.setArgName("attribute metrics file");
A.setArgs(1);
A.setRequired(false);
options.addOption(A);
}
{
final Option s = new Option("s", "AnalyzeStatement", false,
"specify this option if you don't need statement information");
s.setRequired(false);
options.addOption(s);
}
{
final Option b = new Option("b", "libraries", true,
"specify libraries (.jar file or .class file or directory that contains .jar and .class files)");
b.setArgName("libraries");
b.setArgs(1);
b.setRequired(false);
options.addOption(b);
}
{
final Option t = new Option("t", "threads", true,
"specify thread number used for multi-thread processings");
t.setArgName("number");
t.setArgs(1);
t.setRequired(false);
options.addOption(t);
}
final MetricsTool metricsTool = new MetricsTool();
try {
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI��
// ���̂Ƃ��C���̃I�v�V�����͑S�Ė��������
if (cmd.hasOption("h") || (0 == args.length)) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MetricsTool", options, true);
// -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉\����ꗗ��\��
if (!cmd.hasOption("l")) {
err.println("Available languages;");
for (final LANGUAGE language : LANGUAGE.values()) {
err.println("\t" + language.getName() + ": can be specified with term \""
+ language.getIdentifierName() + "\"");
}
// -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�\�ȃ��g���N�X�ꗗ��\��
} else {
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
err.println("Available metrics for "
+ Settings.getInstance().getLanguage().getName());
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager()
.getPlugins()) {
final PluginInfo pluginInfo = plugin.getPluginInfo();
if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) {
err.println("\t" + pluginInfo.getMetricName());
}
}
}
System.exit(0);
}
Settings.getInstance().setVerbose(cmd.hasOption("v"));
if (cmd.hasOption("d")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("d"), ",");
while (tokenizer.hasMoreElements()) {
final String directory = tokenizer.nextToken();
Settings.getInstance().addTargetDirectory(directory);
}
}
if (cmd.hasOption("i")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("i"), ",");
while (tokenizer.hasMoreElements()) {
final String listFile = tokenizer.nextToken();
Settings.getInstance().addListFile(listFile);
}
}
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
if (cmd.hasOption("m")) {
Settings.getInstance().setMetrics(cmd.getOptionValue("m"));
}
if (cmd.hasOption("F")) {
Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F"));
}
if (cmd.hasOption("C")) {
Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C"));
}
if (cmd.hasOption("M")) {
Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M"));
}
if (cmd.hasOption("A")) {
Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A"));
}
Settings.getInstance().setStatement(!cmd.hasOption("s"));
if (cmd.hasOption("b")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("b"), ",");
while (tokenizer.hasMoreElements()) {
final String library = tokenizer.nextToken();
Settings.getInstance().addLibrary(library);
}
}
if (cmd.hasOption("t")) {
Settings.getInstance().setThreadNumber(Integer.parseInt(cmd.getOptionValue("t")));
}
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
// �R�}���h���C�����������������ǂ����`�F�b�N����
{
// -d �� -i �̂ǂ�����w�肳��Ă���͕̂s��
if (!cmd.hasOption("d") && !cmd.hasOption("l")) {
err.println("-d and/or -i must be specified in the analysis mode!");
System.exit(0);
}
// ���ꂪ�w�肳��Ȃ������͕̂s��
if (!cmd.hasOption("l")) {
err.println("-l must be specified for analysis");
System.exit(0);
}
{
// �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& !cmd.hasOption("F")) {
err.println("-F must be specified for file metrics!");
System.exit(0);
}
// �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& !cmd.hasOption("C")) {
err.println("-C must be specified for class metrics!");
System.exit(0);
}
// ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& !cmd.hasOption("M")) {
err.println("-M must be specified for method metrics!");
System.exit(0);
}
// �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& !cmd.hasOption("A")) {
err.println("-A must be specified for field metrics!");
System.exit(0);
}
}
{
// �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& cmd.hasOption("F")) {
err.println("No file metric is specified. -F is ignored.");
}
// �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& cmd.hasOption("C")) {
err.println("No class metric is specified. -C is ignored.");
}
// ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& cmd.hasOption("M")) {
err.println("No method metric is specified. -M is ignored.");
}
// �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& cmd.hasOption("A")) {
err.println("No field metric is specified. -A is ignored.");
}
}
}
} catch (ParseException e) {
System.out.println(e.getMessage());
System.exit(0);
}
final long start = System.nanoTime();
metricsTool.analyzeLibraries();
metricsTool.readTargetFiles();
metricsTool.analyzeTargetFiles();
metricsTool.launchPlugins();
metricsTool.writeMetrics();
out.println("successfully finished.");
final long end = System.nanoTime();
if (Settings.getInstance().isVerbose()) {
out.println("elapsed time: " + (end - start) / 1000000000 + " seconds");
out.println("number of analyzed files: "
+ DataManager.getInstance().getFileInfoManager().getFileInfos().size());
int loc = 0;
for (final FileInfo file : DataManager.getInstance().getFileInfoManager()
.getFileInfos()) {
loc += file.getLOC();
}
out.println("analyzed lines of code: " + loc);
}
MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener);
}
| public static void main(String[] args) {
initSecurityManager();
// ���\���p�̃��X�i���쐬
final MessageListener outListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
System.out.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
final MessageListener errListener = new MessageListener() {
public void messageReceived(MessageEvent event) {
System.err.print(event.getSource().getMessageSourceName() + " > "
+ event.getMessage());
}
};
MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(errListener);
final Options options = new Options();
{
final Option h = new Option("h", "help", false, "display usage");
h.setRequired(false);
options.addOption(h);
}
{
final Option v = new Option("v", "verbose", false, "output progress verbosely");
v.setRequired(false);
options.addOption(v);
}
{
final Option d = new Option("d", "directores", true,
"specify target directories (separate with comma \',\' if you specify multiple directories");
d.setArgName("directories");
d.setArgs(1);
d.setRequired(false);
options.addOption(d);
}
{
final Option i = new Option(
"i",
"input",
true,
"specify the input that contains the list of target files (separate with comma \',\' if you specify multiple inputs)");
i.setArgName("input");
i.setArgs(1);
i.setRequired(false);
options.addOption(i);
}
{
final Option l = new Option("l", "language", true, "specify programming language");
l.setArgName("input");
l.setArgs(1);
l.setRequired(false);
options.addOption(l);
}
{
final Option m = new Option("m", "metrics", true,
"specify measured metrics with comma separeted format (e.g., -m rfc,dit,lcom)");
m.setArgName("metrics");
m.setArgs(1);
m.setRequired(false);
options.addOption(m);
}
{
final Option F = new Option("F", "FileMetricsFile", true,
"specify file that measured FILE metrics were stored into");
F.setArgName("file metrics file");
F.setArgs(1);
F.setRequired(false);
options.addOption(F);
}
{
final Option C = new Option("C", "ClassMetricsFile", true,
"specify file that measured CLASS metrics were stored into");
C.setArgName("class metrics file");
C.setArgs(1);
C.setRequired(false);
options.addOption(C);
}
{
final Option M = new Option("M", "MethodMetricsFile", true,
"specify file that measured METHOD metrics were stored into");
M.setArgName("method metrics file");
M.setArgs(1);
M.setRequired(false);
options.addOption(M);
}
{
final Option A = new Option("A", "AttributeMetricsFile", true,
"specify file that measured ATTRIBUTE metrics were stored into");
A.setArgName("attribute metrics file");
A.setArgs(1);
A.setRequired(false);
options.addOption(A);
}
{
final Option s = new Option("s", "AnalyzeStatement", false,
"specify this option if you don't need statement information");
s.setRequired(false);
options.addOption(s);
}
{
final Option b = new Option("b", "libraries", true,
"specify libraries (.jar file or .class file or directory that contains .jar and .class files)");
b.setArgName("libraries");
b.setArgs(1);
b.setRequired(false);
options.addOption(b);
}
{
final Option t = new Option("t", "threads", true,
"specify thread number used for multi-thread processings");
t.setArgName("number");
t.setArgs(1);
t.setRequired(false);
options.addOption(t);
}
final MetricsTool metricsTool = new MetricsTool();
try {
final CommandLineParser parser = new PosixParser();
final CommandLine cmd = parser.parse(options, args);
// "-h"���w�肳��Ă���ꍇ�̓w���v��\�����ďI��
// ���̂Ƃ��C���̃I�v�V�����͑S�Ė��������
if (cmd.hasOption("h") || (0 == args.length)) {
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("MetricsTool", options, true);
// -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉\����ꗗ��\��
if (!cmd.hasOption("l")) {
err.println("Available languages;");
for (final LANGUAGE language : LANGUAGE.values()) {
err.println("\t" + language.getName() + ": can be specified with term \""
+ language.getIdentifierName() + "\"");
}
// -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�\�ȃ��g���N�X�ꗗ��\��
} else {
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
err.println("Available metrics for "
+ Settings.getInstance().getLanguage().getName());
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
for (final AbstractPlugin plugin : DataManager.getInstance().getPluginManager()
.getPlugins()) {
final PluginInfo pluginInfo = plugin.getPluginInfo();
if (pluginInfo.isMeasurable(Settings.getInstance().getLanguage())) {
err.println("\t" + pluginInfo.getMetricName());
}
}
}
System.exit(0);
}
Settings.getInstance().setVerbose(cmd.hasOption("v"));
if (cmd.hasOption("d")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("d"), ",");
while (tokenizer.hasMoreElements()) {
final String directory = tokenizer.nextToken();
Settings.getInstance().addTargetDirectory(directory);
}
}
if (cmd.hasOption("i")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("i"), ",");
while (tokenizer.hasMoreElements()) {
final String listFile = tokenizer.nextToken();
Settings.getInstance().addListFile(listFile);
}
}
Settings.getInstance().setLanguage(cmd.getOptionValue("l"));
if (cmd.hasOption("m")) {
Settings.getInstance().setMetrics(cmd.getOptionValue("m"));
}
if (cmd.hasOption("F")) {
Settings.getInstance().setFileMetricsFile(cmd.getOptionValue("F"));
}
if (cmd.hasOption("C")) {
Settings.getInstance().setClassMetricsFile(cmd.getOptionValue("C"));
}
if (cmd.hasOption("M")) {
Settings.getInstance().setMethodMetricsFile(cmd.getOptionValue("M"));
}
if (cmd.hasOption("A")) {
Settings.getInstance().setFieldMetricsFile(cmd.getOptionValue("A"));
}
Settings.getInstance().setStatement(!cmd.hasOption("s"));
if (cmd.hasOption("b")) {
final StringTokenizer tokenizer = new StringTokenizer(cmd.getOptionValue("b"), ",");
while (tokenizer.hasMoreElements()) {
final String library = tokenizer.nextToken();
Settings.getInstance().addLibrary(library);
}
}
if (cmd.hasOption("t")) {
Settings.getInstance().setThreadNumber(Integer.parseInt(cmd.getOptionValue("t")));
}
metricsTool.loadPlugins(Settings.getInstance().getMetrics());
// �R�}���h���C�����������������ǂ����`�F�b�N����
{
// -d �� -i �̂ǂ�����w�肳��Ă���͕̂s��
if (!cmd.hasOption("d") && !cmd.hasOption("l")) {
err.println("-d and/or -i must be specified in the analysis mode!");
System.exit(0);
}
// ���ꂪ�w�肳��Ȃ������͕̂s��
if (!cmd.hasOption("l")) {
err.println("-l must be specified for analysis");
System.exit(0);
}
{
// �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& !cmd.hasOption("F")) {
err.println("-F must be specified for file metrics!");
System.exit(0);
}
// �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& !cmd.hasOption("C")) {
err.println("-C must be specified for class metrics!");
System.exit(0);
}
// ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& !cmd.hasOption("M")) {
err.println("-M must be specified for method metrics!");
System.exit(0);
}
// �t�B�[���h���g���N�X���v������ꍇ�� -A �I�v�V�������w�肳��Ă��Ȃ���Ȃ�Ȃ�
if ((0 < DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& !cmd.hasOption("A")) {
err.println("-A must be specified for field metrics!");
System.exit(0);
}
}
{
// �t�@�C�����g���N�X���v�����Ȃ��̂� -F�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFileMetricPlugins()
.size())
&& cmd.hasOption("F")) {
err.println("No file metric is specified. -F is ignored.");
}
// �N���X���g���N�X���v�����Ȃ��̂� -C�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getClassMetricPlugins()
.size())
&& cmd.hasOption("C")) {
err.println("No class metric is specified. -C is ignored.");
}
// ���\�b�h���g���N�X���v�����Ȃ��̂� -M�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getMethodMetricPlugins()
.size())
&& cmd.hasOption("M")) {
err.println("No method metric is specified. -M is ignored.");
}
// �t�B�[���h���g���N�X���v�����Ȃ��̂� -A�@�I�v�V�������w�肳��Ă���ꍇ�͖�������|��ʒm
if ((0 == DataManager.getInstance().getPluginManager().getFieldMetricPlugins()
.size())
&& cmd.hasOption("A")) {
err.println("No field metric is specified. -A is ignored.");
}
}
}
} catch (ParseException e) {
System.out.println(e.getMessage());
System.exit(0);
}
final long start = System.nanoTime();
metricsTool.analyzeLibraries();
metricsTool.readTargetFiles();
metricsTool.analyzeTargetFiles();
metricsTool.launchPlugins();
metricsTool.writeMetrics();
out.println("successfully finished.");
final long end = System.nanoTime();
if (Settings.getInstance().isVerbose()) {
out.println("elapsed time: " + (end - start) / 1000000000 + " seconds");
out.println("number of analyzed files: "
+ DataManager.getInstance().getFileInfoManager().getFileInfos().size());
int loc = 0;
for (final FileInfo file : DataManager.getInstance().getFileInfoManager()
.getFileInfos()) {
loc += file.getLOC();
}
out.println("analyzed lines of code: " + loc);
}
MessagePool.getInstance(MESSAGE_TYPE.OUT).removeMessageListener(outListener);
MessagePool.getInstance(MESSAGE_TYPE.ERROR).removeMessageListener(errListener);
}
|
diff --git a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
index 398b483..81a84e0 100644
--- a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
+++ b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java
@@ -1,603 +1,603 @@
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.csstudio.swt.xygraph.linearscale;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Tick factory produces the different axis ticks. When specifying a format and
* given the screen size parameters and range it will return a list of Ticks
*/
public class TickFactory {
public enum TickFormatting {
/**
* Plain mode no rounding no chopping maximum 6 figures before the
* fraction point and four after
*/
plainMode,
/**
* Rounded or chopped to the nearest decimal
*/
roundAndChopMode,
/**
* Use Exponent
*/
useExponent,
/**
* Use SI units (k,M,G,etc.)
*/
useSIunits,
/**
* Use external scale provider
*/
useCustom;
}
private TickFormatting formatOfTicks;
private final static BigDecimal EPSILON = new BigDecimal("1.0E-20");
private static final int DIGITS_UPPER_LIMIT = 6; // limit for number of digits to display left of decimal point
private static final int DIGITS_LOWER_LIMIT = -6; // limit for number of zeros to display right of decimal point
private static final double ROUND_FRACTION = 2e-6; // fraction of denominator to round to
private static final BigDecimal BREL_ERROR = new BigDecimal("1e-15");
private static final double REL_ERROR = BREL_ERROR.doubleValue();
private double graphMin;
private double graphMax;
private String tickFormat;
private IScaleProvider scale;
private int intervals; // number of intervals
private boolean isReversed;
/**
* @param format
*/
public TickFactory(IScaleProvider scale) {
this(TickFormatting.useCustom, scale);
}
/**
* @param format
*/
public TickFactory(TickFormatting format, IScaleProvider scale) {
formatOfTicks = format;
this.scale = scale;
}
private String getTickString(double value) {
if (scale!=null) value = scale.getLabel(value);
String returnString = "";
if (Double.isNaN(value))
return returnString;
switch (formatOfTicks) {
case plainMode:
returnString = String.format(tickFormat, value);
break;
case useExponent:
returnString = String.format(tickFormat, value);
break;
case roundAndChopMode:
returnString = String.format("%d", Math.round(value));
break;
case useSIunits:
double absValue = Math.abs(value);
if (absValue == 0.0) {
returnString = String.format("%6.2f", value);
} else if (absValue <= 1E-15) {
returnString = String.format("%6.2ff", value * 1E15);
} else if (absValue <= 1E-12) {
returnString = String.format("%6.2fp", value * 1E12);
} else if (absValue <= 1E-9) {
returnString = String.format("%6.2fn", value * 1E9);
} else if (absValue <= 1E-6) {
returnString = String.format("%6.2fµ", value * 1E6);
} else if (absValue <= 1E-3) {
returnString = String.format("%6.2fm", value * 1E3);
} else if (absValue < 1E3) {
returnString = String.format("%6.2f", value);
} else if (absValue < 1E6) {
returnString = String.format("%6.2fk", value * 1E-3);
} else if (absValue < 1E9) {
returnString = String.format("%6.2fM", value * 1E-6);
} else if (absValue < 1E12) {
returnString = String.format("%6.2fG", value * 1E-9);
} else if (absValue < 1E15) {
returnString = String.format("%6.2fT", value * 1E-12);
} else if (absValue < 1E18)
returnString = String.format("%6.2fP", value * 1E-15);
break;
case useCustom:
returnString = scale.format(value);
break;
}
return returnString;
}
private void createFormatString(final int precision, final boolean b) {
switch (formatOfTicks) {
case plainMode:
tickFormat = b ? String.format("%%.%de", precision) : String.format("%%.%df", precision);
break;
case useExponent:
tickFormat = String.format("%%.%de", precision);
break;
default:
tickFormat = null;
break;
}
}
/**
* Round numerator down to multiples of denominators
* @param n numerator
* @param d denominator
* @return
*/
protected static double roundDown(BigDecimal n, BigDecimal d) {
final int ns = n.signum();
if (ns == 0)
return 0;
final int ds = d.signum();
if (ds == 0)
throw new IllegalArgumentException("Zero denominator is not allowed");
n = n.abs();
d = d.abs();
final BigDecimal[] x = n.divideAndRemainder(d);
double rx = x[1].doubleValue();
if (rx > (1-ROUND_FRACTION)*d.doubleValue()) {
// trim up if close to denominator
x[1] = BigDecimal.ZERO;
x[0] = x[0].add(BigDecimal.ONE);
} else if (rx < ROUND_FRACTION*d.doubleValue()) {
x[1] = BigDecimal.ZERO;
}
final int xs = x[1].signum();
if (xs == 0) {
return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue();
} else if (xs < 0) {
throw new IllegalStateException("Cannot happen!");
}
if (ns != ds)
return x[0].signum() == 0 ? -d.doubleValue() : -x[0].add(BigDecimal.ONE).multiply(d).doubleValue();
return x[0].multiply(d).doubleValue();
}
/**
* Round numerator up to multiples of denominators
* @param n numerator
* @param d denominator
* @return
*/
protected static double roundUp(BigDecimal n, BigDecimal d) {
final int ns = n.signum();
if (ns == 0)
return 0;
final int ds = d.signum();
if (ds == 0)
throw new IllegalArgumentException("Zero denominator is not allowed");
n = n.abs();
d = d.abs();
final BigDecimal[] x = n.divideAndRemainder(d);
double rx = x[1].doubleValue();
if (rx != 0) {
if (rx < ROUND_FRACTION*d.doubleValue()) {
// trim down if close to zero
x[1] = BigDecimal.ZERO;
} else if (rx > (1-ROUND_FRACTION)*d.doubleValue()) {
x[1] = BigDecimal.ZERO;
x[0] = x[0].add(BigDecimal.ONE);
}
}
final int xs = x[1].signum();
if (xs == 0) {
return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue();
} else if (xs < 0) {
throw new IllegalStateException("Cannot happen!");
}
if (ns != ds)
return x[0].signum() == 0 ? 0 : -x[0].multiply(d).doubleValue();
return x[0].add(BigDecimal.ONE).multiply(d).doubleValue();
}
/**
* @param x
* @return floor of log 10
*/
private static int log10(BigDecimal x) {
int c = x.compareTo(BigDecimal.ONE);
int e = 0;
while (c < 0) {
e--;
x = x.scaleByPowerOfTen(1);
c = x.compareTo(BigDecimal.ONE);
}
c = x.compareTo(BigDecimal.TEN);
while (c >= 0) {
e++;
x = x.scaleByPowerOfTen(-1);
c = x.compareTo(BigDecimal.TEN);
}
return e;
}
/**
* @param x
* @param round if true, then round else take ceiling
* @return a nice number
*/
protected static BigDecimal nicenum(BigDecimal x, boolean round) {
int expv; /* exponent of x */
double f; /* fractional part of x */
double nf; /* nice, rounded number */
BigDecimal bf;
expv = log10(x);
bf = x.scaleByPowerOfTen(-expv);
f = bf.doubleValue(); /* between 1 and 10 */
if (round) {
if (f < 1.5)
nf = 1;
else if (f < 2.25)
nf = 2;
else if (f < 3.25)
nf = 2.5;
else if (f < 7.5)
nf = 5;
else
nf = 10;
}
else if (f <= 1.)
nf = 1;
else if (f <= 2.)
nf = 2;
else if (f <= 5.)
nf = 5;
else
nf = 10;
return BigDecimal.valueOf(BigDecimal.valueOf(nf).scaleByPowerOfTen(expv).doubleValue());
}
private double determineNumTicks(int size, double min, double max, int maxTicks,
boolean allowMinMaxOver, boolean isIndexBased) {
BigDecimal bMin = BigDecimal.valueOf(min);
BigDecimal bMax = BigDecimal.valueOf(max);
BigDecimal bRange = bMax.subtract(bMin);
if (bRange.signum() < 0) {
BigDecimal bt = bMin;
bMin = bMax;
bMax = bt;
bRange = bRange.negate();
isReversed = true;
} else {
isReversed = false;
}
BigDecimal magnitude = BigDecimal.valueOf(Math.max(Math.abs(min), Math.abs(max)));
// tick points too dense to do anything
if (bRange.compareTo(EPSILON.multiply(magnitude)) < 0) {
return 0;
}
bRange = nicenum(bRange, false);
BigDecimal bUnit;
int nTicks = maxTicks - 1;
if (Math.signum(min)*Math.signum(max) < 0) {
// straddle case
nTicks++;
}
do {
long n;
do { // ensure number of ticks is less or equal to number requested
bUnit = nicenum(BigDecimal.valueOf(bRange.doubleValue() / nTicks), true);
n = bRange.divideToIntegralValue(bUnit).longValue();
} while (n > maxTicks && --nTicks > 0);
if (allowMinMaxOver) {
graphMin = roundDown(bMin, bUnit);
if (graphMin == 0) // ensure positive zero
graphMin = 0;
graphMax = roundUp(bMax, bUnit);
if (graphMax == 0)
graphMax = 0;
} else {
graphMin = min;
graphMax = max;
}
if (bUnit.compareTo(BREL_ERROR.multiply(magnitude)) <= 0) {
intervals = -1; // signal that we hit the limit of precision
} else {
intervals = (int) Math.round((graphMax - graphMin) / bUnit.doubleValue());
}
} while (intervals > maxTicks && --nTicks > 0);
if (isReversed) {
double t = graphMin;
graphMin = graphMax;
graphMax = t;
}
double tickUnit = isReversed ? -bUnit.doubleValue() : bUnit.doubleValue();
if (isIndexBased) {
switch (formatOfTicks) {
case plainMode:
tickFormat = "%g";
break;
case useExponent:
tickFormat = "%e";
break;
default:
tickFormat = null;
break;
}
} else {
/**
* We get the labelled max and min for determining the precision
* which the ticks should be shown at.
*/
int d = bUnit.scale() == bUnit.precision() ? -bUnit.scale() : bUnit.precision() - bUnit.scale() - 1;
int p = (int) Math.max(Math.floor(Math.log10(Math.abs(graphMin))),
Math.floor(Math.log10(Math.abs(graphMax))));
// System.err.println("P: " + bUnit.precision() + ", S: " +
// bUnit.scale() + " => " + d + ", " + p);
if (p <= DIGITS_LOWER_LIMIT || p >= DIGITS_UPPER_LIMIT) {
createFormatString(Math.max(p - d, 0), true);
} else {
createFormatString(Math.max(-d, 0), false);
}
}
return tickUnit;
}
private boolean inRange(double x, double min, double max) {
if (isReversed) {
return x >= max && x <= min;
}
return x >= min && x <= max;
}
private static final DecimalFormat INDEX_FORMAT = new DecimalFormat("#####0.###");
/**
* Generate a list of ticks that span range given by min and max. The maximum number of
* ticks is exceed by one in the case where the range straddles zero.
* @param displaySize
* @param min
* @param max
* @param maxTicks
* @param allowMinMaxOver allow min/maximum overwrite
* @param tight if true then remove ticks outside range
* @return a list of the ticks for the axis
*/
public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased);
if (tickUnit == 0)
return ticks;
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
if (Math.abs(p/tickUnit) < REL_ERROR)
p = 0; // ensure positive zero
boolean r = inRange(p, min, max);
if (!tight || r) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
}
int imax = ticks.size();
if (imax > 1) {
if (!tight && allowMinMaxOver) {
Tick t = ticks.get(imax - 1);
if (!isReversed && t.getValue() < max) { // last is >= max
t.setValue(graphMax);
t.setText(getTickString(graphMax));
}
}
double lo = tight ? min : ticks.get(0).getValue();
double hi = tight ? max : ticks.get(imax - 1).getValue();
double range = hi - lo;
if (isReversed) {
for (Tick t : ticks) {
t.setPosition(1 - (t.getValue() - lo) / range);
}
} else {
for (Tick t : ticks) {
t.setPosition((t.getValue() - lo) / range);
}
}
} else if (maxTicks > 1) {
if (imax == 0) {
imax++;
Tick newTick = new Tick();
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
if (isReversed) {
newTick.setPosition(1);
} else {
newTick.setPosition(0);
}
ticks.add(newTick);
}
if (imax == 1) {
Tick t = ticks.get(0);
Tick newTick = new Tick();
if (t.getText().equals(getTickString(graphMax))) {
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
ticks.add(0, newTick);
} else {
newTick.setValue(graphMax);
newTick.setText(getTickString(graphMax));
ticks.add(newTick);
}
if (isReversed) {
ticks.get(0).setPosition(1);
ticks.get(1).setPosition(0);
} else {
- ticks.get(0).setPosition(1);
- ticks.get(1).setPosition(0);
+ ticks.get(0).setPosition(0);
+ ticks.get(1).setPosition(1);
}
}
}
if (isIndexBased && formatOfTicks == TickFormatting.plainMode) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
// override labels
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
t.setText(INDEX_FORMAT.format(v));
}
}
}
return ticks;
}
private double determineNumLogTicks(int size, double min, double max, int maxTicks,
boolean allowMinMaxOver) {
final boolean isReverse = min > max;
final int loDecade; // lowest decade (or power of ten)
final int hiDecade;
if (isReverse) {
loDecade = (int) Math.floor(Math.log10(max));
hiDecade = (int) Math.ceil(Math.log10(min));
} else {
loDecade = (int) Math.floor(Math.log10(min));
hiDecade = (int) Math.ceil(Math.log10(max));
}
int decades = hiDecade - loDecade;
int unit = 0;
int n;
do {
n = decades/++unit;
} while (n > maxTicks);
double tickUnit = isReverse ? Math.pow(10, -unit) : Math.pow(10, unit);
if (allowMinMaxOver) {
graphMin = Math.pow(10, loDecade);
graphMax = Math.pow(10, hiDecade);
} else {
graphMin = min;
graphMax = max;
}
if (isReverse) {
double t = graphMin;
graphMin = graphMax;
graphMax = t;
}
createFormatString((int) Math.max(-Math.floor(loDecade), 0), false);
return tickUnit;
}
/**
* @param displaySize
* @param min
* @param max
* @param maxTicks
* @param allowMinMaxOver allow min/maximum overwrite
* @param tight if true then remove ticks outside range
* @return a list of the ticks for the axis
*/
public List<Tick> generateLogTicks(int displaySize, double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumLogTicks(displaySize, min, max, maxTicks, allowMinMaxOver);
double p = graphMin;
if (tickUnit > 1) {
final double pmax = graphMax * Math.sqrt(tickUnit);
while (p < pmax) {
if (!tight || (p >= min && p <= max))
if (allowMinMaxOver || p <= max) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
double newTickValue = p * tickUnit;
if (p == newTickValue)
break;
p = newTickValue;
}
final int imax = ticks.size();
if (imax == 1) {
ticks.get(0).setPosition(0.5);
} else if (imax > 1) {
double lo = Math.log(tight ? min : ticks.get(0).getValue());
double hi = Math.log(tight ? max : ticks.get(imax - 1).getValue());
double range = hi - lo;
for (Tick t : ticks) {
t.setPosition((Math.log(t.getValue()) - lo) / range);
}
}
} else {
final double pmin = graphMax * Math.sqrt(tickUnit);
while (p > pmin) {
if (!tight || (p >= max && p <= min))
if (allowMinMaxOver || p <= max) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
}
double newTickValue = p * tickUnit;
if (p == newTickValue)
break;
p = newTickValue;
}
final int imax = ticks.size();
if (imax == 1) {
ticks.get(0).setPosition(0.5);
} else if (imax > 1) {
double lo = Math.log(tight ? max : ticks.get(0).getValue());
double hi = Math.log(tight ? min : ticks.get(imax - 1).getValue());
double range = hi - lo;
for (Tick t : ticks) {
t.setPosition(1 - (Math.log(t.getValue()) - lo) / range);
}
}
}
return ticks;
}
}
| true | true | public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased);
if (tickUnit == 0)
return ticks;
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
if (Math.abs(p/tickUnit) < REL_ERROR)
p = 0; // ensure positive zero
boolean r = inRange(p, min, max);
if (!tight || r) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
}
int imax = ticks.size();
if (imax > 1) {
if (!tight && allowMinMaxOver) {
Tick t = ticks.get(imax - 1);
if (!isReversed && t.getValue() < max) { // last is >= max
t.setValue(graphMax);
t.setText(getTickString(graphMax));
}
}
double lo = tight ? min : ticks.get(0).getValue();
double hi = tight ? max : ticks.get(imax - 1).getValue();
double range = hi - lo;
if (isReversed) {
for (Tick t : ticks) {
t.setPosition(1 - (t.getValue() - lo) / range);
}
} else {
for (Tick t : ticks) {
t.setPosition((t.getValue() - lo) / range);
}
}
} else if (maxTicks > 1) {
if (imax == 0) {
imax++;
Tick newTick = new Tick();
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
if (isReversed) {
newTick.setPosition(1);
} else {
newTick.setPosition(0);
}
ticks.add(newTick);
}
if (imax == 1) {
Tick t = ticks.get(0);
Tick newTick = new Tick();
if (t.getText().equals(getTickString(graphMax))) {
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
ticks.add(0, newTick);
} else {
newTick.setValue(graphMax);
newTick.setText(getTickString(graphMax));
ticks.add(newTick);
}
if (isReversed) {
ticks.get(0).setPosition(1);
ticks.get(1).setPosition(0);
} else {
ticks.get(0).setPosition(1);
ticks.get(1).setPosition(0);
}
}
}
if (isIndexBased && formatOfTicks == TickFormatting.plainMode) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
// override labels
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
t.setText(INDEX_FORMAT.format(v));
}
}
}
return ticks;
}
| public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks,
boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) {
List<Tick> ticks = new ArrayList<Tick>();
double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased);
if (tickUnit == 0)
return ticks;
for (int i = 0; i <= intervals; i++) {
double p = graphMin + i * tickUnit;
if (Math.abs(p/tickUnit) < REL_ERROR)
p = 0; // ensure positive zero
boolean r = inRange(p, min, max);
if (!tight || r) {
Tick newTick = new Tick();
newTick.setValue(p);
newTick.setText(getTickString(p));
ticks.add(newTick);
}
}
int imax = ticks.size();
if (imax > 1) {
if (!tight && allowMinMaxOver) {
Tick t = ticks.get(imax - 1);
if (!isReversed && t.getValue() < max) { // last is >= max
t.setValue(graphMax);
t.setText(getTickString(graphMax));
}
}
double lo = tight ? min : ticks.get(0).getValue();
double hi = tight ? max : ticks.get(imax - 1).getValue();
double range = hi - lo;
if (isReversed) {
for (Tick t : ticks) {
t.setPosition(1 - (t.getValue() - lo) / range);
}
} else {
for (Tick t : ticks) {
t.setPosition((t.getValue() - lo) / range);
}
}
} else if (maxTicks > 1) {
if (imax == 0) {
imax++;
Tick newTick = new Tick();
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
if (isReversed) {
newTick.setPosition(1);
} else {
newTick.setPosition(0);
}
ticks.add(newTick);
}
if (imax == 1) {
Tick t = ticks.get(0);
Tick newTick = new Tick();
if (t.getText().equals(getTickString(graphMax))) {
newTick.setValue(graphMin);
newTick.setText(getTickString(graphMin));
ticks.add(0, newTick);
} else {
newTick.setValue(graphMax);
newTick.setText(getTickString(graphMax));
ticks.add(newTick);
}
if (isReversed) {
ticks.get(0).setPosition(1);
ticks.get(1).setPosition(0);
} else {
ticks.get(0).setPosition(0);
ticks.get(1).setPosition(1);
}
}
}
if (isIndexBased && formatOfTicks == TickFormatting.plainMode) {
double vmin = Double.POSITIVE_INFINITY;
double vmax = Double.NEGATIVE_INFINITY;
for (Tick t : ticks) {
double v = Math.abs(scale.getLabel(t.getValue()));
if (v < vmin && v > 0)
vmin = v;
if (v > vmax)
vmax = v;
}
if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) {
// override labels
for (Tick t : ticks) {
double v = scale.getLabel(t.getValue());
t.setText(INDEX_FORMAT.format(v));
}
}
}
return ticks;
}
|
diff --git a/src/minecraft/net/minecraft/src/WorldRenderer.java b/src/minecraft/net/minecraft/src/WorldRenderer.java
index 526cbd96..45c3ce8f 100644
--- a/src/minecraft/net/minecraft/src/WorldRenderer.java
+++ b/src/minecraft/net/minecraft/src/WorldRenderer.java
@@ -1,357 +1,357 @@
package net.minecraft.src;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import net.minecraft.src.AxisAlignedBB;
import net.minecraft.src.Block;
import net.minecraft.src.Chunk;
import net.minecraft.src.Entity;
import net.minecraft.src.ICamera;
import net.minecraft.src.MathHelper;
import net.minecraft.src.RenderBlocks;
import net.minecraft.src.RenderItem;
import net.minecraft.src.Tessellator;
import net.minecraft.src.TileEntity;
import net.minecraft.src.TileEntityRenderer;
import net.minecraft.src.World;
import org.lwjgl.opengl.GL11;
//Spout start
import org.newdawn.slick.opengl.Texture;
import org.spoutcraft.client.SpoutClient;
import org.spoutcraft.client.io.CustomTextureManager;
import org.spoutcraft.client.item.SpoutItem;
import org.spoutcraft.spoutcraftapi.Spoutcraft;
import org.spoutcraft.spoutcraftapi.block.design.GenericBlockDesign;
import org.spoutcraft.spoutcraftapi.material.CustomBlock;
import org.spoutcraft.spoutcraftapi.material.MaterialData;
import net.minecraft.client.Minecraft;
//Spout end
public class WorldRenderer {
public World worldObj;
private int glRenderList = -1;
private static Tessellator tessellator = Tessellator.instance;
public static int chunksUpdated = 0;
public int posX;
public int posY;
public int posZ;
public int posXMinus;
public int posYMinus;
public int posZMinus;
public int posXClip;
public int posYClip;
public int posZClip;
public boolean isInFrustum = false;
public boolean[] skipRenderPass = new boolean[3]; //Spout
public int posXPlus;
public int posYPlus;
public int posZPlus;
public boolean needsUpdate;
public AxisAlignedBB rendererBoundingBox;
public int chunkIndex;
public boolean isVisible = true;
public boolean isWaitingOnOcclusionQuery;
public int glOcclusionQuery;
public boolean isChunkLit;
private boolean isInitialized = false;
public List tileEntityRenderers = new ArrayList();
private List tileEntities;
public WorldRenderer(World par1World, List par2List, int par3, int par4, int par5, int par6) {
this.worldObj = par1World;
this.tileEntities = par2List;
this.glRenderList = par6;
this.posX = -999;
this.setPosition(par3, par4, par5);
this.needsUpdate = false;
}
public void setPosition(int par1, int par2, int par3) {
if (par1 != this.posX || par2 != this.posY || par3 != this.posZ) {
this.setDontDraw();
this.posX = par1;
this.posY = par2;
this.posZ = par3;
this.posXPlus = par1 + 8;
this.posYPlus = par2 + 8;
this.posZPlus = par3 + 8;
this.posXClip = par1 & 1023;
this.posYClip = par2;
this.posZClip = par3 & 1023;
this.posXMinus = par1 - this.posXClip;
this.posYMinus = par2 - this.posYClip;
this.posZMinus = par3 - this.posZClip;
float var4 = 6.0F;
this.rendererBoundingBox = AxisAlignedBB.getBoundingBox((double)((float)par1 - var4), (double)((float)par2 - var4), (double)((float)par3 - var4), (double)((float)(par1 + 16) + var4), (double)((float)(par2 + 16) + var4), (double)((float)(par3 + 16) + var4));
GL11.glNewList(this.glRenderList + 2, GL11.GL_COMPILE);
RenderItem.renderAABB(AxisAlignedBB.getBoundingBoxFromPool((double)((float)this.posXClip - var4), (double)((float)this.posYClip - var4), (double)((float)this.posZClip - var4), (double)((float)(this.posXClip + 16) + var4), (double)((float)(this.posYClip + 16) + var4), (double)((float)(this.posZClip + 16) + var4)));
GL11.glEndList();
this.markDirty();
}
}
private void setupGLTranslation() {
GL11.glTranslatef((float)this.posXClip, (float)this.posYClip, (float)this.posZClip);
}
public void updateRenderer() {
//Spout Start
if(this.needsUpdate) {
++chunksUpdated;
int x = this.posX;
int y = this.posY;
int z = this.posZ;
int sizeXOffset = this.posX + 16;
int sizeYOffset = this.posY + 16;
int sizeZOffset = this.posZ + 16;
for(int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
this.skipRenderPass[renderPass] = true;
}
Chunk.isLit = false;
HashSet tileRenderers = new HashSet();
tileRenderers.addAll(this.tileEntityRenderers);
this.tileEntityRenderers.clear();
//ChunkCache chunkCache = new ChunkCache(this.worldObj, x - 1, y - 1, z - 1, sizeXOffset + 1, sizeYOffset + 1, sizeZOffset + 1);
RenderBlocks blockRenderer = new RenderBlocks(worldObj);
List<String> hitTextures = new ArrayList<String>();
List<String> hitTexturesPlugins = new ArrayList<String>();
int currentTexture = 0;
Minecraft game = SpoutClient.getHandle();
hitTextures.add("/terrain.png");
hitTexturesPlugins.add("");
int defaultTexture = game.renderEngine.getTexture("/terrain.png");
game.renderEngine.bindTexture(defaultTexture);
short[] customBlockIds = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockIds();
byte[] customBlockData = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockData();
blockRenderer.customIds = customBlockIds;
for (int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
boolean skipRenderPass = false;
boolean rendered = false;
boolean drawBlock = false;
if (!drawBlock) {
drawBlock = true;
GL11.glNewList(this.glRenderList + renderPass, GL11.GL_COMPILE);
GL11.glPushMatrix();
this.setupGLTranslation();
GL11.glTranslatef(-8F, -8F, -8F);
GL11.glScalef(1F, 1F, 1F);
GL11.glTranslatef(8F, 8F, 8F);
tessellator.startDrawingQuads();
tessellator.setTranslation((double)(-this.posX), (double)(-this.posY), (double)(-this.posZ));
}
game.renderEngine.bindTexture(defaultTexture);
for (currentTexture = 0; currentTexture < hitTextures.size(); currentTexture++) {
int texture = defaultTexture;
//First pass (currentTexture == 0) is for the default terrain.png texture. Subsquent passes are for custom textures
//This design is to avoid unnessecary glBindTexture calls.
if(currentTexture > 0) {
Texture customTexture = CustomTextureManager.getTextureFromUrl(hitTexturesPlugins.get(currentTexture), hitTextures.get(currentTexture));
if (customTexture != null) {
texture = customTexture.getTextureID();
game.renderEngine.bindTexture(texture);
if(texture <= 0) {
texture = defaultTexture;
}
}
}
if(tessellator.textureOverride != texture){
tessellator.draw();
tessellator.textureOverride = texture;
tessellator.startDrawingQuads();
}
float[] oldBounds = new float[6];
//The x,y,z order is important, don't change!
for (int dx = x; dx < sizeXOffset; ++dx) {
for (int dz = z; dz < sizeZOffset; ++dz) {
for (int dy = y; dy < sizeYOffset; ++dy) {
int id = worldObj.getBlockId(dx, dy, dz);
if (id > 0) {
String customTexture = null;
String customTextureAddon = null;
GenericBlockDesign design = null;
CustomBlock mat = null;
if (customBlockIds != null) {
int key = ((dx & 0xF) << 12) | ((dz & 0xF) << 8) | (dy & 0xFF);
if (customBlockIds[key] != 0) {
mat = MaterialData.getCustomBlock(customBlockIds[key]);
if (mat != null) {
- design = (GenericBlockDesign) mat.getBlockDesign(customBlockData[key]);
+ design = (GenericBlockDesign) mat.getBlockDesign(customBlockData == null ? 0 : customBlockData[key]);
}
}
}
if (design != null) {
customTexture = design.getTexureURL();
customTextureAddon = design.getTextureAddon();
}
if(customTexture != null){
boolean found = false;
//Search for the custom texture in our list
for(int i = 0; i < hitTextures.size(); i++){
if(hitTextures.get(i).equals(customTexture) && hitTexturesPlugins.get(i).equals(customTextureAddon)) {
found = true;
break;
}
}
//If it is not already accounted for, add it so we do an additional pass for it.
if(!found) {
hitTextures.add(customTexture);
hitTexturesPlugins.add(customTextureAddon);
}
//Do not render if we are using a different texture than the current one
if(!hitTextures.get(currentTexture).equals(customTexture) || !hitTexturesPlugins.get(currentTexture).equals(customTextureAddon)) {
continue;
}
}
//Do not render if we are not using the terrain.png and can't find a valid texture for this custom block
else if (currentTexture != 0) {
continue;
}
Block block = Block.blocksList[id];
if (renderPass == 0 && block.hasTileEntity()) {
TileEntity var20 = worldObj.getBlockTileEntity(dx, dy, dz);
if (TileEntityRenderer.instance.hasSpecialRenderer(var20)) {
this.tileEntityRenderers.add(var20);
}
}
//Determine which pass this block needs to be rendered on
int blockRenderPass = block.getRenderBlockPass();
if (design != null) {
blockRenderPass = design.getRenderPass();
}
if (blockRenderPass != renderPass) {
skipRenderPass = true;
}
else {
Tessellator.instance.setEntity(block.blockID); //shaders
if (design != null) {
oldBounds[0] = (float) block.minX;
oldBounds[1] = (float) block.minY;
oldBounds[2] = (float) block.minZ;
oldBounds[3] = (float) block.maxX;
oldBounds[4] = (float) block.maxY;
oldBounds[5] = (float) block.maxZ;
block.setBlockBounds(design.getLowXBound(), design.getLowYBound(), design.getLowZBound(), design.getHighXBound(), design.getHighYBound(), design.getHighZBound());
rendered |= design.renderBlock(mat, dx, dy, dz);
block.setBlockBounds(oldBounds[0], oldBounds[1], oldBounds[2], oldBounds[3], oldBounds[4], oldBounds[5]);
}
else {
rendered |= blockRenderer.renderBlockByRenderType(block, dx, dy, dz);
}
}
}
}
}
}
}
if (drawBlock) {
tessellator.draw();
tessellator.textureOverride = 0;
GL11.glPopMatrix();
GL11.glEndList();
game.renderEngine.bindTexture(defaultTexture);
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
} else {
rendered = false;
}
if (rendered) {
this.skipRenderPass[renderPass] = false;
}
if (!skipRenderPass) {
break;
}
}
HashSet var24 = new HashSet();
var24.addAll(this.tileEntityRenderers);
var24.removeAll(tileRenderers);
this.tileEntities.addAll(var24);
tileRenderers.removeAll(this.tileEntityRenderers);
Tessellator.instance.setEntity(-1); //shaders
//Spout End
this.tileEntities.removeAll(tileRenderers);
this.isChunkLit = Chunk.isLit;
this.isInitialized = true;
blockRenderer.customIds = null;
}
}
public float distanceToEntitySquared(Entity var1) {
float var2 = (float)(var1.posX - (double)this.posXPlus);
float var3 = (float)(var1.posY - (double)this.posYPlus);
float var4 = (float)(var1.posZ - (double)this.posZPlus);
return var2 * var2 + var3 * var3 + var4 * var4;
}
public void setDontDraw() {
for(int var1 = 0; var1 < skipRenderPass.length; ++var1) { //Spout
this.skipRenderPass[var1] = true;
}
this.isInFrustum = false;
this.isInitialized = false;
}
public void stopRendering() {
this.setDontDraw();
this.worldObj = null;
}
//Spout start
public int getGLCallListForPass(int par1) {
return !this.isInFrustum?-1:(!this.skipRenderPass[par1]?this.glRenderList + par1:-1);
}
public void updateInFrustum(ICamera par1ICamera) {
this.isInFrustum = par1ICamera.isBoundingBoxInFrustum(this.rendererBoundingBox);
}
public void callOcclusionQueryList() {
GL11.glCallList(this.glRenderList + 2);
}
public boolean skipAllRenderPasses() {
if (this.isInitialized) {
for (int pass = 0; pass < skipRenderPass.length; pass++) {
if (!skipRenderPass[pass]) {
return false;
}
}
return true;
}
return false;
}
//Spout end
public void markDirty() {
this.needsUpdate = true;
}
}
| true | true | public void updateRenderer() {
//Spout Start
if(this.needsUpdate) {
++chunksUpdated;
int x = this.posX;
int y = this.posY;
int z = this.posZ;
int sizeXOffset = this.posX + 16;
int sizeYOffset = this.posY + 16;
int sizeZOffset = this.posZ + 16;
for(int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
this.skipRenderPass[renderPass] = true;
}
Chunk.isLit = false;
HashSet tileRenderers = new HashSet();
tileRenderers.addAll(this.tileEntityRenderers);
this.tileEntityRenderers.clear();
//ChunkCache chunkCache = new ChunkCache(this.worldObj, x - 1, y - 1, z - 1, sizeXOffset + 1, sizeYOffset + 1, sizeZOffset + 1);
RenderBlocks blockRenderer = new RenderBlocks(worldObj);
List<String> hitTextures = new ArrayList<String>();
List<String> hitTexturesPlugins = new ArrayList<String>();
int currentTexture = 0;
Minecraft game = SpoutClient.getHandle();
hitTextures.add("/terrain.png");
hitTexturesPlugins.add("");
int defaultTexture = game.renderEngine.getTexture("/terrain.png");
game.renderEngine.bindTexture(defaultTexture);
short[] customBlockIds = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockIds();
byte[] customBlockData = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockData();
blockRenderer.customIds = customBlockIds;
for (int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
boolean skipRenderPass = false;
boolean rendered = false;
boolean drawBlock = false;
if (!drawBlock) {
drawBlock = true;
GL11.glNewList(this.glRenderList + renderPass, GL11.GL_COMPILE);
GL11.glPushMatrix();
this.setupGLTranslation();
GL11.glTranslatef(-8F, -8F, -8F);
GL11.glScalef(1F, 1F, 1F);
GL11.glTranslatef(8F, 8F, 8F);
tessellator.startDrawingQuads();
tessellator.setTranslation((double)(-this.posX), (double)(-this.posY), (double)(-this.posZ));
}
game.renderEngine.bindTexture(defaultTexture);
for (currentTexture = 0; currentTexture < hitTextures.size(); currentTexture++) {
int texture = defaultTexture;
//First pass (currentTexture == 0) is for the default terrain.png texture. Subsquent passes are for custom textures
//This design is to avoid unnessecary glBindTexture calls.
if(currentTexture > 0) {
Texture customTexture = CustomTextureManager.getTextureFromUrl(hitTexturesPlugins.get(currentTexture), hitTextures.get(currentTexture));
if (customTexture != null) {
texture = customTexture.getTextureID();
game.renderEngine.bindTexture(texture);
if(texture <= 0) {
texture = defaultTexture;
}
}
}
if(tessellator.textureOverride != texture){
tessellator.draw();
tessellator.textureOverride = texture;
tessellator.startDrawingQuads();
}
float[] oldBounds = new float[6];
//The x,y,z order is important, don't change!
for (int dx = x; dx < sizeXOffset; ++dx) {
for (int dz = z; dz < sizeZOffset; ++dz) {
for (int dy = y; dy < sizeYOffset; ++dy) {
int id = worldObj.getBlockId(dx, dy, dz);
if (id > 0) {
String customTexture = null;
String customTextureAddon = null;
GenericBlockDesign design = null;
CustomBlock mat = null;
if (customBlockIds != null) {
int key = ((dx & 0xF) << 12) | ((dz & 0xF) << 8) | (dy & 0xFF);
if (customBlockIds[key] != 0) {
mat = MaterialData.getCustomBlock(customBlockIds[key]);
if (mat != null) {
design = (GenericBlockDesign) mat.getBlockDesign(customBlockData[key]);
}
}
}
if (design != null) {
customTexture = design.getTexureURL();
customTextureAddon = design.getTextureAddon();
}
if(customTexture != null){
boolean found = false;
//Search for the custom texture in our list
for(int i = 0; i < hitTextures.size(); i++){
if(hitTextures.get(i).equals(customTexture) && hitTexturesPlugins.get(i).equals(customTextureAddon)) {
found = true;
break;
}
}
//If it is not already accounted for, add it so we do an additional pass for it.
if(!found) {
hitTextures.add(customTexture);
hitTexturesPlugins.add(customTextureAddon);
}
//Do not render if we are using a different texture than the current one
if(!hitTextures.get(currentTexture).equals(customTexture) || !hitTexturesPlugins.get(currentTexture).equals(customTextureAddon)) {
continue;
}
}
//Do not render if we are not using the terrain.png and can't find a valid texture for this custom block
else if (currentTexture != 0) {
continue;
}
Block block = Block.blocksList[id];
if (renderPass == 0 && block.hasTileEntity()) {
TileEntity var20 = worldObj.getBlockTileEntity(dx, dy, dz);
if (TileEntityRenderer.instance.hasSpecialRenderer(var20)) {
this.tileEntityRenderers.add(var20);
}
}
//Determine which pass this block needs to be rendered on
int blockRenderPass = block.getRenderBlockPass();
if (design != null) {
blockRenderPass = design.getRenderPass();
}
if (blockRenderPass != renderPass) {
skipRenderPass = true;
}
else {
Tessellator.instance.setEntity(block.blockID); //shaders
if (design != null) {
oldBounds[0] = (float) block.minX;
oldBounds[1] = (float) block.minY;
oldBounds[2] = (float) block.minZ;
oldBounds[3] = (float) block.maxX;
oldBounds[4] = (float) block.maxY;
oldBounds[5] = (float) block.maxZ;
block.setBlockBounds(design.getLowXBound(), design.getLowYBound(), design.getLowZBound(), design.getHighXBound(), design.getHighYBound(), design.getHighZBound());
rendered |= design.renderBlock(mat, dx, dy, dz);
block.setBlockBounds(oldBounds[0], oldBounds[1], oldBounds[2], oldBounds[3], oldBounds[4], oldBounds[5]);
}
else {
rendered |= blockRenderer.renderBlockByRenderType(block, dx, dy, dz);
}
}
}
}
}
}
}
if (drawBlock) {
tessellator.draw();
tessellator.textureOverride = 0;
GL11.glPopMatrix();
GL11.glEndList();
game.renderEngine.bindTexture(defaultTexture);
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
} else {
rendered = false;
}
if (rendered) {
this.skipRenderPass[renderPass] = false;
}
if (!skipRenderPass) {
break;
}
}
HashSet var24 = new HashSet();
var24.addAll(this.tileEntityRenderers);
var24.removeAll(tileRenderers);
this.tileEntities.addAll(var24);
tileRenderers.removeAll(this.tileEntityRenderers);
Tessellator.instance.setEntity(-1); //shaders
//Spout End
this.tileEntities.removeAll(tileRenderers);
this.isChunkLit = Chunk.isLit;
this.isInitialized = true;
blockRenderer.customIds = null;
}
}
| public void updateRenderer() {
//Spout Start
if(this.needsUpdate) {
++chunksUpdated;
int x = this.posX;
int y = this.posY;
int z = this.posZ;
int sizeXOffset = this.posX + 16;
int sizeYOffset = this.posY + 16;
int sizeZOffset = this.posZ + 16;
for(int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
this.skipRenderPass[renderPass] = true;
}
Chunk.isLit = false;
HashSet tileRenderers = new HashSet();
tileRenderers.addAll(this.tileEntityRenderers);
this.tileEntityRenderers.clear();
//ChunkCache chunkCache = new ChunkCache(this.worldObj, x - 1, y - 1, z - 1, sizeXOffset + 1, sizeYOffset + 1, sizeZOffset + 1);
RenderBlocks blockRenderer = new RenderBlocks(worldObj);
List<String> hitTextures = new ArrayList<String>();
List<String> hitTexturesPlugins = new ArrayList<String>();
int currentTexture = 0;
Minecraft game = SpoutClient.getHandle();
hitTextures.add("/terrain.png");
hitTexturesPlugins.add("");
int defaultTexture = game.renderEngine.getTexture("/terrain.png");
game.renderEngine.bindTexture(defaultTexture);
short[] customBlockIds = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockIds();
byte[] customBlockData = Spoutcraft.getWorld().getChunkAt(posX, posY, posZ).getCustomBlockData();
blockRenderer.customIds = customBlockIds;
for (int renderPass = 0; renderPass < skipRenderPass.length; ++renderPass) {
boolean skipRenderPass = false;
boolean rendered = false;
boolean drawBlock = false;
if (!drawBlock) {
drawBlock = true;
GL11.glNewList(this.glRenderList + renderPass, GL11.GL_COMPILE);
GL11.glPushMatrix();
this.setupGLTranslation();
GL11.glTranslatef(-8F, -8F, -8F);
GL11.glScalef(1F, 1F, 1F);
GL11.glTranslatef(8F, 8F, 8F);
tessellator.startDrawingQuads();
tessellator.setTranslation((double)(-this.posX), (double)(-this.posY), (double)(-this.posZ));
}
game.renderEngine.bindTexture(defaultTexture);
for (currentTexture = 0; currentTexture < hitTextures.size(); currentTexture++) {
int texture = defaultTexture;
//First pass (currentTexture == 0) is for the default terrain.png texture. Subsquent passes are for custom textures
//This design is to avoid unnessecary glBindTexture calls.
if(currentTexture > 0) {
Texture customTexture = CustomTextureManager.getTextureFromUrl(hitTexturesPlugins.get(currentTexture), hitTextures.get(currentTexture));
if (customTexture != null) {
texture = customTexture.getTextureID();
game.renderEngine.bindTexture(texture);
if(texture <= 0) {
texture = defaultTexture;
}
}
}
if(tessellator.textureOverride != texture){
tessellator.draw();
tessellator.textureOverride = texture;
tessellator.startDrawingQuads();
}
float[] oldBounds = new float[6];
//The x,y,z order is important, don't change!
for (int dx = x; dx < sizeXOffset; ++dx) {
for (int dz = z; dz < sizeZOffset; ++dz) {
for (int dy = y; dy < sizeYOffset; ++dy) {
int id = worldObj.getBlockId(dx, dy, dz);
if (id > 0) {
String customTexture = null;
String customTextureAddon = null;
GenericBlockDesign design = null;
CustomBlock mat = null;
if (customBlockIds != null) {
int key = ((dx & 0xF) << 12) | ((dz & 0xF) << 8) | (dy & 0xFF);
if (customBlockIds[key] != 0) {
mat = MaterialData.getCustomBlock(customBlockIds[key]);
if (mat != null) {
design = (GenericBlockDesign) mat.getBlockDesign(customBlockData == null ? 0 : customBlockData[key]);
}
}
}
if (design != null) {
customTexture = design.getTexureURL();
customTextureAddon = design.getTextureAddon();
}
if(customTexture != null){
boolean found = false;
//Search for the custom texture in our list
for(int i = 0; i < hitTextures.size(); i++){
if(hitTextures.get(i).equals(customTexture) && hitTexturesPlugins.get(i).equals(customTextureAddon)) {
found = true;
break;
}
}
//If it is not already accounted for, add it so we do an additional pass for it.
if(!found) {
hitTextures.add(customTexture);
hitTexturesPlugins.add(customTextureAddon);
}
//Do not render if we are using a different texture than the current one
if(!hitTextures.get(currentTexture).equals(customTexture) || !hitTexturesPlugins.get(currentTexture).equals(customTextureAddon)) {
continue;
}
}
//Do not render if we are not using the terrain.png and can't find a valid texture for this custom block
else if (currentTexture != 0) {
continue;
}
Block block = Block.blocksList[id];
if (renderPass == 0 && block.hasTileEntity()) {
TileEntity var20 = worldObj.getBlockTileEntity(dx, dy, dz);
if (TileEntityRenderer.instance.hasSpecialRenderer(var20)) {
this.tileEntityRenderers.add(var20);
}
}
//Determine which pass this block needs to be rendered on
int blockRenderPass = block.getRenderBlockPass();
if (design != null) {
blockRenderPass = design.getRenderPass();
}
if (blockRenderPass != renderPass) {
skipRenderPass = true;
}
else {
Tessellator.instance.setEntity(block.blockID); //shaders
if (design != null) {
oldBounds[0] = (float) block.minX;
oldBounds[1] = (float) block.minY;
oldBounds[2] = (float) block.minZ;
oldBounds[3] = (float) block.maxX;
oldBounds[4] = (float) block.maxY;
oldBounds[5] = (float) block.maxZ;
block.setBlockBounds(design.getLowXBound(), design.getLowYBound(), design.getLowZBound(), design.getHighXBound(), design.getHighYBound(), design.getHighZBound());
rendered |= design.renderBlock(mat, dx, dy, dz);
block.setBlockBounds(oldBounds[0], oldBounds[1], oldBounds[2], oldBounds[3], oldBounds[4], oldBounds[5]);
}
else {
rendered |= blockRenderer.renderBlockByRenderType(block, dx, dy, dz);
}
}
}
}
}
}
}
if (drawBlock) {
tessellator.draw();
tessellator.textureOverride = 0;
GL11.glPopMatrix();
GL11.glEndList();
game.renderEngine.bindTexture(defaultTexture);
tessellator.setTranslation(0.0D, 0.0D, 0.0D);
} else {
rendered = false;
}
if (rendered) {
this.skipRenderPass[renderPass] = false;
}
if (!skipRenderPass) {
break;
}
}
HashSet var24 = new HashSet();
var24.addAll(this.tileEntityRenderers);
var24.removeAll(tileRenderers);
this.tileEntities.addAll(var24);
tileRenderers.removeAll(this.tileEntityRenderers);
Tessellator.instance.setEntity(-1); //shaders
//Spout End
this.tileEntities.removeAll(tileRenderers);
this.isChunkLit = Chunk.isLit;
this.isInitialized = true;
blockRenderer.customIds = null;
}
}
|
diff --git a/dspace/src/org/dspace/content/InstallItem.java b/dspace/src/org/dspace/content/InstallItem.java
index e0f1c9102..3a7743e50 100644
--- a/dspace/src/org/dspace/content/InstallItem.java
+++ b/dspace/src/org/dspace/content/InstallItem.java
@@ -1,177 +1,178 @@
/*
* InstallItem.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2001, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.content;
import java.io.IOException;
import java.sql.SQLException;
import org.dspace.browse.Browse;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSIndexer;
import org.dspace.storage.rdbms.TableRowIterator;
import org.dspace.storage.rdbms.DatabaseManager;
/**
* Support to install item in the archive
*
* @author dstuve
* @version $Revision$
*/
public class InstallItem
{
public static Item installItem(Context c, InProgressSubmission is)
throws SQLException, IOException, AuthorizeException
{
return installItem(c, is, c.getCurrentUser());
}
public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
- Browse.itemAdded(c, item);
+ // item.update() above adds item to browse indices
+ //Browse.itemChanged(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
/** generate provenance-worthy description of the bitstreams
* contained in an item
*/
public static String getBitstreamProvenanceMessage(Item myitem)
{
// Get non-internal format bitstreams
Bitstream[] bitstreams = myitem.getNonInternalBitstreams();
// Create provenance description
String mymessage = "No. of bitstreams: " + bitstreams.length + "\n";
// Add sizes and checksums of bitstreams
for (int j = 0; j < bitstreams.length; j++)
{
mymessage = mymessage + bitstreams[j].getName() + ": " +
bitstreams[j].getSize() + " bytes, checksum: " +
bitstreams[j].getChecksum() + " (" +
bitstreams[j].getChecksumAlgorithm() + ")\n";
}
return mymessage;
}
}
| true | true | public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
Browse.itemAdded(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
| public static Item installItem(Context c, InProgressSubmission is, EPerson e)
throws SQLException, IOException, AuthorizeException
{
Item item = is.getItem();
// create accession date
DCDate now = DCDate.getCurrent();
item.addDC("date", "accessioned", null, now.toString());
item.addDC("date", "available", null, now.toString());
// create issue date if not present
DCValue[] currentDateIssued = item.getDC("date", "issued", null);
if(currentDateIssued.length == 0)
{
item.addDC("date", "issued", null, now.toString());
}
// create handle
String handle = HandleManager.createHandle(c, item);
// Add handle as identifier.uri DC value
item.addDC("identifier", "uri", null, handle);
// Add format.mimetype and format.extent DC values
Bitstream[] bitstreams = item.getNonInternalBitstreams();
for (int i = 0; i < bitstreams.length; i++)
{
BitstreamFormat bf = bitstreams[i].getFormat();
item.addDC("format",
"extent",
null,
String.valueOf(bitstreams[i].getSize()));
item.addDC("format", "mimetype", null, bf.getMIMEType());
}
String provDescription = "Made available in DSpace on " + now +
" (GMT). " + getBitstreamProvenanceMessage(item);
if (currentDateIssued.length != 0)
{
DCDate d = new DCDate(currentDateIssued[0].value);
provDescription = provDescription + " Previous issue date: " +
d.toString();
}
// Add provenance description
item.addDC("description", "provenance", "en", provDescription);
// create collection2item mapping
is.getCollection().addItem(item);
// create date.available
// set in_archive=true
item.setArchived(true);
// save changes ;-)
item.update();
// add item to search and browse indices
DSIndexer.indexItem(c, item);
// item.update() above adds item to browse indices
//Browse.itemChanged(c, item);
// remove in-progress submission
is.deleteWrapper();
// remove the submit authorization policies
// and replace them with the collection's READ
// policies
// FIXME: this is an inelegant hack, but out of time!
TableRowIterator tri = DatabaseManager.query(c,
"resourcepolicy",
"SELECT * FROM resourcepolicy WHERE " +
"resource_type_id=" + Constants.COLLECTION + " AND " +
"resource_id=" + is.getCollection().getID() + " AND " +
"action_id=" + Constants.READ );
item.replaceAllPolicies(tri);
return item;
}
|
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java
index 75d1f334b..194888c65 100644
--- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java
+++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java
@@ -1,369 +1,369 @@
// ========================================================================
// Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.
// ========================================================================
package org.eclipse.jetty.security.authentication;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.security.Constraint;
import org.eclipse.jetty.security.Authenticator;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
/**
* FORM Authenticator.
*
* The form authenticator redirects unauthenticated requests to a log page
* which should use a form to gather username/password from the user and send them
* to the /j_security_check URI within the context. FormAuthentication is intended
* to be used together with the {@link SessionCachingAuthenticator} so that the
* auth results may be associated with the session.
*
* This authenticator implements form authentication using dispatchers unless
* the {@link #__FORM_DISPATCH} init parameters is set to false.
*
*/
public class FormAuthenticator extends LoginAuthenticator
{
public final static String __FORM_LOGIN_PAGE="org.eclipse.jetty.security.form_login_page";
public final static String __FORM_ERROR_PAGE="org.eclipse.jetty.security.form_error_page";
public final static String __FORM_DISPATCH="org.eclipse.jetty.security.dispatch";
public final static String __J_URI = "org.eclipse.jetty.util.URI";
public final static String __J_AUTHENTICATED = "org.eclipse.jetty.server.Auth";
public final static String __J_SECURITY_CHECK = "/j_security_check";
public final static String __J_USERNAME = "j_username";
public final static String __J_PASSWORD = "j_password";
private String _formErrorPage;
private String _formErrorPath;
private String _formLoginPage;
private String _formLoginPath;
private boolean _dispatch;
public FormAuthenticator()
{
}
/* ------------------------------------------------------------ */
public FormAuthenticator(String login,String error)
{
if (login!=null)
setLoginPage(login);
if (error!=null)
setErrorPage(error);
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.Configuration)
*/
@Override
public void setConfiguration(Configuration configuration)
{
super.setConfiguration(configuration);
String login=configuration.getInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE);
if (login!=null)
setLoginPage(login);
String error=configuration.getInitParameter(FormAuthenticator.__FORM_ERROR_PAGE);
if (error!=null)
setErrorPage(error);
String dispatch=configuration.getInitParameter(FormAuthenticator.__FORM_DISPATCH);
_dispatch=dispatch==null || Boolean.getBoolean(dispatch);
}
/* ------------------------------------------------------------ */
public String getAuthMethod()
{
return Constraint.__FORM_AUTH;
}
/* ------------------------------------------------------------ */
private void setLoginPage(String path)
{
if (!path.startsWith("/"))
{
Log.warn("form-login-page must start with /");
path = "/" + path;
}
_formLoginPage = path;
_formLoginPath = path;
if (_formLoginPath.indexOf('?') > 0)
_formLoginPath = _formLoginPath.substring(0, _formLoginPath.indexOf('?'));
}
/* ------------------------------------------------------------ */
private void setErrorPage(String path)
{
if (path == null || path.trim().length() == 0)
{
_formErrorPath = null;
_formErrorPage = null;
}
else
{
if (!path.startsWith("/"))
{
Log.warn("form-error-page must start with /");
path = "/" + path;
}
_formErrorPage = path;
_formErrorPath = path;
if (_formErrorPath.indexOf('?') > 0)
_formErrorPath = _formErrorPath.substring(0, _formErrorPath.indexOf('?'));
}
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
HttpSession session = request.getSession(mandatory);
- String uri = request.getPathInfo();
+ String uri = request.getRequestURL().toString();//getPathInfo();
// not mandatory or not authenticated
if (session == null || isLoginOrErrorPage(uri))
{
return Authentication.NOT_CHECKED;
}
try
{
// Handle a request for authentication.
if (uri==null)
uri=URIUtil.SLASH;
else if (uri.endsWith(__J_SECURITY_CHECK))
{
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = _loginService.login(username,password);
if (user!=null)
{
// Redirect to original request
String nuri;
synchronized(session)
{
nuri = (String) session.getAttribute(__J_URI);
session.removeAttribute(__J_URI);
}
if (nuri == null || nuri.length() == 0)
{
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(nuri));
return new FormAuthentication(this,user);
}
// not authenticated
if (Log.isDebugEnabled())
Log.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null)
{
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage));
}
return Authentication.SEND_FAILURE;
}
if (mandatory)
{
// redirect to login page
synchronized (session)
{
if (session.getAttribute(__J_URI)==null)
{
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
}
}
if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage));
}
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
catch (ServletException e)
{
throw new ServerAuthException(e);
}
}
/* ------------------------------------------------------------ */
public boolean isLoginOrErrorPage(String pathInContext)
{
return pathInContext != null && (pathInContext.equals(_formErrorPath) || pathInContext.equals(_formLoginPath));
}
/* ------------------------------------------------------------ */
public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException
{
return true;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
protected static class FormRequest extends HttpServletRequestWrapper
{
public FormRequest(HttpServletRequest request)
{
super(request);
}
@Override
public long getDateHeader(String name)
{
if (name.toLowerCase().startsWith("if-"))
return -1;
return super.getDateHeader(name);
}
@Override
public String getHeader(String name)
{
if (name.toLowerCase().startsWith("if-"))
return null;
return super.getHeader(name);
}
@Override
public Enumeration getHeaderNames()
{
return Collections.enumeration(Collections.list(super.getHeaderNames()));
}
@Override
public Enumeration getHeaders(String name)
{
if (name.toLowerCase().startsWith("if-"))
return Collections.enumeration(Collections.EMPTY_LIST);
return super.getHeaders(name);
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
protected static class FormResponse extends HttpServletResponseWrapper
{
public FormResponse(HttpServletResponse response)
{
super(response);
}
@Override
public void addDateHeader(String name, long date)
{
if (notIgnored(name))
super.addDateHeader(name,date);
}
@Override
public void addHeader(String name, String value)
{
if (notIgnored(name))
super.addHeader(name,value);
}
@Override
public void setDateHeader(String name, long date)
{
if (notIgnored(name))
super.setDateHeader(name,date);
}
@Override
public void setHeader(String name, String value)
{
if (notIgnored(name))
super.setHeader(name,value);
}
private boolean notIgnored(String name)
{
if (HttpHeaders.CACHE_CONTROL.equalsIgnoreCase(name) ||
HttpHeaders.PRAGMA.equalsIgnoreCase(name) ||
HttpHeaders.ETAG.equalsIgnoreCase(name) ||
HttpHeaders.EXPIRES.equalsIgnoreCase(name) ||
HttpHeaders.LAST_MODIFIED.equalsIgnoreCase(name) ||
HttpHeaders.AGE.equalsIgnoreCase(name))
return false;
return true;
}
}
public static class FormAuthentication extends UserAuthentication implements Authentication.ResponseSent
{
public FormAuthentication(Authenticator authenticator, UserIdentity userIdentity)
{
super(authenticator,userIdentity);
}
public String toString()
{
return "Form"+super.toString();
}
}
}
| true | true | public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
HttpSession session = request.getSession(mandatory);
String uri = request.getPathInfo();
// not mandatory or not authenticated
if (session == null || isLoginOrErrorPage(uri))
{
return Authentication.NOT_CHECKED;
}
try
{
// Handle a request for authentication.
if (uri==null)
uri=URIUtil.SLASH;
else if (uri.endsWith(__J_SECURITY_CHECK))
{
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = _loginService.login(username,password);
if (user!=null)
{
// Redirect to original request
String nuri;
synchronized(session)
{
nuri = (String) session.getAttribute(__J_URI);
session.removeAttribute(__J_URI);
}
if (nuri == null || nuri.length() == 0)
{
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(nuri));
return new FormAuthentication(this,user);
}
// not authenticated
if (Log.isDebugEnabled())
Log.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null)
{
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage));
}
return Authentication.SEND_FAILURE;
}
if (mandatory)
{
// redirect to login page
synchronized (session)
{
if (session.getAttribute(__J_URI)==null)
{
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
}
}
if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage));
}
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
catch (ServletException e)
{
throw new ServerAuthException(e);
}
}
| public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
{
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
HttpSession session = request.getSession(mandatory);
String uri = request.getRequestURL().toString();//getPathInfo();
// not mandatory or not authenticated
if (session == null || isLoginOrErrorPage(uri))
{
return Authentication.NOT_CHECKED;
}
try
{
// Handle a request for authentication.
if (uri==null)
uri=URIUtil.SLASH;
else if (uri.endsWith(__J_SECURITY_CHECK))
{
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = _loginService.login(username,password);
if (user!=null)
{
// Redirect to original request
String nuri;
synchronized(session)
{
nuri = (String) session.getAttribute(__J_URI);
session.removeAttribute(__J_URI);
}
if (nuri == null || nuri.length() == 0)
{
nuri = request.getContextPath();
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(nuri));
return new FormAuthentication(this,user);
}
// not authenticated
if (Log.isDebugEnabled())
Log.debug("Form authentication FAILED for " + StringUtil.printable(username));
if (_formErrorPage == null)
{
if (response != null)
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
else if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage));
}
return Authentication.SEND_FAILURE;
}
if (mandatory)
{
// redirect to login page
synchronized (session)
{
if (session.getAttribute(__J_URI)==null)
{
StringBuffer buf = request.getRequestURL();
if (request.getQueryString() != null)
buf.append("?").append(request.getQueryString());
session.setAttribute(__J_URI, buf.toString());
}
}
if (_dispatch)
{
RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache");
response.setDateHeader(HttpHeaders.EXPIRES,1);
dispatcher.forward(new FormRequest(request), new FormResponse(response));
}
else
{
response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage));
}
return Authentication.SEND_CONTINUE;
}
return Authentication.UNAUTHENTICATED;
}
catch (IOException e)
{
throw new ServerAuthException(e);
}
catch (ServletException e)
{
throw new ServerAuthException(e);
}
}
|
diff --git a/src/org/red5/server/net/rtmp/RTMPConnection.java b/src/org/red5/server/net/rtmp/RTMPConnection.java
index 397a14e0..004fc0ff 100644
--- a/src/org/red5/server/net/rtmp/RTMPConnection.java
+++ b/src/org/red5/server/net/rtmp/RTMPConnection.java
@@ -1,862 +1,862 @@
package org.red5.server.net.rtmp;
/*
* RED5 Open Source Flash Server - http://www.osflash.org/red5
*
* Copyright (c) 2006-2007 by respective authors (see below). 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 2.1 of the License, or (at your option) any later
* version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import static org.red5.server.api.ScopeUtils.getScopeService;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.common.ByteBuffer;
import org.red5.server.BaseConnection;
import org.red5.server.api.IBandwidthConfigure;
import org.red5.server.api.IConnectionBWConfig;
import org.red5.server.api.IContext;
import org.red5.server.api.IBWControllable;
import org.red5.server.api.IScope;
import org.red5.server.api.Red5;
import org.red5.server.api.scheduling.IScheduledJob;
import org.red5.server.api.scheduling.ISchedulingService;
import org.red5.server.api.service.IPendingServiceCall;
import org.red5.server.api.service.IPendingServiceCallback;
import org.red5.server.api.service.IServiceCall;
import org.red5.server.api.service.IServiceCapableConnection;
import org.red5.server.api.stream.IClientBroadcastStream;
import org.red5.server.api.stream.IClientStream;
import org.red5.server.api.stream.IPlaylistSubscriberStream;
import org.red5.server.api.stream.ISingleItemSubscriberStream;
import org.red5.server.api.stream.IStreamCapableConnection;
import org.red5.server.api.stream.IStreamService;
import org.red5.server.net.rtmp.event.BytesRead;
import org.red5.server.net.rtmp.event.ClientBW;
import org.red5.server.net.rtmp.event.Invoke;
import org.red5.server.net.rtmp.event.Notify;
import org.red5.server.net.rtmp.event.Ping;
import org.red5.server.net.rtmp.event.ServerBW;
import org.red5.server.net.rtmp.event.VideoData;
import org.red5.server.net.rtmp.message.Packet;
import org.red5.server.service.Call;
import org.red5.server.service.PendingCall;
import org.red5.server.stream.ClientBroadcastStream;
import org.red5.server.stream.IBWControlContext;
import org.red5.server.stream.IBWControlService;
import org.red5.server.stream.OutputStream;
import org.red5.server.stream.PlaylistSubscriberStream;
import org.red5.server.stream.StreamService;
import org.red5.server.stream.VideoCodecFactory;
import org.springframework.context.ApplicationContext;
/**
* RTMP connection. Stores information about client streams, data transfer channels,
* pending RPC calls, bandwidth configuration, used encoding (AMF0/AMF3), connection state (is alive, last
* ping time and ping result) and session.
*/
public abstract class RTMPConnection extends BaseConnection implements
IStreamCapableConnection, IServiceCapableConnection {
/**
* Logger
*/
protected static Log log = LogFactory
.getLog(RTMPConnection.class.getName());
/**
* Video codec factory constant
*/
private static final String VIDEO_CODEC_FACTORY = "videoCodecFactory";
// private Context context;
/**
* Connection channels
*
* @see org.red5.server.net.rtmp.Channel
*/
private Map<Integer, Channel> channels = new ConcurrentHashMap<Integer, Channel>();
/**
* Client streams
*
* @see org.red5.server.api.stream.IClientStream
*/
private Map<Integer, IClientStream> streams = new ConcurrentHashMap<Integer, IClientStream>();
private Map<Integer, Boolean> reservedStreams = new ConcurrentHashMap<Integer, Boolean>();
/**
* Identifier for remote calls
*/
protected Integer invokeId = 1;
/**
* Hash map that stores pending calls and ids as pairs.
*/
protected Map<Integer, IPendingServiceCall> pendingCalls = new ConcurrentHashMap<Integer, IPendingServiceCall>();
/**
* Deferred results set
*
* @see org.red5.server.net.rtmp.DeferredResult
*/
protected HashSet<DeferredResult> deferredResults = new HashSet<DeferredResult>();
/**
* Last ping timestamp
*/
protected int lastPingTime = -1;
/**
* Whether ping replied or not
*/
protected boolean pingReplied = true;
/**
* Name of quartz job that keeps connection alive
*/
protected String keepAliveJobName;
/**
* Keep alive interval
*/
protected int keepAliveInterval = 1000;
/**
* Data read interval
*/
private int bytesReadInterval = 125000;
/**
* Number of bytes to read next
*/
private int nextBytesRead = 125000;
/**
* Bandwidth configure
*/
private IConnectionBWConfig bwConfig;
/**
* Bandwidth context used by bandwidth controller
*/
private IBWControlContext bwContext;
/**
* Map for pending video packets and stream IDs
*/
private Map<Integer, Integer> pendingVideos = new ConcurrentHashMap<Integer, Integer>();
/**
* Number of streams used
*/
private int usedStreams;
/**
* AMF version, AMF0 by default
*/
protected Encoding encoding = Encoding.AMF0;
/**
* Creates anonymous RTMP connection without scope
* @param type Connection type
*/
public RTMPConnection(String type) {
// We start with an anonymous connection without a scope.
// These parameters will be set during the call of "connect" later.
// super(null, ""); temp fix to get things to compile
super(type, null, null, 0, null, null, null);
}
@Override
public boolean connect(IScope newScope, Object[] params) {
boolean success = super.connect(newScope, params);
if (success) {
// XXX Bandwidth control service should not be bound to
// a specific scope because it's designed to control
// the bandwidth system-wide.
if (getScope() != null && getScope().getContext() != null) {
IBWControlService bwController = (IBWControlService) getScope()
.getContext().getBean(IBWControlService.KEY);
bwContext = bwController.registerBWControllable(this);
}
}
return success;
}
/**
* Initialize connection
*
* @param host Connection host
* @param path Connection path
* @param sessionId Connection session id
* @param params Params passed from client
*/
public void setup(String host, String path, String sessionId,
Map<String, Object> params) {
this.host = host;
this.path = path;
this.sessionId = sessionId;
this.params = params;
if (params.get("objectEncoding") == Integer.valueOf(3))
encoding = Encoding.AMF3;
}
/**
* Return AMF protocol encoding used by this connection
* @return AMF encoding used by connection
*/
public Encoding getEncoding() {
return encoding;
}
/**
* Getter for next available channel id
*
* @return Next available channel id
*/
public synchronized int getNextAvailableChannelId() {
int result = 4;
while (isChannelUsed(result))
result++;
return result;
}
/**
* Checks whether channel is used
* @param channelId Channel id
* @return <code>true</code> if channel is in use, <code>false</code> otherwise
*/
public boolean isChannelUsed(int channelId) {
return channels.get(channelId) != null;
}
/**
* Return channel by id
* @param channelId Channel id
* @return Channel by id
*/
public Channel getChannel(int channelId) {
Channel result = channels.get(channelId);
if (result == null) {
result = new Channel(this, channelId);
channels.put(channelId, result);
}
return result;
}
/**
* Closes channel
* @param channelId Channel id
*/
public void closeChannel(int channelId) {
channels.remove(channelId);
}
/**
* Getter for client streams
*
* @return Client streams as array
*/
protected Collection<IClientStream> getStreams() {
return streams.values();
}
/** {@inheritDoc} */
public int reserveStreamId() {
int result = -1;
synchronized (reservedStreams) {
for (int i = 0; true; i++) {
Boolean value = reservedStreams.get(i);
if (value == null || !value) {
reservedStreams.put(i, true);
result = i;
break;
}
}
}
return result + 1;
}
/**
* Creates output stream object from stream id. Output stream consists of audio, data and video channels.
*
* @see org.red5.server.stream.OutputStream
* @param streamId Stream id
* @return Output stream object
*/
public OutputStream createOutputStream(int streamId) {
int channelId = (4 + ((streamId - 1) * 5));
final Channel data = getChannel(channelId++);
final Channel video = getChannel(channelId++);
final Channel audio = getChannel(channelId++);
// final Channel unknown = getChannel(channelId++);
// final Channel ctrl = getChannel(channelId++);
return new OutputStream(video, audio, data);
}
/**
* Getter for video codec factory
*
* @return Video codec factory
*/
public VideoCodecFactory getVideoCodecFactory() {
final IContext context = scope.getContext();
ApplicationContext appCtx = context.getApplicationContext();
if (!appCtx.containsBean(VIDEO_CODEC_FACTORY)) {
return null;
}
return (VideoCodecFactory) appCtx.getBean(VIDEO_CODEC_FACTORY);
}
/** {@inheritDoc} */
public IClientBroadcastStream newBroadcastStream(int streamId) {
Boolean value = reservedStreams.get(streamId - 1);
if (value == null || !value) {
// StreamId has not been reserved before
return null;
}
synchronized (streams) {
if (streams.get(streamId - 1) != null) {
// Another stream already exists with this id
return null;
}
ApplicationContext appCtx =
scope.getContext().getApplicationContext();
ClientBroadcastStream cbs = (ClientBroadcastStream)
appCtx.getBean("clientBroadcastStream");
/**
* Picking up the ClientBroadcastStream defined as a spring prototype
* in red5-common.xml
*/
cbs.setStreamId(streamId);
cbs.setConnection(this);
cbs.setName(createStreamName());
cbs.setScope(this.getScope());
streams.put(streamId - 1, cbs);
usedStreams++;
return cbs;
}
}
/** {@inheritDoc}
* To be implemented.
*/
public ISingleItemSubscriberStream newSingleItemSubscriberStream(
int streamId) {
// TODO implement it
return null;
}
/** {@inheritDoc} */
public IPlaylistSubscriberStream newPlaylistSubscriberStream(int streamId) {
Boolean value = reservedStreams.get(streamId - 1);
if (value == null || !value) {
// StreamId has not been reserved before
return null;
}
synchronized (streams) {
if (streams.get(streamId - 1) != null) {
// Another stream already exists with this id
return null;
}
ApplicationContext appCtx =
scope.getContext().getApplicationContext();
/**
* Picking up the PlaylistSubscriberStream defined as a spring prototype
* in red5-common.xml
*/
PlaylistSubscriberStream pss = (PlaylistSubscriberStream)
appCtx.getBean("playlistSubscriberStream");
pss.setName(createStreamName());
pss.setConnection(this);
pss.setScope(this.getScope());
pss.setStreamId(streamId);
streams.put(streamId - 1, pss);
usedStreams++;
return pss;
}
}
/**
* Getter for used stream count
*
* @return Value for property 'usedStreamCount'.
*/
protected int getUsedStreamCount() {
return usedStreams;
}
/** {@inheritDoc} */
public IClientStream getStreamById(int id) {
if (id <= 0) {
return null;
}
return streams.get(id - 1);
}
/**
* Return stream id for given channel id
* @param channelId Channel id
* @return ID of stream that channel belongs to
*/
public int getStreamIdForChannel(int channelId) {
if (channelId < 4) {
return 0;
}
return (int) Math.floor((channelId - 4) / 5) + 1;
}
/**
* Return stream for given channel id
* @param channelId Channel id
* @return Stream that channel belongs to
*/
public IClientStream getStreamByChannelId(int channelId) {
if (channelId < 4) {
return null;
}
return streams.get(getStreamIdForChannel(channelId) - 1);
}
/** {@inheritDoc} */
@Override
public void close() {
if (keepAliveJobName != null) {
ISchedulingService schedulingService =
(ISchedulingService) getScope().getContext().getBean(ISchedulingService.BEAN_NAME);
schedulingService.removeScheduledJob(keepAliveJobName);
keepAliveJobName = null;
}
Red5.setConnectionLocal(this);
IStreamService streamService = (IStreamService) getScopeService(scope,
IStreamService.class, StreamService.class);
if (streamService != null) {
synchronized (streams) {
for (Map.Entry<Integer, IClientStream> entry: streams.entrySet()) {
IClientStream stream = entry.getValue();
if (stream != null) {
if (log.isDebugEnabled()) {
log.debug("Closing stream: " + stream.getStreamId());
}
streamService.deleteStream(this, stream.getStreamId());
usedStreams--;
}
}
streams.clear();
}
}
- if (getScope() != null && getScope().getContext() != null) {
+ if (bwContext != null && getScope() != null && getScope().getContext() != null) {
IBWControlService bwController = (IBWControlService) getScope()
.getContext().getBean(IBWControlService.KEY);
bwController.unregisterBWControllable(bwContext);
}
super.close();
}
/** {@inheritDoc} */
public void unreserveStreamId(int streamId) {
deleteStreamById(streamId);
if (streamId > 0) {
reservedStreams.remove(streamId - 1);
}
}
/** {@inheritDoc} */
public void deleteStreamById(int streamId) {
if (streamId > 0) {
if (streams.get(streamId - 1) != null) {
synchronized (pendingVideos) {
pendingVideos.remove(streamId);
}
usedStreams--;
streams.remove(streamId - 1);
}
}
}
/**
* Handler for ping event
* @param ping Ping event context
*/
public void ping(Ping ping) {
getChannel((byte) 2).write(ping);
}
/**
* Write raw byte buffer
* @param out Byte buffer
*/
public abstract void rawWrite(ByteBuffer out);
/**
* Write packet
* @param out Packet
*/
public abstract void write(Packet out);
/**
* Update number of bytes to read next value
*/
protected void updateBytesRead() {
long bytesRead = getReadBytes();
if (bytesRead >= nextBytesRead) {
BytesRead sbr = new BytesRead((int) bytesRead);
getChannel((byte) 2).write(sbr);
log.info(sbr);
nextBytesRead += bytesReadInterval;
}
}
/**
* Read number of recieved bytes
* @param bytes Number of bytes
*/
public void receivedBytesRead(int bytes) {
log.info("Client received " + bytes + " bytes, written "
+ getWrittenBytes() + " bytes, " + getPendingMessages()
+ " messages pending");
}
/** {@inheritDoc} */
public void invoke(IServiceCall call) {
invoke(call, (byte) 3);
}
/**
* Generate next invoke id
*
* @return Next invoke id for RPC
*/
protected synchronized int getInvokeId() {
return invokeId++;
}
/**
* Register pending call (remote function call that is yet to finish)
* @param invokeId Deferred operation id
* @param call Call service
*/
protected void registerPendingCall(int invokeId, IPendingServiceCall call) {
synchronized (pendingCalls) {
pendingCalls.put(invokeId, call);
}
}
/** {@inheritDoc} */
public void invoke(IServiceCall call, byte channel) {
// We need to use Invoke for all calls to the client
Invoke invoke = new Invoke();
invoke.setCall(call);
invoke.setInvokeId(getInvokeId());
if (call instanceof IPendingServiceCall) {
registerPendingCall(invoke.getInvokeId(), (IPendingServiceCall) call);
}
getChannel(channel).write(invoke);
}
/** {@inheritDoc} */
public void invoke(String method) {
invoke(method, null, null);
}
/** {@inheritDoc} */
public void invoke(String method, Object[] params) {
invoke(method, params, null);
}
/** {@inheritDoc} */
public void invoke(String method, IPendingServiceCallback callback) {
invoke(method, null, callback);
}
/** {@inheritDoc} */
public void invoke(String method, Object[] params,
IPendingServiceCallback callback) {
IPendingServiceCall call = new PendingCall(method, params);
if (callback != null) {
call.registerCallback(callback);
}
invoke(call);
}
/** {@inheritDoc} */
public void notify(IServiceCall call) {
notify(call, (byte) 3);
}
/** {@inheritDoc} */
public void notify(IServiceCall call, byte channel) {
Notify notify = new Notify();
notify.setCall(call);
getChannel(channel).write(notify);
}
/** {@inheritDoc} */
public void notify(String method) {
notify(method, null);
}
/** {@inheritDoc} */
public void notify(String method, Object[] params) {
IServiceCall call = new Call(method, params);
notify(call);
}
/** {@inheritDoc} */
public IBandwidthConfigure getBandwidthConfigure() {
return bwConfig;
}
/** {@inheritDoc} */
public IBWControllable getParentBWControllable() {
// TODO return the client object
return null;
}
/** {@inheritDoc} */
public void setBandwidthConfigure(IBandwidthConfigure config) {
if (!(config instanceof IConnectionBWConfig)) {
return;
}
this.bwConfig = (IConnectionBWConfig) config;
// Notify client about new bandwidth settings (in bytes per second)
if (bwConfig.getDownstreamBandwidth() > 0) {
ServerBW serverBW = new ServerBW((int) bwConfig
.getDownstreamBandwidth() / 8);
getChannel((byte) 2).write(serverBW);
}
if (bwConfig.getUpstreamBandwidth() > 0) {
ClientBW clientBW = new ClientBW((int) bwConfig
.getUpstreamBandwidth() / 8, (byte) 0);
getChannel((byte) 2).write(clientBW);
// Update generation of BytesRead messages
// TODO: what are the correct values here?
bytesReadInterval = (int) bwConfig.getUpstreamBandwidth() / 8;
nextBytesRead = (int) getWrittenBytes();
}
if (bwContext != null) {
IBWControlService bwController = (IBWControlService) getScope().getContext()
.getBean(IBWControlService.KEY);
bwController.updateBWConfigure(bwContext);
}
}
/** {@inheritDoc} */
@Override
public long getReadBytes() {
// TODO Auto-generated method stub
return 0;
}
/** {@inheritDoc} */
@Override
public long getWrittenBytes() {
// TODO Auto-generated method stub
return 0;
}
/**
* Get pending call service by id
* @param invokeId Pending call service id
* @return Pending call service object
*/
protected IPendingServiceCall getPendingCall(int invokeId) {
IPendingServiceCall result;
synchronized (pendingCalls) {
result = pendingCalls.get(invokeId);
if (result != null) {
pendingCalls.remove(invokeId);
}
}
return result;
}
/**
* Generates new stream name
* @return New stream name
*/
protected String createStreamName() {
return UUID.randomUUID().toString();
}
/**
* Mark message as being written.
*
* @param message Message to mark
*/
protected void writingMessage(Packet message) {
if (message.getMessage() instanceof VideoData) {
int streamId = message.getHeader().getStreamId();
synchronized (pendingVideos) {
Integer old = pendingVideos.get(streamId);
if (old == null) {
old = Integer.valueOf(0);
}
pendingVideos.put(streamId, old + 1);
}
}
}
/**
* Increases number of read messages by one. Updates number of bytes read.
*/
protected void messageReceived() {
readMessages++;
// Trigger generation of BytesRead messages
updateBytesRead();
}
/**
* Mark message as sent.
*
* @param message Message to mark
*/
protected void messageSent(Packet message) {
if (message.getMessage() instanceof VideoData) {
int streamId = message.getHeader().getStreamId();
synchronized (pendingVideos) {
Integer pending = pendingVideos.get(streamId);
if (pending != null) {
pendingVideos.put(streamId, pending - 1);
}
}
}
writtenMessages++;
}
/**
* Increases number of dropped messages
*/
protected void messageDropped() {
droppedMessages++;
}
/** {@inheritDoc} */
@Override
public long getPendingVideoMessages(int streamId) {
synchronized (pendingVideos) {
Integer count = pendingVideos.get(streamId);
long result = (count != null ? count.intValue()
- getUsedStreamCount() : 0);
return (result > 0 ? result : 0);
}
}
/** {@inheritDoc} */
public void ping() {
Ping pingRequest = new Ping();
pingRequest.setValue1((short) 6);
int now = (int) (System.currentTimeMillis() & 0xffffffff);
pingRequest.setValue2(now);
pingRequest.setValue3(Ping.UNDEFINED);
pingReplied = false;
ping(pingRequest);
}
/**
* Marks that pingback was recieved
* @param pong Ping object
*/
protected void pingReceived(Ping pong) {
pingReplied = true;
int now = (int) (System.currentTimeMillis() & 0xffffffff);
lastPingTime = now - pong.getValue2();
}
/** {@inheritDoc} */
public int getLastPingTime() {
return lastPingTime;
}
/**
* Setter for keep alive interval
*
* @param keepAliveInterval Keep alive interval
*/
public void setKeepAliveInterval(int keepAliveInterval) {
this.keepAliveInterval = keepAliveInterval;
}
/**
* Starts measurement
*/
public void startRoundTripMeasurement() {
ISchedulingService schedulingService =
(ISchedulingService) getScope().getContext().getBean(ISchedulingService.BEAN_NAME);
IScheduledJob keepAliveJob = new KeepAliveJob();
keepAliveJobName = schedulingService.addScheduledJob(keepAliveInterval, keepAliveJob);
}
/**
* Inactive state event handler
*/
protected abstract void onInactive();
/** {@inheritDoc} */
@Override
public String toString() {
return getClass().getSimpleName() + " from " + getRemoteAddress() + ':'
+ getRemotePort() + " to " + getHost() + " (in: "
+ getReadBytes() + ", out: " + getWrittenBytes() + ')';
}
/**
* Registers deffered result
* @param result Result to register
*/
protected void registerDeferredResult(DeferredResult result) {
deferredResults.add(result);
}
/**
* Unregister deffered result
* @param result Result to unregister
*/
protected void unregisterDeferredResult(DeferredResult result) {
deferredResults.remove(result);
}
/**
* Quartz job that keeps connection alive
*/
private class KeepAliveJob implements IScheduledJob {
/** {@inheritDoc} */
public void execute(ISchedulingService service) {
if (!pingReplied) {
onInactive();
}
ping();
}
}
}
| true | true | public void close() {
if (keepAliveJobName != null) {
ISchedulingService schedulingService =
(ISchedulingService) getScope().getContext().getBean(ISchedulingService.BEAN_NAME);
schedulingService.removeScheduledJob(keepAliveJobName);
keepAliveJobName = null;
}
Red5.setConnectionLocal(this);
IStreamService streamService = (IStreamService) getScopeService(scope,
IStreamService.class, StreamService.class);
if (streamService != null) {
synchronized (streams) {
for (Map.Entry<Integer, IClientStream> entry: streams.entrySet()) {
IClientStream stream = entry.getValue();
if (stream != null) {
if (log.isDebugEnabled()) {
log.debug("Closing stream: " + stream.getStreamId());
}
streamService.deleteStream(this, stream.getStreamId());
usedStreams--;
}
}
streams.clear();
}
}
if (getScope() != null && getScope().getContext() != null) {
IBWControlService bwController = (IBWControlService) getScope()
.getContext().getBean(IBWControlService.KEY);
bwController.unregisterBWControllable(bwContext);
}
super.close();
}
| public void close() {
if (keepAliveJobName != null) {
ISchedulingService schedulingService =
(ISchedulingService) getScope().getContext().getBean(ISchedulingService.BEAN_NAME);
schedulingService.removeScheduledJob(keepAliveJobName);
keepAliveJobName = null;
}
Red5.setConnectionLocal(this);
IStreamService streamService = (IStreamService) getScopeService(scope,
IStreamService.class, StreamService.class);
if (streamService != null) {
synchronized (streams) {
for (Map.Entry<Integer, IClientStream> entry: streams.entrySet()) {
IClientStream stream = entry.getValue();
if (stream != null) {
if (log.isDebugEnabled()) {
log.debug("Closing stream: " + stream.getStreamId());
}
streamService.deleteStream(this, stream.getStreamId());
usedStreams--;
}
}
streams.clear();
}
}
if (bwContext != null && getScope() != null && getScope().getContext() != null) {
IBWControlService bwController = (IBWControlService) getScope()
.getContext().getBean(IBWControlService.KEY);
bwController.unregisterBWControllable(bwContext);
}
super.close();
}
|
diff --git a/ChessFeud/src/se/chalmers/chessfeud/model/pieces/Rook.java b/ChessFeud/src/se/chalmers/chessfeud/model/pieces/Rook.java
index 6cc1d76..8b8a1ff 100644
--- a/ChessFeud/src/se/chalmers/chessfeud/model/pieces/Rook.java
+++ b/ChessFeud/src/se/chalmers/chessfeud/model/pieces/Rook.java
@@ -1,79 +1,79 @@
package se.chalmers.chessfeud.model.pieces;
import java.util.ArrayList;
import java.util.List;
import se.chalmers.chessfeud.constants.C;
import se.chalmers.chessfeud.model.utils.Position;
/**
* The piece Rook. Reprecents the rook on the board. Contains the movement
* pattern and what team the piece is on.
*
* @author Arvid
*
* Copyright � 2012 Arvid Karlsson
*/
public class Rook extends Piece {
public Rook(int team) {
super(team, C.PIECE_ROOK);
// TODO Auto-generated constructor stub
}
/**
*
*
* Returns a list of all the theoretical moves the King can do. Even the
* moves that are out of bounds. That will be checked in the rules class.
* Gets a List of positions from the method moveDirection. That list gets
* stacked in a new list that is returned.
*
* @param p
* the piece current position.
* @return posList A list that contains Lists of possible positions in the
* diffrent directions.
*/
@Override
public List<List<Position>> theoreticalMoves(Position p) {
List<List<Position>> posList = new ArrayList<List<Position>>();
- for (int x = -1; x < 2; x++) {
- for (int y = -1; y < 2; y++) {
- if ((x != 0 && y != 0) && (x == 0 || y == 0)) {
+ for (int x = -1; x <= 1; x++) {
+ for (int y = -1; y <= 1; y++) {
+ if (x != y && x*y == 0) {
List<Position> moveList = moveDirection(x, y, p);
if (moveList.size() != 0)
posList.add(moveList);
}
}
}
return posList;
}
/*
* Takes the Rooks current position and returns all the possible squares it
* can go on in the directions the Rook goes (horizontal and vertical).
*
* @param dx the x-Position value
*
* @param dy the y-Position value
*
* @return moveList a List with all the possible moves in each direction.
*/
private List<Position> moveDirection(int dx, int dy, Position p) {
List<Position> moveList = new ArrayList<Position>();
int x = p.getX() + dx;
int y = p.getY() + dy;
while (Position.inBounds(x, y)) {
moveList.add(new Position(x, y));
x += dx;
y += dy;
}
return moveList;
}
@Override
public String toString() {
return "Piece: Rook " + "Team: " + getTeam();
}
}
| true | true | public List<List<Position>> theoreticalMoves(Position p) {
List<List<Position>> posList = new ArrayList<List<Position>>();
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
if ((x != 0 && y != 0) && (x == 0 || y == 0)) {
List<Position> moveList = moveDirection(x, y, p);
if (moveList.size() != 0)
posList.add(moveList);
}
}
}
return posList;
}
| public List<List<Position>> theoreticalMoves(Position p) {
List<List<Position>> posList = new ArrayList<List<Position>>();
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
if (x != y && x*y == 0) {
List<Position> moveList = moveDirection(x, y, p);
if (moveList.size() != 0)
posList.add(moveList);
}
}
}
return posList;
}
|
diff --git a/milton-server/src/main/java/io/milton/http/http11/PutHandler.java b/milton-server/src/main/java/io/milton/http/http11/PutHandler.java
index fe40ef2..078f569 100644
--- a/milton-server/src/main/java/io/milton/http/http11/PutHandler.java
+++ b/milton-server/src/main/java/io/milton/http/http11/PutHandler.java
@@ -1,425 +1,426 @@
/*
* Copyright 2012 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 io.milton.http.http11;
import io.milton.http.Handler;
import io.milton.resource.ReplaceableResource;
import io.milton.resource.PutableResource;
import io.milton.resource.CollectionResource;
import io.milton.resource.Resource;
import io.milton.http.HandlerHelper;
import io.milton.http.HttpManager;
import io.milton.resource.GetableResource;
import io.milton.http.Range;
import io.milton.resource.MakeCollectionableResource;
import io.milton.http.exceptions.BadRequestException;
import io.milton.http.exceptions.NotFoundException;
import io.milton.http.quota.StorageChecker.StorageErrorReason;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.milton.common.Path;
import io.milton.http.Request.Method;
import io.milton.http.Response.Status;
import io.milton.http.exceptions.ConflictException;
import io.milton.http.exceptions.NotAuthorizedException;
import io.milton.http.webdav.WebDavResponseHandler;
import io.milton.common.FileUtils;
import io.milton.common.RandomFileOutputStream;
import io.milton.common.LogUtils;
import io.milton.event.NewFolderEvent;
import io.milton.event.PutEvent;
import io.milton.http.Request;
import io.milton.http.Response;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
public class PutHandler implements Handler {
private static final Logger log = LoggerFactory.getLogger(PutHandler.class);
private final Http11ResponseHandler responseHandler;
private final HandlerHelper handlerHelper;
private final PutHelper putHelper;
private final MatchHelper matchHelper;
public PutHandler(Http11ResponseHandler responseHandler, HandlerHelper handlerHelper, PutHelper putHelper, MatchHelper matchHelper) {
this.responseHandler = responseHandler;
this.handlerHelper = handlerHelper;
this.putHelper = putHelper;
this.matchHelper = matchHelper;
checkResponseHandler();
}
private void checkResponseHandler() {
if (!(responseHandler instanceof WebDavResponseHandler)) {
log.warn("response handler is not a WebDavResponseHandler, so locking and quota checking will not be enabled");
}
}
@Override
public String[] getMethods() {
return new String[]{Method.PUT.code};
}
@Override
public boolean isCompatible(Resource handler) {
return (handler instanceof PutableResource);
}
@Override
public void process(HttpManager manager, Request request, Response response) throws NotAuthorizedException, ConflictException, BadRequestException, NotFoundException {
if (!handlerHelper.checkExpects(responseHandler, request, response)) {
return;
}
String host = request.getHostHeader();
String urlToCreateOrUpdate = HttpManager.decodeUrl(request.getAbsolutePath());
LogUtils.debug(log, "PUT request. Host:", host, " Url:", urlToCreateOrUpdate, " content length header:", request.getContentLengthHeader());
Path path = Path.path(urlToCreateOrUpdate);
urlToCreateOrUpdate = path.toString();
Resource existingResource = manager.getResourceFactory().getResource(host, urlToCreateOrUpdate);
ReplaceableResource replacee;
StorageErrorReason storageErr = null;
if (existingResource != null) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, existingResource)) {
log.warn("resource is locked, but not by the current user");
respondLocked(request, response, existingResource);
return;
}
// Check if the resource has been modified based on etags
if( !matchHelper.checkIfMatch(existingResource, request)) {
log.info("if-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(existingResource, request)) {
log.info("if-none-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
Resource parent = manager.getResourceFactory().getResource(host, path.getParent().toString());
if (parent instanceof CollectionResource) {
CollectionResource parentCol = (CollectionResource) parent;
storageErr = handlerHelper.checkStorageOnReplace(request, parentCol, existingResource, host);
} else {
log.warn("parent exists but is not a collection resource: " + path.getParent());
}
} else {
if( !matchHelper.checkIfMatch(null, request)) {
log.info("if-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(null, request)) {
log.info("if-none-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
CollectionResource parentCol = putHelper.findNearestParent(manager, host, path);
storageErr = handlerHelper.checkStorageOnAdd(request, parentCol, path.getParent(), host);
}
if (storageErr != null) {
respondInsufficientStorage(request, response, storageErr);
return;
}
if (existingResource != null && existingResource instanceof ReplaceableResource) {
replacee = (ReplaceableResource) existingResource;
} else {
replacee = null;
}
if (replacee != null) {
if (log.isTraceEnabled()) {
log.trace("replacing content in: " + replacee.getName() + " - " + replacee.getClass());
}
long t = System.currentTimeMillis();
try {
manager.onProcessResourceStart(request, response, replacee);
processReplace(manager, request, response, replacee);
+ manager.getEventManager().fireEvent(new PutEvent(replacee));
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, replacee, t);
}
} else {
// either no existing resource, or its not replaceable. check for folder
String nameToCreate = path.getName();
CollectionResource folderResource = findOrCreateFolders(manager, host, path.getParent());
if (folderResource != null) {
long t = System.currentTimeMillis();
try {
if (folderResource instanceof PutableResource) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, folderResource)) {
respondLocked(request, response, folderResource);
return;
}
PutableResource putableResource = (PutableResource) folderResource;
processCreate(manager, request, response, putableResource, nameToCreate);
} else {
LogUtils.debug(log, "method not implemented: PUT on class: ", folderResource.getClass(), folderResource.getName());
manager.getResponseHandler().respondMethodNotImplemented(folderResource, response, request);
}
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, folderResource, t);
}
} else {
responseHandler.respondNotFound(response, request);
}
}
}
private void processCreate(HttpManager manager, Request request, Response response, PutableResource folder, String newName) throws ConflictException, BadRequestException, NotAuthorizedException {
if (!handlerHelper.checkAuthorisation(manager, folder, request)) {
responseHandler.respondUnauthorised(folder, response, request);
return;
}
LogUtils.debug(log, "process: putting to: ", folder.getName());
try {
Long l = putHelper.getContentLength(request);
String ct = putHelper.findContentTypes(request, newName);
LogUtils.debug(log, "PutHandler: creating resource of type: ", ct);
Resource newlyCreated = folder.createNew(newName, request.getInputStream(), l, ct);
if (newlyCreated != null) {
if (newName != null && !newName.equals(newlyCreated.getName())) {
log.warn("getName on the created resource does not match the name requested by the client! requested: " + newName + " - created: " + newlyCreated.getName());
}
manager.getEventManager().fireEvent(new PutEvent(newlyCreated));
manager.getResponseHandler().respondCreated(newlyCreated, response, request);
} else {
throw new RuntimeException("createNew method on: " + folder.getClass() + " returned a null resource. Must return a reference to the newly created or modified resource");
}
} catch (IOException ex) {
throw new RuntimeException("IOException reading input stream. Probably interrupted upload", ex);
}
}
private CollectionResource findOrCreateFolders(HttpManager manager, String host, Path path) throws NotAuthorizedException, ConflictException, BadRequestException {
if (path == null) {
return null;
}
Resource thisResource = manager.getResourceFactory().getResource(host, path.toString());
if (thisResource != null) {
// Defensive programming test for a common problem where resource factories
// return the wrong resource for a given path
if (thisResource.getName() != null && !thisResource.getName().equals(path.getName())) {
log.warn("Your resource factory returned a resource with a different name to that requested!!! Requested: " + path.getName() + " returned: " + thisResource.getName() + " - resource factory: " + manager.getResourceFactory().getClass());
}
if (thisResource instanceof CollectionResource) {
return (CollectionResource) thisResource;
} else {
log.warn("parent is not a collection: " + path);
return null;
}
}
CollectionResource parent = findOrCreateFolders(manager, host, path.getParent());
if (parent == null) {
log.warn("couldnt find parent: " + path);
return null;
}
Resource r = parent.child(path.getName());
if (r == null) {
if (parent instanceof MakeCollectionableResource) {
MakeCollectionableResource mkcol = (MakeCollectionableResource) parent;
LogUtils.debug(log, "autocreating new folder: ", path.getName());
CollectionResource newCol = mkcol.createCollection(path.getName());
manager.getEventManager().fireEvent(new NewFolderEvent(newCol));
return newCol;
} else {
log.debug("parent folder isnt a MakeCollectionableResource: " + parent.getName());
return null;
}
} else if (r instanceof CollectionResource) {
return (CollectionResource) r;
} else {
log.debug("parent in URL is not a collection: " + r.getName());
return null;
}
}
/**
* "If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request."
*
* @param request
* @param response
* @param replacee
*/
private void processReplace(HttpManager manager, Request request, Response response, ReplaceableResource replacee) throws BadRequestException, NotAuthorizedException, ConflictException, NotFoundException {
if (!handlerHelper.checkAuthorisation(manager, replacee, request)) {
responseHandler.respondUnauthorised(replacee, response, request);
return;
}
try {
Range range = putHelper.parseContentRange(replacee, request);
if (range != null) {
log.debug("partial put: " + range);
if (replacee instanceof PartialllyUpdateableResource) {
log.debug("doing partial put on a PartialllyUpdateableResource");
PartialllyUpdateableResource partialllyUpdateableResource = (PartialllyUpdateableResource) replacee;
partialllyUpdateableResource.replacePartialContent(range, request.getInputStream());
} else if (replacee instanceof GetableResource) {
log.debug("doing partial put on a GetableResource");
File tempFile = File.createTempFile("milton-partial", null);
RandomAccessFile randomAccessFile = null;
// The new length of the resource
long length;
try {
randomAccessFile = new RandomAccessFile(tempFile, "rw");
RandomFileOutputStream tempOut = new RandomFileOutputStream(tempFile);
GetableResource gr = (GetableResource) replacee;
// Update the content with the supplied partial content, and get the result as an inputstream
gr.sendContent(tempOut, null, null, null);
// Calculate new length, if the partial put is extending it
length = randomAccessFile.length();
if (range.getFinish() + 1 > length) {
length = range.getFinish() + 1;
}
randomAccessFile.setLength(length);
randomAccessFile.seek(range.getStart());
int numBytesRead;
byte[] copyBuffer = new byte[1024];
InputStream newContent = request.getInputStream();
while ((numBytesRead = newContent.read(copyBuffer)) != -1) {
randomAccessFile.write(copyBuffer, 0, numBytesRead);
}
} finally {
FileUtils.close(randomAccessFile);
}
InputStream updatedContent = new FileInputStream(tempFile);
BufferedInputStream bufin = new BufferedInputStream(updatedContent);
// Now, finally, we can just do a normal update
replacee.replaceContent(bufin, length);
} else {
throw new BadRequestException(replacee, "Cant apply partial update. Resource does not support PartialllyUpdateableResource or GetableResource");
}
} else {
// Not a partial update, but resource implements Replaceable, so give it the new data
Long l = request.getContentLengthHeader();
replacee.replaceContent(request.getInputStream(), l);
}
} catch (IOException ex) {
log.warn("IOException reading input stream. Probably interrupted upload: " + ex.getMessage());
return;
}
// Respond with a 204
responseHandler.respondNoContent(replacee, response, request);
log.debug("process: finished");
}
public void processExistingResource(HttpManager manager, Request request, Response response, Resource resource) throws NotAuthorizedException, BadRequestException, ConflictException, NotFoundException {
String host = request.getHostHeader();
String urlToCreateOrUpdate = HttpManager.decodeUrl(request.getAbsolutePath());
log.debug("process request: host: " + host + " url: " + urlToCreateOrUpdate);
Path path = Path.path(urlToCreateOrUpdate);
urlToCreateOrUpdate = path.toString();
Resource existingResource = manager.getResourceFactory().getResource(host, urlToCreateOrUpdate);
ReplaceableResource replacee;
if (existingResource != null) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, existingResource)) {
log.warn("resource is locked, but not by the current user");
response.setStatus(Status.SC_LOCKED); //423
return;
}
}
if (existingResource != null && existingResource instanceof ReplaceableResource) {
replacee = (ReplaceableResource) existingResource;
} else {
replacee = null;
}
if (replacee != null) {
processReplace(manager, request, response, (ReplaceableResource) existingResource);
} else {
// either no existing resource, or its not replaceable. check for folder
String urlFolder = path.getParent().toString();
String nameToCreate = path.getName();
CollectionResource folderResource = findOrCreateFolders(manager, host, path.getParent());
if (folderResource != null) {
if (log.isDebugEnabled()) {
log.debug("found folder: " + urlFolder + " - " + folderResource.getClass());
}
if (folderResource instanceof PutableResource) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, folderResource)) {
response.setStatus(Status.SC_LOCKED); //423
return;
}
PutableResource putableResource = (PutableResource) folderResource;
processCreate(manager, request, response, putableResource, nameToCreate);
} else {
responseHandler.respondMethodNotImplemented(folderResource, response, request);
}
} else {
responseHandler.respondNotFound(response, request);
}
}
}
private void respondLocked(Request request, Response response, Resource existingResource) {
if (responseHandler instanceof WebDavResponseHandler) {
WebDavResponseHandler rh = (WebDavResponseHandler) responseHandler;
rh.respondLocked(request, response, existingResource);
} else {
response.setStatus(Status.SC_LOCKED); //423
}
}
private void respondInsufficientStorage(Request request, Response response, StorageErrorReason storageErrorReason) {
if (responseHandler instanceof WebDavResponseHandler) {
WebDavResponseHandler rh = (WebDavResponseHandler) responseHandler;
rh.respondInsufficientStorage(request, response, storageErrorReason);
} else {
response.setStatus(Status.SC_INSUFFICIENT_STORAGE);
}
}
}
| true | true | public void process(HttpManager manager, Request request, Response response) throws NotAuthorizedException, ConflictException, BadRequestException, NotFoundException {
if (!handlerHelper.checkExpects(responseHandler, request, response)) {
return;
}
String host = request.getHostHeader();
String urlToCreateOrUpdate = HttpManager.decodeUrl(request.getAbsolutePath());
LogUtils.debug(log, "PUT request. Host:", host, " Url:", urlToCreateOrUpdate, " content length header:", request.getContentLengthHeader());
Path path = Path.path(urlToCreateOrUpdate);
urlToCreateOrUpdate = path.toString();
Resource existingResource = manager.getResourceFactory().getResource(host, urlToCreateOrUpdate);
ReplaceableResource replacee;
StorageErrorReason storageErr = null;
if (existingResource != null) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, existingResource)) {
log.warn("resource is locked, but not by the current user");
respondLocked(request, response, existingResource);
return;
}
// Check if the resource has been modified based on etags
if( !matchHelper.checkIfMatch(existingResource, request)) {
log.info("if-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(existingResource, request)) {
log.info("if-none-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
Resource parent = manager.getResourceFactory().getResource(host, path.getParent().toString());
if (parent instanceof CollectionResource) {
CollectionResource parentCol = (CollectionResource) parent;
storageErr = handlerHelper.checkStorageOnReplace(request, parentCol, existingResource, host);
} else {
log.warn("parent exists but is not a collection resource: " + path.getParent());
}
} else {
if( !matchHelper.checkIfMatch(null, request)) {
log.info("if-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(null, request)) {
log.info("if-none-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
CollectionResource parentCol = putHelper.findNearestParent(manager, host, path);
storageErr = handlerHelper.checkStorageOnAdd(request, parentCol, path.getParent(), host);
}
if (storageErr != null) {
respondInsufficientStorage(request, response, storageErr);
return;
}
if (existingResource != null && existingResource instanceof ReplaceableResource) {
replacee = (ReplaceableResource) existingResource;
} else {
replacee = null;
}
if (replacee != null) {
if (log.isTraceEnabled()) {
log.trace("replacing content in: " + replacee.getName() + " - " + replacee.getClass());
}
long t = System.currentTimeMillis();
try {
manager.onProcessResourceStart(request, response, replacee);
processReplace(manager, request, response, replacee);
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, replacee, t);
}
} else {
// either no existing resource, or its not replaceable. check for folder
String nameToCreate = path.getName();
CollectionResource folderResource = findOrCreateFolders(manager, host, path.getParent());
if (folderResource != null) {
long t = System.currentTimeMillis();
try {
if (folderResource instanceof PutableResource) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, folderResource)) {
respondLocked(request, response, folderResource);
return;
}
PutableResource putableResource = (PutableResource) folderResource;
processCreate(manager, request, response, putableResource, nameToCreate);
} else {
LogUtils.debug(log, "method not implemented: PUT on class: ", folderResource.getClass(), folderResource.getName());
manager.getResponseHandler().respondMethodNotImplemented(folderResource, response, request);
}
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, folderResource, t);
}
} else {
responseHandler.respondNotFound(response, request);
}
}
}
| public void process(HttpManager manager, Request request, Response response) throws NotAuthorizedException, ConflictException, BadRequestException, NotFoundException {
if (!handlerHelper.checkExpects(responseHandler, request, response)) {
return;
}
String host = request.getHostHeader();
String urlToCreateOrUpdate = HttpManager.decodeUrl(request.getAbsolutePath());
LogUtils.debug(log, "PUT request. Host:", host, " Url:", urlToCreateOrUpdate, " content length header:", request.getContentLengthHeader());
Path path = Path.path(urlToCreateOrUpdate);
urlToCreateOrUpdate = path.toString();
Resource existingResource = manager.getResourceFactory().getResource(host, urlToCreateOrUpdate);
ReplaceableResource replacee;
StorageErrorReason storageErr = null;
if (existingResource != null) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, existingResource)) {
log.warn("resource is locked, but not by the current user");
respondLocked(request, response, existingResource);
return;
}
// Check if the resource has been modified based on etags
if( !matchHelper.checkIfMatch(existingResource, request)) {
log.info("if-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(existingResource, request)) {
log.info("if-none-match comparison failed, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
Resource parent = manager.getResourceFactory().getResource(host, path.getParent().toString());
if (parent instanceof CollectionResource) {
CollectionResource parentCol = (CollectionResource) parent;
storageErr = handlerHelper.checkStorageOnReplace(request, parentCol, existingResource, host);
} else {
log.warn("parent exists but is not a collection resource: " + path.getParent());
}
} else {
if( !matchHelper.checkIfMatch(null, request)) {
log.info("if-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
if( matchHelper.checkIfNoneMatch(null, request)) {
log.info("if-none-match comparison failed on null resource, aborting PUT request");
responseHandler.respondPreconditionFailed(request, response, existingResource);
return ;
}
CollectionResource parentCol = putHelper.findNearestParent(manager, host, path);
storageErr = handlerHelper.checkStorageOnAdd(request, parentCol, path.getParent(), host);
}
if (storageErr != null) {
respondInsufficientStorage(request, response, storageErr);
return;
}
if (existingResource != null && existingResource instanceof ReplaceableResource) {
replacee = (ReplaceableResource) existingResource;
} else {
replacee = null;
}
if (replacee != null) {
if (log.isTraceEnabled()) {
log.trace("replacing content in: " + replacee.getName() + " - " + replacee.getClass());
}
long t = System.currentTimeMillis();
try {
manager.onProcessResourceStart(request, response, replacee);
processReplace(manager, request, response, replacee);
manager.getEventManager().fireEvent(new PutEvent(replacee));
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, replacee, t);
}
} else {
// either no existing resource, or its not replaceable. check for folder
String nameToCreate = path.getName();
CollectionResource folderResource = findOrCreateFolders(manager, host, path.getParent());
if (folderResource != null) {
long t = System.currentTimeMillis();
try {
if (folderResource instanceof PutableResource) {
//Make sure the parent collection is not locked by someone else
if (handlerHelper.isLockedOut(request, folderResource)) {
respondLocked(request, response, folderResource);
return;
}
PutableResource putableResource = (PutableResource) folderResource;
processCreate(manager, request, response, putableResource, nameToCreate);
} else {
LogUtils.debug(log, "method not implemented: PUT on class: ", folderResource.getClass(), folderResource.getName());
manager.getResponseHandler().respondMethodNotImplemented(folderResource, response, request);
}
} finally {
t = System.currentTimeMillis() - t;
manager.onProcessResourceFinish(request, response, folderResource, t);
}
} else {
responseHandler.respondNotFound(response, request);
}
}
}
|
diff --git a/src/plugins/Library/index/xml/XMLIndex.java b/src/plugins/Library/index/xml/XMLIndex.java
index e8b5409..f4fb329 100644
--- a/src/plugins/Library/index/xml/XMLIndex.java
+++ b/src/plugins/Library/index/xml/XMLIndex.java
@@ -1,860 +1,863 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Library.index.xml;
import plugins.Library.Library;
import plugins.Library.Index;
import plugins.Library.index.TermEntry;
import plugins.Library.index.TermPageEntry;
import plugins.Library.index.URIEntry;
import plugins.Library.search.InvalidSearchException;
import plugins.Library.util.exec.Execution;
import plugins.Library.util.exec.TaskAbortException;
import com.db4o.ObjectContainer;
import freenet.support.Fields;
import freenet.support.Logger;
import freenet.support.api.Bucket;
import freenet.support.io.FileBucket;
import freenet.client.async.ClientGetCallback;
import freenet.client.async.ClientGetter;
import freenet.client.async.ClientContext;
import freenet.client.events.ClientEventListener;
import freenet.client.events.ClientEvent;
import freenet.client.FetchException;
import freenet.client.HighLevelSimpleClient;
import freenet.client.FetchResult;
import freenet.node.RequestStarter;
import freenet.node.RequestClient;
import freenet.keys.FreenetURI;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Executor;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.TreeMap;
import java.util.SortedMap;
import java.util.HashMap;
/**
* The xml index format
* @author MikeB
*/
public class XMLIndex implements Index, ClientGetCallback, RequestClient{
final public static String MIME_TYPE = "application/xml";
final public static String DEFAULT_FILE = "index.xml";
private PluginRespirator pr;
private Executor executor;
private ClientGetter rootGetter;
private int fetchFailures = 0;
public enum FetchStatus{UNFETCHED, FETCHING, FETCHED, FAILED}
protected FetchStatus fetchStatus = FetchStatus.UNFETCHED;
protected HashMap<String, String> indexMeta = new HashMap<String, String>();
// TODO it could be tidier if this was converted to a FreenetURI
protected String indexuri;
private URLUpdateHook updateHook;
private String updateContext;
private HighLevelSimpleClient hlsc;
/**
* Index format version:
* <ul>
* <li>1 = XMLSpider 8 to 33</li>
* </ul>
* Earlier format are no longer supported.
*/
private int version;
private List<String> subIndiceList;
private SortedMap<String, SubIndex> subIndice;
private ArrayList<FindRequest> waitingOnMainIndex = new ArrayList<FindRequest>();
static volatile boolean logMINOR;
static volatile boolean logDEBUG;
static {
Logger.registerClass(XMLIndex.class);
}
/**
* Create an XMLIndex from a URI
* @param baseURI
* Base URI of the index (exclude the <tt>index.xml</tt> part)
*/
public XMLIndex(String baseURI, PluginRespirator pr, URLUpdateHook hook, String context) throws InvalidSearchException {
this.pr = pr;
this.updateHook = hook;
this.updateContext = context;
if (pr!=null)
executor = pr.getNode().executor;
if (baseURI.endsWith(DEFAULT_FILE))
baseURI = baseURI.replace(DEFAULT_FILE, "");
if (!baseURI.endsWith("/"))
baseURI += "/";
indexuri = baseURI;
// check if index is valid file or URI
if(!Util.isValid(baseURI))
throw new InvalidSearchException(baseURI + " is neither a valid file nor valid Freenet URI");
if(pr!=null){
hlsc = pr.getNode().clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS);
hlsc.addEventHook(mainIndexListener);
}
}
/**
* process the bucket containing the main index file
* @param bucket
*/
private void processRequests(Bucket bucket){
try {
InputStream is = bucket.getInputStream();
parse(is);
is.close();
fetchStatus = FetchStatus.FETCHED;
for(FindRequest req : waitingOnMainIndex)
setdependencies(req);
waitingOnMainIndex.clear();
}catch(Exception e){
fetchStatus = FetchStatus.FAILED;
for (FindRequest findRequest : waitingOnMainIndex) {
findRequest.setError(new TaskAbortException("Failure parsing "+toString(), e));
}
Logger.error(this, indexuri, e);
} finally {
bucket.free();
}
}
/**
* Listener to receive events when fetching the main index
*/
ClientEventListener mainIndexListener = new ClientEventListener(){
/**
* Hears an event.
**/
public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context){
FindRequest.updateWithEvent(waitingOnMainIndex, ce);
// Logger.normal(this, "Updated with event : "+ce.getDescription());
}
public void onRemoveEventProducer(ObjectContainer container){
throw new UnsupportedOperationException();
}
};
/**
* Callback for when index fetching completes
*/
/** Called on successful fetch */
public void onSuccess(FetchResult result, ClientGetter state, ObjectContainer container){
// Logger.normal(this, "Fetch successful " + toString());
processRequests(result.asBucket());
}
/** Called on failed/canceled fetch */
public void onFailure(FetchException e, ClientGetter state, ObjectContainer container){
fetchFailures++;
if(fetchFailures < 20 && e.newURI!=null){
try {
if(logMINOR) Logger.minor(this, "Trying new URI: "+e.newURI);
indexuri = e.newURI.setMetaString(new String[]{""}).toString();
if(logMINOR) Logger.minor(this, "Trying new URI: "+e.newURI+" : "+indexuri);
startFetch(true);
if(updateHook != null)
updateHook.update(updateContext, indexuri);
return;
} catch (FetchException ex) {
e = ex;
} catch (MalformedURLException ex) {
Logger.error(this, "what?", ex);
}
}
fetchStatus = FetchStatus.FAILED;
for (FindRequest findRequest : waitingOnMainIndex) {
findRequest.setError(new TaskAbortException("Failure fetching rootindex of "+toString(), e));
}
Logger.error(this, "Fetch failed on "+toString() + " -- state = "+state, e);
}
public void onMajorProgress(ObjectContainer container){}
public boolean persistent() {
return false;
}
public void removeFrom(ObjectContainer container) {
throw new UnsupportedOperationException();
}
/**
* Fetch main index & process if local or fetch in background with callback if Freenet URI
* @throws freenet.client.FetchException
* @throws java.net.MalformedURLException
*/
private synchronized void startFetch(boolean retry) throws FetchException, MalformedURLException {
if ((!retry) && (fetchStatus != FetchStatus.UNFETCHED && fetchStatus != FetchStatus.FAILED))
return;
fetchStatus = FetchStatus.FETCHING;
String uri = indexuri + DEFAULT_FILE;
// try local file first
File file = new File(uri);
if (file.exists() && file.canRead()) {
processRequests(new FileBucket(file, true, false, false, false, false));
return;
}
if(logMINOR) Logger.minor(this, "Fetching "+uri);
// FreenetURI, try to fetch from freenet
FreenetURI u = new FreenetURI(uri);
while (true) {
try {
rootGetter = hlsc.fetch(u, -1, this, this, hlsc.getFetchContext().clone());
Logger.normal(this, "Fetch started : "+toString());
break;
} catch (FetchException e) {
if (e.newURI != null) {
u = e.newURI;
if(logMINOR) Logger.minor(this, "New URI: "+uri);
continue;
} else
throw e;
}
}
}
/**
* Parse the xml in the main index to read fields for this object
* @param is InputStream for main index file
* @throws org.xml.sax.SAXException
* @throws java.io.IOException
*/
private void parse(InputStream is) throws SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
// Logger.normal(this, "Parsing main index");
try {
factory.setNamespaceAware(true);
factory.setFeature("http://xml.org/sax/features/namespaces", true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = factory.newSAXParser();
MainIndexParser parser = new MainIndexParser();
saxParser.parse(is, parser);
version = parser.getVersion();
if (version == 1) {
indexMeta.put("title", parser.getHeader("title"));
indexMeta.put("ownerName", parser.getHeader("owner"));
indexMeta.put("ownerEmail", parser.getHeader("email"));
subIndiceList = new ArrayList<String>();
subIndice = new TreeMap<String, SubIndex>();
for (String key : parser.getSubIndice()) {
subIndiceList.add(key);
String stillbase;
try{
FreenetURI furi = new FreenetURI(indexuri);
stillbase = ( furi.isUSK() ? furi.sskForUSK() : furi ).toString();
}catch(MalformedURLException e){
stillbase = indexuri;
}
subIndice.put(key, new SubIndex(stillbase, "index_" + key + ".xml"));
}
Collections.sort(subIndiceList);
}
} catch (ParserConfigurationException e) {
Logger.error(this, "SAX ParserConfigurationException", e);
throw new SAXException(e);
}
}
@Override
public String toString(){
String output = "Index:[ "+indexuri+" "+fetchStatus+" "+waitingOnMainIndex+"\n\t"+subIndice + (rootGetter==null?"]":(" GETTING("+rootGetter.toString()+")]"));
//for (SubIndex s : subIndice)
// output = output+"\n -"+s;
return output;
}
/**
* Gets the SubIndex object which should hold the keyword
*/
private SubIndex getSubIndex(String keyword) {
String md5 = Library.MD5(keyword);
int idx = Collections.binarySearch(subIndiceList, md5);
if (idx < 0)
idx = -idx - 2;
return subIndice.get(subIndiceList.get(idx));
}
/**
* Find the term in this Index
*/
public synchronized Execution<Set<TermEntry>> getTermEntries(String term){
try {
FindRequest request = new FindRequest(term);
setdependencies(request);
notifyAll();
return request;
} catch (FetchException ex) {
Logger.error(this, "Trying to find " + term, ex);
return null;
} catch (MalformedURLException ex) {
Logger.error(this, "Trying to find " + term, ex);
return null;
}
}
public Execution<URIEntry> getURIEntry(FreenetURI uri){
throw new UnsupportedOperationException("getURIEntry not Implemented in XMLIndex");
}
/**
* Puts request into the dependency List of either the main index or the
* subindex depending on whether the main index is availiable
* @param request
* @throws freenet.client.FetchException
* @throws java.net.MalformedURLException
*/
private synchronized void setdependencies(FindRequest request) throws FetchException, MalformedURLException{
// Logger.normal(this, "setting dependencies for "+request+" on "+this.toString());
if (fetchStatus!=FetchStatus.FETCHED){
waitingOnMainIndex.add(request);
request.setStage(FindRequest.Stages.FETCHROOT);
startFetch(false);
}else{
request.setStage(FindRequest.Stages.FETCHSUBINDEX);
SubIndex subindex = getSubIndex(request.getSubject());
subindex.addRequest(request);
// Logger.normal(this, "STarting "+getSubIndex(request.getSubject())+" to look for "+request.getSubject());
if(executor!=null)
executor.execute(subindex, "Subindex:"+subindex.getFileName());
else
(new Thread(subindex, "Subindex:"+subindex.getFileName())).start();
}
}
/**
* @return the uri of this index prefixed with "xml:" to show what type it is
*/
public String getIndexURI(){
return indexuri;
}
private class SubIndex implements Runnable {
String indexuri, filename;
private final ArrayList<FindRequest> waitingOnSubindex=new ArrayList<FindRequest>();
private final ArrayList<FindRequest> parsingSubindex = new ArrayList<FindRequest>();
FetchStatus fetchStatus = FetchStatus.UNFETCHED;
HighLevelSimpleClient hlsc;
Bucket bucket;
Exception error;
/**
* Listens for progress on a subIndex fetch
*/
ClientEventListener subIndexListener = new ClientEventListener(){
/**
* Hears an event and updates those Requests waiting on this subindex fetch
**/
public void receive(ClientEvent ce, ObjectContainer maybeContainer, ClientContext context){
FindRequest.updateWithEvent(waitingOnSubindex, ce);
// Logger.normal(this, "Updated with event : "+ce.getDescription());
}
public void onRemoveEventProducer(ObjectContainer container){
throw new UnsupportedOperationException();
}
};
SubIndex(String indexuri, String filename){
this.indexuri = indexuri;
this.filename = filename;
if(pr!=null){
hlsc = pr.getNode().clientCore.makeClient(RequestStarter.INTERACTIVE_PRIORITY_CLASS);
hlsc.addEventHook(subIndexListener);
}
}
String getFileName(){
return filename;
}
FetchStatus getFetchStatus(){
return fetchStatus;
}
/**
* Add a request to the List of requests looking in this subindex
* @param request
*/
void addRequest(FindRequest request){
if(fetchStatus==FetchStatus.FETCHED)
request.setStage(FindRequest.Stages.PARSE);
else
request.setStage(FindRequest.Stages.FETCHSUBINDEX);
synchronized(waitingOnSubindex){
waitingOnSubindex.add(request);
}
}
@Override
public String toString(){
return filename+" "+fetchStatus+" "+waitingOnSubindex;
}
public synchronized void run(){
try{
while(waitingOnSubindex.size()>0){
if(fetchStatus==FetchStatus.UNFETCHED || fetchStatus == FetchStatus.FAILED){
try {
fetchStatus = FetchStatus.FETCHING;
// TODO tidy the fetch stuff
bucket = Util.fetchBucket(indexuri + filename, hlsc);
fetchStatus = FetchStatus.FETCHED;
} catch (Exception e) { // TODO tidy the exceptions
//java.net.MalformedURLException
//freenet.client.FetchException
String msg = indexuri + filename + " could not be opened: " + e.toString();
Logger.error(this, msg, e);
throw new TaskAbortException(msg, e);
}
}else if(fetchStatus==FetchStatus.FETCHED){
parseSubIndex();
} else {
break;
}
}
} catch (TaskAbortException e) {
fetchStatus = FetchStatus.FAILED;
this.error = e;
Logger.error(this, "Dropping from subindex run loop", e);
for (FindRequest r : parsingSubindex)
r.setError(e);
for (FindRequest r : waitingOnSubindex)
r.setError(e);
}
}
public void parseSubIndex() throws TaskAbortException {
synchronized(parsingSubindex){
// Transfer all requests waiting on this subindex to the parsing list
synchronized (waitingOnSubindex){
parsingSubindex.addAll(waitingOnSubindex);
waitingOnSubindex.removeAll(parsingSubindex);
}
// Set status of all those about to be parsed to PARSE
for(FindRequest r : parsingSubindex)
r.setStage(FindRequest.Stages.PARSE);
// Multi-stage parse to minimise memory usage.
// Stage 1: Extract the declaration (first tag), copy everything before "<files " to one bucket, plus everything after "</files>".
// Copy the declaration, plus everything between the two (inclusive) to another bucket.
Bucket mainBucket, filesBucket;
try {
InputStream is = bucket.getInputStream();
mainBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
filesBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
OutputStream mainOS = new BufferedOutputStream(mainBucket.getOutputStream());
OutputStream filesOS = new BufferedOutputStream(filesBucket.getOutputStream());
//OutputStream mainOS = new BufferedOutputStream(new FileOutputStream("main.tmp"));
//OutputStream filesOS = new BufferedOutputStream(new FileOutputStream("files.tmp"));
BufferedInputStream bis = new BufferedInputStream(is);
byte greaterThan = ">".getBytes("UTF-8")[0];
byte[] filesPrefix = "<files ".getBytes("UTF-8");
+ byte[] filesPrefixAlt = "<files>".getBytes("UTF-8");
+ assert(filesPrefix.length == filesPrefixAlt.length);
byte[] filesEnd = "</files>".getBytes("UTF-8");
final int MODE_SEEKING_DECLARATION = 1;
final int MODE_SEEKING_FILES = 2;
final int MODE_COPYING_FILES = 3;
final int MODE_COPYING_REST = 4;
int mode = MODE_SEEKING_DECLARATION;
int b;
byte[] declarationBuf = new byte[100];
int declarationPtr = 0;
byte[] prefixBuffer = new byte[filesPrefix.length];
int prefixPtr = 0;
byte[] endBuffer = new byte[filesEnd.length];
int endPtr = 0;
while((b = bis.read()) != -1) {
if(mode == MODE_SEEKING_DECLARATION) {
if(declarationPtr == declarationBuf.length)
throw new TaskAbortException("Could not split up XML: declaration too long", null);
declarationBuf[declarationPtr++] = (byte)b;
mainOS.write(b);
filesOS.write(b);
if(b == greaterThan) {
mode = MODE_SEEKING_FILES;
}
} else if(mode == MODE_SEEKING_FILES) {
if(prefixPtr != prefixBuffer.length) {
prefixBuffer[prefixPtr++] = (byte)b;
} else {
- if(Fields.byteArrayEqual(filesPrefix, prefixBuffer)) {
+ if(Fields.byteArrayEqual(filesPrefix, prefixBuffer)
+ || Fields.byteArrayEqual(filesPrefixAlt, prefixBuffer)) {
mode = MODE_COPYING_FILES;
filesOS.write(prefixBuffer);
filesOS.write(b);
} else {
mainOS.write(prefixBuffer[0]);
System.arraycopy(prefixBuffer, 1, prefixBuffer, 0, prefixBuffer.length-1);
prefixBuffer[prefixBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_FILES) {
if(endPtr != endBuffer.length) {
endBuffer[endPtr++] = (byte)b;
} else {
if(Fields.byteArrayEqual(filesEnd, endBuffer)) {
mode = MODE_COPYING_REST;
filesOS.write(endBuffer);
mainOS.write(b);
} else {
filesOS.write(endBuffer[0]);
System.arraycopy(endBuffer, 1, endBuffer, 0, endBuffer.length-1);
endBuffer[endBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_REST) {
mainOS.write(b);
}
}
if(mode != MODE_COPYING_REST)
throw new TaskAbortException("Could not split up XML: Last mode was "+mode, null);
mainOS.close();
filesOS.close();
} catch (IOException e) {
throw new TaskAbortException("Could not split XML: ", e);
}
if(logMINOR) Logger.minor(this, "Finished splitting XML");
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = factory.newSAXParser();
// Stage 2: Parse the first bucket, find the keyword we want, find the file id's.
InputStream is = mainBucket.getInputStream();
StageTwoHandler stageTwoHandler = new StageTwoHandler();
saxParser.parse(is, stageTwoHandler);
if(logMINOR) Logger.minor(this, "Finished stage two XML parse");
is.close();
// Stage 3: Parse the second bucket, extract the <file>'s for the specific ID's.
is = filesBucket.getInputStream();
StageThreeHandler stageThreeHandler = new StageThreeHandler();
saxParser.parse(is, stageThreeHandler);
if(logMINOR) Logger.minor(this, "Finished stage three XML parse");
is.close();
Logger.minor(this, "parsing finished "+ parsingSubindex.toString());
for (FindRequest findRequest : parsingSubindex) {
findRequest.setFinished();
}
parsingSubindex.clear();
} catch (Exception err) {
Logger.error(this, "Error parsing "+filename, err);
throw new TaskAbortException("Could not parse XML: ", err);
}
}
}
class WordMatch {
public WordMatch(ArrayList<FindRequest> searches, int inWordFileCount) {
this.searches = searches;
this.inWordFileCount = inWordFileCount;
}
final List<FindRequest> searches;
int inWordFileCount;
}
class FileMatch {
public FileMatch(String id2, HashMap<Integer, String> termpositions2, WordMatch thisWordMatch) {
id = id2;
termpositions = termpositions2;
word = thisWordMatch;
}
final String id;
final HashMap<Integer, String> termpositions;
final WordMatch word;
}
Map<String, ArrayList<FileMatch>> idToFileMatches = new HashMap<String, ArrayList<FileMatch>>();
int totalFileCount = -1;
// Parse the main XML file, including the keywords list.
// We do not see the files list.
class StageTwoHandler extends DefaultHandler {
private boolean processingWord;
// Requests and matches being made
private List<FindRequest> requests;
private List<FindRequest> wordMatches;
private int inWordFileCount;
// About the file tag being processed
private StringBuilder characters;
private String match;
private ArrayList<FileMatch> fileMatches = new ArrayList<FileMatch>();
private String id;
private WordMatch thisWordMatch;
StageTwoHandler() {
this.requests = new ArrayList(parsingSubindex);
for (FindRequest r : parsingSubindex){
r.setResult(new HashSet<TermPageEntry>());
}
}
@Override public void setDocumentLocator(Locator value) {
}
@Override public void endDocument() throws SAXException {
}
@Override public void startDocument() throws SAXException {
// Do nothing
}
@Override public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attrs)
throws SAXException {
if(requests.size()==0&&(wordMatches == null || wordMatches.size()==0))
return;
if (rawName == null) {
rawName = localName;
}
String elt_name = rawName;
if (elt_name.equals("keywords"))
processingWord = true;
/*
* looks for the word in the given subindex file if the word is found then the parser
* fetches the corresponding fileElements
*/
if (elt_name.equals("word")) {
try {
fileMatches.clear();
wordMatches = null;
match = attrs.getValue("v");
if (requests!=null){
for (Iterator<FindRequest> it = requests.iterator(); it.hasNext();) {
FindRequest r = it.next();
if (match.equals(r.getSubject())){
if(wordMatches == null)
wordMatches = new ArrayList<FindRequest>();
wordMatches.add(r);
it.remove();
Logger.minor(this, "found word match "+wordMatches);
}
}
if(wordMatches != null) {
if (attrs.getValue("fileCount")!=null)
inWordFileCount = Integer.parseInt(attrs.getValue("fileCount"));
thisWordMatch = new WordMatch(new ArrayList<FindRequest>(wordMatches), inWordFileCount);
}
}
} catch (Exception e) {
throw new SAXException(e);
}
}
if (elt_name.equals("file")) {
if (processingWord == true && wordMatches!=null) {
try{
id = attrs.getValue("id");
characters = new StringBuilder();
}
catch (Exception e) {
Logger.error(this, "Index format may be outdated " + e.toString(), e);
}
}
}
}
@Override public void characters(char[] ch, int start, int length) {
if(processingWord && wordMatches!= null && characters!=null){
characters.append(ch, start, length);
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName) {
if(processingWord && wordMatches != null && qName.equals("file")){
HashMap<Integer, String> termpositions = null;
if(characters!=null){
String[] termposs = characters.toString().split(",");
termpositions = new HashMap<Integer, String>();
for (String pos : termposs) {
try{
termpositions.put(Integer.valueOf(pos), null);
}catch(NumberFormatException e){
Logger.error(this, "Position in index not an integer :"+pos, e);
}
}
characters = null;
}
FileMatch thisFile = new FileMatch(id, termpositions, thisWordMatch);
ArrayList<FileMatch> matchList = idToFileMatches.get(id);
if(matchList == null) {
matchList = new ArrayList<FileMatch>();
idToFileMatches.put(id, matchList);
}
if(logMINOR) Logger.minor(this, "Match: id="+id+" for word "+match);
matchList.add(thisFile);
}
}
}
class StageThreeHandler extends DefaultHandler {
@Override public void setDocumentLocator(Locator value) {
}
@Override public void endDocument() throws SAXException {
}
@Override public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attrs)
throws SAXException {
if(idToFileMatches.isEmpty())
return;
if (rawName == null) {
rawName = localName;
}
String elt_name = rawName;
if (elt_name.equals("files")){
String fileCount = attrs.getValue("", "totalFileCount");
if(fileCount != null)
totalFileCount = Integer.parseInt(fileCount);
Logger.minor(this, "totalfilecount = "+totalFileCount);
}
if (elt_name.equals("file")) {
try {
String id = attrs.getValue("id");
ArrayList<FileMatch> matches = idToFileMatches.get(id);
if(matches != null) {
for(FileMatch match : matches) {
String key = attrs.getValue("key");
int l = attrs.getLength();
String title = null;
int wordCount = -1;
if (l >= 3) {
try {
title = attrs.getValue("title");
} catch (Exception e) {
Logger.error(this, "Index Format not compatible " + e.toString(), e);
}
try {
String wordCountString = attrs.getValue("wordCount");
if(wordCountString != null) {
wordCount = Integer.parseInt(attrs.getValue("wordCount"));
}
} catch (Exception e) {
//Logger.minor(this, "No wordcount found " + e.toString(), e);
}
}
for(FindRequest req : match.word.searches) {
Set<TermPageEntry> result = req.getUnfinishedResult();
float relevance = 0;
if(logDEBUG) Logger.debug(this, "termcount "+(match.termpositions == null ? 0 : match.termpositions.size())+" filewordcount = "+wordCount);
if(match.termpositions!=null && match.termpositions.size()>0 && wordCount>0 ){
relevance = (float)(match.termpositions.size()/(float)wordCount);
if( totalFileCount > 0 && match.word.inWordFileCount > 0)
relevance *= Math.log( (float)totalFileCount/(float)match.word.inWordFileCount);
if(logDEBUG) Logger.debug(this, "Set relevance of "+title+" to "+relevance+" - "+key);
}
TermPageEntry pageEntry = new TermPageEntry(req.getSubject(), relevance, new FreenetURI(key), title, match.termpositions);
result.add(pageEntry);
//Logger.minor(this, "added "+inFileURI+ " to "+ match);
}
}
}
}
catch (Exception e) {
Logger.error(this, "File id and key could not be retrieved. May be due to format clash", e);
}
}
}
}
}
}
| false | true | public void parseSubIndex() throws TaskAbortException {
synchronized(parsingSubindex){
// Transfer all requests waiting on this subindex to the parsing list
synchronized (waitingOnSubindex){
parsingSubindex.addAll(waitingOnSubindex);
waitingOnSubindex.removeAll(parsingSubindex);
}
// Set status of all those about to be parsed to PARSE
for(FindRequest r : parsingSubindex)
r.setStage(FindRequest.Stages.PARSE);
// Multi-stage parse to minimise memory usage.
// Stage 1: Extract the declaration (first tag), copy everything before "<files " to one bucket, plus everything after "</files>".
// Copy the declaration, plus everything between the two (inclusive) to another bucket.
Bucket mainBucket, filesBucket;
try {
InputStream is = bucket.getInputStream();
mainBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
filesBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
OutputStream mainOS = new BufferedOutputStream(mainBucket.getOutputStream());
OutputStream filesOS = new BufferedOutputStream(filesBucket.getOutputStream());
//OutputStream mainOS = new BufferedOutputStream(new FileOutputStream("main.tmp"));
//OutputStream filesOS = new BufferedOutputStream(new FileOutputStream("files.tmp"));
BufferedInputStream bis = new BufferedInputStream(is);
byte greaterThan = ">".getBytes("UTF-8")[0];
byte[] filesPrefix = "<files ".getBytes("UTF-8");
byte[] filesEnd = "</files>".getBytes("UTF-8");
final int MODE_SEEKING_DECLARATION = 1;
final int MODE_SEEKING_FILES = 2;
final int MODE_COPYING_FILES = 3;
final int MODE_COPYING_REST = 4;
int mode = MODE_SEEKING_DECLARATION;
int b;
byte[] declarationBuf = new byte[100];
int declarationPtr = 0;
byte[] prefixBuffer = new byte[filesPrefix.length];
int prefixPtr = 0;
byte[] endBuffer = new byte[filesEnd.length];
int endPtr = 0;
while((b = bis.read()) != -1) {
if(mode == MODE_SEEKING_DECLARATION) {
if(declarationPtr == declarationBuf.length)
throw new TaskAbortException("Could not split up XML: declaration too long", null);
declarationBuf[declarationPtr++] = (byte)b;
mainOS.write(b);
filesOS.write(b);
if(b == greaterThan) {
mode = MODE_SEEKING_FILES;
}
} else if(mode == MODE_SEEKING_FILES) {
if(prefixPtr != prefixBuffer.length) {
prefixBuffer[prefixPtr++] = (byte)b;
} else {
if(Fields.byteArrayEqual(filesPrefix, prefixBuffer)) {
mode = MODE_COPYING_FILES;
filesOS.write(prefixBuffer);
filesOS.write(b);
} else {
mainOS.write(prefixBuffer[0]);
System.arraycopy(prefixBuffer, 1, prefixBuffer, 0, prefixBuffer.length-1);
prefixBuffer[prefixBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_FILES) {
if(endPtr != endBuffer.length) {
endBuffer[endPtr++] = (byte)b;
} else {
if(Fields.byteArrayEqual(filesEnd, endBuffer)) {
mode = MODE_COPYING_REST;
filesOS.write(endBuffer);
mainOS.write(b);
} else {
filesOS.write(endBuffer[0]);
System.arraycopy(endBuffer, 1, endBuffer, 0, endBuffer.length-1);
endBuffer[endBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_REST) {
mainOS.write(b);
}
}
if(mode != MODE_COPYING_REST)
throw new TaskAbortException("Could not split up XML: Last mode was "+mode, null);
mainOS.close();
filesOS.close();
} catch (IOException e) {
throw new TaskAbortException("Could not split XML: ", e);
}
if(logMINOR) Logger.minor(this, "Finished splitting XML");
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = factory.newSAXParser();
// Stage 2: Parse the first bucket, find the keyword we want, find the file id's.
InputStream is = mainBucket.getInputStream();
StageTwoHandler stageTwoHandler = new StageTwoHandler();
saxParser.parse(is, stageTwoHandler);
if(logMINOR) Logger.minor(this, "Finished stage two XML parse");
is.close();
// Stage 3: Parse the second bucket, extract the <file>'s for the specific ID's.
is = filesBucket.getInputStream();
StageThreeHandler stageThreeHandler = new StageThreeHandler();
saxParser.parse(is, stageThreeHandler);
if(logMINOR) Logger.minor(this, "Finished stage three XML parse");
is.close();
Logger.minor(this, "parsing finished "+ parsingSubindex.toString());
for (FindRequest findRequest : parsingSubindex) {
findRequest.setFinished();
}
parsingSubindex.clear();
} catch (Exception err) {
Logger.error(this, "Error parsing "+filename, err);
throw new TaskAbortException("Could not parse XML: ", err);
}
}
}
| public void parseSubIndex() throws TaskAbortException {
synchronized(parsingSubindex){
// Transfer all requests waiting on this subindex to the parsing list
synchronized (waitingOnSubindex){
parsingSubindex.addAll(waitingOnSubindex);
waitingOnSubindex.removeAll(parsingSubindex);
}
// Set status of all those about to be parsed to PARSE
for(FindRequest r : parsingSubindex)
r.setStage(FindRequest.Stages.PARSE);
// Multi-stage parse to minimise memory usage.
// Stage 1: Extract the declaration (first tag), copy everything before "<files " to one bucket, plus everything after "</files>".
// Copy the declaration, plus everything between the two (inclusive) to another bucket.
Bucket mainBucket, filesBucket;
try {
InputStream is = bucket.getInputStream();
mainBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
filesBucket = pr.getNode().clientCore.tempBucketFactory.makeBucket(-1);
OutputStream mainOS = new BufferedOutputStream(mainBucket.getOutputStream());
OutputStream filesOS = new BufferedOutputStream(filesBucket.getOutputStream());
//OutputStream mainOS = new BufferedOutputStream(new FileOutputStream("main.tmp"));
//OutputStream filesOS = new BufferedOutputStream(new FileOutputStream("files.tmp"));
BufferedInputStream bis = new BufferedInputStream(is);
byte greaterThan = ">".getBytes("UTF-8")[0];
byte[] filesPrefix = "<files ".getBytes("UTF-8");
byte[] filesPrefixAlt = "<files>".getBytes("UTF-8");
assert(filesPrefix.length == filesPrefixAlt.length);
byte[] filesEnd = "</files>".getBytes("UTF-8");
final int MODE_SEEKING_DECLARATION = 1;
final int MODE_SEEKING_FILES = 2;
final int MODE_COPYING_FILES = 3;
final int MODE_COPYING_REST = 4;
int mode = MODE_SEEKING_DECLARATION;
int b;
byte[] declarationBuf = new byte[100];
int declarationPtr = 0;
byte[] prefixBuffer = new byte[filesPrefix.length];
int prefixPtr = 0;
byte[] endBuffer = new byte[filesEnd.length];
int endPtr = 0;
while((b = bis.read()) != -1) {
if(mode == MODE_SEEKING_DECLARATION) {
if(declarationPtr == declarationBuf.length)
throw new TaskAbortException("Could not split up XML: declaration too long", null);
declarationBuf[declarationPtr++] = (byte)b;
mainOS.write(b);
filesOS.write(b);
if(b == greaterThan) {
mode = MODE_SEEKING_FILES;
}
} else if(mode == MODE_SEEKING_FILES) {
if(prefixPtr != prefixBuffer.length) {
prefixBuffer[prefixPtr++] = (byte)b;
} else {
if(Fields.byteArrayEqual(filesPrefix, prefixBuffer)
|| Fields.byteArrayEqual(filesPrefixAlt, prefixBuffer)) {
mode = MODE_COPYING_FILES;
filesOS.write(prefixBuffer);
filesOS.write(b);
} else {
mainOS.write(prefixBuffer[0]);
System.arraycopy(prefixBuffer, 1, prefixBuffer, 0, prefixBuffer.length-1);
prefixBuffer[prefixBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_FILES) {
if(endPtr != endBuffer.length) {
endBuffer[endPtr++] = (byte)b;
} else {
if(Fields.byteArrayEqual(filesEnd, endBuffer)) {
mode = MODE_COPYING_REST;
filesOS.write(endBuffer);
mainOS.write(b);
} else {
filesOS.write(endBuffer[0]);
System.arraycopy(endBuffer, 1, endBuffer, 0, endBuffer.length-1);
endBuffer[endBuffer.length-1] = (byte)b;
}
}
} else if(mode == MODE_COPYING_REST) {
mainOS.write(b);
}
}
if(mode != MODE_COPYING_REST)
throw new TaskAbortException("Could not split up XML: Last mode was "+mode, null);
mainOS.close();
filesOS.close();
} catch (IOException e) {
throw new TaskAbortException("Could not split XML: ", e);
}
if(logMINOR) Logger.minor(this, "Finished splitting XML");
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser saxParser = factory.newSAXParser();
// Stage 2: Parse the first bucket, find the keyword we want, find the file id's.
InputStream is = mainBucket.getInputStream();
StageTwoHandler stageTwoHandler = new StageTwoHandler();
saxParser.parse(is, stageTwoHandler);
if(logMINOR) Logger.minor(this, "Finished stage two XML parse");
is.close();
// Stage 3: Parse the second bucket, extract the <file>'s for the specific ID's.
is = filesBucket.getInputStream();
StageThreeHandler stageThreeHandler = new StageThreeHandler();
saxParser.parse(is, stageThreeHandler);
if(logMINOR) Logger.minor(this, "Finished stage three XML parse");
is.close();
Logger.minor(this, "parsing finished "+ parsingSubindex.toString());
for (FindRequest findRequest : parsingSubindex) {
findRequest.setFinished();
}
parsingSubindex.clear();
} catch (Exception err) {
Logger.error(this, "Error parsing "+filename, err);
throw new TaskAbortException("Could not parse XML: ", err);
}
}
}
|
diff --git a/src/main/java/net/praqma/hudson/scm/PucmScm.java b/src/main/java/net/praqma/hudson/scm/PucmScm.java
index 88bb52c..300458b 100644
--- a/src/main/java/net/praqma/hudson/scm/PucmScm.java
+++ b/src/main/java/net/praqma/hudson/scm/PucmScm.java
@@ -1,715 +1,709 @@
package net.praqma.hudson.scm;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.FilePath.FileCallable;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import hudson.model.ParameterValue;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Job;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogParser;
import hudson.scm.PollingResult;
import hudson.scm.SCMDescriptor;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCM;
import hudson.util.FormValidation;
import hudson.util.VariableResolver;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.praqma.clearcase.ucm.UCMException;
import net.praqma.clearcase.ucm.entities.Project;
import net.praqma.clearcase.ucm.entities.Baseline;
import net.praqma.clearcase.ucm.entities.Activity;
import net.praqma.clearcase.ucm.entities.Component;
import net.praqma.clearcase.ucm.utils.BaselineList;
import net.praqma.clearcase.ucm.entities.Stream;
import net.praqma.clearcase.ucm.entities.UCMEntity;
import net.praqma.clearcase.ucm.entities.Version;
import net.praqma.clearcase.ucm.view.SnapshotView;
import net.praqma.clearcase.ucm.view.SnapshotView.COMP;
import net.praqma.clearcase.ucm.view.UCMView;
import net.praqma.clearcase.ucm.utils.BaselineDiff;
import net.praqma.hudson.Config;
import net.praqma.hudson.exception.ScmException;
import net.praqma.hudson.scm.PucmState.State;
import net.praqma.util.debug.Logger;
import net.sf.json.JSONObject;
//import net.praqma.hudson.Version;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.export.Exported;
/**
* CC4HClass is responsible for everything regarding Hudsons connection to
* ClearCase pre-build. This class defines all the files required by the user.
* The information can be entered on the config page.
*
* @author Troels Selch S�rensen
* @author Margit Bennetzen
*
*/
public class PucmScm extends SCM
{
private String levelToPoll;
private String loadModule;
private String component;
private String stream;
private boolean newest;
private Baseline bl;
private List<String> levels = null;
private List<String> loadModules = null;
//private BaselineList baselines;
private boolean compRevCalled;
private StringBuffer pollMsgs = new StringBuffer();
private Stream integrationstream;
private Component comp;
private SnapshotView sv = null;
private boolean doPostBuild = true;
private String buildProject;
private String jobName = "";
private Integer jobNumber;
private String id = "";
protected static Logger logger = Logger.getLogger();
public static PucmState pucm = new PucmState();
/**
* The constructor is used by Hudson to create the instance of the plugin
* needed for a connection to ClearCase. It is annotated with
* <code>@DataBoundConstructor</code> to tell Hudson where to put the
* information retrieved from the configuration page in the WebUI.
*
* @param component
* defines the component needed to find baselines.
* @param levelToPoll
* defines the level to poll ClearCase for.
* @param loadModule
* tells if we should load all modules or only the ones that are
* modifiable.
* @param stream
* defines the stream needed to find baselines.
* @param newest
* tells whether we should build only the newest baseline.
* @param newerThanRecommended
* tells whether we should look at all baselines or only ones
* newer than the recommended baseline
*/
@DataBoundConstructor
public PucmScm( String component, String levelToPoll, String loadModule, String stream, boolean newest, boolean testing, String buildProject )
{
logger.trace_function();
logger.debug( "PucmSCM constructor" );
this.component = component;
this.levelToPoll = levelToPoll;
this.loadModule = loadModule;
this.stream = stream;
this.newest = newest;
this.buildProject = buildProject;
}
@Override
public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException
{
logger.trace_function();
logger.debug( "PucmSCM checkout" );
boolean result = true;
// consoleOutput Printstream is from Hudson, so it can only be accessed
// here
PrintStream consoleOutput = listener.getLogger();
consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" );
/* Recalculate the states */
int count = pucm.recalculate( build.getProject() );
logger.info( "Removed " + count + " from states." );
doPostBuild = true;
jobName = build.getParent().getDisplayName();
jobNumber = build.getNumber();
/* If we polled, we should get the same object created at that point */
State state = pucm.getState( jobName, jobNumber );
logger.debug( id + "The initial state:\n" + state.stringify() );
this.id = "[" + jobName + "::" + jobNumber + "]";
if ( build.getBuildVariables().get( "include_classes" ) != null )
{
String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," );
for( String i : is )
{
logger.includeClass( i.trim() );
}
}
if ( build.getBuildVariables().get( "pucm_baseline" ) != null )
{
Stream integrationstream = null;
String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" );
try
{
state.setBaseline( UCMEntity.GetBaseline( baselinename ) );
state.setStream( state.getBaseline().GetStream() );
consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() );
}
catch ( UCMException e )
{
consoleOutput.println( "[PUCM] Could not find baseline from parameter." );
state.setPostBuild( false );
result = false;
}
}
else
{
// compRevCalled tells whether we have polled for baselines to build
// -
// so if we haven't polled, we do it now
if ( !compRevCalled )
{
try
{
//baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() );
baselinesToBuild( build.getProject(), state );
}
catch ( ScmException e )
{
pollMsgs.append( e.getMessage() );
result = false;
}
}
compRevCalled = false;
// pollMsgs are set in either compareRemoteRevisionWith() or
// baselinesToBuild()
consoleOutput.println( pollMsgs );
pollMsgs = new StringBuffer();
}
if ( result )
{
try
{
/* Force the Baseline to be loaded */
try
{
- bl.Load();
+ state.getBaseline().Load();
}
catch( UCMException e )
{
logger.debug( id + "Could not load Baseline" );
consoleOutput.println( "[PUCM] Could not load Baseline." );
}
/* Check parameters */
- consoleOutput.println( "[PUCM] Check 1" );
if( listener == null )
{
consoleOutput.println( "[PUCM] Listener is null" );
}
- consoleOutput.println( "[PUCM] Check 2" );
if( jobName == null )
{
consoleOutput.println( "[PUCM] jobname is null" );
}
- consoleOutput.println( "[PUCM] Check 3" );
if( build == null )
{
consoleOutput.println( "[PUCM] BUILD is null" );
}
- consoleOutput.println( "[PUCM] Check 4" );
if( stream == null )
{
consoleOutput.println( "[PUCM] stream is null" );
}
- consoleOutput.println( "[PUCM] Check 5" );
if( loadModule == null )
{
consoleOutput.println( "[PUCM] loadModule is null" );
}
- consoleOutput.println( "[PUCM] Check 6" );
if( buildProject == null )
{
consoleOutput.println( "[PUCM] buildProject is null" );
}
/*
if( bl == null )
{
consoleOutput.println( "[PUCM] bl is null" );
}
*/
consoleOutput.println( "[PUCM] Initializing checkout task" );
- CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject );
+ CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, state.getBaseline().GetFQName(), buildProject );
consoleOutput.println( "[PUCM] Launching checkout tast" );
String changelog = workspace.act( ct );
consoleOutput.println( "[PUCM] Checkout tast done" );
/* Write change log */
try
{
FileOutputStream fos = new FileOutputStream( changelogFile );
fos.write( changelog.getBytes() );
fos.close();
}
catch( IOException e )
{
logger.debug( id + "Could not write change log file" );
consoleOutput.println( "[PUCM] Could not write change log file" );
}
//doPostBuild = changelog.length() > 0 ? true : false;
}
catch ( Exception e )
{
consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() );
doPostBuild = false;
result = false;
}
}
//pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) );
//state.save();
logger.debug( id + "The CO state:\n" + state.stringify() );
return result;
}
@Override
public ChangeLogParser createChangeLogParser()
{
logger.trace_function();
return new ChangeLogParserImpl();
}
@Override
public PollingResult compareRemoteRevisionWith( AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState baseline ) throws IOException, InterruptedException
{
this.id = "[" + project.getDisplayName() + "::" + project.getNextBuildNumber() + "]";
logger.trace_function();
logger.debug( id + "PucmSCM Pollingresult" );
/* Make a state object, which is only temporary, only to determine if there's baselines to build this object will be stored in checkout */
jobName = project.getDisplayName();
jobNumber = project.getNextBuildNumber(); /* This number is not the final job number */
State state = pucm.getState( jobName, jobNumber );
PollingResult p;
try
{
//baselinesToBuild( component, stream, project, project.getDisplayName(), project.getNextBuildNumber() );
baselinesToBuild( project, state );
compRevCalled = true;
logger.info( id + "Polling result = BUILD NOW" );
p = PollingResult.BUILD_NOW;
}
catch ( ScmException e )
{
logger.info( id + "Polling result = NO CHANGES" );
p = PollingResult.NO_CHANGES;
PrintStream consoleOut = listener.getLogger();
consoleOut.println( pollMsgs + "\n" + e.getMessage() );
pollMsgs = new StringBuffer();
logger.debug( id + "Removed job " + state.getJobNumber() + " from list" );
state.remove();
}
logger.debug( id + "FINAL Polling result = " + p.change.toString() );
return p;
}
@Override
public SCMRevisionState calcRevisionsFromBuild( AbstractBuild<?, ?> build, Launcher launcher, TaskListener listener ) throws IOException, InterruptedException
{
logger.trace_function();
logger.debug( id + "PucmSCM calcRevisionsFromBuild" );
// PrintStream hudsonOut = listener.getLogger();
SCMRevisionStateImpl scmRS = null;
if ( !( bl == null ) )
{
scmRS = new SCMRevisionStateImpl();
}
return scmRS;
}
private void baselinesToBuild( AbstractProject<?, ?> project, State state ) throws ScmException
{
logger.trace_function();
/* Store the component to the state */
try
{
state.setComponent( UCMEntity.GetComponent( component, false ) );
}
catch ( UCMException e )
{
throw new ScmException( "Could not get component. " + e.getMessage() );
}
/* Store the stream to the state */
try
{
state.setStream( UCMEntity.GetStream( stream, false ) );
}
catch ( UCMException e )
{
throw new ScmException( "Could not get stream. " + e.getMessage() );
}
state.setPlevel( Project.Plevel.valueOf( levelToPoll ) );
/* The baseline list */
BaselineList baselines = null;
try
{
pollMsgs.append( "[PUCM] Getting all baselines for :\n[PUCM] * Stream: " );
pollMsgs.append( stream );
pollMsgs.append( "\n[PUCM] * Component: " );
pollMsgs.append( component );
pollMsgs.append( "\n[PUCM] * Promotionlevel: " );
pollMsgs.append( levelToPoll );
pollMsgs.append( "\n" );
baselines = state.getComponent().GetBaselines( state.getStream(), state.getPlevel() );
}
catch ( UCMException e )
{
throw new ScmException( "Could not retrieve baselines from repository. " + e.getMessage() );
}
if ( baselines.size() > 0 )
{
printBaselines( baselines );
logger.debug( id + "PUCM=" + pucm.stringify() );
try
{
List<Baseline> baselinelist = state.getStream().GetRecommendedBaselines();
pollMsgs.append( "\n[PUCM] Recommended baseline(s): \n" );
for ( Baseline b : baselinelist )
{
pollMsgs.append( b.GetShortname() + "\n" );
}
/* Determine the baseline to build */
bl = null;
state.setBaseline( null );
/* For each baseline retrieved from ClearCase */
//for ( Baseline b : baselinelist )
int start = 0;
int stop = baselines.size();
int increment = 1;
if( newest )
{
start = baselines.size() - 1;
//stop = 0;
increment = -1;
}
/* Find the Baseline to build */
for( int i = start ; i < stop && i >= 0 ; i += increment )
{
/* The current baseline */
Baseline b = baselines.get( i );
State cstate = pucm.getStateByBaseline( jobName, b.GetFQName() );
/* The baseline is in progress, determine if the job is still running */
//if( thisJob.containsKey( b.GetFQName() ) )
if( cstate != null )
{
//Integer bnum = thisJob.get( b.GetFQName() );
//State
Integer bnum = cstate.getJobNumber();
Object o = project.getBuildByNumber( bnum );
Build bld = (Build)o;
/* The job is not running */
if( !bld.isLogUpdated() )
{
logger.debug( id + "Job " + bld.getNumber() + " is not building, using baseline: " + b );
bl = b;
//thisJob.put( b.GetFQName(), state.getJobNumber() );
break;
}
else
{
logger.debug( id + "Job " + bld.getNumber() + " is building " + cstate.getBaseline().GetFQName() );
}
}
/* The baseline is available */
else
{
bl = b;
//thisJob.put( b.GetFQName(), state.getJobNumber() );
logger.debug( id + "The baseline " + b + " is available" );
break;
}
}
if( bl == null )
{
logger.log( id + "No baselines available on chosen parameters." );
throw new ScmException( "No baselines available on chosen parameters." );
}
pollMsgs.append( "\n[PUCM] Building baseline: " + bl + "\n" );
state.setBaseline( bl );
/* Store the baseline to build */
//thisJob.put( bl.GetFQName(), state.getJobNumber() );
}
catch ( UCMException e )
{
throw new ScmException( "Could not get recommended baselines. " + e.getMessage() );
}
}
else
{
throw new ScmException( "No baselines on chosen parameters." );
}
//logger.debug( id + "PRINTING THIS JOB:" );
//logger.debug( net.praqma.util.structure.Printer.mapPrinterToString( thisJob ) );
}
private void printBaselines( BaselineList baselines )
{
pollMsgs.append( "[PUCM] Retrieved baselines:\n" );
if ( !( baselines.size() > 20 ) )
{
for ( Baseline b : baselines )
{
pollMsgs.append( b.GetShortname() );
pollMsgs.append( "\n" );
}
}
else
{
int i = baselines.size();
pollMsgs.append( "[PUCM] There are " + i + " baselines - only printing first and last three\n" );
pollMsgs.append( baselines.get( 0 ).GetShortname() + "\n" );
pollMsgs.append( baselines.get( 1 ).GetShortname() + "\n" );
pollMsgs.append( baselines.get( 2 ).GetShortname() + "\n" );
pollMsgs.append( "...\n" );
pollMsgs.append( baselines.get( i - 3 ).GetShortname() + "\n" );
pollMsgs.append( baselines.get( i - 2 ).GetShortname() + "\n" );
pollMsgs.append( baselines.get( i - 1 ).GetShortname() + "\n" );
}
}
/*
* The following getters and booleans (six in all) are used to display saved
* userdata in Hudsons gui
*/
public String getLevelToPoll()
{
logger.trace_function();
return levelToPoll;
}
public String getComponent()
{
logger.trace_function();
return component;
}
public String getStream()
{
logger.trace_function();
return stream;
}
public String getLoadModule()
{
logger.trace_function();
return loadModule;
}
public boolean isNewest()
{
logger.trace_function();
return newest;
}
/*
* getStreamObject() and getBaseline() are used by PucmNotifier to get the
* Baseline and Stream in use
*/
public Stream getStreamObject()
{
logger.trace_function();
return integrationstream;
}
@Exported
public Baseline getBaseline()
{
logger.trace_function();
return bl;
}
@Exported
public boolean doPostbuild()
{
logger.trace_function();
return doPostBuild;
}
public String getBuildProject()
{
logger.trace_function();
return buildProject;
}
/**
* This class is used to describe the plugin to Hudson
*
* @author Troels Selch S�rensen
* @author Margit Bennetzen
*
*/
@Extension
public static class PucmScmDescriptor extends SCMDescriptor<PucmScm>
{
private String cleartool;
private List<String> loadModules;
public PucmScmDescriptor()
{
super( PucmScm.class, null );
logger.trace_function();
loadModules = getLoadModules();
load();
Config.setContext();
}
/**
* This method is called, when the user saves the global Hudson
* configuration.
*/
@Override
public boolean configure( org.kohsuke.stapler.StaplerRequest req, JSONObject json ) throws FormException
{
logger.trace_function();
cleartool = req.getParameter( "PUCM.cleartool" ).trim();
save();
return true;
}
/**
* This is called by Hudson to discover the plugin name
*/
@Override
public String getDisplayName()
{
logger.trace_function();
return "Praqmatic UCM";
}
/**
* This method is called by the scm/Pucm/global.jelly to validate the
* input without reloading the global configuration page
*
* @param value
* @return
*/
public FormValidation doExecutableCheck( @QueryParameter String value )
{
logger.trace_function();
return FormValidation.validateExecutable( value );
}
/**
* Called by Hudson. If the user does not input a command for Hudson to
* use when polling, default value is returned
*
* @return
*/
public String getCleartool()
{
logger.trace_function();
if ( cleartool == null || cleartool.equals( "" ) )
{
return "cleartool";
}
return cleartool;
}
/**
* Used by Hudson to display a list of valid promotion levels to build
* from. The list of promotion levels is hard coded in
* net.praqma.hudson.Config.java
*
* @return
*/
public List<String> getLevels()
{
logger.trace_function();
return Config.getLevels();
}
/**
* Used by Hudson to display a list of loadModules (whether to poll all
* or only modifiable elements
*
* @return
*/
public List<String> getLoadModules()
{
logger.trace_function();
loadModules = new ArrayList<String>();
loadModules.add( "All" );
loadModules.add( "Modifiable" );
return loadModules;
}
}
}
| false | true | public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException
{
logger.trace_function();
logger.debug( "PucmSCM checkout" );
boolean result = true;
// consoleOutput Printstream is from Hudson, so it can only be accessed
// here
PrintStream consoleOutput = listener.getLogger();
consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" );
/* Recalculate the states */
int count = pucm.recalculate( build.getProject() );
logger.info( "Removed " + count + " from states." );
doPostBuild = true;
jobName = build.getParent().getDisplayName();
jobNumber = build.getNumber();
/* If we polled, we should get the same object created at that point */
State state = pucm.getState( jobName, jobNumber );
logger.debug( id + "The initial state:\n" + state.stringify() );
this.id = "[" + jobName + "::" + jobNumber + "]";
if ( build.getBuildVariables().get( "include_classes" ) != null )
{
String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," );
for( String i : is )
{
logger.includeClass( i.trim() );
}
}
if ( build.getBuildVariables().get( "pucm_baseline" ) != null )
{
Stream integrationstream = null;
String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" );
try
{
state.setBaseline( UCMEntity.GetBaseline( baselinename ) );
state.setStream( state.getBaseline().GetStream() );
consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() );
}
catch ( UCMException e )
{
consoleOutput.println( "[PUCM] Could not find baseline from parameter." );
state.setPostBuild( false );
result = false;
}
}
else
{
// compRevCalled tells whether we have polled for baselines to build
// -
// so if we haven't polled, we do it now
if ( !compRevCalled )
{
try
{
//baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() );
baselinesToBuild( build.getProject(), state );
}
catch ( ScmException e )
{
pollMsgs.append( e.getMessage() );
result = false;
}
}
compRevCalled = false;
// pollMsgs are set in either compareRemoteRevisionWith() or
// baselinesToBuild()
consoleOutput.println( pollMsgs );
pollMsgs = new StringBuffer();
}
if ( result )
{
try
{
/* Force the Baseline to be loaded */
try
{
bl.Load();
}
catch( UCMException e )
{
logger.debug( id + "Could not load Baseline" );
consoleOutput.println( "[PUCM] Could not load Baseline." );
}
/* Check parameters */
consoleOutput.println( "[PUCM] Check 1" );
if( listener == null )
{
consoleOutput.println( "[PUCM] Listener is null" );
}
consoleOutput.println( "[PUCM] Check 2" );
if( jobName == null )
{
consoleOutput.println( "[PUCM] jobname is null" );
}
consoleOutput.println( "[PUCM] Check 3" );
if( build == null )
{
consoleOutput.println( "[PUCM] BUILD is null" );
}
consoleOutput.println( "[PUCM] Check 4" );
if( stream == null )
{
consoleOutput.println( "[PUCM] stream is null" );
}
consoleOutput.println( "[PUCM] Check 5" );
if( loadModule == null )
{
consoleOutput.println( "[PUCM] loadModule is null" );
}
consoleOutput.println( "[PUCM] Check 6" );
if( buildProject == null )
{
consoleOutput.println( "[PUCM] buildProject is null" );
}
/*
if( bl == null )
{
consoleOutput.println( "[PUCM] bl is null" );
}
*/
consoleOutput.println( "[PUCM] Initializing checkout task" );
CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, bl.GetFQName(), buildProject );
consoleOutput.println( "[PUCM] Launching checkout tast" );
String changelog = workspace.act( ct );
consoleOutput.println( "[PUCM] Checkout tast done" );
/* Write change log */
try
{
FileOutputStream fos = new FileOutputStream( changelogFile );
fos.write( changelog.getBytes() );
fos.close();
}
catch( IOException e )
{
logger.debug( id + "Could not write change log file" );
consoleOutput.println( "[PUCM] Could not write change log file" );
}
//doPostBuild = changelog.length() > 0 ? true : false;
}
catch ( Exception e )
{
consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() );
doPostBuild = false;
result = false;
}
}
//pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) );
//state.save();
logger.debug( id + "The CO state:\n" + state.stringify() );
return result;
}
| public boolean checkout( AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile ) throws IOException, InterruptedException
{
logger.trace_function();
logger.debug( "PucmSCM checkout" );
boolean result = true;
// consoleOutput Printstream is from Hudson, so it can only be accessed
// here
PrintStream consoleOutput = listener.getLogger();
consoleOutput.println( "[PUCM] Praqmatic UCM v." + net.praqma.hudson.Version.version + " - SCM section started" );
/* Recalculate the states */
int count = pucm.recalculate( build.getProject() );
logger.info( "Removed " + count + " from states." );
doPostBuild = true;
jobName = build.getParent().getDisplayName();
jobNumber = build.getNumber();
/* If we polled, we should get the same object created at that point */
State state = pucm.getState( jobName, jobNumber );
logger.debug( id + "The initial state:\n" + state.stringify() );
this.id = "[" + jobName + "::" + jobNumber + "]";
if ( build.getBuildVariables().get( "include_classes" ) != null )
{
String[] is = build.getBuildVariables().get( "include_classes" ).toString().split( "," );
for( String i : is )
{
logger.includeClass( i.trim() );
}
}
if ( build.getBuildVariables().get( "pucm_baseline" ) != null )
{
Stream integrationstream = null;
String baselinename = (String) build.getBuildVariables().get( "pucm_baseline" );
try
{
state.setBaseline( UCMEntity.GetBaseline( baselinename ) );
state.setStream( state.getBaseline().GetStream() );
consoleOutput.println( "[PUCM] Starting parameterized build with a pucm_baseline.\nUsing baseline: " + baselinename + " from integrationstream " + state.getStream().GetShortname() );
}
catch ( UCMException e )
{
consoleOutput.println( "[PUCM] Could not find baseline from parameter." );
state.setPostBuild( false );
result = false;
}
}
else
{
// compRevCalled tells whether we have polled for baselines to build
// -
// so if we haven't polled, we do it now
if ( !compRevCalled )
{
try
{
//baselinesToBuild( component, stream, build.getProject(), build.getParent().getDisplayName(), build.getNumber() );
baselinesToBuild( build.getProject(), state );
}
catch ( ScmException e )
{
pollMsgs.append( e.getMessage() );
result = false;
}
}
compRevCalled = false;
// pollMsgs are set in either compareRemoteRevisionWith() or
// baselinesToBuild()
consoleOutput.println( pollMsgs );
pollMsgs = new StringBuffer();
}
if ( result )
{
try
{
/* Force the Baseline to be loaded */
try
{
state.getBaseline().Load();
}
catch( UCMException e )
{
logger.debug( id + "Could not load Baseline" );
consoleOutput.println( "[PUCM] Could not load Baseline." );
}
/* Check parameters */
if( listener == null )
{
consoleOutput.println( "[PUCM] Listener is null" );
}
if( jobName == null )
{
consoleOutput.println( "[PUCM] jobname is null" );
}
if( build == null )
{
consoleOutput.println( "[PUCM] BUILD is null" );
}
if( stream == null )
{
consoleOutput.println( "[PUCM] stream is null" );
}
if( loadModule == null )
{
consoleOutput.println( "[PUCM] loadModule is null" );
}
if( buildProject == null )
{
consoleOutput.println( "[PUCM] buildProject is null" );
}
/*
if( bl == null )
{
consoleOutput.println( "[PUCM] bl is null" );
}
*/
consoleOutput.println( "[PUCM] Initializing checkout task" );
CheckoutTask ct = new CheckoutTask( listener, jobName, build.getNumber(), stream, loadModule, state.getBaseline().GetFQName(), buildProject );
consoleOutput.println( "[PUCM] Launching checkout tast" );
String changelog = workspace.act( ct );
consoleOutput.println( "[PUCM] Checkout tast done" );
/* Write change log */
try
{
FileOutputStream fos = new FileOutputStream( changelogFile );
fos.write( changelog.getBytes() );
fos.close();
}
catch( IOException e )
{
logger.debug( id + "Could not write change log file" );
consoleOutput.println( "[PUCM] Could not write change log file" );
}
//doPostBuild = changelog.length() > 0 ? true : false;
}
catch ( Exception e )
{
consoleOutput.println( "[PUCM] An unknown error occured: " + e.getMessage() );
doPostBuild = false;
result = false;
}
}
//pucm.add( new PucmState( build.getParent().getDisplayName(), build.getNumber(), bl, null, comp, doPostBuild ) );
//state.save();
logger.debug( id + "The CO state:\n" + state.stringify() );
return result;
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListBackupManager.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListBackupManager.java
index 7413ee0ea..f5ff86dbc 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListBackupManager.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskListBackupManager.java
@@ -1,341 +1,341 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Locale;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.ui.util.TaskDataExportJob;
import org.eclipse.mylyn.internal.tasks.ui.wizards.TaskDataExportWizard;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;
/**
* @author Rob Elves
*/
public class TaskListBackupManager implements IPropertyChangeListener {
public static final String TIMESTAMP_FORMAT = "yyyy-MM-dd-HHmmss";
private static final String TITLE_TASKLIST_BACKUP = "Tasklist Backup";
private static final String BACKUP_JOB_NAME = "Scheduled task data backup";
public static final String BACKUP_FAILURE_MESSAGE = "Could not backup task data. Check backup preferences.\n";
private static final long SECOND = 1000;
private static final long MINUTE = 60 * SECOND;
private static final long HOUR = 60 * MINUTE;
private static final long DAY = 24 * HOUR;
private Timer timer;
//private static final Pattern zipPattern = Pattern.compile("^" + TaskDataExportWizard.ZIP_FILE_PREFIX + ".*");
public TaskListBackupManager() {
int days = TasksUiPlugin.getDefault().getPreferenceStore().getInt(TasksUiPreferenceConstants.BACKUP_SCHEDULE);
if (days > 0) {
start(2 * MINUTE);
}
}
public void start(long delay) {
timer = new Timer();
timer.schedule(new CheckBackupRequired(), delay, HOUR);
}
public void stop() {
timer.cancel();
}
public void propertyChange(PropertyChangeEvent event) {
// if (event.getProperty().equals(TaskListPreferenceConstants.BACKUP_AUTOMATICALLY)) {
// if ((Boolean) event.getNewValue() == true) {
// start(MINUTE);
// } else {
// stop();
// }
// }
}
public void backupNow(boolean synchronous) {
String destination = TasksUiPlugin.getDefault().getBackupFolderPath();
File backupFolder = new File(destination);
if (!backupFolder.exists()) {
backupFolder.mkdir();
}
removeOldBackups(backupFolder);
String fileName = TaskDataExportWizard.getZipFileName();
if (!synchronous) {
ExportJob export = new ExportJob(destination, fileName);
export.schedule();
} else {
final TaskDataExportJob backupJob = new TaskDataExportJob(destination, true, fileName);
IProgressService service = PlatformUI.getWorkbench().getProgressService();
try {
service.run(true, false, backupJob);
TasksUiPlugin.getDefault().getPreferenceStore().setValue(TasksUiPreferenceConstants.BACKUP_LAST,
new Date().getTime());
} catch (InterruptedException e) {
// ignore
} catch (InvocationTargetException e) {
MessageDialog.openError(null, TITLE_TASKLIST_BACKUP, BACKUP_FAILURE_MESSAGE);
}
}
}
/** public for testing purposes */
public void removeOldBackups(File folder) {
int maxBackups = TasksUiPlugin.getDefault().getPreferenceStore().getInt(
TasksUiPreferenceConstants.BACKUP_MAXFILES);
File[] files = folder.listFiles();
ArrayList<File> backupFiles = new ArrayList<File>();
for (File file : files) {
if (file.getName().startsWith(TaskDataExportWizard.ZIP_FILE_PREFIX)) {
backupFiles.add(file);
}
}
File[] backupFileArray = backupFiles.toArray(new File[backupFiles.size()]);
if (backupFileArray != null && backupFileArray.length > 0) {
Arrays.sort(backupFileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
return new Long((file1).lastModified()).compareTo(new Long((file2).lastModified()));
}
});
int toomany = backupFileArray.length - maxBackups;
if (toomany > 0) {
for (int x = 0; x < toomany; x++) {
if (backupFileArray[x] != null) {
backupFileArray[x].delete();
}
}
}
}
}
/** public for testing purposes */
public synchronized static void removeOldBackups(File folder, Pattern pattern, int maxBackups) {
if (maxBackups <= 0) {
maxBackups = 1;
}
File[] files = folder.listFiles();
ArrayList<File> backupFiles = new ArrayList<File>();
for (File file : files) {
Matcher matcher = pattern.matcher(file.getName());
if (matcher.find()) {
backupFiles.add(file);
}
}
File[] backupFileArray = backupFiles.toArray(new File[backupFiles.size()]);
if (backupFileArray != null && backupFileArray.length > 0) {
Arrays.sort(backupFileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
return new Long((file1).lastModified()).compareTo(new Long((file2).lastModified()));
}
});
SortedMap<Long, File> filesMap = new TreeMap<Long, File>();
for (File file2 : backupFileArray) {
String name = file2.getName();
if (name.startsWith(ITasksUiConstants.PREFIX_TASKLIST)) {
try {
String dateString = name.substring(ITasksUiConstants.PREFIX_TASKLIST.length() + 1,
ITasksUiConstants.PREFIX_TASKLIST.length() + TIMESTAMP_FORMAT.length() + 1);
SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.ENGLISH);
Date date = format.parse(dateString);
filesMap.put(new Long(date.getTime()), file2);
} catch (Exception e) {
continue;
}
}
}
if (filesMap.size() > 0) {
Calendar rangeStart = TaskActivityUtil.getCalendar();
rangeStart.setTimeInMillis(filesMap.lastKey());
TaskActivityUtil.snapStartOfHour(rangeStart);
int startHour = rangeStart.get(Calendar.HOUR_OF_DAY);
Calendar rangeEnd = TaskActivityUtil.getCalendar();
rangeEnd.setTimeInMillis(rangeStart.getTimeInMillis());
rangeEnd.add(Calendar.HOUR_OF_DAY, 1);
// Keep one backup for last 8 hours of today
for (int x = 1; x <= startHour && x < 9; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.HOUR_OF_DAY, -1);
rangeEnd.add(Calendar.HOUR_OF_DAY, -1);
}
// Keep one backup a day for the past 12 days
- rangeEnd.setTimeInMillis(rangeStart.getTimeInMillis());
+ TaskActivityUtil.snapStartOfDay(rangeEnd);
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
for (int x = 1; x <= 12; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
rangeEnd.add(Calendar.DAY_OF_YEAR, -1);
}
// Remove all older backups
SortedMap<Long, File> subMap = filesMap.subMap(0l, rangeStart.getTimeInMillis());
if (subMap.size() > 0) {
while (subMap.size() > 0) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
}
}
}
// public File getMostRecentBackup() {
// String destination = TasksUiPlugin.getDefault().getBackupFolderPath();
//
// File backupFolder = new File(destination);
// ArrayList<File> backupFiles = new ArrayList<File>();
// if (backupFolder.exists()) {
// File[] files = backupFolder.listFiles();
// for (File file : files) {
// if (file.getName().startsWith(TaskDataExportWizard.ZIP_FILE_PREFIX)) {
// backupFiles.add(file);
// }
// }
// }
//
// File[] backupFileArray = backupFiles.toArray(new File[backupFiles.size()]);
//
// if (backupFileArray != null && backupFileArray.length > 0) {
// Arrays.sort(backupFileArray, new Comparator<File>() {
// public int compare(File file1, File file2) {
// return (new Long((file1).lastModified()).compareTo(new Long((file2).lastModified()))) * -1;
// }
//
// });
// }
// if (backupFileArray != null && backupFileArray.length > 0) {
// return backupFileArray[0];
// }
//
// return null;
// }
class CheckBackupRequired extends TimerTask {
@Override
public void run() {
if (!Platform.isRunning() || TasksUiPlugin.getDefault() == null) {
return;
} else {
long lastBackup = TasksUiPlugin.getDefault().getPreferenceStore().getLong(
TasksUiPreferenceConstants.BACKUP_LAST);
int days = TasksUiPlugin.getDefault().getPreferenceStore().getInt(
TasksUiPreferenceConstants.BACKUP_SCHEDULE);
long waitPeriod = days * DAY;
final long now = new Date().getTime();
if ((now - lastBackup) > waitPeriod) {
if (Platform.isRunning() && !PlatformUI.getWorkbench().isClosing()
&& PlatformUI.getWorkbench().getDisplay() != null
&& !PlatformUI.getWorkbench().getDisplay().isDisposed()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
backupNow(false);
}
});
}
}
}
}
}
static class ExportJob extends Job {
final TaskDataExportJob backupJob;
public ExportJob(String destination, String filename) {
super(BACKUP_JOB_NAME);
backupJob = new TaskDataExportJob(destination, true, filename);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
if (Platform.isRunning()) {
backupJob.run(monitor);
TasksUiPlugin.getDefault().getPreferenceStore().setValue(TasksUiPreferenceConstants.BACKUP_LAST,
new Date().getTime());
}
} catch (InvocationTargetException e) {
MessageDialog.openError(null, BACKUP_JOB_NAME,
"Error occured during scheduled tasklist backup.\nCheck settings on Tasklist preferences page.");
} catch (InterruptedException e) {
return Status.CANCEL_STATUS;
}
return Status.OK_STATUS;
}
}
}
| true | true | public synchronized static void removeOldBackups(File folder, Pattern pattern, int maxBackups) {
if (maxBackups <= 0) {
maxBackups = 1;
}
File[] files = folder.listFiles();
ArrayList<File> backupFiles = new ArrayList<File>();
for (File file : files) {
Matcher matcher = pattern.matcher(file.getName());
if (matcher.find()) {
backupFiles.add(file);
}
}
File[] backupFileArray = backupFiles.toArray(new File[backupFiles.size()]);
if (backupFileArray != null && backupFileArray.length > 0) {
Arrays.sort(backupFileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
return new Long((file1).lastModified()).compareTo(new Long((file2).lastModified()));
}
});
SortedMap<Long, File> filesMap = new TreeMap<Long, File>();
for (File file2 : backupFileArray) {
String name = file2.getName();
if (name.startsWith(ITasksUiConstants.PREFIX_TASKLIST)) {
try {
String dateString = name.substring(ITasksUiConstants.PREFIX_TASKLIST.length() + 1,
ITasksUiConstants.PREFIX_TASKLIST.length() + TIMESTAMP_FORMAT.length() + 1);
SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.ENGLISH);
Date date = format.parse(dateString);
filesMap.put(new Long(date.getTime()), file2);
} catch (Exception e) {
continue;
}
}
}
if (filesMap.size() > 0) {
Calendar rangeStart = TaskActivityUtil.getCalendar();
rangeStart.setTimeInMillis(filesMap.lastKey());
TaskActivityUtil.snapStartOfHour(rangeStart);
int startHour = rangeStart.get(Calendar.HOUR_OF_DAY);
Calendar rangeEnd = TaskActivityUtil.getCalendar();
rangeEnd.setTimeInMillis(rangeStart.getTimeInMillis());
rangeEnd.add(Calendar.HOUR_OF_DAY, 1);
// Keep one backup for last 8 hours of today
for (int x = 1; x <= startHour && x < 9; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.HOUR_OF_DAY, -1);
rangeEnd.add(Calendar.HOUR_OF_DAY, -1);
}
// Keep one backup a day for the past 12 days
rangeEnd.setTimeInMillis(rangeStart.getTimeInMillis());
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
for (int x = 1; x <= 12; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
rangeEnd.add(Calendar.DAY_OF_YEAR, -1);
}
// Remove all older backups
SortedMap<Long, File> subMap = filesMap.subMap(0l, rangeStart.getTimeInMillis());
if (subMap.size() > 0) {
while (subMap.size() > 0) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
}
}
}
| public synchronized static void removeOldBackups(File folder, Pattern pattern, int maxBackups) {
if (maxBackups <= 0) {
maxBackups = 1;
}
File[] files = folder.listFiles();
ArrayList<File> backupFiles = new ArrayList<File>();
for (File file : files) {
Matcher matcher = pattern.matcher(file.getName());
if (matcher.find()) {
backupFiles.add(file);
}
}
File[] backupFileArray = backupFiles.toArray(new File[backupFiles.size()]);
if (backupFileArray != null && backupFileArray.length > 0) {
Arrays.sort(backupFileArray, new Comparator<File>() {
public int compare(File file1, File file2) {
return new Long((file1).lastModified()).compareTo(new Long((file2).lastModified()));
}
});
SortedMap<Long, File> filesMap = new TreeMap<Long, File>();
for (File file2 : backupFileArray) {
String name = file2.getName();
if (name.startsWith(ITasksUiConstants.PREFIX_TASKLIST)) {
try {
String dateString = name.substring(ITasksUiConstants.PREFIX_TASKLIST.length() + 1,
ITasksUiConstants.PREFIX_TASKLIST.length() + TIMESTAMP_FORMAT.length() + 1);
SimpleDateFormat format = new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.ENGLISH);
Date date = format.parse(dateString);
filesMap.put(new Long(date.getTime()), file2);
} catch (Exception e) {
continue;
}
}
}
if (filesMap.size() > 0) {
Calendar rangeStart = TaskActivityUtil.getCalendar();
rangeStart.setTimeInMillis(filesMap.lastKey());
TaskActivityUtil.snapStartOfHour(rangeStart);
int startHour = rangeStart.get(Calendar.HOUR_OF_DAY);
Calendar rangeEnd = TaskActivityUtil.getCalendar();
rangeEnd.setTimeInMillis(rangeStart.getTimeInMillis());
rangeEnd.add(Calendar.HOUR_OF_DAY, 1);
// Keep one backup for last 8 hours of today
for (int x = 1; x <= startHour && x < 9; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.HOUR_OF_DAY, -1);
rangeEnd.add(Calendar.HOUR_OF_DAY, -1);
}
// Keep one backup a day for the past 12 days
TaskActivityUtil.snapStartOfDay(rangeEnd);
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
for (int x = 1; x <= 12; x++) {
SortedMap<Long, File> subMap = filesMap.subMap(rangeStart.getTimeInMillis(),
rangeEnd.getTimeInMillis());
if (subMap.size() > 1) {
while (subMap.size() > 1) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
rangeStart.add(Calendar.DAY_OF_YEAR, -1);
rangeEnd.add(Calendar.DAY_OF_YEAR, -1);
}
// Remove all older backups
SortedMap<Long, File> subMap = filesMap.subMap(0l, rangeStart.getTimeInMillis());
if (subMap.size() > 0) {
while (subMap.size() > 0) {
File toDelete = subMap.remove(subMap.firstKey());
toDelete.delete();
}
}
}
}
}
|
diff --git a/examples/itests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java b/examples/itests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java
index 932f7c66..c391cc19 100644
--- a/examples/itests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java
+++ b/examples/itests/src/test/java/org/apache/servicemix/examples/IntegrationTest.java
@@ -1,96 +1,97 @@
/*
* 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.servicemix.examples;
import java.io.File;
import java.util.Properties;
import java.util.List;
import org.apache.servicemix.kernel.testing.support.AbstractIntegrationTest;
import org.springframework.osgi.test.platform.OsgiPlatform;
public class IntegrationTest extends AbstractIntegrationTest {
private Properties dependencies;
/**
* The manifest to use for the "virtual bundle" created
* out of the test classes and resources in this project
*
* This is actually the boilerplate manifest with one additional
* import-package added. We should provide a simpler customization
* point for such use cases that doesn't require duplication
* of the entire manifest...
*/
protected String getManifestLocation() {
return "classpath:org/apache/servicemix/MANIFEST.MF";
}
/**
* The location of the packaged OSGi bundles to be installed
* for this test. Values are Spring resource paths. The bundles
* we want to use are part of the same multi-project maven
* build as this project is. Hence we use the localMavenArtifact
* helper method to find the bundles produced by the package
* phase of the maven build (these tests will run after the
* packaging phase, in the integration-test phase).
*
* JUnit, commons-logging, spring-core and the spring OSGi
* test bundle are automatically included so do not need
* to be specified here.
*/
protected String[] getTestBundlesNames() {
return new String[] {
getBundle("org.apache.felix", "org.apache.felix.prefs"),
getBundle("org.apache.geronimo.specs", "geronimo-activation_1.1_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-javamail_1.4_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-ws-metadata_2.0_spec"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.stax-api-1.0"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.saaj-api-1.3"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxb-api-2.1"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxws-api-2.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.asm-2.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl-2.1.6"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi-2.0.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.woodstox-3.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j-1.6.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlschema-1.4.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver-1.2"),
getBundle("org.mortbay.jetty", "jetty-util"),
getBundle("org.mortbay.jetty", "jetty"),
getBundle("org.ops4j.pax.web", "pax-web-bundle"),
getBundle("org.ops4j.pax.web-extender", "pax-web-ex-whiteboard"),
getBundle("org.apache.cxf", "cxf-bundle"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.osgi"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.nmr"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.api"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.core"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.spring"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.osgi"),
+ getBundle("org.apache.servicemix.document", "org.apache.servicemix.document")
};
}
public void testJbiComponent() throws Exception {
Thread.sleep(5000);
installBundle("org.apache.servicemix.examples", "cxf-osgi", null, "jar");
Thread.sleep(5000);
}
}
| true | true | protected String[] getTestBundlesNames() {
return new String[] {
getBundle("org.apache.felix", "org.apache.felix.prefs"),
getBundle("org.apache.geronimo.specs", "geronimo-activation_1.1_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-javamail_1.4_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-ws-metadata_2.0_spec"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.stax-api-1.0"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.saaj-api-1.3"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxb-api-2.1"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxws-api-2.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.asm-2.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl-2.1.6"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi-2.0.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.woodstox-3.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j-1.6.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlschema-1.4.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver-1.2"),
getBundle("org.mortbay.jetty", "jetty-util"),
getBundle("org.mortbay.jetty", "jetty"),
getBundle("org.ops4j.pax.web", "pax-web-bundle"),
getBundle("org.ops4j.pax.web-extender", "pax-web-ex-whiteboard"),
getBundle("org.apache.cxf", "cxf-bundle"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.osgi"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.nmr"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.api"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.core"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.spring"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.osgi"),
};
}
| protected String[] getTestBundlesNames() {
return new String[] {
getBundle("org.apache.felix", "org.apache.felix.prefs"),
getBundle("org.apache.geronimo.specs", "geronimo-activation_1.1_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-annotation_1.0_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-javamail_1.4_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec"),
getBundle("org.apache.geronimo.specs", "geronimo-ws-metadata_2.0_spec"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.stax-api-1.0"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.saaj-api-1.3"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxb-api-2.1"),
getBundle("org.apache.servicemix.specs", "org.apache.servicemix.specs.jaxws-api-2.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.asm-2.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.jaxb-impl-2.1.6"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.neethi-2.0.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.woodstox-3.2.3"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.wsdl4j-1.6.1"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlschema-1.4.2"),
getBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.xmlresolver-1.2"),
getBundle("org.mortbay.jetty", "jetty-util"),
getBundle("org.mortbay.jetty", "jetty"),
getBundle("org.ops4j.pax.web", "pax-web-bundle"),
getBundle("org.ops4j.pax.web-extender", "pax-web-ex-whiteboard"),
getBundle("org.apache.cxf", "cxf-bundle"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.osgi"),
getBundle("org.apache.servicemix.cxf", "org.apache.servicemix.cxf.transport.nmr"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.api"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.core"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.spring"),
getBundle("org.apache.servicemix.nmr", "org.apache.servicemix.nmr.osgi"),
getBundle("org.apache.servicemix.document", "org.apache.servicemix.document")
};
}
|
diff --git a/src/cz/android/monet/restexample/fragments/InputFragment.java b/src/cz/android/monet/restexample/fragments/InputFragment.java
index d1e461a..360a5de 100644
--- a/src/cz/android/monet/restexample/fragments/InputFragment.java
+++ b/src/cz/android/monet/restexample/fragments/InputFragment.java
@@ -1,157 +1,157 @@
package cz.android.monet.restexample.fragments;
import java.util.List;
import cz.android.monet.restexample.R;
import cz.android.monet.restexample.SendUserIdAsyncTask;
import cz.android.monet.restexample.interfaces.OnServerResultReturned;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class InputFragment extends Fragment {
private static final String TAG = "InputFragment";
private EditText host;
private EditText sendData;
OnServerResultReturned mResultCallback;
// The resul code
static final int RESULT_OK = -1;
// The request code
static final int PICK_CONTACT_REQUEST = 1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
- host = (EditText) getView().findViewById(R.id.editHostAddress);
+ host = ((EditText) getView().findViewById(R.id.editHostAddress));
sendData = (EditText) getView().findViewById(R.id.editSendData);
// Get the intent that started this activity
Intent intent = getActivity().getIntent();
Uri data = intent.getData();
if (data != null && intent.getType().equals("text/plain")) {
- host.setText(data.getHost().toString());
+ host.setText(data.getHost().toString());
}
else
{
host.setText("193.33.22.109");
}
sendData.setText("1");
Button butSend = (Button) getView().findViewById(R.id.btnSend);
butSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new SendUserIdAsyncTask().execute(host.getText().toString(),
sendData.getText().toString(), mResultCallback);
}
});
Button butTest = (Button) getView().findViewById(R.id.btnReadBarCode);
butTest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri
.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only
// contacts w/
// phone numbers
PackageManager packageManager = getActivity()
.getApplicationContext().getPackageManager();
List<ResolveInfo> activities = packageManager
.queryIntentActivities(pickContactIntent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivityForResult(pickContactIntent,
PICK_CONTACT_REQUEST);
} else {
Log.e(TAG, "Activity pickContactIntent isn't safe.");
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.input, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mResultCallback = (OnServerResultReturned) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnServerResultReturned");
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
switch (requestCode) {
case PICK_CONTACT_REQUEST:
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only
// one row in the result
String[] projection = { Phone.NUMBER };
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one
// result for the given URI)
// CAUTION: The query() method should be called from a separate
// thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this
// code doesn't do that.)
// Consider using CursorLoader to perform the query.
Cursor cursor = getActivity().getContentResolver().query(
contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
mResultCallback.onResultReturned(number);
sendData.setText(number);
}
break;
}
}
}
| false | true | public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
host = (EditText) getView().findViewById(R.id.editHostAddress);
sendData = (EditText) getView().findViewById(R.id.editSendData);
// Get the intent that started this activity
Intent intent = getActivity().getIntent();
Uri data = intent.getData();
if (data != null && intent.getType().equals("text/plain")) {
host.setText(data.getHost().toString());
}
else
{
host.setText("193.33.22.109");
}
sendData.setText("1");
Button butSend = (Button) getView().findViewById(R.id.btnSend);
butSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new SendUserIdAsyncTask().execute(host.getText().toString(),
sendData.getText().toString(), mResultCallback);
}
});
Button butTest = (Button) getView().findViewById(R.id.btnReadBarCode);
butTest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri
.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only
// contacts w/
// phone numbers
PackageManager packageManager = getActivity()
.getApplicationContext().getPackageManager();
List<ResolveInfo> activities = packageManager
.queryIntentActivities(pickContactIntent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivityForResult(pickContactIntent,
PICK_CONTACT_REQUEST);
} else {
Log.e(TAG, "Activity pickContactIntent isn't safe.");
}
}
});
}
| public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
host = ((EditText) getView().findViewById(R.id.editHostAddress));
sendData = (EditText) getView().findViewById(R.id.editSendData);
// Get the intent that started this activity
Intent intent = getActivity().getIntent();
Uri data = intent.getData();
if (data != null && intent.getType().equals("text/plain")) {
host.setText(data.getHost().toString());
}
else
{
host.setText("193.33.22.109");
}
sendData.setText("1");
Button butSend = (Button) getView().findViewById(R.id.btnSend);
butSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new SendUserIdAsyncTask().execute(host.getText().toString(),
sendData.getText().toString(), mResultCallback);
}
});
Button butTest = (Button) getView().findViewById(R.id.btnReadBarCode);
butTest.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri
.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only
// contacts w/
// phone numbers
PackageManager packageManager = getActivity()
.getApplicationContext().getPackageManager();
List<ResolveInfo> activities = packageManager
.queryIntentActivities(pickContactIntent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivityForResult(pickContactIntent,
PICK_CONTACT_REQUEST);
} else {
Log.e(TAG, "Activity pickContactIntent isn't safe.");
}
}
});
}
|
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index ab58dd509..7ca58152c 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -1,401 +1,409 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.security.KeyStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.Phone;
import com.android.internal.widget.LockPatternUtils;
import java.util.ArrayList;
/**
* Gesture lock pattern settings.
*/
public class SecuritySettings extends SettingsPreferenceFragment
implements OnPreferenceChangeListener, DialogInterface.OnClickListener {
// Lock Settings
private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
private static final String KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING =
"biometric_weak_improve_matching";
private static final String KEY_LOCK_ENABLED = "lockenabled";
private static final String KEY_VISIBLE_PATTERN = "visiblepattern";
private static final String KEY_TACTILE_FEEDBACK_ENABLED = "unlock_tactile_feedback";
private static final String KEY_SECURITY_CATEGORY = "security_category";
private static final String KEY_LOCK_AFTER_TIMEOUT = "lock_after_timeout";
private static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
private static final int CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST = 124;
// Misc Settings
private static final String KEY_SIM_LOCK = "sim_lock";
private static final String KEY_SHOW_PASSWORD = "show_password";
private static final String KEY_RESET_CREDENTIALS = "reset_credentials";
private static final String KEY_TOGGLE_INSTALL_APPLICATIONS = "toggle_install_applications";
DevicePolicyManager mDPM;
private ChooseLockSettingsHelper mChooseLockSettingsHelper;
private LockPatternUtils mLockPatternUtils;
private ListPreference mLockAfter;
private CheckBoxPreference mVisiblePattern;
private CheckBoxPreference mTactileFeedback;
private CheckBoxPreference mShowPassword;
private Preference mResetCredentials;
private CheckBoxPreference mToggleAppInstallation;
private DialogInterface mWarnInstallApps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLockPatternUtils = new LockPatternUtils(getActivity());
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity());
}
private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for CDMA phone
TelephonyManager tm = TelephonyManager.getDefault();
if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&
(tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
+ } else {
+ // Disable SIM lock if sim card is missing or unknown
+ if ((TelephonyManager.getDefault().getSimState() ==
+ TelephonyManager.SIM_STATE_ABSENT) ||
+ (TelephonyManager.getDefault().getSimState() ==
+ TelephonyManager.SIM_STATE_UNKNOWN)) {
+ root.findPreference(KEY_SIM_LOCK).setEnabled(false);
+ }
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
return root;
}
private boolean isNonMarketAppsAllowed() {
return Settings.Secure.getInt(getContentResolver(),
Settings.Secure.INSTALL_NON_MARKET_APPS, 0) > 0;
}
private void setNonMarketAppsAllowed(boolean enabled) {
// Change the system setting
Settings.Secure.putInt(getContentResolver(), Settings.Secure.INSTALL_NON_MARKET_APPS,
enabled ? 1 : 0);
}
private void warnAppInstallation() {
// TODO: DialogFragment?
mWarnInstallApps = new AlertDialog.Builder(getActivity()).setTitle(
getResources().getString(R.string.error_title))
.setIcon(com.android.internal.R.drawable.ic_dialog_alert)
.setMessage(getResources().getString(R.string.install_all_warning))
.setPositiveButton(android.R.string.yes, this)
.setNegativeButton(android.R.string.no, null)
.show();
}
public void onClick(DialogInterface dialog, int which) {
if (dialog == mWarnInstallApps && which == DialogInterface.BUTTON_POSITIVE) {
setNonMarketAppsAllowed(true);
mToggleAppInstallation.setChecked(true);
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mWarnInstallApps != null) {
mWarnInstallApps.dismiss();
}
}
private void setupLockAfterPreference() {
// Compatible with pre-Froyo
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
mLockAfter.setValue(String.valueOf(currentTimeout));
mLockAfter.setOnPreferenceChangeListener(this);
final long adminTimeout = (mDPM != null ? mDPM.getMaximumTimeToLock(null) : 0);
final long displayTimeout = Math.max(0,
Settings.System.getInt(getContentResolver(), SCREEN_OFF_TIMEOUT, 0));
if (adminTimeout > 0) {
// This setting is a slave to display timeout when a device policy is enforced.
// As such, maxLockTimeout = adminTimeout - displayTimeout.
// If there isn't enough time, shows "immediately" setting.
disableUnusableTimeouts(Math.max(0, adminTimeout - displayTimeout));
}
}
private void updateLockAfterPreferenceSummary() {
// Update summary message with current value
long currentTimeout = Settings.Secure.getLong(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, 5000);
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
int best = 0;
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (currentTimeout >= timeout) {
best = i;
}
}
mLockAfter.setSummary(getString(R.string.lock_after_timeout_summary, entries[best]));
}
private void disableUnusableTimeouts(long maxTimeout) {
final CharSequence[] entries = mLockAfter.getEntries();
final CharSequence[] values = mLockAfter.getEntryValues();
ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>();
ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>();
for (int i = 0; i < values.length; i++) {
long timeout = Long.valueOf(values[i].toString());
if (timeout <= maxTimeout) {
revisedEntries.add(entries[i]);
revisedValues.add(values[i]);
}
}
if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) {
mLockAfter.setEntries(
revisedEntries.toArray(new CharSequence[revisedEntries.size()]));
mLockAfter.setEntryValues(
revisedValues.toArray(new CharSequence[revisedValues.size()]));
final int userPreference = Integer.valueOf(mLockAfter.getValue());
if (userPreference <= maxTimeout) {
mLockAfter.setValue(String.valueOf(userPreference));
} else {
// There will be no highlighted selection since nothing in the list matches
// maxTimeout. The user can still select anything less than maxTimeout.
// TODO: maybe append maxTimeout to the list and mark selected.
}
}
mLockAfter.setEnabled(revisedEntries.size() > 0);
}
@Override
public void onResume() {
super.onResume();
// Make sure we reload the preference hierarchy since some of these settings
// depend on others...
createPreferenceHierarchy();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (mVisiblePattern != null) {
mVisiblePattern.setChecked(lockPatternUtils.isVisiblePatternEnabled());
}
if (mTactileFeedback != null) {
mTactileFeedback.setChecked(lockPatternUtils.isTactileFeedbackEnabled());
}
mShowPassword.setChecked(Settings.System.getInt(getContentResolver(),
Settings.System.TEXT_SHOW_PASSWORD, 1) != 0);
KeyStore.State state = KeyStore.getInstance().state();
mResetCredentials.setEnabled(state != KeyStore.State.UNINITIALIZED);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
final String key = preference.getKey();
final LockPatternUtils lockPatternUtils = mChooseLockSettingsHelper.utils();
if (KEY_UNLOCK_SET_OR_CHANGE.equals(key)) {
startFragment(this, "com.android.settings.ChooseLockGeneric$ChooseLockGenericFragment",
SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
} else if (KEY_BIOMETRIC_WEAK_IMPROVE_MATCHING.equals(key)) {
ChooseLockSettingsHelper helper =
new ChooseLockSettingsHelper(this.getActivity(), this);
if (!helper.launchConfirmationActivity(
CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST, null, null)) {
startBiometricWeakImprove(); // no password set, so no need to confirm
}
} else if (KEY_LOCK_ENABLED.equals(key)) {
lockPatternUtils.setLockPatternEnabled(isToggled(preference));
} else if (KEY_VISIBLE_PATTERN.equals(key)) {
lockPatternUtils.setVisiblePatternEnabled(isToggled(preference));
} else if (KEY_TACTILE_FEEDBACK_ENABLED.equals(key)) {
lockPatternUtils.setTactileFeedbackEnabled(isToggled(preference));
} else if (preference == mShowPassword) {
Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
mShowPassword.isChecked() ? 1 : 0);
} else if (preference == mToggleAppInstallation) {
if (mToggleAppInstallation.isChecked()) {
mToggleAppInstallation.setChecked(false);
warnAppInstallation();
} else {
setNonMarketAppsAllowed(false);
}
} else {
// If we didn't handle it, let preferences handle it.
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
return true;
}
private boolean isToggled(Preference pref) {
return ((CheckBoxPreference) pref).isChecked();
}
/**
* see confirmPatternThenDisableAndClear
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CONFIRM_EXISTING_FOR_BIOMETRIC_IMPROVE_REQUEST &&
resultCode == Activity.RESULT_OK) {
startBiometricWeakImprove();
return;
}
createPreferenceHierarchy();
}
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference == mLockAfter) {
int timeout = Integer.parseInt((String) value);
try {
Settings.Secure.putInt(getContentResolver(),
Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT, timeout);
} catch (NumberFormatException e) {
Log.e("SecuritySettings", "could not persist lockAfter timeout setting", e);
}
updateLockAfterPreferenceSummary();
}
return true;
}
public void startBiometricWeakImprove(){
Intent intent = new Intent();
intent.setClassName("com.android.facelock", "com.android.facelock.AddToSetup");
startActivity(intent);
}
}
| true | true | private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for CDMA phone
TelephonyManager tm = TelephonyManager.getDefault();
if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&
(tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
return root;
}
| private PreferenceScreen createPreferenceHierarchy() {
PreferenceScreen root = getPreferenceScreen();
if (root != null) {
root.removeAll();
}
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
// Add options for lock/unlock screen
int resid = 0;
if (!mLockPatternUtils.isSecure()) {
if (mLockPatternUtils.isLockScreenDisabled()) {
resid = R.xml.security_settings_lockscreen;
} else {
resid = R.xml.security_settings_chooser;
}
} else if (mLockPatternUtils.usingBiometricWeak() &&
mLockPatternUtils.isBiometricWeakInstalled()) {
resid = R.xml.security_settings_biometric_weak;
} else {
switch (mLockPatternUtils.getKeyguardStoredPasswordQuality()) {
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
resid = R.xml.security_settings_pattern;
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
resid = R.xml.security_settings_pin;
break;
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
resid = R.xml.security_settings_password;
break;
}
}
addPreferencesFromResource(resid);
// Add options for device encryption
DevicePolicyManager dpm =
(DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
switch (dpm.getStorageEncryptionStatus()) {
case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
// The device is currently encrypted.
addPreferencesFromResource(R.xml.security_settings_encrypted);
break;
case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
// This device supports encryption but isn't encrypted.
addPreferencesFromResource(R.xml.security_settings_unencrypted);
break;
}
// lock after preference
mLockAfter = (ListPreference) root.findPreference(KEY_LOCK_AFTER_TIMEOUT);
if (mLockAfter != null) {
setupLockAfterPreference();
updateLockAfterPreferenceSummary();
}
// visible pattern
mVisiblePattern = (CheckBoxPreference) root.findPreference(KEY_VISIBLE_PATTERN);
// don't display visible pattern if biometric and backup is not pattern
if (resid == R.xml.security_settings_biometric_weak &&
mLockPatternUtils.getKeyguardStoredPasswordQuality() !=
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mVisiblePattern != null) {
securityCategory.removePreference(root.findPreference(KEY_VISIBLE_PATTERN));
}
}
// tactile feedback. Should be common to all unlock preference screens.
mTactileFeedback = (CheckBoxPreference) root.findPreference(KEY_TACTILE_FEEDBACK_ENABLED);
if (!((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).hasVibrator()) {
PreferenceGroup securityCategory = (PreferenceGroup)
root.findPreference(KEY_SECURITY_CATEGORY);
if (securityCategory != null && mTactileFeedback != null) {
securityCategory.removePreference(mTactileFeedback);
}
}
// Append the rest of the settings
addPreferencesFromResource(R.xml.security_settings_misc);
// Do not display SIM lock for CDMA phone
TelephonyManager tm = TelephonyManager.getDefault();
if ((TelephonyManager.PHONE_TYPE_CDMA == tm.getCurrentPhoneType()) &&
(tm.getLteOnCdmaMode() != Phone.LTE_ON_CDMA_TRUE)) {
root.removePreference(root.findPreference(KEY_SIM_LOCK));
} else {
// Disable SIM lock if sim card is missing or unknown
if ((TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_ABSENT) ||
(TelephonyManager.getDefault().getSimState() ==
TelephonyManager.SIM_STATE_UNKNOWN)) {
root.findPreference(KEY_SIM_LOCK).setEnabled(false);
}
}
// Show password
mShowPassword = (CheckBoxPreference) root.findPreference(KEY_SHOW_PASSWORD);
// Credential storage
mResetCredentials = root.findPreference(KEY_RESET_CREDENTIALS);
mToggleAppInstallation = (CheckBoxPreference) findPreference(
KEY_TOGGLE_INSTALL_APPLICATIONS);
mToggleAppInstallation.setChecked(isNonMarketAppsAllowed());
return root;
}
|
diff --git a/org.eclipse.riena.example.client/src/org/eclipse/riena/example/client/views/SharedViewDemoSubModuleView.java b/org.eclipse.riena.example.client/src/org/eclipse/riena/example/client/views/SharedViewDemoSubModuleView.java
index 8f4fc2369..30061ab2e 100644
--- a/org.eclipse.riena.example.client/src/org/eclipse/riena/example/client/views/SharedViewDemoSubModuleView.java
+++ b/org.eclipse.riena.example.client/src/org/eclipse/riena/example/client/views/SharedViewDemoSubModuleView.java
@@ -1,75 +1,75 @@
/*******************************************************************************
* Copyright (c) 2007, 2009 compeople AG and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.example.client.views;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.riena.example.client.controllers.SharedViewDemoSubModuleController;
import org.eclipse.riena.navigation.ui.swt.views.SubModuleView;
import org.eclipse.riena.ui.swt.DefaultButtonManager;
import org.eclipse.riena.ui.swt.lnf.LnfKeyConstants;
import org.eclipse.riena.ui.swt.lnf.LnfManager;
import org.eclipse.riena.ui.swt.utils.UIControlsFactory;
/**
* Demonstrates shared views (i.e. one view instance, with several distrinct
* controllers and data).
*/
public class SharedViewDemoSubModuleView extends SubModuleView<SharedViewDemoSubModuleController> {
public static final String ID = SharedViewDemoSubModuleView.class.getName();
private static List<SharedViewDemoSubModuleView> instances = new ArrayList<SharedViewDemoSubModuleView>();
private int instanceIndex = 0;
public SharedViewDemoSubModuleView() {
instances.add(this);
instanceIndex = instances.size();
}
@Override
public void basicCreatePartControl(Composite parent) {
parent.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.SUB_MODULE_BACKGROUND));
GridLayoutFactory.fillDefaults().numColumns(2).margins(20, 20).applyTo(parent);
String text = String.format("(Instance %d Data)", instanceIndex); //$NON-NLS-1$
Label lblInfo = UIControlsFactory.createLabel(parent, text);
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblInfo);
UIControlsFactory.createLabel(parent, "&First Name:"); //$NON-NLS-1$
Text txtFirst = UIControlsFactory.createText(parent, SWT.SINGLE, "txtFirst"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtFirst);
UIControlsFactory.createLabel(parent, "&Last Name:"); //$NON-NLS-1$
Text txtLast = UIControlsFactory.createText(parent, SWT.SINGLE, "txtLast"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtLast);
Button button = UIControlsFactory.createButton(parent, "Default Button"); // TODO [ev] remove
DefaultButtonManager dmb = new DefaultButtonManager(parent.getShell());
- dmb.addButton(button, parent);
+ // dmb.addButton(button, parent);
}
@Override
public void setFocus() {
super.setFocus();
}
}
| true | true | public void basicCreatePartControl(Composite parent) {
parent.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.SUB_MODULE_BACKGROUND));
GridLayoutFactory.fillDefaults().numColumns(2).margins(20, 20).applyTo(parent);
String text = String.format("(Instance %d Data)", instanceIndex); //$NON-NLS-1$
Label lblInfo = UIControlsFactory.createLabel(parent, text);
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblInfo);
UIControlsFactory.createLabel(parent, "&First Name:"); //$NON-NLS-1$
Text txtFirst = UIControlsFactory.createText(parent, SWT.SINGLE, "txtFirst"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtFirst);
UIControlsFactory.createLabel(parent, "&Last Name:"); //$NON-NLS-1$
Text txtLast = UIControlsFactory.createText(parent, SWT.SINGLE, "txtLast"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtLast);
Button button = UIControlsFactory.createButton(parent, "Default Button"); // TODO [ev] remove
DefaultButtonManager dmb = new DefaultButtonManager(parent.getShell());
dmb.addButton(button, parent);
}
| public void basicCreatePartControl(Composite parent) {
parent.setBackground(LnfManager.getLnf().getColor(LnfKeyConstants.SUB_MODULE_BACKGROUND));
GridLayoutFactory.fillDefaults().numColumns(2).margins(20, 20).applyTo(parent);
String text = String.format("(Instance %d Data)", instanceIndex); //$NON-NLS-1$
Label lblInfo = UIControlsFactory.createLabel(parent, text);
GridDataFactory.fillDefaults().span(2, 1).applyTo(lblInfo);
UIControlsFactory.createLabel(parent, "&First Name:"); //$NON-NLS-1$
Text txtFirst = UIControlsFactory.createText(parent, SWT.SINGLE, "txtFirst"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtFirst);
UIControlsFactory.createLabel(parent, "&Last Name:"); //$NON-NLS-1$
Text txtLast = UIControlsFactory.createText(parent, SWT.SINGLE, "txtLast"); //$NON-NLS-1$
GridDataFactory.fillDefaults().hint(200, SWT.DEFAULT).applyTo(txtLast);
Button button = UIControlsFactory.createButton(parent, "Default Button"); // TODO [ev] remove
DefaultButtonManager dmb = new DefaultButtonManager(parent.getShell());
// dmb.addButton(button, parent);
}
|
diff --git a/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java b/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
index ee46e82..f40f74f 100644
--- a/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
+++ b/src/main/java/ru/urbancamper/audiobookmarker/text/BitapSubtextFinding.java
@@ -1,230 +1,230 @@
/*
* This class is supposed to find snippet of text in full text pattern
* by means of Bitap algorithm
*/
package ru.urbancamper.audiobookmarker.text;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.TreeMap;
/**
*
* @author pozpl
*/
public class BitapSubtextFinding {
public BitSet fillBitSetFromWordsNumberArray(Integer[] text, Integer wordToMark){
BitSet textVectorBitSet = new BitSet(text.length);
for(Integer wordsCounter = 0; wordsCounter < text.length; wordsCounter++){
if(text[wordsCounter] == wordToMark){
textVectorBitSet.set(wordsCounter);
}else{
textVectorBitSet.set(wordsCounter, false);
}
}
return textVectorBitSet;
}
@Deprecated
public Byte[] fillByteArrayFromWordsNumbersArray(Integer[] text, Integer wordTomark){
Integer bytesArrayLength = text.length / 8;
bytesArrayLength = text.length % 8 == 0 ? bytesArrayLength : bytesArrayLength + 1;
Byte[] byteArray = new Byte[bytesArrayLength];
Byte byteOne = 1;
for(Integer bytesCounter = 0; bytesCounter < bytesArrayLength; bytesCounter++){
Integer textArrayIndex = bytesCounter * 8;
byteArray[bytesCounter] = 0;
for(Integer bitCounter = 0; bitCounter < 8; bitCounter++){
if(text.length >= textArrayIndex + bitCounter + 1){
if ( text[textArrayIndex + bitCounter] == wordTomark){
byteArray[bytesCounter] = (byte)(byteArray[bytesCounter] | byteOne << bitCounter);
}
}
}
}
return byteArray;
}
// /**
// * Shift bytes array on n positions to the right
// * @param bytes
// * @param rightShifts
// */
// public static void shiftBitsRight(Byte[] bytes, final Integer rightShifts) {
// assert rightShifts >= 1 && rightShifts <= 7;
//
// final Integer leftShifts = 8 - rightShifts;
//
// Byte previousByte = bytes[0]; // keep the byte before modification
// bytes[0] = (byte) (((bytes[0] & 0xff) >> rightShifts) | ((bytes[bytes.length - 1] & 0xff) << leftShifts));
// for (Integer i = 1; i < bytes.length; i++) {
// Byte tmp = bytes[i];
// bytes[i] = (byte) (((bytes[i] & 0xff) >> rightShifts) | ((previousByte & 0xff) << leftShifts));
// previousByte = tmp;
// }
// }
/**
* Shifts bytes array for one bit. Last bit from previous byte
* is tranmitted to current
* @param bytes
* @return Shifted vector of bytes
*/
@Deprecated
private Byte[] shiftBitsLeft(Byte[] bytes) {
Byte previousBit = 0;
Byte currentBit = 0;
previousBit = (byte)(bytes[0] & (1 << 7));
for(Integer bytesCounter = 0; bytesCounter < bytes.length; bytesCounter++){
currentBit = (byte)(bytes[bytesCounter] & (1 << 7));
bytes[bytesCounter] = (byte)(bytes[bytesCounter] << 1);
if(bytesCounter > 0){
bytes[bytesCounter] = (byte)(bytes[bytesCounter] | previousBit);
}
previousBit = (byte)((currentBit >> 7) & 1);
}
return bytes;
}
/**
* Shifts Bit set for on bit to the left
* @param bitSet
* @return
*/
public BitSet shiftBitSetLeft(BitSet bitSet) {
final long maskOfCarry = 0x8000000000000000L;
long[] aLong = bitSet.toLongArray();
boolean carry = false;
for (int i = 0; i < aLong.length; ++i) {
if (carry) {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
++aLong[i];
} else {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
}
}
if (carry) {
long[] tmp = new long[aLong.length + 1];
System.arraycopy(aLong, 0, tmp, 0, aLong.length);
++tmp[aLong.length];
aLong = tmp;
}
return BitSet.valueOf(aLong);
}
@Deprecated
private Byte[] byteArrayAnd(Byte[] firstArray, Byte[] secondArray){
assert firstArray.length == secondArray.length;
Byte[] resultArray = new Byte[firstArray.length];
for(Integer indexCounter = 0; indexCounter < firstArray.length; indexCounter++){
resultArray[indexCounter] = (byte)(firstArray[indexCounter] & secondArray[indexCounter]);
}
return resultArray;
}
/**
* Return the list of indexes where the pattern was found.
*
* The indexes are not exacts because of the addition and deletion : Example
* : the text "aa bb cc" with the pattern "bb" and k=1 will match "
* b","b","bb","b ". and only the index of the first result " b" is added to
* the list even if "bb" have q lower error rate.
*
* @param doc
* @param pattern
* @param k
* @return
*/
public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
- patternMask.put(k, patternMaskForWord);
+ patternMask.put(pattern[i], patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
BitSet rDShifted = this.shiftBitSetLeft(r[d]);
rDShifted.and(symbolMask);
BitSet ins = (BitSet)(rDShifted.clone());
BitSet del = (BitSet)(rDShifted.clone());
BitSet sub = (BitSet)(rDShifted.clone());
ins.or(old);
BitSet oldShifted = this.shiftBitSetLeft(old);
sub.or(oldShifted);
BitSet nextOldShifted = this.shiftBitSetLeft(nextOld);
del.or(nextOldShifted);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
}
| true | true | public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
patternMask.put(k, patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
BitSet rDShifted = this.shiftBitSetLeft(r[d]);
rDShifted.and(symbolMask);
BitSet ins = (BitSet)(rDShifted.clone());
BitSet del = (BitSet)(rDShifted.clone());
BitSet sub = (BitSet)(rDShifted.clone());
ins.or(old);
BitSet oldShifted = this.shiftBitSetLeft(old);
sub.or(oldShifted);
BitSet nextOldShifted = this.shiftBitSetLeft(nextOld);
del.or(nextOldShifted);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
| public List<Integer> find(Integer[] doc, Integer[] pattern, int k) {
// Range of the alphabet
// 128 is enough if we stay in the ASCII range (0-127)
int alphabetRange = 128;
int firstMatchedText = -1;
// Indexes where the pattern was found
ArrayList<Integer> indexes = new ArrayList<Integer>();
BitSet[] r = new BitSet[k + 1];
// BitSet patternMask = new BitSet(pattern.length);
for (int i = 0; i <= k; i++) {
r[i] = new BitSet();
}
// Example : The mask for the letter 'e' and the pattern "hello" is
// 11101 (0 means this letter is at this place in the pattern)
TreeMap<Integer, BitSet> patternMask = new TreeMap<Integer, BitSet>();
// BitSet[] patternMask = new BitSet[pattern.length];
for (int i = 0; i < pattern.length; ++i) {
if(! patternMask.containsKey(pattern[i])){
BitSet patternMaskForWord = this.fillBitSetFromWordsNumberArray(pattern, pattern[i]);
patternMask.put(pattern[i], patternMaskForWord);
}
}
int i = 0;
while (i < doc.length) {
BitSet textMask = this.fillBitSetFromWordsNumberArray(doc, doc[i]);
BitSet symbolMask = (patternMask.containsKey(doc[i])) ? patternMask.get(doc[i])
:new BitSet();
BitSet old = new BitSet();
BitSet nextOld = new BitSet();
for (int d = 0; d <= k; ++d) {
BitSet rDShifted = this.shiftBitSetLeft(r[d]);
rDShifted.and(symbolMask);
BitSet ins = (BitSet)(rDShifted.clone());
BitSet del = (BitSet)(rDShifted.clone());
BitSet sub = (BitSet)(rDShifted.clone());
ins.or(old);
BitSet oldShifted = this.shiftBitSetLeft(old);
sub.or(oldShifted);
BitSet nextOldShifted = this.shiftBitSetLeft(nextOld);
del.or(nextOldShifted);
old = (BitSet)(r[d].clone());
nextOld = (BitSet)(ins.clone());
nextOld.or(sub);
nextOld.or(del);
r[d] = nextOld;
// Three operations of the Levenshtein distance
// long sub = (old | (r[d] & patternMask[doc.charAt(i)])) << 1;
// long ins = old | ((r[d] & patternMask[doc.charAt(i)]) << 1);
// long del = (nextOld | (r[d] & patternMask[doc.charAt(i)])) << 1;
// old = r[d];
// r[d] = sub | ins | del | 1;
// nextOld = r[d];
}
// When r[k] is full of zeros, it means we matched the pattern
// (modulo k errors)
if(r[k].get(pattern.length)){
// if (0 < (r[k] & (1 << pattern.length()))) {
// The pattern "aaa" for the document "bbaaavv" with k=2
// will slide from "bba","baa","aaa","aav","avv"
// Because we allow two errors !
// This test keep only the first one and skip all the others.
// (We can't skip by increasing i otherwise the r[d] will be
// wrong)
if ((firstMatchedText == -1) || (i - firstMatchedText > pattern.length)) {
firstMatchedText = i;
indexes.add(firstMatchedText - pattern.length + 1);
}
}
i++;
}
return indexes;
}
|
diff --git a/lib/java/src/protocol/TProtocolUtil.java b/lib/java/src/protocol/TProtocolUtil.java
index 935163c..ad333bc 100644
--- a/lib/java/src/protocol/TProtocolUtil.java
+++ b/lib/java/src/protocol/TProtocolUtil.java
@@ -1,93 +1,104 @@
// Copyright (c) 2006- Facebook
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
package com.facebook.thrift.protocol;
import com.facebook.thrift.TException;
import com.facebook.thrift.transport.TTransport;
/**
* Utility class with static methods for interacting with protocol data
* streams.
*
* @author Mark Slee <[email protected]>
*/
public class TProtocolUtil {
public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
+ break;
}
case TType.BYTE:
{
prot.readByte();
+ break;
}
case TType.I16:
{
prot.readI16();
+ break;
}
case TType.I32:
{
prot.readI32();
+ break;
}
case TType.I64:
{
prot.readI64();
+ break;
}
case TType.DOUBLE:
{
prot.readDouble();
+ break;
}
case TType.STRING:
{
prot.readString();
+ break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
+ break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
+ break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
+ break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
+ break;
}
default:
- return;
+ break;
}
}
}
| false | true | public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
}
case TType.BYTE:
{
prot.readByte();
}
case TType.I16:
{
prot.readI16();
}
case TType.I32:
{
prot.readI32();
}
case TType.I64:
{
prot.readI64();
}
case TType.DOUBLE:
{
prot.readDouble();
}
case TType.STRING:
{
prot.readString();
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
}
default:
return;
}
}
| public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readString();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
|
diff --git a/teams/baseNuke/ArtilleryRobot.java b/teams/baseNuke/ArtilleryRobot.java
index c8a063f..d3fc51c 100644
--- a/teams/baseNuke/ArtilleryRobot.java
+++ b/teams/baseNuke/ArtilleryRobot.java
@@ -1,58 +1,57 @@
package baseNuke;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.Robot;
import battlecode.common.RobotController;
public class ArtilleryRobot extends BaseRobot {
public ArtilleryRobot(RobotController rc) {
super(rc);
}
@Override
public void run() {
try {
if (rc.isActive()) {
Robot[] potentialTargets = rc.senseNearbyGameObjects(Robot.class, rc.getLocation(), 63, rc.getTeam().opponent());
MapLocation target = getBestTarget(potentialTargets);
if (target != null && rc.canAttackSquare(target)) {
rc.attackSquare(target);
}
}
} catch (Exception e) {
//
}
}
public MapLocation getBestTarget(Robot[] potentialTargets) throws GameActionException {
int highestScore = 0;
MapLocation bestLocation = null;
for (Robot potentialTarget : potentialTargets){
- int currentScore = 0;
+ int currentScore = 40;
MapLocation location = rc.senseLocationOf(potentialTarget);
Robot[] splashRobots = rc.senseNearbyGameObjects(Robot.class, location, GameConstants.ARTILLERY_SPLASH_RADIUS_SQUARED, null);
for (Robot splashRobot : splashRobots) {
if (splashRobot.getTeam() == rc.getTeam()) {
currentScore -= 20;
} else {
currentScore += 20;
}
}
if (currentScore > highestScore) {
bestLocation = location;
highestScore = currentScore;
}
}
- int totalScore = highestScore + 40;
- if (totalScore > 0) {
+ if (highestScore > 0) {
return bestLocation;
} else {
return null;
}
}
}
| false | true | public MapLocation getBestTarget(Robot[] potentialTargets) throws GameActionException {
int highestScore = 0;
MapLocation bestLocation = null;
for (Robot potentialTarget : potentialTargets){
int currentScore = 0;
MapLocation location = rc.senseLocationOf(potentialTarget);
Robot[] splashRobots = rc.senseNearbyGameObjects(Robot.class, location, GameConstants.ARTILLERY_SPLASH_RADIUS_SQUARED, null);
for (Robot splashRobot : splashRobots) {
if (splashRobot.getTeam() == rc.getTeam()) {
currentScore -= 20;
} else {
currentScore += 20;
}
}
if (currentScore > highestScore) {
bestLocation = location;
highestScore = currentScore;
}
}
int totalScore = highestScore + 40;
if (totalScore > 0) {
return bestLocation;
} else {
return null;
}
}
| public MapLocation getBestTarget(Robot[] potentialTargets) throws GameActionException {
int highestScore = 0;
MapLocation bestLocation = null;
for (Robot potentialTarget : potentialTargets){
int currentScore = 40;
MapLocation location = rc.senseLocationOf(potentialTarget);
Robot[] splashRobots = rc.senseNearbyGameObjects(Robot.class, location, GameConstants.ARTILLERY_SPLASH_RADIUS_SQUARED, null);
for (Robot splashRobot : splashRobots) {
if (splashRobot.getTeam() == rc.getTeam()) {
currentScore -= 20;
} else {
currentScore += 20;
}
}
if (currentScore > highestScore) {
bestLocation = location;
highestScore = currentScore;
}
}
if (highestScore > 0) {
return bestLocation;
} else {
return null;
}
}
|
diff --git a/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/RectangleFillToolIntegrationTest.java b/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/RectangleFillToolIntegrationTest.java
index 54e3db25..91a9ff00 100644
--- a/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/RectangleFillToolIntegrationTest.java
+++ b/PaintroidTest/src/org/catrobat/paintroid/test/integration/tools/RectangleFillToolIntegrationTest.java
@@ -1,223 +1,223 @@
/**
* Paintroid: An image manipulation application for Android.
* Copyright (C) 2010-2013 The Catrobat Team
* (<http://developer.catrobat.org/credits>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.catrobat.paintroid.test.integration.tools;
import org.catrobat.paintroid.MainActivity;
import org.catrobat.paintroid.PaintroidApplication;
import org.catrobat.paintroid.R;
import org.catrobat.paintroid.test.integration.BaseIntegrationTestClass;
import org.catrobat.paintroid.test.utils.PrivateAccess;
import org.catrobat.paintroid.tools.Tool;
import org.catrobat.paintroid.tools.ToolType;
import org.catrobat.paintroid.tools.implementation.BaseToolWithRectangleShape;
import org.catrobat.paintroid.tools.implementation.BaseToolWithShape;
import org.catrobat.paintroid.ui.DrawingSurface;
import org.catrobat.paintroid.ui.Statusbar;
import org.junit.Before;
import org.junit.Test;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.widget.Button;
import android.widget.TableRow;
public class RectangleFillToolIntegrationTest extends BaseIntegrationTestClass {
private static final String PRIVATE_ACCESS_STATUSBAR_NAME = "mStatusbar";
private static final String TOOL_MEMBER_WIDTH = "mBoxWidth";
private static final String TOOL_MEMBER_HEIGHT = "mBoxHeight";
private static final String TOOL_MEMBER_POSITION = "mToolPosition";
private static final String TOOL_MEMBER_BITMAP = "mDrawingBitmap";
protected Statusbar mStatusbar;
public RectangleFillToolIntegrationTest() throws Exception {
super();
}
@Override
@Before
protected void setUp() {
super.setUp();
resetBrush();
try {
mStatusbar = (Statusbar) PrivateAccess.getMemberValue(MainActivity.class, getActivity(),
PRIVATE_ACCESS_STATUSBAR_NAME);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test
public void testFilledRectIsCreated() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
selectTool(ToolType.RECT);
Tool mRectangleFillTool = mStatusbar.getCurrentTool();
float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_WIDTH);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_HEIGHT);
PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mRectangleFillTool,
TOOL_MEMBER_POSITION);
assertTrue("Width should not be zero", rectWidth != 0.0f);
assertTrue("Width should not be zero", rectHeight != 0.0f);
assertNotNull("Position should not be NULL", rectPosition);
}
@Test
public void testFilledRectIsDrawnOnBitmap() throws SecurityException, IllegalArgumentException,
NoSuchFieldException, IllegalAccessException {
PaintroidApplication.perspective.setScale(1.0f);
selectTool(ToolType.RECT);
Tool mRectangleFillTool = mStatusbar.getCurrentTool();
PointF point = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mRectangleFillTool,
TOOL_MEMBER_POSITION);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_HEIGHT);
PointF pointOnBitmap = new PointF(point.x, (point.y + (rectHeight / 4.0f)));
PointF pointOnScreen = new PointF(pointOnBitmap.x, pointOnBitmap.y);
mSolo.clickOnScreen(pointOnScreen.x, pointOnScreen.y); // to draw rectangle
mSolo.sleep(50);
mSolo.goBack();
mSolo.sleep(50);
int colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointOnBitmap);
int colorPickerColor = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
}
@Test
public void testEllipseIsDrawnOnBitmap() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
PaintroidApplication.perspective.setScale(1.0f);
selectTool(ToolType.ELLIPSE);
Tool ellipseTool = mStatusbar.getCurrentTool();
PointF centerPointTool = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, ellipseTool,
TOOL_MEMBER_POSITION);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, ellipseTool,
TOOL_MEMBER_HEIGHT);
mSolo.clickOnScreen(centerPointTool.x - 1, centerPointTool.y - 1);
mSolo.sleep(50);
mSolo.goBack();
mSolo.sleep(50);
int colorPickerColor = mStatusbar.getCurrentTool().getDrawPaint().getColor();
PointF pointUnderTest = new PointF(centerPointTool.x, centerPointTool.y);
int colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
- pointUnderTest.x = centerPointTool.x + (rectHeight / 2.2f);
+ pointUnderTest.x = centerPointTool.x + (rectHeight / 2.5f);
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
- pointUnderTest.y = centerPointTool.y + (rectHeight / 2.2f);
+ pointUnderTest.y = centerPointTool.y + (rectHeight / 2.5f);
// now the point under test is diagonal from the center -> if its a circle there should be no color
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertTrue("Pixel should not have been filled for a circle", (colorPickerColor != colorAfterDrawing));
}
@Test
public void testRectOnBitmapHasSameColorAsInColorPickerAfterColorChange() throws SecurityException,
IllegalArgumentException, NoSuchFieldException, IllegalAccessException {
assertTrue("Waiting for DrawingSurface", mSolo.waitForView(DrawingSurface.class, 1, TIMEOUT));
int colorPickerColorBeforeChange = mStatusbar.getCurrentTool().getDrawPaint().getColor();
mSolo.clickOnView(mMenuBottomParameter2);
assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.done), 1, TIMEOUT * 2));
Button colorButton = mSolo.getButton(5);
assertTrue(colorButton.getParent() instanceof TableRow);
mSolo.clickOnButton(5);
mSolo.sleep(50);
mSolo.clickOnButton(getActivity().getResources().getString(R.string.done));
int colorPickerColorAfterChange = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertTrue("Colors should not be the same", colorPickerColorAfterChange != colorPickerColorBeforeChange);
selectTool(ToolType.RECT);
int colorInRectangleTool = mStatusbar.getCurrentTool().getDrawPaint().getColor();
assertEquals("Colors should be the same", colorPickerColorAfterChange, colorInRectangleTool);
Tool mRectangleFillTool = mStatusbar.getCurrentTool();
float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_WIDTH);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_HEIGHT);
Bitmap drawingBitmap = (Bitmap) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class,
mRectangleFillTool, TOOL_MEMBER_BITMAP);
int colorInRectangle = drawingBitmap.getPixel((int) (rectWidth / 2), (int) (rectHeight / 2));
assertEquals("Colors should be the same", colorPickerColorAfterChange, colorInRectangle);
}
@Test
public void testFilledRectChangesColor() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
selectTool(ToolType.RECT);
Tool mRectangleFillTool = mStatusbar.getCurrentTool();
int colorInRectangleTool = mStatusbar.getCurrentTool().getDrawPaint().getColor();
Bitmap drawingBitmap = (Bitmap) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class,
mRectangleFillTool, TOOL_MEMBER_BITMAP);
float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_WIDTH);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mRectangleFillTool,
TOOL_MEMBER_HEIGHT);
int colorInRectangle = drawingBitmap.getPixel((int) (rectWidth / 2), (int) (rectHeight / 2));
assertEquals("Colors should be equal", colorInRectangleTool, colorInRectangle);
// change color and check
mSolo.clickOnView(mMenuBottomParameter2);
assertTrue("Waiting for DrawingSurface", mSolo.waitForText(mSolo.getString(R.string.done), 1, TIMEOUT * 2));
Button colorButton = mSolo.getButton(5);
assertTrue(colorButton.getParent() instanceof TableRow);
mSolo.clickOnButton(5);
mSolo.sleep(50);
mSolo.clickOnButton(getActivity().getResources().getString(R.string.done));
mSolo.sleep(50);
int colorInRectangleToolAfter = mStatusbar.getCurrentTool().getDrawPaint().getColor();
Bitmap drawingBitmapAfter = (Bitmap) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class,
mRectangleFillTool, TOOL_MEMBER_BITMAP);
int colorInRectangleAfter = drawingBitmapAfter.getPixel((int) (rectWidth / 2), (int) (rectHeight / 2));
assertTrue("Colors should have changed", colorInRectangle != colorInRectangleAfter);
assertTrue("Colors should have changed", colorInRectangleTool != colorInRectangleToolAfter);
assertEquals("Colors should be equal", colorInRectangleTool, colorInRectangle);
}
}
| false | true | public void testEllipseIsDrawnOnBitmap() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
PaintroidApplication.perspective.setScale(1.0f);
selectTool(ToolType.ELLIPSE);
Tool ellipseTool = mStatusbar.getCurrentTool();
PointF centerPointTool = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, ellipseTool,
TOOL_MEMBER_POSITION);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, ellipseTool,
TOOL_MEMBER_HEIGHT);
mSolo.clickOnScreen(centerPointTool.x - 1, centerPointTool.y - 1);
mSolo.sleep(50);
mSolo.goBack();
mSolo.sleep(50);
int colorPickerColor = mStatusbar.getCurrentTool().getDrawPaint().getColor();
PointF pointUnderTest = new PointF(centerPointTool.x, centerPointTool.y);
int colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
pointUnderTest.x = centerPointTool.x + (rectHeight / 2.2f);
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
pointUnderTest.y = centerPointTool.y + (rectHeight / 2.2f);
// now the point under test is diagonal from the center -> if its a circle there should be no color
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertTrue("Pixel should not have been filled for a circle", (colorPickerColor != colorAfterDrawing));
}
| public void testEllipseIsDrawnOnBitmap() throws SecurityException, IllegalArgumentException, NoSuchFieldException,
IllegalAccessException {
PaintroidApplication.perspective.setScale(1.0f);
selectTool(ToolType.ELLIPSE);
Tool ellipseTool = mStatusbar.getCurrentTool();
PointF centerPointTool = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, ellipseTool,
TOOL_MEMBER_POSITION);
float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, ellipseTool,
TOOL_MEMBER_HEIGHT);
mSolo.clickOnScreen(centerPointTool.x - 1, centerPointTool.y - 1);
mSolo.sleep(50);
mSolo.goBack();
mSolo.sleep(50);
int colorPickerColor = mStatusbar.getCurrentTool().getDrawPaint().getColor();
PointF pointUnderTest = new PointF(centerPointTool.x, centerPointTool.y);
int colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
pointUnderTest.x = centerPointTool.x + (rectHeight / 2.5f);
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertEquals("Pixel should have the same color as currently in color picker", colorPickerColor,
colorAfterDrawing);
pointUnderTest.y = centerPointTool.y + (rectHeight / 2.5f);
// now the point under test is diagonal from the center -> if its a circle there should be no color
colorAfterDrawing = PaintroidApplication.drawingSurface.getPixel(pointUnderTest);
assertTrue("Pixel should not have been filled for a circle", (colorPickerColor != colorAfterDrawing));
}
|
diff --git a/loci/formats/in/LeicaReader.java b/loci/formats/in/LeicaReader.java
index ef10c18b4..f9882cdd9 100644
--- a/loci/formats/in/LeicaReader.java
+++ b/loci/formats/in/LeicaReader.java
@@ -1,931 +1,931 @@
//
// LeicaReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program 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 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 Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import loci.formats.*;
/**
* LeicaReader is the file format reader for Leica files.
*
* @author Melissa Linkert linkert at cs.wisc.edu
*/
public class LeicaReader extends BaseTiffReader {
// -- Constants -
/** All Leica TIFFs have this tag. */
private static final int LEICA_MAGIC_TAG = 33923;
// -- Fields --
/** Flag indicating whether current file is little endian. */
protected boolean littleEndian;
/** Array of IFD-like structures containing metadata. */
protected Hashtable[] headerIFDs;
/** Helper readers. */
protected TiffReader[][] tiff;
/** Number of channels in the current series. */
protected int[] numChannels;
/** Array of image file names. */
protected Vector[] files;
/** Number of series in the file. */
private int numSeries;
/** Image widths. */
private int[] widths;
/** Image heights. */
private int[] heights;
/** Number of Z slices. */
private int[] zs;
/** Total number of planes in each series. */
private int[] numPlanes;
/** Number of significant bits per pixel. */
private int[][] validBits;
// -- Constructor --
/** Constructs a new Leica reader. */
public LeicaReader() {
super("Leica", new String[] {"lei", "tif", "tiff"});
}
// -- FormatReader API methods --
/** Checks if the given block is a valid header for a Leica file. */
public boolean isThisType(byte[] block) {
if (block.length < 4) return false;
if (block.length < 8) {
// we can only check whether it is a TIFF
return (block[0] == 0x49 && block[1] == 0x49 && block[2] == 0x49 &&
block[3] == 0x49) || (block[0] == 0x4d && block[1] == 0x4d &&
block[2] == 0x4d && block[3] == 0x4d);
}
int ifdlocation = DataTools.bytesToInt(block, 4, true);
if (ifdlocation < 0 || ifdlocation + 1 > block.length) {
return false;
}
else {
int ifdnumber = DataTools.bytesToInt(block, ifdlocation, 2, true);
for (int i=0; i<ifdnumber; i++) {
if (ifdlocation + 3 + (i*12) > block.length) return false;
else {
int ifdtag = DataTools.bytesToInt(block,
ifdlocation + 2 + (i*12), 2, true);
if (ifdtag == LEICA_MAGIC_TAG) return true;
}
}
return false;
}
}
/** Determines the number of images in the given Leica file. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) {
initFile(id);
}
return numPlanes[series];
}
/** Return the number of series in the given Leica file. */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) {
initFile(id);
}
return numSeries;
}
/** Checks if the images in the file are RGB. */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) {
initFile(id);
}
tiff[series][0].setColorTableIgnored(isColorTableIgnored());
return tiff[series][0].isRGB((String) files[series].get(0));
}
/** Return true if the data is in little-endian format. */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return littleEndian;
}
/** Returns whether or not the channels are interleaved. */
public boolean isInterleaved(String id) throws FormatException, IOException {
return true;
}
/** Obtains the specified image from the given Leica file as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) {
initFile(id);
}
if (no < 0 || no >= getImageCount(id)) {
throw new FormatException("Invalid image number: " + no);
}
tiff[series][no].setColorTableIgnored(ignoreColorTable);
byte[] b = tiff[series][no].openBytes((String) files[series].get(no), 0);
tiff[series][no].close();
return b;
}
/** Obtains the specified image from the given Leica file. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId) && !DataTools.samePrefix(id, currentId)) {
initFile(id);
}
if (no < 0 || no >= getImageCount(id)) {
throw new FormatException("Invalid image number: " + no);
}
tiff[series][no].setColorTableIgnored(ignoreColorTable);
BufferedImage b =
tiff[series][no].openImage((String) files[series].get(no), 0);
b = ImageTools.makeBuffered(b,
ImageTools.makeColorModel(b.getRaster().getNumBands(),
b.getRaster().getTransferType(), validBits[series]));
tiff[series][no].close();
return b;
}
/** Closes any open files. */
public void close() throws FormatException, IOException {
if (in != null) in.close();
in = null;
currentId = null;
if (tiff != null) {
for (int i=0; i<tiff.length; i++) {
if (tiff[i] != null) {
for (int j=0; j<tiff[i].length; j++) {
if (tiff[i][j] != null) tiff[i][j].close();
}
}
}
}
}
/** Initializes the given Leica file. */
protected void initFile(String id) throws FormatException, IOException {
String idLow = id.toLowerCase();
if (idLow.endsWith("tif") || idLow.endsWith("tiff")) {
if (ifds == null) super.initFile(id);
in = new RandomAccessStream(getMappedId(id));
if (in.readShort() == 0x4949) {
in.order(true);
}
in.seek(0);
// open the TIFF file and look for the "Image Description" field
ifds = TiffTools.getIFDs(in);
try {
super.initMetadata();
}
catch (NullPointerException n) { }
if (ifds == null) throw new FormatException("No IFDs found");
String descr = (String) metadata.get("Comment");
metadata.remove("Comment");
int ndx = descr.indexOf("Series Name");
// should be more graceful about this
if (ndx == -1) throw new FormatException("LEI file not found");
String lei = descr.substring(descr.indexOf("=", ndx) + 1);
int newLineNdx = lei.indexOf("\n");
lei = lei.substring(0, newLineNdx == -1 ? lei.length() : newLineNdx);
lei = lei.trim();
String dir = id.substring(0, id.lastIndexOf("/") + 1);
lei = dir + lei;
// parse key/value pairs in ImageDescription
// first thing is to remove anything of the form "[blah]"
String first;
String last;
while(descr.indexOf("[") != -1) {
first = descr.substring(0, descr.indexOf("["));
last = descr.substring(descr.indexOf("\n", descr.indexOf("[")));
descr = first + last;
}
// each remaining line in descr is a (key, value) pair,
// where '=' separates the key from the value
String key;
String value;
int eqIndex = descr.indexOf("=");
while(eqIndex != -1) {
key = descr.substring(0, eqIndex);
newLineNdx = descr.indexOf("\n", eqIndex);
if (newLineNdx == -1) newLineNdx = descr.length();
value = descr.substring(eqIndex+1, newLineNdx);
metadata.put(key.trim(), value.trim());
newLineNdx = descr.indexOf("\n", eqIndex);
if (newLineNdx == -1) newLineNdx = descr.length();
descr = descr.substring(newLineNdx);
eqIndex = descr.indexOf("=");
}
// now open the LEI file
initFile(lei);
//super.initMetadata();
}
else {
// parse the LEI file
if (metadata == null) {
currentId = id;
metadata = new Hashtable();
}
else {
if (currentId != id) currentId = id;
}
in = new RandomAccessStream(getMappedId(id));
byte[] fourBytes = new byte[4];
in.read(fourBytes);
littleEndian = (fourBytes[0] == TiffTools.LITTLE &&
fourBytes[1] == TiffTools.LITTLE &&
fourBytes[2] == TiffTools.LITTLE &&
fourBytes[3] == TiffTools.LITTLE);
in.order(littleEndian);
in.skipBytes(8);
int addr = in.readInt();
Vector v = new Vector();
while (addr != 0) {
numSeries++;
Hashtable ifd = new Hashtable();
v.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
byte[] data = new byte[size];
in.read(data);
ifd.put(new Integer(tag), (Object) data);
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
if (v.size() < numSeries) numSeries = v.size();
numChannels = new int[numSeries];
widths = new int[numSeries];
heights = new int[numSeries];
zs = new int[numSeries];
headerIFDs = new Hashtable[numSeries];
files = new Vector[numSeries];
numPlanes = new int[numSeries];
v.copyInto(headerIFDs);
// determine the length of a filename
int nameLength = 0;
int maxPlanes = 0;
for (int i=0; i<headerIFDs.length; i++) {
if (headerIFDs[i].get(new Integer(10)) != null) {
byte[] temp = (byte[]) headerIFDs[i].get(new Integer(10));
nameLength = DataTools.bytesToInt(temp, 8, 4, littleEndian);
}
Vector f = new Vector();
byte[] tempData = (byte[]) headerIFDs[i].get(new Integer(15));
int tempImages = DataTools.bytesToInt(tempData, 0, 4, littleEndian);
String dirPrefix =
new File(getMappedId(id)).getAbsoluteFile().getParent();
dirPrefix = dirPrefix == null ? "" : (dirPrefix + File.separator);
for (int j=0; j<tempImages; j++) {
// read in each filename
f.add(dirPrefix + DataTools.stripString(
new String(tempData, 20 + 2*(j*nameLength), 2*nameLength)));
// test to make sure the path is valid
File test = new File((String) f.get(f.size() - 1));
if (!test.exists()) {
// TIFF files were renamed
File[] dirListing = (new File(dirPrefix)).listFiles();
int pos = 0;
int maxChars = 0;
for (int k=0; k<dirListing.length; k++) {
int pt = 0;
int chars = 0;
String path = dirListing[k].getAbsolutePath();
if (path.toLowerCase().endsWith("tif") ||
path.toLowerCase().endsWith("tiff"))
{
while (path.charAt(pt) == test.getAbsolutePath().charAt(pt)) {
pt++;
chars++;
}
int newPt = path.length() - 1;
int oldPt = test.getAbsolutePath().length() - 1;
while (path.charAt(newPt) ==
test.getAbsolutePath().charAt(oldPt))
{
newPt--;
oldPt--;
chars++;
}
if (chars > maxChars) {
maxChars = chars;
pos = k;
}
}
}
f.set(f.size() - 1, dirListing[pos].getAbsolutePath());
}
}
files[i] = f;
numPlanes[i] = f.size();
if (numPlanes[i] > maxPlanes) maxPlanes = numPlanes[i];
}
tiff = new TiffReader[numSeries][maxPlanes];
for (int i=0; i<tiff.length; i++) {
for (int j=0; j<tiff[i].length; j++) {
tiff[i][j] = new TiffReader();
}
}
initMetadata();
}
}
// -- FormatHandler API methods --
/**
* Checks if the given string is a valid filename for a Leica file.
* @param open If true, the (existing) file is opened for further analysis,
* since the file extension is insufficient to confirm that the file is in
* Leica format.
*/
public boolean isThisType(String name, boolean open) {
String lname = name.toLowerCase();
if (lname.endsWith(".lei")) return true;
else if (!lname.endsWith(".tif") && !lname.endsWith(".tiff")) return false;
if (!open) return true; // now allowed to be any more thorough
// just checking the filename isn't enough to differentiate between
// Leica and regular TIFF; open the file and check more thoroughly
File file = new File(getMappedId(name));
if (!file.exists()) return false;
long len = file.length();
if (len < 4) return false;
try {
RandomAccessStream ras = new RandomAccessStream(getMappedId(name));
Hashtable ifd = TiffTools.getFirstIFD(ras);
if (ifd == null) return false;
String descr = (String) ifd.get(new Integer(TiffTools.IMAGE_DESCRIPTION));
int ndx = descr.indexOf("Series Name");
if (ndx == -1) return false;
String lei = descr.substring(descr.indexOf("=", ndx) + 1);
lei = lei.substring(0, lei.indexOf("\n"));
lei = lei.trim();
String dir = name.substring(0, name.lastIndexOf("/") + 1);
lei = dir + lei;
File check = new File(getMappedId(lei));
return check.exists();
}
catch (IOException exc) { }
catch (NullPointerException exc) { }
return false;
}
// -- Helper methods --
/* @see loci.formats.BaseTiffReader#initMetadata() */
protected void initMetadata() {
if (headerIFDs == null) headerIFDs = ifds;
for (int i=0; i<headerIFDs.length; i++) {
byte[] temp = (byte[]) headerIFDs[i].get(new Integer(10));
if (temp != null) {
// the series data
// ID_SERIES
metadata.put("Version",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
metadata.put("Number of Series",
new Integer(DataTools.bytesToInt(temp, 4, 4, littleEndian)));
metadata.put("Length of filename",
new Integer(DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Length of file extension",
new Integer(DataTools.bytesToInt(temp, 12, 4, littleEndian)));
Integer fileExtLen = (Integer) metadata.get("Length of file extension");
metadata.put("Image file extension",
DataTools.stripString(new String(temp, 16, fileExtLen.intValue())));
}
temp = (byte[]) headerIFDs[i].get(new Integer(15));
if (temp != null) {
// the image data
// ID_IMAGES
zs[i] = DataTools.bytesToInt(temp, 0, 4, littleEndian);
widths[i] = DataTools.bytesToInt(temp, 4, 4, littleEndian);
heights[i] = DataTools.bytesToInt(temp, 8, 4, littleEndian);
metadata.put("Number of images", new Integer(zs[i]));
metadata.put("Image width", new Integer(widths[i]));
metadata.put("Image height", new Integer(heights[i]));
metadata.put("Bits per Sample", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
metadata.put("Samples per pixel", new Integer(
DataTools.bytesToInt(temp, 16, 4, littleEndian)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(20));
if (temp != null) {
// dimension description
// ID_DIMDESCR
int pt = 0;
metadata.put("Voxel Version", new Integer(
DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int voxelType = DataTools.bytesToInt(temp, 4, 4, littleEndian);
String type = "";
switch (voxelType) {
case 0:
type = "undefined";
break;
case 10:
type = "gray normal";
break;
case 20:
type = "RGB";
break;
}
metadata.put("VoxelType", type);
metadata.put("Bytes per pixel", new Integer(
DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Real world resolution", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
int length = DataTools.bytesToInt(temp, 16, 4, littleEndian);
metadata.put("Maximum voxel intensity",
DataTools.stripString(new String(temp, 20, length)));
pt = 20 + length;
pt += 4;
metadata.put("Minimum voxel intensity",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4 + length + 4;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
for (int j=0; j<length; j++) {
int dimId = DataTools.bytesToInt(temp, pt, 4, littleEndian);
String dimType = "";
switch (dimId) {
case 0:
dimType = "undefined";
break;
case 120:
dimType = "x";
break;
case 121:
dimType = "y";
break;
case 122:
dimType = "z";
break;
case 116:
dimType = "t";
break;
case 6815843:
dimType = "channel";
break;
case 6357100:
dimType = "wave length";
break;
case 7602290:
dimType = "rotation";
break;
case 7798904:
dimType = "x-wide for the motorized xy-stage";
break;
case 7798905:
dimType = "y-wide for the motorized xy-stage";
break;
case 7798906:
dimType = "z-wide for the z-stage-drive";
break;
case 4259957:
dimType = "user1 - unspecified";
break;
case 4325493:
dimType = "user2 - unspecified";
break;
case 4391029:
dimType = "user3 - unspecified";
break;
case 6357095:
dimType = "graylevel";
break;
case 6422631:
dimType = "graylevel1";
break;
case 6488167:
dimType = "graylevel2";
break;
case 6553703:
dimType = "graylevel3";
break;
case 7864398:
dimType = "logical x";
break;
case 7929934:
dimType = "logical y";
break;
case 7995470:
dimType = "logical z";
break;
case 7602254:
dimType = "logical t";
break;
case 7077966:
dimType = "logical lambda";
break;
case 7471182:
dimType = "logical rotation";
break;
case 5767246:
dimType = "logical x-wide";
break;
case 5832782:
dimType = "logical y-wide";
break;
case 5898318:
dimType = "logical z-wide";
break;
}
//if (dimType.equals("channel")) numChannels++;
metadata.put("Dim" + j + " type", dimType);
pt += 4;
metadata.put("Dim" + j + " size", new Integer(
DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dim" + j + " distance between sub-dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical length",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical origin",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " name",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " description",
DataTools.stripString(new String(temp, pt, len)));
}
}
temp = (byte[]) headerIFDs[i].get(new Integer(30));
if (temp != null) {
// filter data
// ID_FILTERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(40));
if (temp != null) {
// time data
// ID_TIMEINFO
try {
metadata.put("Number of time-stamped dimensions",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int nDims = DataTools.bytesToInt(temp, 4, 4, littleEndian);
metadata.put("Time-stamped dimension", new Integer(nDims));
int pt = 8;
for (int j=0; j < nDims; j++) {
metadata.put("Dimension " + j + " ID",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " size",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " distance between dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
int numStamps = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-stamps", new Integer(numStamps));
for (int j=0; j<numStamps; j++) {
metadata.put("Timestamp " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
int numTMs = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-markers", new Integer(numTMs));
for (int j=0; j<numTMs; j++) {
int numDims = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
for (int k=0; k<numDims; k++) {
metadata.put("Time-marker " + j +
" Dimension " + k + " coordinate",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
metadata.put("Time-marker " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
}
catch (Throwable t) { }
}
temp = (byte[]) headerIFDs[i].get(new Integer(50));
if (temp != null) {
// scanner data
// ID_SCANNERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(60));
if (temp != null) {
// experiment data
// ID_EXPERIMENT
int pt = 8;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Image Description",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Main file extension",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image format identifier",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image extension",
DataTools.stripString(new String(temp, pt, 2*len)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(70));
if (temp != null) {
// LUT data
// ID_LUTDESC
int pt = 0;
int nChannels = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of LUT channels", new Integer(nChannels));
metadata.put("ID of colored dimension",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
numChannels[i] = nChannels;
for (int j=0; j<nChannels; j++) {
metadata.put("LUT Channel " + j + " version",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int invert = DataTools.bytesToInt(temp, pt, 1, littleEndian);
pt += 1;
boolean inverted = invert == 1;
metadata.put("LUT Channel " + j + " inverted?",
new Boolean(inverted).toString());
int length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " description",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " filename",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
String name = DataTools.stripString(new String(temp, pt, length));
if (name.equals("Green") || name.equals("Red") || name.equals("Blue"))
{
numChannels[i] = 3;
}
metadata.put("LUT Channel " + j + " name", name);
pt += length;
pt += 8;
}
}
}
sizeX = widths;
sizeY = heights;
sizeZ = zs;
sizeC = numChannels;
sizeT = new int[numSeries];
pixelType = new int[numSeries];
currentOrder = new String[numSeries];
orderCertain = new boolean[numSeries];
Arrays.fill(orderCertain, true);
try {
int oldSeries = getSeries(currentId);
for (int i=0; i<sizeC.length; i++) {
setSeries(currentId, i);
if (isRGB(currentId)) sizeC[i] = 3;
else sizeC[i] = 1;
}
setSeries(currentId, oldSeries);
}
catch (Exception e) {
// NullPointerException caught here if the file we opened was a TIFF.
// However, the sizeC field will be adjusted anyway by a later call to
// BaseTiffReader.initMetadata
}
Integer v = (Integer) metadata.get("Real world resolution");
if (v != null) {
validBits = new int[sizeC.length][];
for (int i=0; i<validBits.length; i++) {
validBits[i] = new int[sizeC[i]];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = v.intValue();
}
}
}
else validBits = null;
// The metadata store we're working with.
MetadataStore store = new DummyMetadataStore();
try {
store = getMetadataStore(currentId);
}
catch (Exception e) { }
for (int i=0; i<numSeries; i++) {
orderCertain[i] = true;
if (sizeC[i] == 0) sizeC[i] = 1;
sizeT[i] += 1;
currentOrder[i] = "XYZTC";
int tPixelType = ((Integer) metadata.get("Bytes per pixel")).intValue();
switch (tPixelType) {
case 1:
pixelType[i] = FormatReader.UINT8;
break;
case 2:
pixelType[i] = FormatReader.UINT16;
break;
case 3:
- pixelType[i] = FormatReader.INT8;
+ pixelType[i] = FormatReader.UINT8;
break;
case 4:
pixelType[i] = FormatReader.INT32;
break;
case 6:
pixelType[i] = FormatReader.INT16;
break;
case 8:
pixelType[i] = FormatReader.DOUBLE;
break;
}
store.setPixels(
new Integer(widths[i]),
new Integer(heights[i]),
new Integer(zs[i]),
new Integer(numChannels[i] == 0 ? 1 : numChannels[i]), // SizeC
new Integer(1), // SizeT
new Integer(pixelType[i]), // PixelType
new Boolean(!littleEndian), // BigEndian
"XYZTC", // DimensionOrder
new Integer(i));
String timestamp = (String) metadata.get("Timestamp " + (i+1));
String description = (String) metadata.get("Image Description");
try {
store.setImage(null, timestamp.substring(3),
description, new Integer(i));
}
catch (NullPointerException n) { }
}
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new LeicaReader().testRead(args);
}
}
| true | true | protected void initMetadata() {
if (headerIFDs == null) headerIFDs = ifds;
for (int i=0; i<headerIFDs.length; i++) {
byte[] temp = (byte[]) headerIFDs[i].get(new Integer(10));
if (temp != null) {
// the series data
// ID_SERIES
metadata.put("Version",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
metadata.put("Number of Series",
new Integer(DataTools.bytesToInt(temp, 4, 4, littleEndian)));
metadata.put("Length of filename",
new Integer(DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Length of file extension",
new Integer(DataTools.bytesToInt(temp, 12, 4, littleEndian)));
Integer fileExtLen = (Integer) metadata.get("Length of file extension");
metadata.put("Image file extension",
DataTools.stripString(new String(temp, 16, fileExtLen.intValue())));
}
temp = (byte[]) headerIFDs[i].get(new Integer(15));
if (temp != null) {
// the image data
// ID_IMAGES
zs[i] = DataTools.bytesToInt(temp, 0, 4, littleEndian);
widths[i] = DataTools.bytesToInt(temp, 4, 4, littleEndian);
heights[i] = DataTools.bytesToInt(temp, 8, 4, littleEndian);
metadata.put("Number of images", new Integer(zs[i]));
metadata.put("Image width", new Integer(widths[i]));
metadata.put("Image height", new Integer(heights[i]));
metadata.put("Bits per Sample", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
metadata.put("Samples per pixel", new Integer(
DataTools.bytesToInt(temp, 16, 4, littleEndian)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(20));
if (temp != null) {
// dimension description
// ID_DIMDESCR
int pt = 0;
metadata.put("Voxel Version", new Integer(
DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int voxelType = DataTools.bytesToInt(temp, 4, 4, littleEndian);
String type = "";
switch (voxelType) {
case 0:
type = "undefined";
break;
case 10:
type = "gray normal";
break;
case 20:
type = "RGB";
break;
}
metadata.put("VoxelType", type);
metadata.put("Bytes per pixel", new Integer(
DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Real world resolution", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
int length = DataTools.bytesToInt(temp, 16, 4, littleEndian);
metadata.put("Maximum voxel intensity",
DataTools.stripString(new String(temp, 20, length)));
pt = 20 + length;
pt += 4;
metadata.put("Minimum voxel intensity",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4 + length + 4;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
for (int j=0; j<length; j++) {
int dimId = DataTools.bytesToInt(temp, pt, 4, littleEndian);
String dimType = "";
switch (dimId) {
case 0:
dimType = "undefined";
break;
case 120:
dimType = "x";
break;
case 121:
dimType = "y";
break;
case 122:
dimType = "z";
break;
case 116:
dimType = "t";
break;
case 6815843:
dimType = "channel";
break;
case 6357100:
dimType = "wave length";
break;
case 7602290:
dimType = "rotation";
break;
case 7798904:
dimType = "x-wide for the motorized xy-stage";
break;
case 7798905:
dimType = "y-wide for the motorized xy-stage";
break;
case 7798906:
dimType = "z-wide for the z-stage-drive";
break;
case 4259957:
dimType = "user1 - unspecified";
break;
case 4325493:
dimType = "user2 - unspecified";
break;
case 4391029:
dimType = "user3 - unspecified";
break;
case 6357095:
dimType = "graylevel";
break;
case 6422631:
dimType = "graylevel1";
break;
case 6488167:
dimType = "graylevel2";
break;
case 6553703:
dimType = "graylevel3";
break;
case 7864398:
dimType = "logical x";
break;
case 7929934:
dimType = "logical y";
break;
case 7995470:
dimType = "logical z";
break;
case 7602254:
dimType = "logical t";
break;
case 7077966:
dimType = "logical lambda";
break;
case 7471182:
dimType = "logical rotation";
break;
case 5767246:
dimType = "logical x-wide";
break;
case 5832782:
dimType = "logical y-wide";
break;
case 5898318:
dimType = "logical z-wide";
break;
}
//if (dimType.equals("channel")) numChannels++;
metadata.put("Dim" + j + " type", dimType);
pt += 4;
metadata.put("Dim" + j + " size", new Integer(
DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dim" + j + " distance between sub-dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical length",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical origin",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " name",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " description",
DataTools.stripString(new String(temp, pt, len)));
}
}
temp = (byte[]) headerIFDs[i].get(new Integer(30));
if (temp != null) {
// filter data
// ID_FILTERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(40));
if (temp != null) {
// time data
// ID_TIMEINFO
try {
metadata.put("Number of time-stamped dimensions",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int nDims = DataTools.bytesToInt(temp, 4, 4, littleEndian);
metadata.put("Time-stamped dimension", new Integer(nDims));
int pt = 8;
for (int j=0; j < nDims; j++) {
metadata.put("Dimension " + j + " ID",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " size",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " distance between dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
int numStamps = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-stamps", new Integer(numStamps));
for (int j=0; j<numStamps; j++) {
metadata.put("Timestamp " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
int numTMs = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-markers", new Integer(numTMs));
for (int j=0; j<numTMs; j++) {
int numDims = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
for (int k=0; k<numDims; k++) {
metadata.put("Time-marker " + j +
" Dimension " + k + " coordinate",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
metadata.put("Time-marker " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
}
catch (Throwable t) { }
}
temp = (byte[]) headerIFDs[i].get(new Integer(50));
if (temp != null) {
// scanner data
// ID_SCANNERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(60));
if (temp != null) {
// experiment data
// ID_EXPERIMENT
int pt = 8;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Image Description",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Main file extension",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image format identifier",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image extension",
DataTools.stripString(new String(temp, pt, 2*len)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(70));
if (temp != null) {
// LUT data
// ID_LUTDESC
int pt = 0;
int nChannels = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of LUT channels", new Integer(nChannels));
metadata.put("ID of colored dimension",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
numChannels[i] = nChannels;
for (int j=0; j<nChannels; j++) {
metadata.put("LUT Channel " + j + " version",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int invert = DataTools.bytesToInt(temp, pt, 1, littleEndian);
pt += 1;
boolean inverted = invert == 1;
metadata.put("LUT Channel " + j + " inverted?",
new Boolean(inverted).toString());
int length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " description",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " filename",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
String name = DataTools.stripString(new String(temp, pt, length));
if (name.equals("Green") || name.equals("Red") || name.equals("Blue"))
{
numChannels[i] = 3;
}
metadata.put("LUT Channel " + j + " name", name);
pt += length;
pt += 8;
}
}
}
sizeX = widths;
sizeY = heights;
sizeZ = zs;
sizeC = numChannels;
sizeT = new int[numSeries];
pixelType = new int[numSeries];
currentOrder = new String[numSeries];
orderCertain = new boolean[numSeries];
Arrays.fill(orderCertain, true);
try {
int oldSeries = getSeries(currentId);
for (int i=0; i<sizeC.length; i++) {
setSeries(currentId, i);
if (isRGB(currentId)) sizeC[i] = 3;
else sizeC[i] = 1;
}
setSeries(currentId, oldSeries);
}
catch (Exception e) {
// NullPointerException caught here if the file we opened was a TIFF.
// However, the sizeC field will be adjusted anyway by a later call to
// BaseTiffReader.initMetadata
}
Integer v = (Integer) metadata.get("Real world resolution");
if (v != null) {
validBits = new int[sizeC.length][];
for (int i=0; i<validBits.length; i++) {
validBits[i] = new int[sizeC[i]];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = v.intValue();
}
}
}
else validBits = null;
// The metadata store we're working with.
MetadataStore store = new DummyMetadataStore();
try {
store = getMetadataStore(currentId);
}
catch (Exception e) { }
for (int i=0; i<numSeries; i++) {
orderCertain[i] = true;
if (sizeC[i] == 0) sizeC[i] = 1;
sizeT[i] += 1;
currentOrder[i] = "XYZTC";
int tPixelType = ((Integer) metadata.get("Bytes per pixel")).intValue();
switch (tPixelType) {
case 1:
pixelType[i] = FormatReader.UINT8;
break;
case 2:
pixelType[i] = FormatReader.UINT16;
break;
case 3:
pixelType[i] = FormatReader.INT8;
break;
case 4:
pixelType[i] = FormatReader.INT32;
break;
case 6:
pixelType[i] = FormatReader.INT16;
break;
case 8:
pixelType[i] = FormatReader.DOUBLE;
break;
}
store.setPixels(
new Integer(widths[i]),
new Integer(heights[i]),
new Integer(zs[i]),
new Integer(numChannels[i] == 0 ? 1 : numChannels[i]), // SizeC
new Integer(1), // SizeT
new Integer(pixelType[i]), // PixelType
new Boolean(!littleEndian), // BigEndian
"XYZTC", // DimensionOrder
new Integer(i));
String timestamp = (String) metadata.get("Timestamp " + (i+1));
String description = (String) metadata.get("Image Description");
try {
store.setImage(null, timestamp.substring(3),
description, new Integer(i));
}
catch (NullPointerException n) { }
}
}
| protected void initMetadata() {
if (headerIFDs == null) headerIFDs = ifds;
for (int i=0; i<headerIFDs.length; i++) {
byte[] temp = (byte[]) headerIFDs[i].get(new Integer(10));
if (temp != null) {
// the series data
// ID_SERIES
metadata.put("Version",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
metadata.put("Number of Series",
new Integer(DataTools.bytesToInt(temp, 4, 4, littleEndian)));
metadata.put("Length of filename",
new Integer(DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Length of file extension",
new Integer(DataTools.bytesToInt(temp, 12, 4, littleEndian)));
Integer fileExtLen = (Integer) metadata.get("Length of file extension");
metadata.put("Image file extension",
DataTools.stripString(new String(temp, 16, fileExtLen.intValue())));
}
temp = (byte[]) headerIFDs[i].get(new Integer(15));
if (temp != null) {
// the image data
// ID_IMAGES
zs[i] = DataTools.bytesToInt(temp, 0, 4, littleEndian);
widths[i] = DataTools.bytesToInt(temp, 4, 4, littleEndian);
heights[i] = DataTools.bytesToInt(temp, 8, 4, littleEndian);
metadata.put("Number of images", new Integer(zs[i]));
metadata.put("Image width", new Integer(widths[i]));
metadata.put("Image height", new Integer(heights[i]));
metadata.put("Bits per Sample", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
metadata.put("Samples per pixel", new Integer(
DataTools.bytesToInt(temp, 16, 4, littleEndian)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(20));
if (temp != null) {
// dimension description
// ID_DIMDESCR
int pt = 0;
metadata.put("Voxel Version", new Integer(
DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int voxelType = DataTools.bytesToInt(temp, 4, 4, littleEndian);
String type = "";
switch (voxelType) {
case 0:
type = "undefined";
break;
case 10:
type = "gray normal";
break;
case 20:
type = "RGB";
break;
}
metadata.put("VoxelType", type);
metadata.put("Bytes per pixel", new Integer(
DataTools.bytesToInt(temp, 8, 4, littleEndian)));
metadata.put("Real world resolution", new Integer(
DataTools.bytesToInt(temp, 12, 4, littleEndian)));
int length = DataTools.bytesToInt(temp, 16, 4, littleEndian);
metadata.put("Maximum voxel intensity",
DataTools.stripString(new String(temp, 20, length)));
pt = 20 + length;
pt += 4;
metadata.put("Minimum voxel intensity",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4 + length + 4;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
for (int j=0; j<length; j++) {
int dimId = DataTools.bytesToInt(temp, pt, 4, littleEndian);
String dimType = "";
switch (dimId) {
case 0:
dimType = "undefined";
break;
case 120:
dimType = "x";
break;
case 121:
dimType = "y";
break;
case 122:
dimType = "z";
break;
case 116:
dimType = "t";
break;
case 6815843:
dimType = "channel";
break;
case 6357100:
dimType = "wave length";
break;
case 7602290:
dimType = "rotation";
break;
case 7798904:
dimType = "x-wide for the motorized xy-stage";
break;
case 7798905:
dimType = "y-wide for the motorized xy-stage";
break;
case 7798906:
dimType = "z-wide for the z-stage-drive";
break;
case 4259957:
dimType = "user1 - unspecified";
break;
case 4325493:
dimType = "user2 - unspecified";
break;
case 4391029:
dimType = "user3 - unspecified";
break;
case 6357095:
dimType = "graylevel";
break;
case 6422631:
dimType = "graylevel1";
break;
case 6488167:
dimType = "graylevel2";
break;
case 6553703:
dimType = "graylevel3";
break;
case 7864398:
dimType = "logical x";
break;
case 7929934:
dimType = "logical y";
break;
case 7995470:
dimType = "logical z";
break;
case 7602254:
dimType = "logical t";
break;
case 7077966:
dimType = "logical lambda";
break;
case 7471182:
dimType = "logical rotation";
break;
case 5767246:
dimType = "logical x-wide";
break;
case 5832782:
dimType = "logical y-wide";
break;
case 5898318:
dimType = "logical z-wide";
break;
}
//if (dimType.equals("channel")) numChannels++;
metadata.put("Dim" + j + " type", dimType);
pt += 4;
metadata.put("Dim" + j + " size", new Integer(
DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dim" + j + " distance between sub-dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical length",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " physical origin",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " name",
DataTools.stripString(new String(temp, pt, len)));
pt += len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Dim" + j + " description",
DataTools.stripString(new String(temp, pt, len)));
}
}
temp = (byte[]) headerIFDs[i].get(new Integer(30));
if (temp != null) {
// filter data
// ID_FILTERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(40));
if (temp != null) {
// time data
// ID_TIMEINFO
try {
metadata.put("Number of time-stamped dimensions",
new Integer(DataTools.bytesToInt(temp, 0, 4, littleEndian)));
int nDims = DataTools.bytesToInt(temp, 4, 4, littleEndian);
metadata.put("Time-stamped dimension", new Integer(nDims));
int pt = 8;
for (int j=0; j < nDims; j++) {
metadata.put("Dimension " + j + " ID",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " size",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
metadata.put("Dimension " + j + " distance between dimensions",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
int numStamps = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-stamps", new Integer(numStamps));
for (int j=0; j<numStamps; j++) {
metadata.put("Timestamp " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
int numTMs = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of time-markers", new Integer(numTMs));
for (int j=0; j<numTMs; j++) {
int numDims = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
for (int k=0; k<numDims; k++) {
metadata.put("Time-marker " + j +
" Dimension " + k + " coordinate",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
}
metadata.put("Time-marker " + j,
DataTools.stripString(new String(temp, pt, 64)));
pt += 64;
}
}
catch (Throwable t) { }
}
temp = (byte[]) headerIFDs[i].get(new Integer(50));
if (temp != null) {
// scanner data
// ID_SCANNERSET
// not currently used
}
temp = (byte[]) headerIFDs[i].get(new Integer(60));
if (temp != null) {
// experiment data
// ID_EXPERIMENT
int pt = 8;
int len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Image Description",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Main file extension",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image format identifier",
DataTools.stripString(new String(temp, pt, 2*len)));
pt += 2*len;
len = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Single image extension",
DataTools.stripString(new String(temp, pt, 2*len)));
}
temp = (byte[]) headerIFDs[i].get(new Integer(70));
if (temp != null) {
// LUT data
// ID_LUTDESC
int pt = 0;
int nChannels = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("Number of LUT channels", new Integer(nChannels));
metadata.put("ID of colored dimension",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
numChannels[i] = nChannels;
for (int j=0; j<nChannels; j++) {
metadata.put("LUT Channel " + j + " version",
new Integer(DataTools.bytesToInt(temp, pt, 4, littleEndian)));
pt += 4;
int invert = DataTools.bytesToInt(temp, pt, 1, littleEndian);
pt += 1;
boolean inverted = invert == 1;
metadata.put("LUT Channel " + j + " inverted?",
new Boolean(inverted).toString());
int length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " description",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
metadata.put("LUT Channel " + j + " filename",
DataTools.stripString(new String(temp, pt, length)));
pt += length;
length = DataTools.bytesToInt(temp, pt, 4, littleEndian);
pt += 4;
String name = DataTools.stripString(new String(temp, pt, length));
if (name.equals("Green") || name.equals("Red") || name.equals("Blue"))
{
numChannels[i] = 3;
}
metadata.put("LUT Channel " + j + " name", name);
pt += length;
pt += 8;
}
}
}
sizeX = widths;
sizeY = heights;
sizeZ = zs;
sizeC = numChannels;
sizeT = new int[numSeries];
pixelType = new int[numSeries];
currentOrder = new String[numSeries];
orderCertain = new boolean[numSeries];
Arrays.fill(orderCertain, true);
try {
int oldSeries = getSeries(currentId);
for (int i=0; i<sizeC.length; i++) {
setSeries(currentId, i);
if (isRGB(currentId)) sizeC[i] = 3;
else sizeC[i] = 1;
}
setSeries(currentId, oldSeries);
}
catch (Exception e) {
// NullPointerException caught here if the file we opened was a TIFF.
// However, the sizeC field will be adjusted anyway by a later call to
// BaseTiffReader.initMetadata
}
Integer v = (Integer) metadata.get("Real world resolution");
if (v != null) {
validBits = new int[sizeC.length][];
for (int i=0; i<validBits.length; i++) {
validBits[i] = new int[sizeC[i]];
for (int j=0; j<validBits[i].length; j++) {
validBits[i][j] = v.intValue();
}
}
}
else validBits = null;
// The metadata store we're working with.
MetadataStore store = new DummyMetadataStore();
try {
store = getMetadataStore(currentId);
}
catch (Exception e) { }
for (int i=0; i<numSeries; i++) {
orderCertain[i] = true;
if (sizeC[i] == 0) sizeC[i] = 1;
sizeT[i] += 1;
currentOrder[i] = "XYZTC";
int tPixelType = ((Integer) metadata.get("Bytes per pixel")).intValue();
switch (tPixelType) {
case 1:
pixelType[i] = FormatReader.UINT8;
break;
case 2:
pixelType[i] = FormatReader.UINT16;
break;
case 3:
pixelType[i] = FormatReader.UINT8;
break;
case 4:
pixelType[i] = FormatReader.INT32;
break;
case 6:
pixelType[i] = FormatReader.INT16;
break;
case 8:
pixelType[i] = FormatReader.DOUBLE;
break;
}
store.setPixels(
new Integer(widths[i]),
new Integer(heights[i]),
new Integer(zs[i]),
new Integer(numChannels[i] == 0 ? 1 : numChannels[i]), // SizeC
new Integer(1), // SizeT
new Integer(pixelType[i]), // PixelType
new Boolean(!littleEndian), // BigEndian
"XYZTC", // DimensionOrder
new Integer(i));
String timestamp = (String) metadata.get("Timestamp " + (i+1));
String description = (String) metadata.get("Image Description");
try {
store.setImage(null, timestamp.substring(3),
description, new Integer(i));
}
catch (NullPointerException n) { }
}
}
|
diff --git a/core/proxy/jms/src/main/java/org/openengsb/core/proxy/jms/JSONSerialisationInvocationHandler.java b/core/proxy/jms/src/main/java/org/openengsb/core/proxy/jms/JSONSerialisationInvocationHandler.java
index 464050d29..55f1d9a4a 100644
--- a/core/proxy/jms/src/main/java/org/openengsb/core/proxy/jms/JSONSerialisationInvocationHandler.java
+++ b/core/proxy/jms/src/main/java/org/openengsb/core/proxy/jms/JSONSerialisationInvocationHandler.java
@@ -1,62 +1,62 @@
/**
* Copyright 2010 OpenEngSB Division, Vienna University of Technology
*
* 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.openengsb.core.proxy.jms;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
public class JSONSerialisationInvocationHandler implements InvocationHandler {
private final Sender sender;
public JSONSerialisationInvocationHandler(Sender sender) {
super();
this.sender = sender;
}
@Override
public Object invoke(Object arg0, Method arg1, Object[] arg2) {
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, arg2);
String send = sender.send(arg1.getName(), writer.toString());
- if ("void".equals(arg1.getReturnType().getName())) {
+ if (!"void".equals(arg1.getReturnType().getName())) {
return mapper.readValue(send, TypeFactory.type(arg1.getGenericReturnType()));
} else {
return null;
}
} catch (JsonGenerationException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonMappingException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonParseException e) {
throw new JMSConnectorException(e.getMessage());
} catch (IOException e) {
throw new JMSConnectorException(e.getMessage());
}
}
}
| true | true | public Object invoke(Object arg0, Method arg1, Object[] arg2) {
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, arg2);
String send = sender.send(arg1.getName(), writer.toString());
if ("void".equals(arg1.getReturnType().getName())) {
return mapper.readValue(send, TypeFactory.type(arg1.getGenericReturnType()));
} else {
return null;
}
} catch (JsonGenerationException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonMappingException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonParseException e) {
throw new JMSConnectorException(e.getMessage());
} catch (IOException e) {
throw new JMSConnectorException(e.getMessage());
}
}
| public Object invoke(Object arg0, Method arg1, Object[] arg2) {
ObjectMapper mapper = new ObjectMapper();
StringWriter writer = new StringWriter();
try {
mapper.writeValue(writer, arg2);
String send = sender.send(arg1.getName(), writer.toString());
if (!"void".equals(arg1.getReturnType().getName())) {
return mapper.readValue(send, TypeFactory.type(arg1.getGenericReturnType()));
} else {
return null;
}
} catch (JsonGenerationException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonMappingException e) {
throw new JMSConnectorException(e.getMessage());
} catch (JsonParseException e) {
throw new JMSConnectorException(e.getMessage());
} catch (IOException e) {
throw new JMSConnectorException(e.getMessage());
}
}
|
diff --git a/src/main/java/com/ids/businessLogic/FirstTimeQuery.java b/src/main/java/com/ids/businessLogic/FirstTimeQuery.java
index e8aa1b8..f72a218 100644
--- a/src/main/java/com/ids/businessLogic/FirstTimeQuery.java
+++ b/src/main/java/com/ids/businessLogic/FirstTimeQuery.java
@@ -1,282 +1,282 @@
package com.ids.businessLogic;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import com.ids.entities.Company;
import com.ids.entities.Country;
import com.ids.entities.Product;
import com.ids.entities.Year;
import com.ids.json.ColumnModel;
import com.ids.json.TitleArray;
import com.ids.json.YearArray;
public class FirstTimeQuery {
private ModelMap model;
private HashMap<String,Integer> totalLine2 = null;
private HashMap<String,Integer> otherLine2 = null;
private final static Logger logger = Logger.getLogger(FirstTimeEdQuery.class.getName());
public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){
try {
Statement statement = con.createStatement();
String query=null;
ResultSet resultSet = null;
TitleArray titleArray= new TitleArray("AUSTRIA","AGRICULTURAL TRACTOR", "SALES" );
int countryId = 7; //Austria
String multiplier="";
if (access.equals("c")) {
titleArray = new TitleArray("CHINA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 210000; //China
multiplier="*10000";
}
if (access.equals("i")) {
titleArray = new TitleArray("INDIA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 20000000; //India
multiplier="*200000";
}
query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 ";
List<Year> years = new ArrayList<Year>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1"));
years.add(year);
for (int i=1;i<=10;i++) {
Year nextYear = new Year(
Integer.toString(Integer.parseInt(year.getId())+i),
Integer.toString(Integer.parseInt(year.getId())+i));
years.add(nextYear);
}
}
YearArray yearArray = new YearArray("Company",years,"TOTAL");
ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray());
String query2="";
if (access.equals("w")) {
query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " +
" from Facts_w a, Company b, Country c, Product d "+
" where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+
" and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+
" group by a.year, substr(b.name,1,20), d.name, 'EUROPE' " +
" order by b.name , a.year asc ";
}else {
- query2 = " select a.year, a.quantity, substr(b.name,1,20) from Facts_"+access+" a, Company b, Country c " +
+ query2 = " select a.year, a.quantity, substr(b.name,1,20) as name from Facts_"+access+" a, Company b, Country c " +
" where a.companyid=b.id " +
" and a.countryid=c.id " +
" and c.id="+countryId +
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and a.sales_production= 1" +
" and a.productid=1"+multiplier +
" and a.access = '" + access + "' " +
" and b.name!='ALL COMPANIES' " +
" order by b.name , a.year asc";
}
logger.warning(query2);
resultSet = statement.executeQuery(query2);
String currentCompany="";
JSONObject obj2a = null;
JSONArray array7 = new JSONArray();
totalLine2 = new HashMap<String,Integer>();
otherLine2 = new HashMap<String,Integer>();
while (resultSet.next()) {
int totalQuantity=0;
if (totalLine2.get(resultSet.getString("year"))!= null) {
totalQuantity= totalLine2.get(resultSet.getString("year"));
}
totalQuantity += Integer.parseInt(resultSet.getString("quantity"));
totalLine2.put(resultSet.getString("year"), totalQuantity);
int otherQuantity=0;
if (otherLine2.get(resultSet.getString("year"))!= null) {
otherQuantity= otherLine2.get(resultSet.getString("year"));
}
otherQuantity += Integer.parseInt(resultSet.getString("quantity"));
otherLine2.put(resultSet.getString("year"), otherQuantity);
if (!currentCompany.equals(resultSet.getString("name"))) {
if (!currentCompany.equals("")){
array7.put(obj2a);
}
obj2a = new JSONObject();
currentCompany=resultSet.getString("name");
obj2a.put("Company",currentCompany);
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
} else {
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
}
}
if (obj2a != null) {
array7.put(obj2a);
}
JSONObject obj7 = new JSONObject();
obj7.put("myData", array7);
JSONArray array4 = new JSONArray();
array4.put(columnModel.getModelObject());
array4.put(yearArray.getJsonYearObject());
array4.put(obj7);
array4.put(titleArray.getJsonTitleObject());
JSONObject obj5 = new JSONObject();
obj5.put("tabData", array4);
AddJsonRowTotal aj = new AddJsonRowTotal(obj5);
JSONObject objTotal = new JSONObject();
objTotal.put("Company","TOTAL");
Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
objTotal.put(pairs.getKey(), pairs.getValue());
}
objTotal.put("TOTAL", aj.getTotal());
JSONArray array8 = new JSONArray();
if (objTotal != null) {
array8.put(objTotal);
JSONObject obj8 = new JSONObject();
obj8.put("myTotals", array8);
model.addAttribute("jsonTotal",obj8);
}
model.addAttribute("jsonData",obj5);
logger.warning(obj5.toString());
if (request.getParameter("list") == null){
query = "select id, UPPER(country) as country from Country where id != 0 and access = '"+access+"' order by country asc " ;
List<Country> countries = new ArrayList<Country>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Country country = new Country(resultSet.getString("id"),resultSet.getString("country"));
countries.add(country);
}
model.addAttribute("dropdown1a",countries);
model.addAttribute("dropdown2a",countries);
query = "select id, UPPER(name) as name from Product where id != 0 and access = '"+access+"' order by name asc " ;
List<Product> products = new ArrayList<Product>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Product product = new Product(resultSet.getString("id"),resultSet.getString("name"));
products.add(product);
}
model.addAttribute("dropdown1b",products);
model.addAttribute("dropdown2b",products);
model.addAttribute("dropdown1c",years);
model.addAttribute("dropdown2c",years);
query = " select distinct a.id, UPPER(substr(a.name,1,20)) as name from Company a , Facts_"+access+" b " +
" where a.id != 0" +
" and b.companyid = a.id " +
" and b.access = '" + access +"' and " +
" a.access = '" + access + "' " +
" and a.name != 'ALL COMPANIES' " +
// " and b.year between "+(curYear - 5)+" and "+(curYear+5)+
" order by a.name asc " ;
logger.warning(query);
List<Company> companies = new ArrayList<Company>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Company company = new Company(resultSet.getString("id"),resultSet.getString("name"));
companies.add(company);
}
model.addAttribute("dropdown1d",companies);
model.addAttribute("dropdown2d",companies);
model.addAttribute("firstTimeFromServer",obj5);
this.model = model;
}
}catch(Exception e) {
logger.warning("ERRRRRRRRRRROR: "+e.getMessage());
e.printStackTrace();
}
}
public ModelMap getModel() {
return this.model;
}
}
| true | true | public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){
try {
Statement statement = con.createStatement();
String query=null;
ResultSet resultSet = null;
TitleArray titleArray= new TitleArray("AUSTRIA","AGRICULTURAL TRACTOR", "SALES" );
int countryId = 7; //Austria
String multiplier="";
if (access.equals("c")) {
titleArray = new TitleArray("CHINA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 210000; //China
multiplier="*10000";
}
if (access.equals("i")) {
titleArray = new TitleArray("INDIA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 20000000; //India
multiplier="*200000";
}
query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 ";
List<Year> years = new ArrayList<Year>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1"));
years.add(year);
for (int i=1;i<=10;i++) {
Year nextYear = new Year(
Integer.toString(Integer.parseInt(year.getId())+i),
Integer.toString(Integer.parseInt(year.getId())+i));
years.add(nextYear);
}
}
YearArray yearArray = new YearArray("Company",years,"TOTAL");
ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray());
String query2="";
if (access.equals("w")) {
query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " +
" from Facts_w a, Company b, Country c, Product d "+
" where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+
" and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+
" group by a.year, substr(b.name,1,20), d.name, 'EUROPE' " +
" order by b.name , a.year asc ";
}else {
query2 = " select a.year, a.quantity, substr(b.name,1,20) from Facts_"+access+" a, Company b, Country c " +
" where a.companyid=b.id " +
" and a.countryid=c.id " +
" and c.id="+countryId +
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and a.sales_production= 1" +
" and a.productid=1"+multiplier +
" and a.access = '" + access + "' " +
" and b.name!='ALL COMPANIES' " +
" order by b.name , a.year asc";
}
logger.warning(query2);
resultSet = statement.executeQuery(query2);
String currentCompany="";
JSONObject obj2a = null;
JSONArray array7 = new JSONArray();
totalLine2 = new HashMap<String,Integer>();
otherLine2 = new HashMap<String,Integer>();
while (resultSet.next()) {
int totalQuantity=0;
if (totalLine2.get(resultSet.getString("year"))!= null) {
totalQuantity= totalLine2.get(resultSet.getString("year"));
}
totalQuantity += Integer.parseInt(resultSet.getString("quantity"));
totalLine2.put(resultSet.getString("year"), totalQuantity);
int otherQuantity=0;
if (otherLine2.get(resultSet.getString("year"))!= null) {
otherQuantity= otherLine2.get(resultSet.getString("year"));
}
otherQuantity += Integer.parseInt(resultSet.getString("quantity"));
otherLine2.put(resultSet.getString("year"), otherQuantity);
if (!currentCompany.equals(resultSet.getString("name"))) {
if (!currentCompany.equals("")){
array7.put(obj2a);
}
obj2a = new JSONObject();
currentCompany=resultSet.getString("name");
obj2a.put("Company",currentCompany);
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
} else {
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
}
}
if (obj2a != null) {
array7.put(obj2a);
}
JSONObject obj7 = new JSONObject();
obj7.put("myData", array7);
JSONArray array4 = new JSONArray();
array4.put(columnModel.getModelObject());
array4.put(yearArray.getJsonYearObject());
array4.put(obj7);
array4.put(titleArray.getJsonTitleObject());
JSONObject obj5 = new JSONObject();
obj5.put("tabData", array4);
AddJsonRowTotal aj = new AddJsonRowTotal(obj5);
JSONObject objTotal = new JSONObject();
objTotal.put("Company","TOTAL");
Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
objTotal.put(pairs.getKey(), pairs.getValue());
}
objTotal.put("TOTAL", aj.getTotal());
JSONArray array8 = new JSONArray();
if (objTotal != null) {
array8.put(objTotal);
JSONObject obj8 = new JSONObject();
obj8.put("myTotals", array8);
model.addAttribute("jsonTotal",obj8);
}
model.addAttribute("jsonData",obj5);
logger.warning(obj5.toString());
if (request.getParameter("list") == null){
query = "select id, UPPER(country) as country from Country where id != 0 and access = '"+access+"' order by country asc " ;
List<Country> countries = new ArrayList<Country>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Country country = new Country(resultSet.getString("id"),resultSet.getString("country"));
countries.add(country);
}
model.addAttribute("dropdown1a",countries);
model.addAttribute("dropdown2a",countries);
query = "select id, UPPER(name) as name from Product where id != 0 and access = '"+access+"' order by name asc " ;
List<Product> products = new ArrayList<Product>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Product product = new Product(resultSet.getString("id"),resultSet.getString("name"));
products.add(product);
}
model.addAttribute("dropdown1b",products);
model.addAttribute("dropdown2b",products);
model.addAttribute("dropdown1c",years);
model.addAttribute("dropdown2c",years);
query = " select distinct a.id, UPPER(substr(a.name,1,20)) as name from Company a , Facts_"+access+" b " +
" where a.id != 0" +
" and b.companyid = a.id " +
" and b.access = '" + access +"' and " +
" a.access = '" + access + "' " +
" and a.name != 'ALL COMPANIES' " +
// " and b.year between "+(curYear - 5)+" and "+(curYear+5)+
" order by a.name asc " ;
logger.warning(query);
List<Company> companies = new ArrayList<Company>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Company company = new Company(resultSet.getString("id"),resultSet.getString("name"));
companies.add(company);
}
model.addAttribute("dropdown1d",companies);
model.addAttribute("dropdown2d",companies);
model.addAttribute("firstTimeFromServer",obj5);
this.model = model;
}
}catch(Exception e) {
logger.warning("ERRRRRRRRRRROR: "+e.getMessage());
e.printStackTrace();
}
}
| public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){
try {
Statement statement = con.createStatement();
String query=null;
ResultSet resultSet = null;
TitleArray titleArray= new TitleArray("AUSTRIA","AGRICULTURAL TRACTOR", "SALES" );
int countryId = 7; //Austria
String multiplier="";
if (access.equals("c")) {
titleArray = new TitleArray("CHINA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 210000; //China
multiplier="*10000";
}
if (access.equals("i")) {
titleArray = new TitleArray("INDIA","AGRICULTURAL TRACTOR", "SALES" );
countryId = 20000000; //India
multiplier="*200000";
}
query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 ";
List<Year> years = new ArrayList<Year>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1"));
years.add(year);
for (int i=1;i<=10;i++) {
Year nextYear = new Year(
Integer.toString(Integer.parseInt(year.getId())+i),
Integer.toString(Integer.parseInt(year.getId())+i));
years.add(nextYear);
}
}
YearArray yearArray = new YearArray("Company",years,"TOTAL");
ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray());
String query2="";
if (access.equals("w")) {
query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " +
" from Facts_w a, Company b, Country c, Product d "+
" where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+
" and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+
" group by a.year, substr(b.name,1,20), d.name, 'EUROPE' " +
" order by b.name , a.year asc ";
}else {
query2 = " select a.year, a.quantity, substr(b.name,1,20) as name from Facts_"+access+" a, Company b, Country c " +
" where a.companyid=b.id " +
" and a.countryid=c.id " +
" and c.id="+countryId +
" and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " +
" and a.sales_production= 1" +
" and a.productid=1"+multiplier +
" and a.access = '" + access + "' " +
" and b.name!='ALL COMPANIES' " +
" order by b.name , a.year asc";
}
logger.warning(query2);
resultSet = statement.executeQuery(query2);
String currentCompany="";
JSONObject obj2a = null;
JSONArray array7 = new JSONArray();
totalLine2 = new HashMap<String,Integer>();
otherLine2 = new HashMap<String,Integer>();
while (resultSet.next()) {
int totalQuantity=0;
if (totalLine2.get(resultSet.getString("year"))!= null) {
totalQuantity= totalLine2.get(resultSet.getString("year"));
}
totalQuantity += Integer.parseInt(resultSet.getString("quantity"));
totalLine2.put(resultSet.getString("year"), totalQuantity);
int otherQuantity=0;
if (otherLine2.get(resultSet.getString("year"))!= null) {
otherQuantity= otherLine2.get(resultSet.getString("year"));
}
otherQuantity += Integer.parseInt(resultSet.getString("quantity"));
otherLine2.put(resultSet.getString("year"), otherQuantity);
if (!currentCompany.equals(resultSet.getString("name"))) {
if (!currentCompany.equals("")){
array7.put(obj2a);
}
obj2a = new JSONObject();
currentCompany=resultSet.getString("name");
obj2a.put("Company",currentCompany);
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
} else {
obj2a.put(resultSet.getString("year"),resultSet.getString("quantity"));
}
}
if (obj2a != null) {
array7.put(obj2a);
}
JSONObject obj7 = new JSONObject();
obj7.put("myData", array7);
JSONArray array4 = new JSONArray();
array4.put(columnModel.getModelObject());
array4.put(yearArray.getJsonYearObject());
array4.put(obj7);
array4.put(titleArray.getJsonTitleObject());
JSONObject obj5 = new JSONObject();
obj5.put("tabData", array4);
AddJsonRowTotal aj = new AddJsonRowTotal(obj5);
JSONObject objTotal = new JSONObject();
objTotal.put("Company","TOTAL");
Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Integer> pairs = it.next();
objTotal.put(pairs.getKey(), pairs.getValue());
}
objTotal.put("TOTAL", aj.getTotal());
JSONArray array8 = new JSONArray();
if (objTotal != null) {
array8.put(objTotal);
JSONObject obj8 = new JSONObject();
obj8.put("myTotals", array8);
model.addAttribute("jsonTotal",obj8);
}
model.addAttribute("jsonData",obj5);
logger.warning(obj5.toString());
if (request.getParameter("list") == null){
query = "select id, UPPER(country) as country from Country where id != 0 and access = '"+access+"' order by country asc " ;
List<Country> countries = new ArrayList<Country>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Country country = new Country(resultSet.getString("id"),resultSet.getString("country"));
countries.add(country);
}
model.addAttribute("dropdown1a",countries);
model.addAttribute("dropdown2a",countries);
query = "select id, UPPER(name) as name from Product where id != 0 and access = '"+access+"' order by name asc " ;
List<Product> products = new ArrayList<Product>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Product product = new Product(resultSet.getString("id"),resultSet.getString("name"));
products.add(product);
}
model.addAttribute("dropdown1b",products);
model.addAttribute("dropdown2b",products);
model.addAttribute("dropdown1c",years);
model.addAttribute("dropdown2c",years);
query = " select distinct a.id, UPPER(substr(a.name,1,20)) as name from Company a , Facts_"+access+" b " +
" where a.id != 0" +
" and b.companyid = a.id " +
" and b.access = '" + access +"' and " +
" a.access = '" + access + "' " +
" and a.name != 'ALL COMPANIES' " +
// " and b.year between "+(curYear - 5)+" and "+(curYear+5)+
" order by a.name asc " ;
logger.warning(query);
List<Company> companies = new ArrayList<Company>();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
Company company = new Company(resultSet.getString("id"),resultSet.getString("name"));
companies.add(company);
}
model.addAttribute("dropdown1d",companies);
model.addAttribute("dropdown2d",companies);
model.addAttribute("firstTimeFromServer",obj5);
this.model = model;
}
}catch(Exception e) {
logger.warning("ERRRRRRRRRRROR: "+e.getMessage());
e.printStackTrace();
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java
index 3be1f3497..8f489ab9e 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IGridLayout.java
@@ -1,1005 +1,1005 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Container;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.RenderSpace;
import com.itmill.toolkit.terminal.gwt.client.StyleConstants;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
import com.itmill.toolkit.terminal.gwt.client.ui.layout.CellBasedLayout;
import com.itmill.toolkit.terminal.gwt.client.ui.layout.ChildComponentContainer;
public class IGridLayout extends SimplePanel implements Paintable, Container {
public static final String CLASSNAME = "i-gridlayout";
private DivElement margin = Document.get().createDivElement();
private final AbsolutePanel canvas = new AbsolutePanel();
private ApplicationConnection client;
protected HashMap<Widget, ChildComponentContainer> widgetToComponentContainer = new HashMap<Widget, ChildComponentContainer>();
private HashMap<Paintable, Cell> paintableToCell = new HashMap<Paintable, Cell>();
private int spacingPixelsHorizontal;
private int spacingPixelsVertical;
private int[] columnWidths;
private int[] rowHeights;
private String height;
private String width;
private int[] colExpandRatioArray;
private int[] rowExpandRatioArray;
private int[] minColumnWidths;
private int[] minRowHeights;
private boolean rendering;
private HashMap<Widget, ChildComponentContainer> nonRenderedWidgets;
public IGridLayout() {
super();
getElement().appendChild(margin);
setStyleName(CLASSNAME);
setWidget(canvas);
}
@Override
protected Element getContainerElement() {
return margin.cast();
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
rendering = true;
this.client = client;
if (client.updateComponent(this, uidl, true)) {
rendering = false;
return;
}
boolean mightToggleVScrollBar = "".equals(height) && !"".equals(width);
boolean mightToggleHScrollBar = "".equals(width) && !"".equals(height);
int wBeforeRender = 0;
int hBeforeRender = 0;
if (mightToggleHScrollBar || mightToggleVScrollBar) {
wBeforeRender = canvas.getOffsetWidth();
hBeforeRender = getOffsetHeight();
}
canvas.setWidth("0px");
handleMargins(uidl);
detectSpacing(uidl);
int cols = uidl.getIntAttribute("w");
int rows = uidl.getIntAttribute("h");
columnWidths = new int[cols];
rowHeights = new int[rows];
if (cells == null) {
cells = new Cell[cols][rows];
} else if (cells.length != cols || cells[0].length != rows) {
Cell[][] newCells = new Cell[cols][rows];
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
if (i < cols && j < rows) {
newCells[i][j] = cells[i][j];
}
}
}
cells = newCells;
}
nonRenderedWidgets = (HashMap<Widget, ChildComponentContainer>) widgetToComponentContainer
.clone();
final int[] alignments = uidl.getIntArrayAttribute("alignments");
int alignmentIndex = 0;
LinkedList<Cell> pendingCells = new LinkedList<Cell>();
LinkedList<Cell> relativeHeighted = new LinkedList<Cell>();
for (final Iterator i = uidl.getChildIterator(); i.hasNext();) {
final UIDL r = (UIDL) i.next();
if ("gr".equals(r.getTag())) {
for (final Iterator j = r.getChildIterator(); j.hasNext();) {
final UIDL c = (UIDL) j.next();
if ("gc".equals(c.getTag())) {
Cell cell = getCell(c);
if (cell.hasContent()) {
boolean rendered = cell.renderIfNoRelativeWidth();
cell.alignment = alignments[alignmentIndex++];
if (!rendered) {
pendingCells.add(cell);
}
if (cell.colspan > 1) {
storeColSpannedCell(cell);
} else if (rendered) {
// strore non-colspanned widths to columnWidth
// array
if (columnWidths[cell.col] < cell.getWidth()) {
columnWidths[cell.col] = cell.getWidth();
}
}
if (cell.hasRelativeHeight()) {
relativeHeighted.add(cell);
}
}
}
}
}
}
distributeColSpanWidths();
colExpandRatioArray = uidl.getIntArrayAttribute("colExpand");
rowExpandRatioArray = uidl.getIntArrayAttribute("rowExpand");
minColumnWidths = cloneArray(columnWidths);
expandColumns();
renderRemainingComponentsWithNoRelativeHeight(pendingCells);
detectRowHeights();
expandRows();
renderRemainingComponents(pendingCells);
for (Cell cell : relativeHeighted) {
Widget widget2 = cell.cc.getWidget();
client.handleComponentRelativeSize(widget2);
}
layoutCells();
// clean non rendered components
for (Widget w : nonRenderedWidgets.keySet()) {
ChildComponentContainer childComponentContainer = widgetToComponentContainer
.get(w);
paintableToCell.remove(w);
widgetToComponentContainer.remove(w);
childComponentContainer.removeFromParent();
client.unregisterPaintable((Paintable) w);
}
nonRenderedWidgets = null;
rendering = false;
boolean needsRelativeSizeCheck = false;
if (mightToggleHScrollBar && wBeforeRender != canvas.getOffsetWidth()) {
needsRelativeSizeCheck = true;
}
if (mightToggleVScrollBar && hBeforeRender != getOffsetHeight()) {
needsRelativeSizeCheck = true;
}
if (needsRelativeSizeCheck) {
client.handleComponentRelativeSize(this);
}
}
private static int[] cloneArray(int[] toBeCloned) {
int[] clone = new int[toBeCloned.length];
for (int i = 0; i < clone.length; i++) {
clone[i] = toBeCloned[i] * 1;
}
return clone;
}
private void expandRows() {
if (!"".equals(height)) {
int usedSpace = minRowHeights[0];
for (int i = 1; i < minRowHeights.length; i++) {
usedSpace += spacingPixelsVertical + minRowHeights[i];
}
int availableSpace = getOffsetHeight() - marginTopAndBottom;
int excessSpace = availableSpace - usedSpace;
int distributed = 0;
if (excessSpace > 0) {
for (int i = 0; i < rowHeights.length; i++) {
int ew = excessSpace * rowExpandRatioArray[i] / 1000;
rowHeights[i] = minRowHeights[i] + ew;
distributed += ew;
}
excessSpace -= distributed;
int c = 0;
while (excessSpace > 0) {
rowHeights[c % rowHeights.length]++;
excessSpace--;
c++;
}
}
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if (!height.equals(this.height)) {
this.height = height;
if (!rendering) {
expandRows();
layoutCells();
for (Paintable c : paintableToCell.keySet()) {
client.handleComponentRelativeSize((Widget) c);
}
}
}
}
@Override
public void setWidth(String width) {
super.setWidth(width);
if (!width.equals(this.width)) {
this.width = width;
if (!rendering) {
int[] oldWidths = cloneArray(columnWidths);
expandColumns();
boolean heightChanged = false;
HashSet<Integer> dirtyRows = null;
for (int i = 0; i < oldWidths.length; i++) {
if (columnWidths[i] != oldWidths[i]) {
Cell[] column = cells[i];
for (int j = 0; j < column.length; j++) {
Cell c = column[j];
if (c != null && c.widthCanAffectHeight()) {
c.cc.setContainerSize(c.getAvailableWidth(), c
.getAvailableHeight());
client.handleComponentRelativeSize(c.cc
.getWidget());
c.cc.updateWidgetSize();
int newHeight = c.getHeight();
if (columnWidths[i] < oldWidths[i]
&& newHeight > minRowHeights[j]) {
minRowHeights[j] = newHeight;
if (newHeight > rowHeights[j]) {
rowHeights[j] = newHeight;
heightChanged = true;
}
} else if (newHeight < minRowHeights[j]) {
// need to recalculate new minimum height
// for this row
if (dirtyRows == null) {
dirtyRows = new HashSet<Integer>();
}
dirtyRows.add(j);
}
}
}
}
}
if (dirtyRows != null) {
/* flag indicating that there is a potential row shrinking */
boolean rowMayShrink = false;
for (Integer rowIndex : dirtyRows) {
int oldMinimum = minRowHeights[rowIndex];
int newMinimum = 0;
for (int colIndex = 0; colIndex < columnWidths.length; colIndex++) {
Cell cell = cells[colIndex][rowIndex];
if (cell != null && !cell.hasRelativeHeight()
&& cell.getHeight() > newMinimum) {
newMinimum = cell.getHeight();
}
}
if (newMinimum < oldMinimum) {
minRowHeights[rowIndex] = rowHeights[rowIndex] = newMinimum;
rowMayShrink = true;
}
}
if (rowMayShrink) {
distributeRowSpanHeights();
minRowHeights = cloneArray(rowHeights);
heightChanged = true;
}
}
layoutCells();
for (Paintable c : paintableToCell.keySet()) {
client.handleComponentRelativeSize((Widget) c);
}
if (heightChanged && "".equals(height)) {
Set<Widget> s = new HashSet<Widget>();
s.add(this);
Util.componentSizeUpdated(s);
}
}
}
}
private void expandColumns() {
if (!"".equals(width)) {
int usedSpace = minColumnWidths[0];
for (int i = 1; i < minColumnWidths.length; i++) {
usedSpace += spacingPixelsHorizontal + minColumnWidths[i];
}
canvas.setWidth("");
int availableSpace = canvas.getOffsetWidth();
int excessSpace = availableSpace - usedSpace;
int distributed = 0;
if (excessSpace > 0) {
for (int i = 0; i < columnWidths.length; i++) {
int ew = excessSpace * colExpandRatioArray[i] / 1000;
columnWidths[i] = minColumnWidths[i] + ew;
distributed += ew;
}
excessSpace -= distributed;
int c = 0;
while (excessSpace > 0) {
columnWidths[c % columnWidths.length]++;
excessSpace--;
c++;
}
}
}
}
private void layoutCells() {
int x = 0;
int y = 0;
for (int i = 0; i < cells.length; i++) {
y = 0;
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
if (cell != null) {
cell.layout(x, y);
}
y += rowHeights[j] + spacingPixelsVertical;
}
x += columnWidths[i] + spacingPixelsHorizontal;
}
if ("".equals(width)) {
canvas.setWidth((x - spacingPixelsHorizontal) + "px");
} else {
// main element defines width
canvas.setWidth("");
}
int canvasHeight;
if ("".equals(height)) {
canvasHeight = y - spacingPixelsVertical;
} else {
canvasHeight = getOffsetHeight() - marginTopAndBottom;
}
canvas.setHeight(canvasHeight + "px");
}
private void renderRemainingComponents(LinkedList<Cell> pendingCells) {
for (Cell cell : pendingCells) {
cell.render();
}
}
private void detectRowHeights() {
// collect min rowheight from non-rowspanned cells
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
if (cell != null) {
/*
* Setting fixing container width may in some situations
* affect height. Example: Label with wrapping text without
* or with relative width.
*/
if (cell.cc != null && cell.widthCanAffectHeight()) {
cell.cc.setWidth(cell.getAvailableWidth() + "px");
cell.cc.updateWidgetSize();
}
if (cell.rowspan == 1) {
if (rowHeights[j] < cell.getHeight()) {
rowHeights[j] = cell.getHeight();
}
} else {
storeRowSpannedCell(cell);
}
}
}
}
distributeRowSpanHeights();
minRowHeights = cloneArray(rowHeights);
}
private void storeRowSpannedCell(Cell cell) {
SpanList l = null;
for (SpanList list : rowSpans) {
if (list.span < cell.rowspan) {
continue;
} else {
// insert before this
l = list;
break;
}
}
if (l == null) {
l = new SpanList(cell.rowspan);
rowSpans.add(l);
} else if (l.span != cell.rowspan) {
SpanList newL = new SpanList(cell.rowspan);
rowSpans.add(rowSpans.indexOf(l), newL);
l = newL;
}
l.cells.add(cell);
}
private void renderRemainingComponentsWithNoRelativeHeight(
LinkedList<Cell> pendingCells) {
for (Iterator iterator = pendingCells.iterator(); iterator.hasNext();) {
Cell cell = (Cell) iterator.next();
if (!cell.hasRelativeHeight()) {
cell.render();
iterator.remove();
}
}
}
/**
* Iterates colspanned cells, ensures cols have enough space to accommodate
* them
*/
private void distributeColSpanWidths() {
for (SpanList list : colSpans) {
for (Cell cell : list.cells) {
int width = cell.getWidth();
int allocated = columnWidths[cell.col];
for (int i = 1; i < cell.colspan; i++) {
allocated += spacingPixelsHorizontal
+ columnWidths[cell.col + i];
}
if (allocated < width) {
// columnWidths needs to be expanded due colspanned cell
int neededExtraSpace = width - allocated;
int spaceForColunms = neededExtraSpace / cell.colspan;
for (int i = 0; i < cell.colspan; i++) {
int col = cell.col + i;
columnWidths[col] += spaceForColunms;
neededExtraSpace -= spaceForColunms;
}
if (neededExtraSpace > 0) {
for (int i = 0; i < cell.colspan; i++) {
int col = cell.col + i;
columnWidths[col] += 1;
neededExtraSpace -= 1;
if (neededExtraSpace == 0) {
break;
}
}
}
}
}
}
}
/**
* Iterates rowspanned cells, ensures rows have enough space to accommodate
* them
*/
private void distributeRowSpanHeights() {
for (SpanList list : rowSpans) {
for (Cell cell : list.cells) {
int height = cell.getHeight();
int allocated = rowHeights[cell.row];
for (int i = 1; i < cell.rowspan; i++) {
allocated += spacingPixelsVertical
+ rowHeights[cell.row + i];
}
if (allocated < height) {
// columnWidths needs to be expanded due colspanned cell
int neededExtraSpace = height - allocated;
int spaceForColunms = neededExtraSpace / cell.rowspan;
for (int i = 0; i < cell.rowspan; i++) {
int row = cell.row + i;
rowHeights[row] += spaceForColunms;
neededExtraSpace -= spaceForColunms;
}
if (neededExtraSpace > 0) {
for (int i = 0; i < cell.rowspan; i++) {
int row = cell.row + i;
rowHeights[row] += 1;
neededExtraSpace -= 1;
if (neededExtraSpace == 0) {
break;
}
}
}
}
}
}
}
private LinkedList<SpanList> colSpans = new LinkedList<SpanList>();
private LinkedList<SpanList> rowSpans = new LinkedList<SpanList>();
private int marginTopAndBottom;
private class SpanList {
final int span;
List<Cell> cells = new LinkedList<Cell>();
public SpanList(int span) {
this.span = span;
}
}
private void storeColSpannedCell(Cell cell) {
SpanList l = null;
for (SpanList list : colSpans) {
if (list.span < cell.colspan) {
continue;
} else {
// insert before this
l = list;
break;
}
}
if (l == null) {
l = new SpanList(cell.colspan);
colSpans.add(l);
} else if (l.span != cell.colspan) {
SpanList newL = new SpanList(cell.colspan);
colSpans.add(colSpans.indexOf(l), newL);
l = newL;
}
l.cells.add(cell);
}
private void detectSpacing(UIDL uidl) {
DivElement spacingmeter = Document.get().createDivElement();
spacingmeter.setClassName(CLASSNAME + "-" + "spacing-"
+ (uidl.getBooleanAttribute("spacing") ? "on" : "off"));
spacingmeter.getStyle().setProperty("width", "0");
canvas.getElement().appendChild(spacingmeter);
spacingPixelsHorizontal = spacingmeter.getOffsetWidth();
spacingPixelsVertical = spacingmeter.getOffsetHeight();
canvas.getElement().removeChild(spacingmeter);
}
private void handleMargins(UIDL uidl) {
final IMarginInfo margins = new IMarginInfo(uidl
.getIntAttribute("margins"));
String styles = CLASSNAME + "-margin";
if (margins.hasTop()) {
styles += " " + CLASSNAME + "-" + StyleConstants.MARGIN_TOP;
}
if (margins.hasRight()) {
styles += " " + CLASSNAME + "-" + StyleConstants.MARGIN_RIGHT;
}
if (margins.hasBottom()) {
styles += " " + CLASSNAME + "-" + StyleConstants.MARGIN_BOTTOM;
}
if (margins.hasLeft()) {
styles += " " + CLASSNAME + "-" + StyleConstants.MARGIN_LEFT;
}
margin.setClassName(styles);
marginTopAndBottom = margin.getOffsetHeight()
- canvas.getOffsetHeight();
}
public boolean hasChildComponent(Widget component) {
return paintableToCell.containsKey(component);
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
ChildComponentContainer componentContainer = widgetToComponentContainer
.remove(oldComponent);
if (componentContainer == null) {
return;
}
componentContainer.setWidget(newComponent);
widgetToComponentContainer.put(newComponent, componentContainer);
paintableToCell.put((Paintable) newComponent, paintableToCell
.get(oldComponent));
}
public void updateCaption(Paintable component, UIDL uidl) {
ChildComponentContainer cc = widgetToComponentContainer.get(component);
if (cc != null) {
cc.updateCaption(uidl, client);
}
if (!rendering) {
// ensure rel size details are updated
paintableToCell.get(component).updateRelSizeStatus(uidl);
}
}
public boolean requestLayout(final Set<Paintable> changedChildren) {
boolean needsLayout = false;
boolean reDistributeColSpanWidths = false;
boolean reDistributeRowSpanHeights = false;
int offsetHeight = canvas.getOffsetHeight();
int offsetWidth = canvas.getOffsetWidth();
if ("".equals(width) || "".equals(height)) {
needsLayout = true;
}
ArrayList<Integer> dirtyColumns = new ArrayList<Integer>();
ArrayList<Integer> dirtyRows = new ArrayList<Integer>();
for (Paintable paintable : changedChildren) {
Cell cell = paintableToCell.get(paintable);
if (!cell.hasRelativeHeight() || !cell.hasRelativeWidth()) {
// cell sizes will only stay still if only relatively
// sized
// components
// check if changed child affects min col widths
cell.cc.setWidth("");
cell.cc.setHeight("");
cell.cc.updateWidgetSize();
int width = cell.getWidth();
int allocated = columnWidths[cell.col];
for (int i = 1; i < cell.colspan; i++) {
allocated += spacingPixelsHorizontal
+ columnWidths[cell.col + i];
}
if (allocated < width) {
needsLayout = true;
if (cell.colspan == 1) {
// do simple column width expansion
columnWidths[cell.col] = minColumnWidths[cell.col] = width;
} else {
// mark that col span expansion is needed
reDistributeColSpanWidths = true;
}
} else if (allocated != width) {
// size is smaller thant allocated, column might
// shrink
dirtyColumns.add(cell.col);
}
int height = cell.getHeight();
allocated = rowHeights[cell.row];
for (int i = 1; i < cell.rowspan; i++) {
allocated += spacingPixelsVertical
+ rowHeights[cell.row + i];
}
if (allocated < height) {
needsLayout = true;
if (cell.rowspan == 1) {
// do simple row expansion
rowHeights[cell.row] = minRowHeights[cell.row] = height;
} else {
// mark that row span expansion is needed
reDistributeRowSpanHeights = true;
}
} else if (allocated != height) {
// size is smaller than allocated, row might shrink
dirtyRows.add(cell.row);
}
}
}
if (dirtyColumns.size() > 0) {
for (Integer colIndex : dirtyColumns) {
int colW = 0;
for (int i = 0; i < rowHeights.length; i++) {
Cell cell = cells[colIndex][i];
if (cell != null && cell.getChildUIDL() != null
- && !cell.hasRelativeWidth()) {
+ && !cell.hasRelativeWidth() && cell.colspan == 1) {
int width = cell.getWidth();
if (width > colW) {
colW = width;
}
}
}
minColumnWidths[colIndex] = colW;
}
needsLayout = true;
// ensure colspanned columns have enough space
columnWidths = cloneArray(minColumnWidths);
distributeColSpanWidths();
reDistributeColSpanWidths = false;
}
if (reDistributeColSpanWidths) {
distributeColSpanWidths();
}
if (dirtyRows.size() > 0) {
needsLayout = true;
for (Integer rowIndex : dirtyRows) {
// recalculate min row height
int rowH = minRowHeights[rowIndex] = 0;
// loop all columns on row rowIndex
for (int i = 0; i < columnWidths.length; i++) {
Cell cell = cells[i][rowIndex];
if (cell != null && cell.getChildUIDL() != null
- && !cell.hasRelativeHeight()) {
+ && !cell.hasRelativeHeight() && cell.rowspan == 1) {
int h = cell.getHeight();
if (h > rowH) {
rowH = h;
}
}
}
minRowHeights[rowIndex] = rowH;
}
// TODO could check only some row spans
rowHeights = cloneArray(minRowHeights);
distributeRowSpanHeights();
reDistributeRowSpanHeights = false;
}
if (reDistributeRowSpanHeights) {
distributeRowSpanHeights();
}
if (needsLayout) {
expandColumns();
expandRows();
layoutCells();
// loop all relative sized components and update their size
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
if (cell != null
&& (cell.hasRelativeHeight() || cell
.hasRelativeWidth())) {
client.handleComponentRelativeSize(cell.cc.getWidget());
}
}
}
}
if (canvas.getOffsetHeight() != offsetHeight
|| canvas.getOffsetWidth() != offsetWidth) {
return false;
} else {
return true;
}
}
public RenderSpace getAllocatedSpace(Widget child) {
Cell cell = paintableToCell.get(child);
assert cell != null;
return cell.getAllocatedSpace();
}
private Cell[][] cells;
/**
* Private helper class.
*/
private class Cell {
private boolean relHeight = false;
private boolean relWidth = false;
private boolean widthCanAffectHeight = false;
public Cell(UIDL c) {
row = c.getIntAttribute("y");
col = c.getIntAttribute("x");
setUidl(c);
}
public boolean widthCanAffectHeight() {
return widthCanAffectHeight;
}
public boolean hasRelativeHeight() {
return relHeight;
}
public RenderSpace getAllocatedSpace() {
return new RenderSpace(getAvailableWidth()
- cc.getCaptionWidthAfterComponent(), getAvailableHeight()
- cc.getCaptionHeightAboveComponent());
}
public boolean hasContent() {
return childUidl != null;
}
/**
* @return total of spanned cols
*/
private int getAvailableWidth() {
int width = columnWidths[col];
for (int i = 1; i < colspan; i++) {
width += spacingPixelsHorizontal + columnWidths[col + i];
}
return width;
}
/**
* @return total of spanned rows
*/
private int getAvailableHeight() {
int height = rowHeights[row];
for (int i = 1; i < rowspan; i++) {
height += spacingPixelsVertical + rowHeights[row + i];
}
return height;
}
public void layout(int x, int y) {
if (cc != null && cc.isAttached()) {
canvas.setWidgetPosition(cc, x, y);
cc.setContainerSize(getAvailableWidth(), getAvailableHeight());
cc.setAlignment(new AlignmentInfo(alignment));
cc.updateAlignments(getAvailableWidth(), getAvailableHeight());
}
}
public int getWidth() {
if (cc != null) {
int w = cc.getWidgetSize().getWidth()
+ cc.getCaptionWidthAfterComponent();
return w;
} else {
return 0;
}
}
public int getHeight() {
if (cc != null) {
return cc.getWidgetSize().getHeight()
+ cc.getCaptionHeightAboveComponent();
} else {
return 0;
}
}
public boolean renderIfNoRelativeWidth() {
if (childUidl == null) {
return false;
}
if (!hasRelativeWidth()) {
render();
return true;
} else {
return false;
}
}
protected boolean hasRelativeWidth() {
return relWidth;
}
protected void render() {
assert childUidl != null;
Paintable paintable = client.getPaintable(childUidl);
assert paintable != null;
if (cc == null || cc.getWidget() != paintable) {
if (widgetToComponentContainer.containsKey(paintable)) {
cc = widgetToComponentContainer.get(paintable);
cc.setWidth("");
cc.setHeight("");
} else {
cc = new ChildComponentContainer((Widget) paintable,
CellBasedLayout.ORIENTATION_VERTICAL);
widgetToComponentContainer.put((Widget) paintable, cc);
paintableToCell.put(paintable, this);
cc.setWidth("");
canvas.add(cc, 0, 0);
}
}
cc.renderChild(childUidl, client, -1);
cc.updateWidgetSize();
nonRenderedWidgets.remove(paintable);
}
public UIDL getChildUIDL() {
return childUidl;
}
final int row;
final int col;
int colspan = 1;
int rowspan = 1;
UIDL childUidl;
int alignment;
ChildComponentContainer cc;
public void setUidl(UIDL c) {
// Set cell width
colspan = c.hasAttribute("w") ? c.getIntAttribute("w") : 1;
// Set cell height
rowspan = c.hasAttribute("h") ? c.getIntAttribute("h") : 1;
// ensure we will lose reference to old cells, now overlapped by
// this cell
for (int i = 0; i < colspan; i++) {
for (int j = 0; j < rowspan; j++) {
if (i > 0 || j > 0) {
cells[col + i][row + j] = null;
}
}
}
c = c.getChildUIDL(0); // we are interested about childUidl
if (childUidl != null) {
if (c == null) {
// content has vanished, old content will be removed from
// canvas
// later durin render phase
cc = null;
} else if (cc != null
&& cc.getWidget() != client.getPaintable(c)) {
// content has changed
cc = null;
if (widgetToComponentContainer.containsKey(client
.getPaintable(c))) {
// cc exist for this component (moved) use that for this
// cell
cc = widgetToComponentContainer.get(client
.getPaintable(c));
cc.setWidth("");
cc.setHeight("");
}
}
}
childUidl = c;
updateRelSizeStatus(c);
}
protected void updateRelSizeStatus(UIDL uidl) {
if (uidl != null && !uidl.getBooleanAttribute("cached")) {
if (uidl.hasAttribute("height")
&& uidl.getStringAttribute("height").contains("%")) {
relHeight = true;
} else {
relHeight = false;
}
if (uidl.hasAttribute("width")) {
widthCanAffectHeight = relWidth = uidl.getStringAttribute(
"width").contains("%");
if (uidl.hasAttribute("height")) {
widthCanAffectHeight = false;
}
} else {
widthCanAffectHeight = !uidl.hasAttribute("height");
relWidth = false;
}
}
}
}
private Cell getCell(UIDL c) {
int row = c.getIntAttribute("y");
int col = c.getIntAttribute("x");
Cell cell = cells[col][row];
if (cell == null) {
cell = new Cell(c);
cells[col][row] = cell;
} else {
cell.setUidl(c);
}
return cell;
}
}
| false | true | public boolean requestLayout(final Set<Paintable> changedChildren) {
boolean needsLayout = false;
boolean reDistributeColSpanWidths = false;
boolean reDistributeRowSpanHeights = false;
int offsetHeight = canvas.getOffsetHeight();
int offsetWidth = canvas.getOffsetWidth();
if ("".equals(width) || "".equals(height)) {
needsLayout = true;
}
ArrayList<Integer> dirtyColumns = new ArrayList<Integer>();
ArrayList<Integer> dirtyRows = new ArrayList<Integer>();
for (Paintable paintable : changedChildren) {
Cell cell = paintableToCell.get(paintable);
if (!cell.hasRelativeHeight() || !cell.hasRelativeWidth()) {
// cell sizes will only stay still if only relatively
// sized
// components
// check if changed child affects min col widths
cell.cc.setWidth("");
cell.cc.setHeight("");
cell.cc.updateWidgetSize();
int width = cell.getWidth();
int allocated = columnWidths[cell.col];
for (int i = 1; i < cell.colspan; i++) {
allocated += spacingPixelsHorizontal
+ columnWidths[cell.col + i];
}
if (allocated < width) {
needsLayout = true;
if (cell.colspan == 1) {
// do simple column width expansion
columnWidths[cell.col] = minColumnWidths[cell.col] = width;
} else {
// mark that col span expansion is needed
reDistributeColSpanWidths = true;
}
} else if (allocated != width) {
// size is smaller thant allocated, column might
// shrink
dirtyColumns.add(cell.col);
}
int height = cell.getHeight();
allocated = rowHeights[cell.row];
for (int i = 1; i < cell.rowspan; i++) {
allocated += spacingPixelsVertical
+ rowHeights[cell.row + i];
}
if (allocated < height) {
needsLayout = true;
if (cell.rowspan == 1) {
// do simple row expansion
rowHeights[cell.row] = minRowHeights[cell.row] = height;
} else {
// mark that row span expansion is needed
reDistributeRowSpanHeights = true;
}
} else if (allocated != height) {
// size is smaller than allocated, row might shrink
dirtyRows.add(cell.row);
}
}
}
if (dirtyColumns.size() > 0) {
for (Integer colIndex : dirtyColumns) {
int colW = 0;
for (int i = 0; i < rowHeights.length; i++) {
Cell cell = cells[colIndex][i];
if (cell != null && cell.getChildUIDL() != null
&& !cell.hasRelativeWidth()) {
int width = cell.getWidth();
if (width > colW) {
colW = width;
}
}
}
minColumnWidths[colIndex] = colW;
}
needsLayout = true;
// ensure colspanned columns have enough space
columnWidths = cloneArray(minColumnWidths);
distributeColSpanWidths();
reDistributeColSpanWidths = false;
}
if (reDistributeColSpanWidths) {
distributeColSpanWidths();
}
if (dirtyRows.size() > 0) {
needsLayout = true;
for (Integer rowIndex : dirtyRows) {
// recalculate min row height
int rowH = minRowHeights[rowIndex] = 0;
// loop all columns on row rowIndex
for (int i = 0; i < columnWidths.length; i++) {
Cell cell = cells[i][rowIndex];
if (cell != null && cell.getChildUIDL() != null
&& !cell.hasRelativeHeight()) {
int h = cell.getHeight();
if (h > rowH) {
rowH = h;
}
}
}
minRowHeights[rowIndex] = rowH;
}
// TODO could check only some row spans
rowHeights = cloneArray(minRowHeights);
distributeRowSpanHeights();
reDistributeRowSpanHeights = false;
}
if (reDistributeRowSpanHeights) {
distributeRowSpanHeights();
}
if (needsLayout) {
expandColumns();
expandRows();
layoutCells();
// loop all relative sized components and update their size
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
if (cell != null
&& (cell.hasRelativeHeight() || cell
.hasRelativeWidth())) {
client.handleComponentRelativeSize(cell.cc.getWidget());
}
}
}
}
if (canvas.getOffsetHeight() != offsetHeight
|| canvas.getOffsetWidth() != offsetWidth) {
return false;
} else {
return true;
}
}
| public boolean requestLayout(final Set<Paintable> changedChildren) {
boolean needsLayout = false;
boolean reDistributeColSpanWidths = false;
boolean reDistributeRowSpanHeights = false;
int offsetHeight = canvas.getOffsetHeight();
int offsetWidth = canvas.getOffsetWidth();
if ("".equals(width) || "".equals(height)) {
needsLayout = true;
}
ArrayList<Integer> dirtyColumns = new ArrayList<Integer>();
ArrayList<Integer> dirtyRows = new ArrayList<Integer>();
for (Paintable paintable : changedChildren) {
Cell cell = paintableToCell.get(paintable);
if (!cell.hasRelativeHeight() || !cell.hasRelativeWidth()) {
// cell sizes will only stay still if only relatively
// sized
// components
// check if changed child affects min col widths
cell.cc.setWidth("");
cell.cc.setHeight("");
cell.cc.updateWidgetSize();
int width = cell.getWidth();
int allocated = columnWidths[cell.col];
for (int i = 1; i < cell.colspan; i++) {
allocated += spacingPixelsHorizontal
+ columnWidths[cell.col + i];
}
if (allocated < width) {
needsLayout = true;
if (cell.colspan == 1) {
// do simple column width expansion
columnWidths[cell.col] = minColumnWidths[cell.col] = width;
} else {
// mark that col span expansion is needed
reDistributeColSpanWidths = true;
}
} else if (allocated != width) {
// size is smaller thant allocated, column might
// shrink
dirtyColumns.add(cell.col);
}
int height = cell.getHeight();
allocated = rowHeights[cell.row];
for (int i = 1; i < cell.rowspan; i++) {
allocated += spacingPixelsVertical
+ rowHeights[cell.row + i];
}
if (allocated < height) {
needsLayout = true;
if (cell.rowspan == 1) {
// do simple row expansion
rowHeights[cell.row] = minRowHeights[cell.row] = height;
} else {
// mark that row span expansion is needed
reDistributeRowSpanHeights = true;
}
} else if (allocated != height) {
// size is smaller than allocated, row might shrink
dirtyRows.add(cell.row);
}
}
}
if (dirtyColumns.size() > 0) {
for (Integer colIndex : dirtyColumns) {
int colW = 0;
for (int i = 0; i < rowHeights.length; i++) {
Cell cell = cells[colIndex][i];
if (cell != null && cell.getChildUIDL() != null
&& !cell.hasRelativeWidth() && cell.colspan == 1) {
int width = cell.getWidth();
if (width > colW) {
colW = width;
}
}
}
minColumnWidths[colIndex] = colW;
}
needsLayout = true;
// ensure colspanned columns have enough space
columnWidths = cloneArray(minColumnWidths);
distributeColSpanWidths();
reDistributeColSpanWidths = false;
}
if (reDistributeColSpanWidths) {
distributeColSpanWidths();
}
if (dirtyRows.size() > 0) {
needsLayout = true;
for (Integer rowIndex : dirtyRows) {
// recalculate min row height
int rowH = minRowHeights[rowIndex] = 0;
// loop all columns on row rowIndex
for (int i = 0; i < columnWidths.length; i++) {
Cell cell = cells[i][rowIndex];
if (cell != null && cell.getChildUIDL() != null
&& !cell.hasRelativeHeight() && cell.rowspan == 1) {
int h = cell.getHeight();
if (h > rowH) {
rowH = h;
}
}
}
minRowHeights[rowIndex] = rowH;
}
// TODO could check only some row spans
rowHeights = cloneArray(minRowHeights);
distributeRowSpanHeights();
reDistributeRowSpanHeights = false;
}
if (reDistributeRowSpanHeights) {
distributeRowSpanHeights();
}
if (needsLayout) {
expandColumns();
expandRows();
layoutCells();
// loop all relative sized components and update their size
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
if (cell != null
&& (cell.hasRelativeHeight() || cell
.hasRelativeWidth())) {
client.handleComponentRelativeSize(cell.cc.getWidget());
}
}
}
}
if (canvas.getOffsetHeight() != offsetHeight
|| canvas.getOffsetWidth() != offsetWidth) {
return false;
} else {
return true;
}
}
|
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java
index e6009c92c..94e27bdfd 100644
--- a/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java
+++ b/SeriesGuide/src/com/battlelancer/seriesguide/appwidget/ListWidgetProvider.java
@@ -1,150 +1,150 @@
/*
* Copyright 2012 Uwe Trottmann
*
* 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.battlelancer.seriesguide.appwidget;
import com.battlelancer.seriesguide.beta.R;
import com.battlelancer.seriesguide.enums.WidgetListType;
import com.battlelancer.seriesguide.ui.EpisodeDetailsActivity;
import com.battlelancer.seriesguide.ui.UpcomingRecentActivity;
import com.uwetrottmann.androidutils.AndroidUtils;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.text.format.DateUtils;
import android.widget.RemoteViews;
@TargetApi(11)
public class ListWidgetProvider extends AppWidgetProvider {
public static final String UPDATE = "com.battlelancer.seriesguide.appwidget.UPDATE";
public static final long REPETITION_INTERVAL = 5 * DateUtils.MINUTE_IN_MILLIS;
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
// remove the update alarm if the last widget is gone
Intent update = new Intent(UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pi);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (UPDATE.equals(intent.getAction())) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context,
ListWidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view);
// Toast.makeText(context,
// "ListWidgets called to refresh " + Arrays.toString(appWidgetIds),
// Toast.LENGTH_SHORT).show();
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// update each of the widgets with the remote adapter
for (int i = 0; i < appWidgetIds.length; ++i) {
// Toast.makeText(context, "Refreshing widget " + appWidgetIds[i],
// Toast.LENGTH_SHORT)
// .show();
RemoteViews rv = buildRemoteViews(context, appWidgetIds[i]);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
// set an alarm to update widgets every x mins if the device is awake
Intent update = new Intent(UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(context, 195, update, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()
+ REPETITION_INTERVAL, REPETITION_INTERVAL, pi);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@SuppressWarnings("deprecation")
public static RemoteViews buildRemoteViews(Context context, int appWidgetId) {
// Here we setup the intent which points to the StackViewService
// which will provide the views for this collection.
Intent intent = new Intent(context, ListWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// When intents are compared, the extras are ignored, so we need to
// embed the extras into the data so that the extras will not be
// ignored.
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11);
if (AndroidUtils.isICSOrHigher()) {
rv.setRemoteAdapter(R.id.list_view, intent);
} else {
rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent);
}
// The empty view is displayed when the collection has no items. It
// should be a sibling of the collection view.
rv.setEmptyView(R.id.list_view, R.id.empty_view);
// change title based on config
SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0);
int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId,
WidgetListType.UPCOMING.index);
int activityTab = 0;
if (typeIndex == WidgetListType.RECENT.index) {
- activityTab = 0;
+ activityTab = 1;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent));
} else {
- activityTab = 1;
+ activityTab = 0;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming));
}
// Create an Intent to launch Upcoming
Intent pi = new Intent(context, UpcomingRecentActivity.class);
pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab);
pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent);
// Create intents for items to launch an EpisodeDetailsActivity
Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class);
PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate);
return rv;
}
}
| false | true | public static RemoteViews buildRemoteViews(Context context, int appWidgetId) {
// Here we setup the intent which points to the StackViewService
// which will provide the views for this collection.
Intent intent = new Intent(context, ListWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// When intents are compared, the extras are ignored, so we need to
// embed the extras into the data so that the extras will not be
// ignored.
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11);
if (AndroidUtils.isICSOrHigher()) {
rv.setRemoteAdapter(R.id.list_view, intent);
} else {
rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent);
}
// The empty view is displayed when the collection has no items. It
// should be a sibling of the collection view.
rv.setEmptyView(R.id.list_view, R.id.empty_view);
// change title based on config
SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0);
int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId,
WidgetListType.UPCOMING.index);
int activityTab = 0;
if (typeIndex == WidgetListType.RECENT.index) {
activityTab = 0;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent));
} else {
activityTab = 1;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming));
}
// Create an Intent to launch Upcoming
Intent pi = new Intent(context, UpcomingRecentActivity.class);
pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab);
pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent);
// Create intents for items to launch an EpisodeDetailsActivity
Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class);
PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate);
return rv;
}
| public static RemoteViews buildRemoteViews(Context context, int appWidgetId) {
// Here we setup the intent which points to the StackViewService
// which will provide the views for this collection.
Intent intent = new Intent(context, ListWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
// When intents are compared, the extras are ignored, so we need to
// embed the extras into the data so that the extras will not be
// ignored.
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.appwidget_v11);
if (AndroidUtils.isICSOrHigher()) {
rv.setRemoteAdapter(R.id.list_view, intent);
} else {
rv.setRemoteAdapter(appWidgetId, R.id.list_view, intent);
}
// The empty view is displayed when the collection has no items. It
// should be a sibling of the collection view.
rv.setEmptyView(R.id.list_view, R.id.empty_view);
// change title based on config
SharedPreferences prefs = context.getSharedPreferences(ListWidgetConfigure.PREFS_NAME, 0);
int typeIndex = prefs.getInt(ListWidgetConfigure.PREF_LISTTYPE_KEY + appWidgetId,
WidgetListType.UPCOMING.index);
int activityTab = 0;
if (typeIndex == WidgetListType.RECENT.index) {
activityTab = 1;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.recent));
} else {
activityTab = 0;
rv.setTextViewText(R.id.widgetTitle, context.getString(R.string.upcoming));
}
// Create an Intent to launch Upcoming
Intent pi = new Intent(context, UpcomingRecentActivity.class);
pi.putExtra(UpcomingRecentActivity.InitBundle.SELECTED_TAB, activityTab);
pi.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, pi,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent);
// Create intents for items to launch an EpisodeDetailsActivity
Intent itemIntent = new Intent(context, EpisodeDetailsActivity.class);
PendingIntent pendingIntentTemplate = PendingIntent.getActivity(context, 1, itemIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate);
return rv;
}
|
diff --git a/src/edu/ucla/cens/genjson/PromptGroupThreeJsonMessageCreator.java b/src/edu/ucla/cens/genjson/PromptGroupThreeJsonMessageCreator.java
index c716088c..81664b4d 100644
--- a/src/edu/ucla/cens/genjson/PromptGroupThreeJsonMessageCreator.java
+++ b/src/edu/ucla/cens/genjson/PromptGroupThreeJsonMessageCreator.java
@@ -1,184 +1,184 @@
package edu.ucla.cens.genjson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
/**
* Simulator of phone/sensor messages that correspond to the prompt type and the prompt group id three ("diary" group).
* See the <a href="http://www.lecs.cs.ucla.edu/wikis/andwellness/index.php/AndWellness-JSON">JSON Protocol documentation</a>
* and the <a href="http://www.lecs.cs.ucla.edu/wikis/andwellness/index.php/AndWellness-Prompts">Prompt Spec</a> on the wiki for
* details.
*
* @author selsky
*/
public class PromptGroupThreeJsonMessageCreator implements JsonMessageCreator {
// # Diary group
// {
// "date":"2009-11-03 10:18:33",
// "time":1257272467077,
// "timezone":"EST",
// "location": {
// "latitude":38.8977,
// "longitude":-77.0366
// },
// "version_id":1,
// "group_id":3,
// "tags": [],
// "responses":[
// {"prompt_id":1,
// "response":0},
// {"prompt_id":2,
// "response":0},
// {"prompt_id":3,
// "response":0},
// {"prompt_id":4,
// "response":0},
// {"prompt_id":5,
// "response":0},
// {"prompt_id":6,
// "response":0},
// {"prompt_id":7,
// "response":0},
// {"prompt_id":8,
// "response":0},
// {"prompt_id":9,
// "response":0},
// {"prompt_id":10,
// "response":0},
// {"prompt_id":11,
// "response":0},
// {"prompt_id":12,
// "response":0},
// {"prompt_id":13,
// "response":["t","t","t","t","t","t"]},
// {"prompt_id":14,
// "response":0},
// {"prompt_id":15,
// "response":0}
// {"prompt_id":16,
// "response":0},
// {"prompt_id":17,
// "response":0},
// {"prompt_id":18,
// "response":0},
// {"prompt_id":19,
// "response":0},
// {"prompt_id":20,
// "response":0},
// {"prompt_id":21,
// "response":0}
// ]
// }
/**
* Returns a JSONArray with numberOfEntries elements that are all of the prompt group id 3 type.
*/
public JSONArray createMessage(int numberOfEntries) {
JSONArray jsonArray = new JSONArray();
String tz = ValueCreator.tz(); // use the same tz for all messages in the returned array (the most likely use case)
int versionId = 1;
- int groupId = 1;
+ int groupId = 3;
List<String> tags = new ArrayList<String>();
for(int i = 0; i < numberOfEntries; i++) {
String date = ValueCreator.date();
long epoch = ValueCreator.epoch();
double latitude = ValueCreator.latitude();
double longitude = ValueCreator.longitude();
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", date);
map.put("time", epoch);
map.put("timezone", tz);
map.put("version_id", versionId);
map.put("group_id", groupId);
map.put("tags", tags); // always empty for now
Map<String, Object> location = new HashMap<String, Object>();
location.put("latitude", latitude);
location.put("longitude", longitude);
map.put("location", location);
List<Map<String, Object>> responses = new ArrayList<Map<String, Object>>();
// p0 is simply a "parent" question
for(int j = 1; j < 4; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
for(int j = 4; j < 9; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(5));
responses.add(p);
}
for(int j = 9; j < 12; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p12 = new HashMap<String, Object>();
p12.put("prompt_id", 12);
p12.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p12);
List<String> booleans = new ArrayList<String>();
for(int j = 0; j < 6; j++) {
booleans.add(ValueCreator.randomBoolean() ? "t" : "f");
}
Map<String, Object> p13 = new HashMap<String, Object>();
p13.put("prompt_id", 13);
p13.put("response", booleans);
responses.add(p13);
for(int j = 14; j < 17; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(10));
responses.add(p);
}
for(int j = 17; j < 19; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p19 = new HashMap<String, Object>();
p19.put("prompt_id", 19);
p19.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p19);
Map<String, Object> p20 = new HashMap<String, Object>();
p20.put("prompt_id", 20);
p20.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p20);
Map<String, Object> p21 = new HashMap<String, Object>();
p21.put("prompt_id", 21);
p21.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p21);
map.put("responses", responses);
jsonArray.put(map);
}
return jsonArray;
}
}
| true | true | public JSONArray createMessage(int numberOfEntries) {
JSONArray jsonArray = new JSONArray();
String tz = ValueCreator.tz(); // use the same tz for all messages in the returned array (the most likely use case)
int versionId = 1;
int groupId = 1;
List<String> tags = new ArrayList<String>();
for(int i = 0; i < numberOfEntries; i++) {
String date = ValueCreator.date();
long epoch = ValueCreator.epoch();
double latitude = ValueCreator.latitude();
double longitude = ValueCreator.longitude();
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", date);
map.put("time", epoch);
map.put("timezone", tz);
map.put("version_id", versionId);
map.put("group_id", groupId);
map.put("tags", tags); // always empty for now
Map<String, Object> location = new HashMap<String, Object>();
location.put("latitude", latitude);
location.put("longitude", longitude);
map.put("location", location);
List<Map<String, Object>> responses = new ArrayList<Map<String, Object>>();
// p0 is simply a "parent" question
for(int j = 1; j < 4; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
for(int j = 4; j < 9; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(5));
responses.add(p);
}
for(int j = 9; j < 12; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p12 = new HashMap<String, Object>();
p12.put("prompt_id", 12);
p12.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p12);
List<String> booleans = new ArrayList<String>();
for(int j = 0; j < 6; j++) {
booleans.add(ValueCreator.randomBoolean() ? "t" : "f");
}
Map<String, Object> p13 = new HashMap<String, Object>();
p13.put("prompt_id", 13);
p13.put("response", booleans);
responses.add(p13);
for(int j = 14; j < 17; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(10));
responses.add(p);
}
for(int j = 17; j < 19; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p19 = new HashMap<String, Object>();
p19.put("prompt_id", 19);
p19.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p19);
Map<String, Object> p20 = new HashMap<String, Object>();
p20.put("prompt_id", 20);
p20.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p20);
Map<String, Object> p21 = new HashMap<String, Object>();
p21.put("prompt_id", 21);
p21.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p21);
map.put("responses", responses);
jsonArray.put(map);
}
return jsonArray;
}
| public JSONArray createMessage(int numberOfEntries) {
JSONArray jsonArray = new JSONArray();
String tz = ValueCreator.tz(); // use the same tz for all messages in the returned array (the most likely use case)
int versionId = 1;
int groupId = 3;
List<String> tags = new ArrayList<String>();
for(int i = 0; i < numberOfEntries; i++) {
String date = ValueCreator.date();
long epoch = ValueCreator.epoch();
double latitude = ValueCreator.latitude();
double longitude = ValueCreator.longitude();
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", date);
map.put("time", epoch);
map.put("timezone", tz);
map.put("version_id", versionId);
map.put("group_id", groupId);
map.put("tags", tags); // always empty for now
Map<String, Object> location = new HashMap<String, Object>();
location.put("latitude", latitude);
location.put("longitude", longitude);
map.put("location", location);
List<Map<String, Object>> responses = new ArrayList<Map<String, Object>>();
// p0 is simply a "parent" question
for(int j = 1; j < 4; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
for(int j = 4; j < 9; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(5));
responses.add(p);
}
for(int j = 9; j < 12; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p12 = new HashMap<String, Object>();
p12.put("prompt_id", 12);
p12.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p12);
List<String> booleans = new ArrayList<String>();
for(int j = 0; j < 6; j++) {
booleans.add(ValueCreator.randomBoolean() ? "t" : "f");
}
Map<String, Object> p13 = new HashMap<String, Object>();
p13.put("prompt_id", 13);
p13.put("response", booleans);
responses.add(p13);
for(int j = 14; j < 17; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomPositiveIntModulus(10));
responses.add(p);
}
for(int j = 17; j < 19; j++) {
Map<String, Object> p = new HashMap<String, Object>();
p.put("prompt_id", j);
p.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p);
}
Map<String, Object> p19 = new HashMap<String, Object>();
p19.put("prompt_id", 19);
p19.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p19);
Map<String, Object> p20 = new HashMap<String, Object>();
p20.put("prompt_id", 20);
p20.put("response", ValueCreator.randomBoolean() ? 1 : 0);
responses.add(p20);
Map<String, Object> p21 = new HashMap<String, Object>();
p21.put("prompt_id", 21);
p21.put("response", ValueCreator.randomPositiveIntModulus(7));
responses.add(p21);
map.put("responses", responses);
jsonArray.put(map);
}
return jsonArray;
}
|
diff --git a/src/main/java/org/codehaus/mojo/osxappbundle/CreateApplicationBundleMojo.java b/src/main/java/org/codehaus/mojo/osxappbundle/CreateApplicationBundleMojo.java
index da33d6a..a1a3fab 100644
--- a/src/main/java/org/codehaus/mojo/osxappbundle/CreateApplicationBundleMojo.java
+++ b/src/main/java/org/codehaus/mojo/osxappbundle/CreateApplicationBundleMojo.java
@@ -1,650 +1,651 @@
package org.codehaus.mojo.osxappbundle;
/*
* Copyright 2001-2008 The Codehaus.
*
* 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.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.zip.ZipArchiver;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.velocity.VelocityComponent;
import org.codehaus.mojo.osxappbundle.encoding.DefaultEncodingDetector;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.ByteArrayInputStream;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Arrays;
/**
* Package dependencies as an Application Bundle for Mac OS X.
*
* @goal bundle
* @phase package
* @requiresDependencyResolution runtime
*/
public class CreateApplicationBundleMojo
extends AbstractMojo
{
/**
* Default includes - everything is included.
*/
private static final String[] DEFAULT_INCLUDES = {"**/**"};
/**
* The Maven Project Object
*
* @parameter default-value="${project}"
* @readonly
*/
private MavenProject project;
/**
* The directory where the application bundle will be created
*
* @parameter default-value="${project.build.directory}/${project.build.finalName}";
*/
private File buildDirectory;
/**
* The location of the generated disk image file
*
* @parameter default-value="${project.build.directory}/${project.build.finalName}.dmg"
*/
private File diskImageFile;
/**
* The location of the Java Application Stub
*
* @parameter default-value="/System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub";
*/
private File javaApplicationStub;
/**
* The main class to execute when double-clicking the Application Bundle
*
* @parameter expression="${mainClass}"
* @required
*/
private String mainClass;
/**
* The name of the Bundle. This is the name that is given to the application bundle;
* and it is also what will show up in the application menu, dock etc.
*
* @parameter default-value="${project.name}"
* @required
*/
private String bundleName;
/**
* The icon file for the bundle
*
* @parameter
*/
private File iconFile;
/**
* The version of the project. Will be used as the value of the CFBundleVersion key.
*
* @parameter default-value="${project.version}"
*/
private String version;
/**
* A value for the JVMVersion key.
*
* @parameter default-value="1.4+"
*/
private String jvmVersion;
/**
* The location of the produced Zip file containing the bundle.
*
* @parameter default-value="${project.build.directory}/${project.build.finalName}-app.zip"
*/
private File zipFile;
/**
* Paths to be put on the classpath in addition to the projects dependencies.
* Might be useful to specifiy locations of dependencies in the provided scope that are not distributed with
* the bundle but have a known location on the system.
* {@see http://jira.codehaus.org/browse/MOJO-874}
*
* @parameter
*/
private List additionalClasspath;
/**
* Additional resources (as a list of FileSet objects) that will be copies into
* the build directory and included in the .dmg and zip files alongside with the
* application bundle.
*
* @parameter
*/
private List additionalResources;
/**
* Velocity Component.
*
* @component
* @readonly
*/
private VelocityComponent velocity;
/**
* The location of the template for Info.plist.
* Classpath is checked before the file system.
*
* @parameter default-value="org/codehaus/mojo/osxappbundle/Info.plist.template"
*/
private String dictionaryFile;
/**
* Options to the JVM, will be used as the value of VMOptions in Info.plist.
*
* @parameter
*/
private String vmOptions;
/**
* The Zip archiver.
*
* @component
* @readonly
*/
private MavenProjectHelper projectHelper;
/**
* The Zip archiver.
*
* @parameter expression="${component.org.codehaus.plexus.archiver.Archiver#zip}"
* @required
* @readonly
*/
private ZipArchiver zipArchiver;
/**
* If this is set to <code>true</code>, the generated DMG file will be internet-enabled.
* The default is ${false}
*
* @parameter default-value="false"
*/
private boolean internetEnable;
/**
* The path to the SetFile tool.
*/
private static final String SET_FILE_PATH = "/Developer/Tools/SetFile";
/**
* Bundle project as a Mac OS X application bundle.
*
* @throws MojoExecutionException If an unexpected error occurs during packaging of the bundle.
*/
public void execute()
throws MojoExecutionException
{
// Set up and create directories
buildDirectory.mkdirs();
File bundleDir = new File( buildDirectory, bundleName + ".app" );
bundleDir.mkdirs();
File contentsDir = new File( bundleDir, "Contents" );
contentsDir.mkdirs();
File resourcesDir = new File( contentsDir, "Resources" );
resourcesDir.mkdirs();
File javaDirectory = new File( resourcesDir, "Java" );
javaDirectory.mkdirs();
File macOSDirectory = new File( contentsDir, "MacOS" );
macOSDirectory.mkdirs();
// Copy in the native java application stub
File stub = new File( macOSDirectory, javaApplicationStub.getName() );
if(! javaApplicationStub.exists()) {
String message = "Can't find JavaApplicationStub binary. File does not exist: " + javaApplicationStub;
if(! isOsX() ) {
message += "\nNOTICE: You are running the osxappbundle plugin on a non OS X platform. To make this work you need to copy the JavaApplicationStub binary into your source tree. Then configure it with the 'javaApplicationStub' configuration property.\nOn an OS X machine, the JavaApplicationStub is typically located under /System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub";
}
throw new MojoExecutionException( message);
} else {
try
{
FileUtils.copyFile( javaApplicationStub, stub );
}
catch ( IOException e )
{
throw new MojoExecutionException(
"Could not copy file " + javaApplicationStub + " to directory " + macOSDirectory, e );
}
}
// Copy icon file to the bundle if specified
if ( iconFile != null )
{
try
{
FileUtils.copyFileToDirectory( iconFile, resourcesDir );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying file " + iconFile + " to " + resourcesDir, e );
}
}
// Resolve and copy in all dependecies from the pom
List files = copyDependencies( javaDirectory );
// Create and write the Info.plist file
File infoPlist = new File( bundleDir, "Contents/Info.plist" );
writeInfoPlist( infoPlist, files );
// Copy specified additional resources into the top level directory
if (additionalResources != null && !additionalResources.isEmpty())
{
copyResources( additionalResources );
}
if ( isOsX() )
{
// Make the stub executable
Commandline chmod = new Commandline();
try
{
chmod.setExecutable( "chmod" );
chmod.createArgument().setValue( "755" );
chmod.createArgument().setValue( stub.getAbsolutePath() );
chmod.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + chmod + " ", e );
}
// This makes sure that the .app dir is actually registered as an application bundle
if ( new File( SET_FILE_PATH ).exists() )
{
Commandline setFile = new Commandline();
try
{
setFile.setExecutable(SET_FILE_PATH);
- setFile.createArgument().setValue( "-a B" );
+ setFile.createArgument().setValue( "-a" );
+ setFile.createArgument().setValue( "B" );
setFile.createArgument().setValue( bundleDir.getAbsolutePath() );
setFile.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + setFile, e );
}
}
else
{
getLog().warn( "Could not set 'Has Bundle' attribute. " +SET_FILE_PATH +" not found, is Developer Tools installed?" );
}
// Create a .dmg file of the app
Commandline dmg = new Commandline();
try
{
dmg.setExecutable( "hdiutil" );
dmg.createArgument().setValue( "create" );
dmg.createArgument().setValue( "-srcfolder" );
dmg.createArgument().setValue( buildDirectory.getAbsolutePath() );
dmg.createArgument().setValue( diskImageFile.getAbsolutePath() );
try
{
dmg.execute().waitFor();
}
catch ( InterruptedException e )
{
throw new MojoExecutionException( "Thread was interrupted while creating DMG " + diskImageFile, e );
}
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error creating disk image " + diskImageFile, e );
}
if(internetEnable) {
try {
Commandline internetEnable = new Commandline();
internetEnable.setExecutable("hdiutil");
internetEnable.createArgument().setValue("internet-enable" );
internetEnable.createArgument().setValue("-yes");
internetEnable.createArgument().setValue(diskImageFile.getAbsolutePath());
internetEnable.execute();
} catch (CommandLineException e) {
throw new MojoExecutionException("Error internet enabling disk image: " + diskImageFile, e);
}
}
projectHelper.attachArtifact(project, "dmg", null, diskImageFile);
}
zipArchiver.setDestFile( zipFile );
try
{
String[] stubPattern = {buildDirectory.getName() + "/" + bundleDir.getName() +"/Contents/MacOS/"
+ javaApplicationStub.getName()};
zipArchiver.addDirectory( buildDirectory.getParentFile(), new String[]{buildDirectory.getName() + "/**"},
stubPattern);
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( buildDirectory.getParentFile() );
scanner.setIncludes( stubPattern);
scanner.scan();
String[] stubs = scanner.getIncludedFiles();
for ( int i = 0; i < stubs.length; i++ )
{
String s = stubs[i];
zipArchiver.addFile( new File( buildDirectory.getParentFile(), s ), s, 0755 );
}
zipArchiver.createArchive();
projectHelper.attachArtifact(project, "zip", null, zipFile);
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "Could not create zip archive of application bundle in " + zipFile, e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IOException creating zip archive of application bundle in " + zipFile,
e );
}
}
private boolean isOsX()
{
return System.getProperty( "mrj.version" ) != null;
}
/**
* Copy all dependencies into the $JAVAROOT directory
*
* @param javaDirectory where to put jar files
* @return A list of file names added
* @throws MojoExecutionException
*/
private List copyDependencies( File javaDirectory )
throws MojoExecutionException
{
ArtifactRepositoryLayout layout = new DefaultRepositoryLayout();
List list = new ArrayList();
File repoDirectory = new File(javaDirectory, "repo");
repoDirectory.mkdirs();
// First, copy the project's own artifact
File artifactFile = project.getArtifact().getFile();
list.add( repoDirectory.getName() +"/" +layout.pathOf(project.getArtifact()));
try
{
FileUtils.copyFile( artifactFile, new File(repoDirectory, layout.pathOf(project.getArtifact())) );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not copy artifact file " + artifactFile + " to " + javaDirectory );
}
Set artifacts = project.getArtifacts();
Iterator i = artifacts.iterator();
while ( i.hasNext() )
{
Artifact artifact = (Artifact) i.next();
File file = artifact.getFile();
File dest = new File(repoDirectory, layout.pathOf(artifact));
getLog().debug( "Adding " + file );
try
{
FileUtils.copyFile( file, dest);
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying file " + file + " into " + javaDirectory, e );
}
list.add( repoDirectory.getName() +"/" + layout.pathOf(artifact) );
}
return list;
}
/**
* Writes an Info.plist file describing this bundle.
*
* @param infoPlist The file to write Info.plist contents to
* @param files A list of file names of the jar files to add in $JAVAROOT
* @throws MojoExecutionException
*/
private void writeInfoPlist( File infoPlist, List files )
throws MojoExecutionException
{
VelocityContext velocityContext = new VelocityContext();
velocityContext.put( "mainClass", mainClass );
velocityContext.put( "cfBundleExecutable", javaApplicationStub.getName());
velocityContext.put( "vmOptions", vmOptions);
velocityContext.put( "bundleName", bundleName );
velocityContext.put( "iconFile", iconFile == null ? "GenericJavaApp.icns" : iconFile.getName() );
velocityContext.put( "version", version );
velocityContext.put( "jvmVersion", jvmVersion );
StringBuffer jarFilesBuffer = new StringBuffer();
jarFilesBuffer.append( "<array>" );
for ( int i = 0; i < files.size(); i++ )
{
String name = (String) files.get( i );
jarFilesBuffer.append( "<string>" );
jarFilesBuffer.append( "$JAVAROOT/" ).append( name );
jarFilesBuffer.append( "</string>" );
}
if ( additionalClasspath != null )
{
for ( int i = 0; i < additionalClasspath.size(); i++ )
{
String pathElement = (String) additionalClasspath.get( i );
jarFilesBuffer.append( "<string>" );
jarFilesBuffer.append( pathElement );
jarFilesBuffer.append( "</string>" );
}
}
jarFilesBuffer.append( "</array>" );
velocityContext.put( "classpath", jarFilesBuffer.toString() );
try
{
String encoding = detectEncoding(dictionaryFile, velocityContext);
getLog().debug( "Detected encoding " + encoding + " for dictionary file " +dictionaryFile );
Writer writer = new OutputStreamWriter( new FileOutputStream(infoPlist), encoding );
velocity.getEngine().mergeTemplate( dictionaryFile, encoding, velocityContext, writer );
writer.close();
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not write Info.plist to file " + infoPlist, e );
}
catch ( ParseErrorException e )
{
throw new MojoExecutionException( "Error parsing " + dictionaryFile, e );
}
catch ( ResourceNotFoundException e )
{
throw new MojoExecutionException( "Could not find resource for template " + dictionaryFile, e );
}
catch ( MethodInvocationException e )
{
throw new MojoExecutionException(
"MethodInvocationException occured merging Info.plist template " + dictionaryFile, e );
}
catch ( Exception e )
{
throw new MojoExecutionException( "Exception occured merging Info.plist template " + dictionaryFile, e );
}
}
private String detectEncoding( String dictionaryFile, VelocityContext velocityContext )
throws Exception
{
StringWriter sw = new StringWriter();
velocity.getEngine().mergeTemplate( dictionaryFile, "utf-8", velocityContext, sw );
return new DefaultEncodingDetector().detectXmlEncoding( new ByteArrayInputStream(sw.toString().getBytes( "utf-8" )) );
}
/**
* Copies given resources to the build directory.
*
* @param fileSets A list of FileSet objects that represent additional resources to copy.
* @throws MojoExecutionException In case af a resource copying error.
*/
private void copyResources( List fileSets )
throws MojoExecutionException
{
final String[] emptyStrArray = {};
for ( Iterator it = fileSets.iterator(); it.hasNext(); )
{
FileSet fileSet = (FileSet) it.next();
File resourceDirectory = new File( fileSet.getDirectory() );
if ( !resourceDirectory.isAbsolute() )
{
resourceDirectory = new File( project.getBasedir(), resourceDirectory.getPath() );
}
if ( !resourceDirectory.exists() )
{
getLog().info( "Additional resource directory does not exist: " + resourceDirectory );
continue;
}
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( resourceDirectory );
if ( fileSet.getIncludes() != null && !fileSet.getIncludes().isEmpty() )
{
scanner.setIncludes( (String[]) fileSet.getIncludes().toArray( emptyStrArray ) );
}
else
{
scanner.setIncludes( DEFAULT_INCLUDES );
}
if ( fileSet.getExcludes() != null && !fileSet.getExcludes().isEmpty() )
{
scanner.setExcludes( (String[]) fileSet.getExcludes().toArray( emptyStrArray ) );
}
if (fileSet.isUseDefaultExcludes())
{
scanner.addDefaultExcludes();
}
scanner.scan();
List includedFiles = Arrays.asList( scanner.getIncludedFiles() );
getLog().info( "Copying " + includedFiles.size() + " additional resource"
+ ( includedFiles.size() > 1 ? "s" : "" ) );
for ( Iterator j = includedFiles.iterator(); j.hasNext(); )
{
String destination = (String) j.next();
File source = new File( resourceDirectory, destination );
File destinationFile = new File( buildDirectory, destination );
if ( !destinationFile.getParentFile().exists() )
{
destinationFile.getParentFile().mkdirs();
}
try
{
FileUtils.copyFile(source, destinationFile);
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying additional resource " + source, e );
}
}
}
}
}
| true | true | public void execute()
throws MojoExecutionException
{
// Set up and create directories
buildDirectory.mkdirs();
File bundleDir = new File( buildDirectory, bundleName + ".app" );
bundleDir.mkdirs();
File contentsDir = new File( bundleDir, "Contents" );
contentsDir.mkdirs();
File resourcesDir = new File( contentsDir, "Resources" );
resourcesDir.mkdirs();
File javaDirectory = new File( resourcesDir, "Java" );
javaDirectory.mkdirs();
File macOSDirectory = new File( contentsDir, "MacOS" );
macOSDirectory.mkdirs();
// Copy in the native java application stub
File stub = new File( macOSDirectory, javaApplicationStub.getName() );
if(! javaApplicationStub.exists()) {
String message = "Can't find JavaApplicationStub binary. File does not exist: " + javaApplicationStub;
if(! isOsX() ) {
message += "\nNOTICE: You are running the osxappbundle plugin on a non OS X platform. To make this work you need to copy the JavaApplicationStub binary into your source tree. Then configure it with the 'javaApplicationStub' configuration property.\nOn an OS X machine, the JavaApplicationStub is typically located under /System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub";
}
throw new MojoExecutionException( message);
} else {
try
{
FileUtils.copyFile( javaApplicationStub, stub );
}
catch ( IOException e )
{
throw new MojoExecutionException(
"Could not copy file " + javaApplicationStub + " to directory " + macOSDirectory, e );
}
}
// Copy icon file to the bundle if specified
if ( iconFile != null )
{
try
{
FileUtils.copyFileToDirectory( iconFile, resourcesDir );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying file " + iconFile + " to " + resourcesDir, e );
}
}
// Resolve and copy in all dependecies from the pom
List files = copyDependencies( javaDirectory );
// Create and write the Info.plist file
File infoPlist = new File( bundleDir, "Contents/Info.plist" );
writeInfoPlist( infoPlist, files );
// Copy specified additional resources into the top level directory
if (additionalResources != null && !additionalResources.isEmpty())
{
copyResources( additionalResources );
}
if ( isOsX() )
{
// Make the stub executable
Commandline chmod = new Commandline();
try
{
chmod.setExecutable( "chmod" );
chmod.createArgument().setValue( "755" );
chmod.createArgument().setValue( stub.getAbsolutePath() );
chmod.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + chmod + " ", e );
}
// This makes sure that the .app dir is actually registered as an application bundle
if ( new File( SET_FILE_PATH ).exists() )
{
Commandline setFile = new Commandline();
try
{
setFile.setExecutable(SET_FILE_PATH);
setFile.createArgument().setValue( "-a B" );
setFile.createArgument().setValue( bundleDir.getAbsolutePath() );
setFile.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + setFile, e );
}
}
else
{
getLog().warn( "Could not set 'Has Bundle' attribute. " +SET_FILE_PATH +" not found, is Developer Tools installed?" );
}
// Create a .dmg file of the app
Commandline dmg = new Commandline();
try
{
dmg.setExecutable( "hdiutil" );
dmg.createArgument().setValue( "create" );
dmg.createArgument().setValue( "-srcfolder" );
dmg.createArgument().setValue( buildDirectory.getAbsolutePath() );
dmg.createArgument().setValue( diskImageFile.getAbsolutePath() );
try
{
dmg.execute().waitFor();
}
catch ( InterruptedException e )
{
throw new MojoExecutionException( "Thread was interrupted while creating DMG " + diskImageFile, e );
}
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error creating disk image " + diskImageFile, e );
}
if(internetEnable) {
try {
Commandline internetEnable = new Commandline();
internetEnable.setExecutable("hdiutil");
internetEnable.createArgument().setValue("internet-enable" );
internetEnable.createArgument().setValue("-yes");
internetEnable.createArgument().setValue(diskImageFile.getAbsolutePath());
internetEnable.execute();
} catch (CommandLineException e) {
throw new MojoExecutionException("Error internet enabling disk image: " + diskImageFile, e);
}
}
projectHelper.attachArtifact(project, "dmg", null, diskImageFile);
}
zipArchiver.setDestFile( zipFile );
try
{
String[] stubPattern = {buildDirectory.getName() + "/" + bundleDir.getName() +"/Contents/MacOS/"
+ javaApplicationStub.getName()};
zipArchiver.addDirectory( buildDirectory.getParentFile(), new String[]{buildDirectory.getName() + "/**"},
stubPattern);
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( buildDirectory.getParentFile() );
scanner.setIncludes( stubPattern);
scanner.scan();
String[] stubs = scanner.getIncludedFiles();
for ( int i = 0; i < stubs.length; i++ )
{
String s = stubs[i];
zipArchiver.addFile( new File( buildDirectory.getParentFile(), s ), s, 0755 );
}
zipArchiver.createArchive();
projectHelper.attachArtifact(project, "zip", null, zipFile);
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "Could not create zip archive of application bundle in " + zipFile, e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IOException creating zip archive of application bundle in " + zipFile,
e );
}
}
| public void execute()
throws MojoExecutionException
{
// Set up and create directories
buildDirectory.mkdirs();
File bundleDir = new File( buildDirectory, bundleName + ".app" );
bundleDir.mkdirs();
File contentsDir = new File( bundleDir, "Contents" );
contentsDir.mkdirs();
File resourcesDir = new File( contentsDir, "Resources" );
resourcesDir.mkdirs();
File javaDirectory = new File( resourcesDir, "Java" );
javaDirectory.mkdirs();
File macOSDirectory = new File( contentsDir, "MacOS" );
macOSDirectory.mkdirs();
// Copy in the native java application stub
File stub = new File( macOSDirectory, javaApplicationStub.getName() );
if(! javaApplicationStub.exists()) {
String message = "Can't find JavaApplicationStub binary. File does not exist: " + javaApplicationStub;
if(! isOsX() ) {
message += "\nNOTICE: You are running the osxappbundle plugin on a non OS X platform. To make this work you need to copy the JavaApplicationStub binary into your source tree. Then configure it with the 'javaApplicationStub' configuration property.\nOn an OS X machine, the JavaApplicationStub is typically located under /System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub";
}
throw new MojoExecutionException( message);
} else {
try
{
FileUtils.copyFile( javaApplicationStub, stub );
}
catch ( IOException e )
{
throw new MojoExecutionException(
"Could not copy file " + javaApplicationStub + " to directory " + macOSDirectory, e );
}
}
// Copy icon file to the bundle if specified
if ( iconFile != null )
{
try
{
FileUtils.copyFileToDirectory( iconFile, resourcesDir );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Error copying file " + iconFile + " to " + resourcesDir, e );
}
}
// Resolve and copy in all dependecies from the pom
List files = copyDependencies( javaDirectory );
// Create and write the Info.plist file
File infoPlist = new File( bundleDir, "Contents/Info.plist" );
writeInfoPlist( infoPlist, files );
// Copy specified additional resources into the top level directory
if (additionalResources != null && !additionalResources.isEmpty())
{
copyResources( additionalResources );
}
if ( isOsX() )
{
// Make the stub executable
Commandline chmod = new Commandline();
try
{
chmod.setExecutable( "chmod" );
chmod.createArgument().setValue( "755" );
chmod.createArgument().setValue( stub.getAbsolutePath() );
chmod.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + chmod + " ", e );
}
// This makes sure that the .app dir is actually registered as an application bundle
if ( new File( SET_FILE_PATH ).exists() )
{
Commandline setFile = new Commandline();
try
{
setFile.setExecutable(SET_FILE_PATH);
setFile.createArgument().setValue( "-a" );
setFile.createArgument().setValue( "B" );
setFile.createArgument().setValue( bundleDir.getAbsolutePath() );
setFile.execute();
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error executing " + setFile, e );
}
}
else
{
getLog().warn( "Could not set 'Has Bundle' attribute. " +SET_FILE_PATH +" not found, is Developer Tools installed?" );
}
// Create a .dmg file of the app
Commandline dmg = new Commandline();
try
{
dmg.setExecutable( "hdiutil" );
dmg.createArgument().setValue( "create" );
dmg.createArgument().setValue( "-srcfolder" );
dmg.createArgument().setValue( buildDirectory.getAbsolutePath() );
dmg.createArgument().setValue( diskImageFile.getAbsolutePath() );
try
{
dmg.execute().waitFor();
}
catch ( InterruptedException e )
{
throw new MojoExecutionException( "Thread was interrupted while creating DMG " + diskImageFile, e );
}
}
catch ( CommandLineException e )
{
throw new MojoExecutionException( "Error creating disk image " + diskImageFile, e );
}
if(internetEnable) {
try {
Commandline internetEnable = new Commandline();
internetEnable.setExecutable("hdiutil");
internetEnable.createArgument().setValue("internet-enable" );
internetEnable.createArgument().setValue("-yes");
internetEnable.createArgument().setValue(diskImageFile.getAbsolutePath());
internetEnable.execute();
} catch (CommandLineException e) {
throw new MojoExecutionException("Error internet enabling disk image: " + diskImageFile, e);
}
}
projectHelper.attachArtifact(project, "dmg", null, diskImageFile);
}
zipArchiver.setDestFile( zipFile );
try
{
String[] stubPattern = {buildDirectory.getName() + "/" + bundleDir.getName() +"/Contents/MacOS/"
+ javaApplicationStub.getName()};
zipArchiver.addDirectory( buildDirectory.getParentFile(), new String[]{buildDirectory.getName() + "/**"},
stubPattern);
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( buildDirectory.getParentFile() );
scanner.setIncludes( stubPattern);
scanner.scan();
String[] stubs = scanner.getIncludedFiles();
for ( int i = 0; i < stubs.length; i++ )
{
String s = stubs[i];
zipArchiver.addFile( new File( buildDirectory.getParentFile(), s ), s, 0755 );
}
zipArchiver.createArchive();
projectHelper.attachArtifact(project, "zip", null, zipFile);
}
catch ( ArchiverException e )
{
throw new MojoExecutionException( "Could not create zip archive of application bundle in " + zipFile, e );
}
catch ( IOException e )
{
throw new MojoExecutionException( "IOException creating zip archive of application bundle in " + zipFile,
e );
}
}
|
diff --git a/extensions/gdx-bullet/src/com/badlogic/gdx/physics/bullet/BulletBuild.java b/extensions/gdx-bullet/src/com/badlogic/gdx/physics/bullet/BulletBuild.java
index 43189f8a4..a0dc4826b 100644
--- a/extensions/gdx-bullet/src/com/badlogic/gdx/physics/bullet/BulletBuild.java
+++ b/extensions/gdx-bullet/src/com/badlogic/gdx/physics/bullet/BulletBuild.java
@@ -1,106 +1,106 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.physics.bullet;
import com.badlogic.gdx.jnigen.AntScriptGenerator;
import com.badlogic.gdx.jnigen.BuildConfig;
import com.badlogic.gdx.jnigen.BuildExecutor;
import com.badlogic.gdx.jnigen.BuildTarget;
import com.badlogic.gdx.jnigen.BuildTarget.TargetOs;
import com.badlogic.gdx.jnigen.NativeCodeGenerator;
public class BulletBuild {
public static void main (String[] args) throws Exception {
// generate C/C++ code
new NativeCodeGenerator().generate("src", "bin", "jni");
// Flags to accomodate SWIG generated code
String cppFlags = "";
// SWIG doesn't emit strict aliasing compliant code
cppFlags += " -fno-strict-aliasing";
// SWIG directors aren't clearly documented to require RTTI, but SWIG
// normally generates a small number of dynamic_casts for director code.
// gdx-bullet's swig build.xml replaces these with static C casts so we
// can compile without RTTI and save some disk space. It seems to work
// with these static casts.
cppFlags += " -fno-rtti";
// Disable profiling (it's on by default). If you change this, you
// must regenerate the SWIG wrappers with the changed value.
cppFlags += " -DBT_NO_PROFILE";
// generate build scripts
String[] excludes = {"src/bullet/BulletMultiThreaded/GpuSoftBodySolvers/**"};
- String[] headers = {"src/bullet/", "src/custom/", "src/extras/serialize/"};
+ String[] headers = {"src/bullet/", "src/custom/", "src/extras/Serialize/"};
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.excludeFromMasterBuildFile = true;
win32home.cExcludes = win32home.cppExcludes = excludes;
win32home.headerDirs = headers;
win32home.cppFlags += cppFlags;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cExcludes = win32.cppExcludes = excludes;
win32.headerDirs = headers;
win32.cppFlags += cppFlags;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cExcludes = win64.cppExcludes = excludes;
win64.headerDirs = headers;
win64.cppFlags += cppFlags;
// special pre and post compile tasks to patch the source and revert the
// changes
//win64.preCompileTask = "<copy todir=\"src\" verbose=\"true\" overwrite=\"true\">" + "<fileset dir=\"../patched\"/>"
//+ "</copy>";
//win64.postCompileTask = "<exec executable=\"svn\" dir=\".\">" + "<arg line=\"revert -R src\"/>" + "</exec>";
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cExcludes = lin32.cppExcludes = excludes;
lin32.headerDirs = headers;
lin32.cppFlags += cppFlags;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cExcludes = lin64.cppExcludes = excludes;
lin64.headerDirs = headers;
lin64.cppFlags += cppFlags;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cExcludes = mac.cppExcludes = excludes;
mac.headerDirs = headers;
mac.cppFlags += cppFlags;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
android.cExcludes = android.cppExcludes = excludes;
android.headerDirs = headers;
android.cppFlags += cppFlags;
BuildTarget ios = BuildTarget.newDefaultTarget(TargetOs.IOS, false);
ios.cExcludes = ios.cppExcludes = excludes;
ios.headerDirs = headers;
ios.cppFlags += cppFlags;
new AntScriptGenerator().generate(new BuildConfig("gdx-bullet"), win32home, win32, win64, lin32, lin64, mac, android, ios);
// build natives
// BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v");
// BuildExecutor.executeAnt("jni/build-linux64.xml", "");
// BuildExecutor.executeAnt("jni/build-android32.xml", "");
// BuildExecutor.executeAnt("jni/build.xml", "pack-natives");
}
}
| true | true | public static void main (String[] args) throws Exception {
// generate C/C++ code
new NativeCodeGenerator().generate("src", "bin", "jni");
// Flags to accomodate SWIG generated code
String cppFlags = "";
// SWIG doesn't emit strict aliasing compliant code
cppFlags += " -fno-strict-aliasing";
// SWIG directors aren't clearly documented to require RTTI, but SWIG
// normally generates a small number of dynamic_casts for director code.
// gdx-bullet's swig build.xml replaces these with static C casts so we
// can compile without RTTI and save some disk space. It seems to work
// with these static casts.
cppFlags += " -fno-rtti";
// Disable profiling (it's on by default). If you change this, you
// must regenerate the SWIG wrappers with the changed value.
cppFlags += " -DBT_NO_PROFILE";
// generate build scripts
String[] excludes = {"src/bullet/BulletMultiThreaded/GpuSoftBodySolvers/**"};
String[] headers = {"src/bullet/", "src/custom/", "src/extras/serialize/"};
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.excludeFromMasterBuildFile = true;
win32home.cExcludes = win32home.cppExcludes = excludes;
win32home.headerDirs = headers;
win32home.cppFlags += cppFlags;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cExcludes = win32.cppExcludes = excludes;
win32.headerDirs = headers;
win32.cppFlags += cppFlags;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cExcludes = win64.cppExcludes = excludes;
win64.headerDirs = headers;
win64.cppFlags += cppFlags;
// special pre and post compile tasks to patch the source and revert the
// changes
//win64.preCompileTask = "<copy todir=\"src\" verbose=\"true\" overwrite=\"true\">" + "<fileset dir=\"../patched\"/>"
//+ "</copy>";
//win64.postCompileTask = "<exec executable=\"svn\" dir=\".\">" + "<arg line=\"revert -R src\"/>" + "</exec>";
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cExcludes = lin32.cppExcludes = excludes;
lin32.headerDirs = headers;
lin32.cppFlags += cppFlags;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cExcludes = lin64.cppExcludes = excludes;
lin64.headerDirs = headers;
lin64.cppFlags += cppFlags;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cExcludes = mac.cppExcludes = excludes;
mac.headerDirs = headers;
mac.cppFlags += cppFlags;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
android.cExcludes = android.cppExcludes = excludes;
android.headerDirs = headers;
android.cppFlags += cppFlags;
BuildTarget ios = BuildTarget.newDefaultTarget(TargetOs.IOS, false);
ios.cExcludes = ios.cppExcludes = excludes;
ios.headerDirs = headers;
ios.cppFlags += cppFlags;
new AntScriptGenerator().generate(new BuildConfig("gdx-bullet"), win32home, win32, win64, lin32, lin64, mac, android, ios);
// build natives
// BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v");
// BuildExecutor.executeAnt("jni/build-linux64.xml", "");
// BuildExecutor.executeAnt("jni/build-android32.xml", "");
// BuildExecutor.executeAnt("jni/build.xml", "pack-natives");
}
| public static void main (String[] args) throws Exception {
// generate C/C++ code
new NativeCodeGenerator().generate("src", "bin", "jni");
// Flags to accomodate SWIG generated code
String cppFlags = "";
// SWIG doesn't emit strict aliasing compliant code
cppFlags += " -fno-strict-aliasing";
// SWIG directors aren't clearly documented to require RTTI, but SWIG
// normally generates a small number of dynamic_casts for director code.
// gdx-bullet's swig build.xml replaces these with static C casts so we
// can compile without RTTI and save some disk space. It seems to work
// with these static casts.
cppFlags += " -fno-rtti";
// Disable profiling (it's on by default). If you change this, you
// must regenerate the SWIG wrappers with the changed value.
cppFlags += " -DBT_NO_PROFILE";
// generate build scripts
String[] excludes = {"src/bullet/BulletMultiThreaded/GpuSoftBodySolvers/**"};
String[] headers = {"src/bullet/", "src/custom/", "src/extras/Serialize/"};
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.excludeFromMasterBuildFile = true;
win32home.cExcludes = win32home.cppExcludes = excludes;
win32home.headerDirs = headers;
win32home.cppFlags += cppFlags;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cExcludes = win32.cppExcludes = excludes;
win32.headerDirs = headers;
win32.cppFlags += cppFlags;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cExcludes = win64.cppExcludes = excludes;
win64.headerDirs = headers;
win64.cppFlags += cppFlags;
// special pre and post compile tasks to patch the source and revert the
// changes
//win64.preCompileTask = "<copy todir=\"src\" verbose=\"true\" overwrite=\"true\">" + "<fileset dir=\"../patched\"/>"
//+ "</copy>";
//win64.postCompileTask = "<exec executable=\"svn\" dir=\".\">" + "<arg line=\"revert -R src\"/>" + "</exec>";
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cExcludes = lin32.cppExcludes = excludes;
lin32.headerDirs = headers;
lin32.cppFlags += cppFlags;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cExcludes = lin64.cppExcludes = excludes;
lin64.headerDirs = headers;
lin64.cppFlags += cppFlags;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cExcludes = mac.cppExcludes = excludes;
mac.headerDirs = headers;
mac.cppFlags += cppFlags;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
android.cExcludes = android.cppExcludes = excludes;
android.headerDirs = headers;
android.cppFlags += cppFlags;
BuildTarget ios = BuildTarget.newDefaultTarget(TargetOs.IOS, false);
ios.cExcludes = ios.cppExcludes = excludes;
ios.headerDirs = headers;
ios.cppFlags += cppFlags;
new AntScriptGenerator().generate(new BuildConfig("gdx-bullet"), win32home, win32, win64, lin32, lin64, mac, android, ios);
// build natives
// BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v");
// BuildExecutor.executeAnt("jni/build-linux64.xml", "");
// BuildExecutor.executeAnt("jni/build-android32.xml", "");
// BuildExecutor.executeAnt("jni/build.xml", "pack-natives");
}
|
diff --git a/src/main/java/jscover/server/WebServer.java b/src/main/java/jscover/server/WebServer.java
index 79086f85..6d9630fd 100644
--- a/src/main/java/jscover/server/WebServer.java
+++ b/src/main/java/jscover/server/WebServer.java
@@ -1,442 +1,442 @@
/**
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
*/
package jscover.server;
import jscover.format.PlainFormatter;
import jscover.format.SourceFormatter;
import jscover.instrument.SourceProcessor;
import jscover.json.JSONDataMerger;
import jscover.util.IoUtils;
import java.io.*;
import java.util.Properties;
public class WebServer extends NanoHTTPD {
private static SourceFormatter sourceFormatter = new PlainFormatter();
private ConfigurationForServer configuration;
private JSONDataMerger jsonDataMerger = new JSONDataMerger();
private File log;
public WebServer(ConfigurationForServer configuration) throws IOException, InterruptedException {
super(configuration.getPort(), configuration.getDocumentRoot());
this.configuration = configuration;
this.log = new File(configuration.getReportDir(), "errors.log");
if (this.log.exists()) {
this.log.delete();
}
File wwwroot = configuration.getDocumentRoot();
myOut.println("Now serving files in port " + configuration.getPort() + " from \"" + wwwroot + "\"");
synchronized (this) {
this.wait();
}
Thread.yield();
Thread.sleep(10);
}
public Response serve(String uri, String method, Properties header, Properties parms, Properties files, String data) {
try {
if (uri.equals("/stop")) {
synchronized (this) {
this.notifyAll();
}
return new NanoHTTPD.Response(HTTP_OK, MIME_PLAINTEXT, "Shutting down server.");
} else if (uri.startsWith("/jscoverage.js")) {
String serverJS = "jscoverage_isServer = true;";
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), IoUtils.loadFromClassPath(uri)+serverJS);
} else if (uri.startsWith("/jscoverage-store")) {
File jsonFile = new File(configuration.getReportDir(), "jscoverage.json");
if (jsonFile.exists()) {
String existingJSON = IoUtils.toString(jsonFile);
data = jsonDataMerger.mergeJSONCoverageData(existingJSON, data);
}
IoUtils.copy(new StringReader(data), jsonFile);
copyResourceToDir("jscoverage.css", configuration.getReportDir());
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
IoUtils.copy(new StringReader(reportHTML), new File(configuration.getReportDir(), "jscoverage.html"));
String reportJS = IoUtils.loadFromClassPath("/jscoverage.js") + "\njscoverage_isReport = true;";
IoUtils.copy(new StringReader(reportJS), new File(configuration.getReportDir(), "jscoverage.js"));
copyResourceToDir("jscoverage-highlight.css", configuration.getReportDir());
copyResourceToDir("jscoverage-ie.css", configuration.getReportDir());
copyResourceToDir("jscoverage-throbber.gif",configuration.getReportDir());
return new NanoHTTPD.Response(HTTP_OK, HTTP_OK, "Report stored at "+configuration.getReportDir());
} else if (uri.startsWith("/jscoverage.html")) {
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), reportHTML);
} else if (uri.startsWith("/jscoverage")) {
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), getClass().getResourceAsStream(uri));
} else if (uri.endsWith(".js") && !configuration.skipInstrumentation(uri)) {
SourceProcessor sourceProcessor = new SourceProcessor(configuration.getCompilerEnvirons(), uri, sourceFormatter, log);
String source = IoUtils.toString(new FileInputStream(myRootDir + uri));
String jsInstrumented = sourceProcessor.processSourceForServer(source);
- return new NanoHTTPD.Response(HTTP_OK, "text/javascript", jsInstrumented);
+ return new NanoHTTPD.Response(HTTP_OK, "application/javascript", jsInstrumented);
} else {
return super.serve(uri, method, header, parms, files, data);
}
} catch (Throwable e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return new NanoHTTPD.Response(HTTP_INTERNALERROR, MIME_PLAINTEXT, stringWriter.toString());
}
}
private void copyResourceToDir(String resource, File parent) {
IoUtils.copy(getClass().getResourceAsStream("/"+resource), new File(parent, resource));
}
private String getMime(String uri) {
String extension = null;
int dot = uri.lastIndexOf('.');
//Get everything after the dot
if (dot >= 0)
extension = uri.substring(dot + 1).toLowerCase();
String mime = (String) theMimeTypes.get(extension);
if (mime == null)
mime = MIME_DEFAULT_BINARY;
return mime;
}
}
| true | true | public Response serve(String uri, String method, Properties header, Properties parms, Properties files, String data) {
try {
if (uri.equals("/stop")) {
synchronized (this) {
this.notifyAll();
}
return new NanoHTTPD.Response(HTTP_OK, MIME_PLAINTEXT, "Shutting down server.");
} else if (uri.startsWith("/jscoverage.js")) {
String serverJS = "jscoverage_isServer = true;";
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), IoUtils.loadFromClassPath(uri)+serverJS);
} else if (uri.startsWith("/jscoverage-store")) {
File jsonFile = new File(configuration.getReportDir(), "jscoverage.json");
if (jsonFile.exists()) {
String existingJSON = IoUtils.toString(jsonFile);
data = jsonDataMerger.mergeJSONCoverageData(existingJSON, data);
}
IoUtils.copy(new StringReader(data), jsonFile);
copyResourceToDir("jscoverage.css", configuration.getReportDir());
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
IoUtils.copy(new StringReader(reportHTML), new File(configuration.getReportDir(), "jscoverage.html"));
String reportJS = IoUtils.loadFromClassPath("/jscoverage.js") + "\njscoverage_isReport = true;";
IoUtils.copy(new StringReader(reportJS), new File(configuration.getReportDir(), "jscoverage.js"));
copyResourceToDir("jscoverage-highlight.css", configuration.getReportDir());
copyResourceToDir("jscoverage-ie.css", configuration.getReportDir());
copyResourceToDir("jscoverage-throbber.gif",configuration.getReportDir());
return new NanoHTTPD.Response(HTTP_OK, HTTP_OK, "Report stored at "+configuration.getReportDir());
} else if (uri.startsWith("/jscoverage.html")) {
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), reportHTML);
} else if (uri.startsWith("/jscoverage")) {
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), getClass().getResourceAsStream(uri));
} else if (uri.endsWith(".js") && !configuration.skipInstrumentation(uri)) {
SourceProcessor sourceProcessor = new SourceProcessor(configuration.getCompilerEnvirons(), uri, sourceFormatter, log);
String source = IoUtils.toString(new FileInputStream(myRootDir + uri));
String jsInstrumented = sourceProcessor.processSourceForServer(source);
return new NanoHTTPD.Response(HTTP_OK, "text/javascript", jsInstrumented);
} else {
return super.serve(uri, method, header, parms, files, data);
}
} catch (Throwable e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return new NanoHTTPD.Response(HTTP_INTERNALERROR, MIME_PLAINTEXT, stringWriter.toString());
}
}
| public Response serve(String uri, String method, Properties header, Properties parms, Properties files, String data) {
try {
if (uri.equals("/stop")) {
synchronized (this) {
this.notifyAll();
}
return new NanoHTTPD.Response(HTTP_OK, MIME_PLAINTEXT, "Shutting down server.");
} else if (uri.startsWith("/jscoverage.js")) {
String serverJS = "jscoverage_isServer = true;";
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), IoUtils.loadFromClassPath(uri)+serverJS);
} else if (uri.startsWith("/jscoverage-store")) {
File jsonFile = new File(configuration.getReportDir(), "jscoverage.json");
if (jsonFile.exists()) {
String existingJSON = IoUtils.toString(jsonFile);
data = jsonDataMerger.mergeJSONCoverageData(existingJSON, data);
}
IoUtils.copy(new StringReader(data), jsonFile);
copyResourceToDir("jscoverage.css", configuration.getReportDir());
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
IoUtils.copy(new StringReader(reportHTML), new File(configuration.getReportDir(), "jscoverage.html"));
String reportJS = IoUtils.loadFromClassPath("/jscoverage.js") + "\njscoverage_isReport = true;";
IoUtils.copy(new StringReader(reportJS), new File(configuration.getReportDir(), "jscoverage.js"));
copyResourceToDir("jscoverage-highlight.css", configuration.getReportDir());
copyResourceToDir("jscoverage-ie.css", configuration.getReportDir());
copyResourceToDir("jscoverage-throbber.gif",configuration.getReportDir());
return new NanoHTTPD.Response(HTTP_OK, HTTP_OK, "Report stored at "+configuration.getReportDir());
} else if (uri.startsWith("/jscoverage.html")) {
String reportHTML = IoUtils.loadFromClassPath("/jscoverage.html").replaceAll("@@version@@",configuration.getVersion());
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), reportHTML);
} else if (uri.startsWith("/jscoverage")) {
return new NanoHTTPD.Response(HTTP_OK, getMime(uri), getClass().getResourceAsStream(uri));
} else if (uri.endsWith(".js") && !configuration.skipInstrumentation(uri)) {
SourceProcessor sourceProcessor = new SourceProcessor(configuration.getCompilerEnvirons(), uri, sourceFormatter, log);
String source = IoUtils.toString(new FileInputStream(myRootDir + uri));
String jsInstrumented = sourceProcessor.processSourceForServer(source);
return new NanoHTTPD.Response(HTTP_OK, "application/javascript", jsInstrumented);
} else {
return super.serve(uri, method, header, parms, files, data);
}
} catch (Throwable e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return new NanoHTTPD.Response(HTTP_INTERNALERROR, MIME_PLAINTEXT, stringWriter.toString());
}
}
|
diff --git a/SITracker/src/main/java/com/andrada/sitracker/SettingsActivity.java b/SITracker/src/main/java/com/andrada/sitracker/SettingsActivity.java
index fd5f267..6d924f3 100644
--- a/SITracker/src/main/java/com/andrada/sitracker/SettingsActivity.java
+++ b/SITracker/src/main/java/com/andrada/sitracker/SettingsActivity.java
@@ -1,91 +1,91 @@
package com.andrada.sitracker;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.andrada.sitracker.tasks.UpdateAuthorsTask_;
import com.google.analytics.tracking.android.EasyTracker;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.SystemService;
/**
* Created by ggodonoga on 22/07/13.
*/
@EActivity
public class SettingsActivity extends SherlockPreferenceActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
@SystemService
AlarmManager alarmManager;
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
addPreferencesFromResource(R.xml.preferences);
} else {
addPreferencesFromResource(R.xml.preferences_no3g);
}
setSummary();
ActionBar actionBar = getSherlock().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
EasyTracker.getInstance().activityStart(this);
}
@Override
protected void onPause() {
super.onPause();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
EasyTracker.getInstance().activityStop(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Boolean isSyncing = sharedPreferences.getBoolean(Constants.UPDATE_PREFERENCE_KEY, true);
Intent intent = UpdateAuthorsTask_.intent(this.getApplicationContext()).get();
PendingIntent pi = PendingIntent.getService(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pi);
- long updateInterval = Long.getLong(sharedPreferences.getString(Constants.UPDATE_INTERVAL_KEY, "3600000L"), 3600000L);
+ long updateInterval = sharedPreferences.getLong(Constants.UPDATE_INTERVAL_KEY, 14400000L);
if (isSyncing) {
alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), updateInterval, pi);
}
if (key.equals(Constants.UPDATE_INTERVAL_KEY)) {
setSummary();
EasyTracker.getTracker().sendEvent(
Constants.GA_UI_CATEGORY,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL, updateInterval);
EasyTracker.getInstance().dispatch();
}
}
private void setSummary() {
ListPreference updateInterval = (ListPreference) findPreference(Constants.UPDATE_INTERVAL_KEY);
// Set summary to be the user-description for the selected value
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int index = updateInterval.findIndexOfValue(sharedPreferences.getString(Constants.UPDATE_INTERVAL_KEY, ""));
if (index >= 0 && index < updateInterval.getEntries().length)
updateInterval.setSummary(updateInterval.getEntries()[index]);
}
}
| true | true | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Boolean isSyncing = sharedPreferences.getBoolean(Constants.UPDATE_PREFERENCE_KEY, true);
Intent intent = UpdateAuthorsTask_.intent(this.getApplicationContext()).get();
PendingIntent pi = PendingIntent.getService(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pi);
long updateInterval = Long.getLong(sharedPreferences.getString(Constants.UPDATE_INTERVAL_KEY, "3600000L"), 3600000L);
if (isSyncing) {
alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), updateInterval, pi);
}
if (key.equals(Constants.UPDATE_INTERVAL_KEY)) {
setSummary();
EasyTracker.getTracker().sendEvent(
Constants.GA_UI_CATEGORY,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL, updateInterval);
EasyTracker.getInstance().dispatch();
}
}
| public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Boolean isSyncing = sharedPreferences.getBoolean(Constants.UPDATE_PREFERENCE_KEY, true);
Intent intent = UpdateAuthorsTask_.intent(this.getApplicationContext()).get();
PendingIntent pi = PendingIntent.getService(this.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pi);
long updateInterval = sharedPreferences.getLong(Constants.UPDATE_INTERVAL_KEY, 14400000L);
if (isSyncing) {
alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), updateInterval, pi);
}
if (key.equals(Constants.UPDATE_INTERVAL_KEY)) {
setSummary();
EasyTracker.getTracker().sendEvent(
Constants.GA_UI_CATEGORY,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL,
Constants.GA_EVENT_CHANGED_UPDATE_INTERVAL, updateInterval);
EasyTracker.getInstance().dispatch();
}
}
|
diff --git a/openjdk/java/util/zip/InflaterHuffmanTree.java b/openjdk/java/util/zip/InflaterHuffmanTree.java
index f6b5816f..1a152d2b 100644
--- a/openjdk/java/util/zip/InflaterHuffmanTree.java
+++ b/openjdk/java/util/zip/InflaterHuffmanTree.java
@@ -1,220 +1,220 @@
/* InflaterHuffmanTree.java --
Copyright (C) 2001, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.util.zip;
class InflaterHuffmanTree
{
private static final int MAX_BITLEN = 15;
private short[] tree;
static InflaterHuffmanTree defLitLenTree, defDistTree;
static
{
try
{
byte[] codeLengths = new byte[288];
int i = 0;
while (i < 144)
codeLengths[i++] = 8;
while (i < 256)
codeLengths[i++] = 9;
while (i < 280)
codeLengths[i++] = 7;
while (i < 288)
codeLengths[i++] = 8;
defLitLenTree = new InflaterHuffmanTree(codeLengths);
codeLengths = new byte[32];
i = 0;
while (i < 32)
codeLengths[i++] = 5;
defDistTree = new InflaterHuffmanTree(codeLengths);
}
catch (DataFormatException ex)
{
throw new InternalError
("InflaterHuffmanTree: static tree length illegal");
}
}
/**
* Constructs a Huffman tree from the array of code lengths.
*
* @param codeLengths the array of code lengths
*/
InflaterHuffmanTree(byte[] codeLengths) throws DataFormatException
{
buildTree(codeLengths);
}
private void buildTree(byte[] codeLengths) throws DataFormatException
{
int[] blCount = new int[MAX_BITLEN+1];
int[] nextCode = new int[MAX_BITLEN+1];
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits > 0)
blCount[bits]++;
}
int max = 0;
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++)
{
nextCode[bits] = code;
if (blCount[bits] > 0)
max = bits;
code += blCount[bits] << (16 - bits);
if (bits >= 10)
{
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
- if (code != 65536 && max != 1)
+ if (code != 65536 && max > 1)
throw new DataFormatException("incomplete dynamic bit lengths tree");
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--)
{
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7)
{
tree[DeflaterHuffman.bitReverse(i)]
= (short) ((-treePtr << 4) | bits);
treePtr += 1 << (bits-9);
}
}
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits == 0)
continue;
code = nextCode[bits];
int revcode = DeflaterHuffman.bitReverse(code);
if (bits <= 9)
{
do
{
tree[revcode] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < 512);
}
else
{
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do
{
tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
/**
* Reads the next symbol from input. The symbol is encoded using the
* huffman tree.
* @param input the input source.
* @return the next symbol, or -1 if not enough input is available.
*/
int getSymbol(StreamManipulator input) throws DataFormatException
{
int lookahead, symbol;
if ((lookahead = input.peekBits(9)) >= 0)
{
if ((symbol = tree[lookahead]) >= 0)
{
input.dropBits(symbol & 15);
return symbol >> 4;
}
int subtree = -(symbol >> 4);
int bitlen = symbol & 15;
if ((lookahead = input.peekBits(bitlen)) >= 0)
{
symbol = tree[subtree | (lookahead >> 9)];
input.dropBits(symbol & 15);
return symbol >> 4;
}
else
{
int bits = input.getAvailableBits();
lookahead = input.peekBits(bits);
symbol = tree[subtree | (lookahead >> 9)];
if ((symbol & 15) <= bits)
{
input.dropBits(symbol & 15);
return symbol >> 4;
}
else
return -1;
}
}
else
{
int bits = input.getAvailableBits();
lookahead = input.peekBits(bits);
symbol = tree[lookahead];
if (symbol >= 0 && (symbol & 15) <= bits)
{
input.dropBits(symbol & 15);
return symbol >> 4;
}
else
return -1;
}
}
}
| true | true | private void buildTree(byte[] codeLengths) throws DataFormatException
{
int[] blCount = new int[MAX_BITLEN+1];
int[] nextCode = new int[MAX_BITLEN+1];
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits > 0)
blCount[bits]++;
}
int max = 0;
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++)
{
nextCode[bits] = code;
if (blCount[bits] > 0)
max = bits;
code += blCount[bits] << (16 - bits);
if (bits >= 10)
{
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
if (code != 65536 && max != 1)
throw new DataFormatException("incomplete dynamic bit lengths tree");
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--)
{
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7)
{
tree[DeflaterHuffman.bitReverse(i)]
= (short) ((-treePtr << 4) | bits);
treePtr += 1 << (bits-9);
}
}
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits == 0)
continue;
code = nextCode[bits];
int revcode = DeflaterHuffman.bitReverse(code);
if (bits <= 9)
{
do
{
tree[revcode] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < 512);
}
else
{
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do
{
tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
| private void buildTree(byte[] codeLengths) throws DataFormatException
{
int[] blCount = new int[MAX_BITLEN+1];
int[] nextCode = new int[MAX_BITLEN+1];
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits > 0)
blCount[bits]++;
}
int max = 0;
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++)
{
nextCode[bits] = code;
if (blCount[bits] > 0)
max = bits;
code += blCount[bits] << (16 - bits);
if (bits >= 10)
{
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
if (code != 65536 && max > 1)
throw new DataFormatException("incomplete dynamic bit lengths tree");
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--)
{
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7)
{
tree[DeflaterHuffman.bitReverse(i)]
= (short) ((-treePtr << 4) | bits);
treePtr += 1 << (bits-9);
}
}
for (int i = 0; i < codeLengths.length; i++)
{
int bits = codeLengths[i];
if (bits == 0)
continue;
code = nextCode[bits];
int revcode = DeflaterHuffman.bitReverse(code);
if (bits <= 9)
{
do
{
tree[revcode] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < 512);
}
else
{
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do
{
tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits);
revcode += 1 << bits;
}
while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
|
diff --git a/server/IDSWrapper/src/uk/ac/ids/linker/Linker.java b/server/IDSWrapper/src/uk/ac/ids/linker/Linker.java
index 8c71f84..b0b2348 100644
--- a/server/IDSWrapper/src/uk/ac/ids/linker/Linker.java
+++ b/server/IDSWrapper/src/uk/ac/ids/linker/Linker.java
@@ -1,103 +1,104 @@
package uk.ac.ids.linker;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.restlet.data.Reference;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
public abstract class Linker {
// Logger instance
protected static final Logger logger = Logger.getLogger(Linker.class.getName());
// Entity type in the AppEngine data store
private final static String DS_ENTITY = "ExternalResource";
// Property for the mapped resources
private final static String RESOURCE_PROPERTY = "Resources";
// Property for the parameters
private final static String PARAMETER_PROPERTY = "Parameters";
/**
* @param countryName
* @param countryCode
* @return
*/
public List<Reference> getResource(LinkerParameters parameters) {
logger.info("Get " + parameters);
try {
// Try to return the result from the cache
return getFromCache(parameters);
} catch (EntityNotFoundException e) {
// Try to get it from geoname
List<Reference> uri = getFromService(parameters);
// If successful, save it
if (uri != null)
saveToCache(parameters, uri);
return uri;
}
}
/**
* @param parameters
* @return
*/
protected abstract List<Reference> getFromService(LinkerParameters parameters);
/**
* @param parameters
* @return
* @throws EntityNotFoundException
*/
private List<Reference> getFromCache(LinkerParameters parameters) throws EntityNotFoundException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
// Get the data
Query q = new Query(DS_ENTITY);
q.addFilter(PARAMETER_PROPERTY, FilterOperator.EQUAL, parameters.toKey());
PreparedQuery pq = datastore.prepare(q);
Entity entity = pq.asSingleEntity();
if (entity == null)
throw new EntityNotFoundException(null);
// De-serialize the data
+ List<Reference> results = new ArrayList<Reference>();
@SuppressWarnings("unchecked")
List<String> uris = (List<String>) entity.getProperty(RESOURCE_PROPERTY);
- List<Reference> results = new ArrayList<Reference>();
- for (String uri : uris)
- results.add(new Reference(uri));
+ if (uris != null)
+ for (String uri : uris)
+ results.add(new Reference(uri));
return results;
}
/**
* @param parameters
* @param uri
*/
private void saveToCache(LinkerParameters parameters, List<Reference> uris) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
// Serialize the uris
List<String> results = new ArrayList<String>();
for (Reference uri : uris)
results.add(uri.toString());
// Persist the data
Entity entity = new Entity(DS_ENTITY);
entity.setProperty(PARAMETER_PROPERTY, parameters.toKey());
entity.setProperty(RESOURCE_PROPERTY, results);
datastore.put(entity);
}
}
| false | true | private List<Reference> getFromCache(LinkerParameters parameters) throws EntityNotFoundException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
// Get the data
Query q = new Query(DS_ENTITY);
q.addFilter(PARAMETER_PROPERTY, FilterOperator.EQUAL, parameters.toKey());
PreparedQuery pq = datastore.prepare(q);
Entity entity = pq.asSingleEntity();
if (entity == null)
throw new EntityNotFoundException(null);
// De-serialize the data
@SuppressWarnings("unchecked")
List<String> uris = (List<String>) entity.getProperty(RESOURCE_PROPERTY);
List<Reference> results = new ArrayList<Reference>();
for (String uri : uris)
results.add(new Reference(uri));
return results;
}
| private List<Reference> getFromCache(LinkerParameters parameters) throws EntityNotFoundException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
// Get the data
Query q = new Query(DS_ENTITY);
q.addFilter(PARAMETER_PROPERTY, FilterOperator.EQUAL, parameters.toKey());
PreparedQuery pq = datastore.prepare(q);
Entity entity = pq.asSingleEntity();
if (entity == null)
throw new EntityNotFoundException(null);
// De-serialize the data
List<Reference> results = new ArrayList<Reference>();
@SuppressWarnings("unchecked")
List<String> uris = (List<String>) entity.getProperty(RESOURCE_PROPERTY);
if (uris != null)
for (String uri : uris)
results.add(new Reference(uri));
return results;
}
|
diff --git a/src/de/azapps/mirakel/model/task/Task.java b/src/de/azapps/mirakel/model/task/Task.java
index cbbd54f7..35c4ec50 100644
--- a/src/de/azapps/mirakel/model/task/Task.java
+++ b/src/de/azapps/mirakel/model/task/Task.java
@@ -1,1042 +1,1037 @@
/*******************************************************************************
* Mirakel is an Android App for managing your ToDo-Lists
*
* Copyright (c) 2013-2014 Anatolij Zelenin, Georg Semmler.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.azapps.mirakel.model.task;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimeZone;
import android.accounts.Account;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Pair;
import android.widget.Toast;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import de.azapps.mirakel.DefinitionsHelper.NoSuchListException;
import de.azapps.mirakel.DefinitionsHelper.SYNC_STATE;
import de.azapps.mirakel.helper.DateTimeHelper;
import de.azapps.mirakel.helper.Helpers;
import de.azapps.mirakel.helper.UndoHistory;
import de.azapps.mirakel.model.DatabaseHelper;
import de.azapps.mirakel.model.MirakelContentProvider;
import de.azapps.mirakel.model.R;
import de.azapps.mirakel.model.account.AccountMirakel;
import de.azapps.mirakel.model.file.FileMirakel;
import de.azapps.mirakel.model.list.ListMirakel;
import de.azapps.mirakel.model.list.SpecialList;
import de.azapps.mirakel.reminders.ReminderAlarm;
import de.azapps.mirakel.services.NotificationService;
import de.azapps.tools.Log;
public class Task extends TaskBase {
public static final String[] allColumns = { DatabaseHelper.ID,
UUID, LIST_ID, DatabaseHelper.NAME, CONTENT, DONE, DUE, REMINDER,
PRIORITY, DatabaseHelper.CREATED_AT, DatabaseHelper.UPDATED_AT,
DatabaseHelper.SYNC_STATE_FIELD, ADDITIONAL_ENTRIES, RECURRING,
RECURRING_REMINDER, PROGRESS };
private static Context context;
private static SQLiteDatabase database;
private static DatabaseHelper dbHelper;
public static final String SUBTASK_TABLE = "subtasks";
public static final String TABLE = "tasks";
private static final String TAG = "TasksDataSource";
/**
* Get all Tasks
*
* @return
*/
public static List<Task> all() {
List<Task> tasks = new ArrayList<Task>();
Cursor c = database.query(TABLE, allColumns, "not "
+ DatabaseHelper.SYNC_STATE_FIELD + "= " + SYNC_STATE.DELETE, null,
null, null, null);
c.moveToFirst();
while (!c.isAfterLast()) {
tasks.add(cursorToTask(c));
c.moveToNext();
}
c.close();
return tasks;
}
/**
* Close the Database-Connection
*/
public static void close() {
dbHelper.close();
}
/**
* Create a task from a Cursor
*
* @param cursor
* @return
*/
private static Task cursorToTask(Cursor cursor) {
int i = 0;
GregorianCalendar due = new GregorianCalendar();
SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'kkmmss'Z'", Helpers.getLocal(context));
try {
due.setTime(DateTimeHelper.dbDateTimeFormat
.parse(cursor.getString(6)));
} catch (ParseException e) {
due = null;
} catch (NullPointerException e) {
due = null;
}
GregorianCalendar reminder = new GregorianCalendar();
try {
reminder.setTime(dateTimeFormat.parse(cursor.getString(7)));
} catch (Exception e) {
reminder = null;
}
GregorianCalendar created_at = new GregorianCalendar();
try {
created_at.setTime(dateTimeFormat.parse(cursor.getString(9)));
} catch (Exception e) {
created_at = new GregorianCalendar();
}
GregorianCalendar updated_at = new GregorianCalendar();
try {
updated_at.setTime(dateTimeFormat.parse(cursor.getString(10)));
} catch (Exception e) {
updated_at = new GregorianCalendar();
}
Task task = new Task(cursor.getLong(i++), cursor.getString(i++),
ListMirakel.getList((int) cursor.getLong(i++)),
cursor.getString(i++), cursor.getString(i++),
cursor.getInt(i++) == 1, due, reminder, cursor.getInt(8),
created_at, updated_at, SYNC_STATE.parseInt(cursor.getInt(11)),
cursor.getString(12), cursor.getInt(13), cursor.getInt(14),
cursor.getInt(15));
return task;
}
private static List<Task> cursorToTaskList(Cursor cursor) {
cursor.moveToFirst();
List<Task> tasks = new ArrayList<Task>();
while (!cursor.isAfterLast()) {
tasks.add(cursorToTask(cursor));
cursor.moveToNext();
}
cursor.close();
return tasks;
}
public static void deleteDoneTasks() {
database.beginTransaction();
ContentValues values = new ContentValues();
values.put("sync_state", SYNC_STATE.DELETE.toInt());
String where = "sync_state!=" + SYNC_STATE.ADD + " AND done=1";
database.update(TABLE, values, where, null);
database.delete(TABLE, "sync_state=" + SYNC_STATE.ADD + " AND done=1",
null);
database.setTransactionSuccessful();
database.endTransaction();
}
/**
* Get a Task by id
*
* @param id
* @return
*/
public static Task get(long id) {
Cursor cursor = database.query(TABLE, allColumns, DatabaseHelper.ID
+ "='" + id + "' and not " + DatabaseHelper.SYNC_STATE_FIELD + "="
+ SYNC_STATE.DELETE, null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
Task t = cursorToTask(cursor);
cursor.close();
return t;
}
cursor.close();
return null;
}
/**
* Get tasks by Sync State
*
* @param state
* @return
*/
public static List<Task> getBySyncState(SYNC_STATE state) {
Cursor c = database.query(TABLE, allColumns, DatabaseHelper.SYNC_STATE_FIELD
+ "=" + state.toInt() + " and " + LIST_ID + ">0", null, null,
null, null);
return cursorToTaskList(c);
}
public static Task getByUUID(String uuid) {
Cursor cursor = database.query(TABLE, allColumns, UUID + "='" + uuid
+ "' and not " + DatabaseHelper.SYNC_STATE_FIELD + "="
+ SYNC_STATE.DELETE, null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
Task t = cursorToTask(cursor);
cursor.close();
return t;
}
cursor.close();
return null;
}
public static Task getDummy(Context ctx) {
return new Task(ctx.getString(R.string.task_empty));
}
public static Task getDummy(Context ctx, ListMirakel list) {
Task task = new Task(ctx.getString(R.string.task_empty));
task.setList(list, false);
return task;
}
private static String getSorting(int sorting) {
String order = "";
switch (sorting) {
case ListMirakel.SORT_BY_PRIO:
order = PRIORITY + " desc";
break;
case ListMirakel.SORT_BY_OPT:
order = ", " + PRIORITY + " DESC";
//$FALL-THROUGH$
case ListMirakel.SORT_BY_DUE:
order = " CASE WHEN (" + DUE
+ " IS NULL) THEN date('now','+1000 years') ELSE date("
+ DUE + ") END ASC" + order;
break;
case ListMirakel.SORT_BY_REVERT_DEFAULT:
order = PRIORITY + " DESC, CASE WHEN (" + DUE
+ " IS NULL) THEN date('now','+1000 years') ELSE date("
+ DUE + ") END ASC" + order;
//$FALL-THROUGH$
default:
order = DatabaseHelper.ID + " ASC";
}
return order;
}
public static List<Pair<Long, String>> getTaskNames() {
Cursor c = database.query(TABLE, new String[] { DatabaseHelper.ID,
DatabaseHelper.NAME }, "not " + DatabaseHelper.SYNC_STATE_FIELD + "="
+ SYNC_STATE.DELETE + " and done = 0", null, null, null, null);
c.moveToFirst();
List<Pair<Long, String>> names = new ArrayList<Pair<Long, String>>();
while (!c.isAfterLast()) {
names.add(new Pair<Long, String>(c.getLong(0), c.getString(1)));
c.moveToNext();
}
c.close();
return names;
}
/**
* Get Tasks from a List Use it only if really necessary!
*
* @param listId
* @param sorting
* The Sorting (@see Mirakel.SORT_*)
* @param showDone
* @return
*/
public static List<Task> getTasks(int listId, int sorting, boolean showDone) {
Cursor cursor = getTasksCursor(listId, sorting, showDone);
return cursorToTaskList(cursor);
}
/**
* Get Tasks from a List Use it only if really necessary!
*
* @param listId
* @param sorting
* The Sorting (@see Mirakel.SORT_*)
* @param showDone
* @return
*/
public static List<Task> getTasks(ListMirakel list, int sorting, boolean showDone) {
return getTasks(list.getId(), sorting, showDone);
}
/**
* Get Tasks from a List Use it only if really necessary!
*
* @param listId
* @param sorting
* The Sorting (@see Mirakel.SORT_*)
* @param showDone
* @return
*/
public static List<Task> getTasks(ListMirakel list, int sorting, boolean showDone, String where) {
Cursor cursor = getTasksCursor(list.getId(), sorting, where);
return cursorToTaskList(cursor);
}
/**
* Get a Cursor with all Tasks of a list
*
* @param listId
* @param sorting
* @return
*/
private static Cursor getTasksCursor(int listId, int sorting, boolean showDone) {
String where;
if (listId < 0) {
where = SpecialList.getSpecialList(-1 * listId).getWhereQuery(true);
} else {
where = "list_id='" + listId + "'";
}
if (!showDone) {
where += (where.trim().equals("") ? "" : " AND ") + " " + DONE
+ "=0";
}
return getTasksCursor(listId, sorting, where);
}
/**
* Get a Cursor with all Tasks of a list
*
* @param listId
* @param sorting
* @return
*/
private static Cursor getTasksCursor(int listId, int sorting, String where) {
if (where == null) {
where = "";
} else if (!where.equals("")) {
where += " and ";
}
where += " not " + DatabaseHelper.SYNC_STATE_FIELD + "=" + SYNC_STATE.DELETE;
String order = getSorting(sorting);
if (listId < 0) {
order += ", " + LIST_ID + " ASC";
}
return database.query(TABLE, allColumns, where, null, null, null, DONE
+ ", " + order);
}
private static Cursor getTasksCursor(Task subtask) {
String columns = "t." + allColumns[0];
for (int i = 1; i < allColumns.length; i++) {
columns += ", t." + allColumns[i];
}
return database.rawQuery("SELECT " + columns + " FROM " + TABLE
+ " t INNER JOIN " + SUBTASK_TABLE
+ " s on t._id=s.child_id WHERE s.parent_id=? ORDER BY "
+ getSorting(ListMirakel.SORT_BY_OPT), new String[] { ""
+ subtask.getId() });
}
// Static Methods
public static List<Task> getTasksToSync(Account account) {
AccountMirakel a = AccountMirakel.get(account);
List<ListMirakel> lists = ListMirakel.getListsForAccount(a);
String listIDs = "";
boolean first = true;
for (ListMirakel l : lists) {
listIDs += (first ? "" : ",") + l.getId();
first = false;
}
String where = "NOT " + DatabaseHelper.SYNC_STATE_FIELD + "='"
+ SYNC_STATE.NOTHING + "' and " + LIST_ID + " IN (" + listIDs
+ ")";
Cursor cursor = MirakelContentProvider.getReadableDatabase().query(TABLE, allColumns,
where, null, null, null, null);
return cursorToTaskList(cursor);
}
public static List<Task> getTasksWithReminders() {
String where = REMINDER + " NOT NULL and " + DONE + "=0";
Cursor cursor = MirakelContentProvider.getReadableDatabase().query(TABLE, allColumns,
where, null, null, null, null);
return cursorToTaskList(cursor);
}
/**
* Get a Task to sync it
*
* @param id
* @return
*/
public static Task getToSync(long id) {
Cursor cursor = database.query(TABLE, allColumns, DatabaseHelper.ID
+ "='" + id + "'", null, null, null, null);
cursor.moveToFirst();
if (cursor.getCount() != 0) {
Task t = cursorToTask(cursor);
cursor.close();
return t;
}
cursor.close();
return null;
}
/**
* Initialize the Database and the preferences
*
* @param context
* The Application-Context
*/
public static void init(Context ctx) {
Task.context = ctx;
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public static Task newTask(String name, ListMirakel list) {
return newTask(name, list, "", false, null, 0);
}
public static Task newTask(String name, ListMirakel list, GregorianCalendar due, int prio) {
return newTask(name, list, "", false, due, prio);
}
/**
* Create a new Task
*
* @param name
* @param list_id
* @param content
* @param done
* @param due
* @param priority
* @return
*/
public static Task newTask(String name, ListMirakel list, String content, boolean done, GregorianCalendar due, int priority) {
Calendar now = new GregorianCalendar();
Task t = new Task(0, java.util.UUID.randomUUID().toString(), list,
name, content, done, due, null, priority, now, now,
SYNC_STATE.ADD, "", -1, -1, 0);
try {
Task task = t.create();
NotificationService.updateNotificationAndWidget(context);
return task;
} catch (NoSuchListException e) {
Log.wtf(TAG, "List vanish");
Log.e(TAG, Log.getStackTraceString(e));
Toast.makeText(context, R.string.no_lists, Toast.LENGTH_LONG)
.show();
return null;
}
}
/**
* Parses a JSON-Object to a task
*
* @param el
* @return
*/
public static Task parse_json(JsonObject el, AccountMirakel account) {
Task t = null;
JsonElement id = el.get("id");
if (id != null) {
t = Task.get(id.getAsLong());
} else {
id = el.get("uuid");
if (id != null) {
t = Task.getByUUID(id.getAsString());
}
}
if (t == null) {
t = new Task();
}
// Name
Set<Entry<String, JsonElement>> entries = el.entrySet();
for (Entry<String, JsonElement> entry : entries) {
String key = entry.getKey();
JsonElement val = entry.getValue();
if (key == null || key.equals("id")) {
continue;
}
if (key.equals("uuid")) {
t.setUUID(val.getAsString());
} else if (key.equals("name") || key.equals("description")) {
t.setName(val.getAsString());
} else if (key.equals("content")) {
String content = val.getAsString();
if (content == null) {
content = "";
}
t.setContent(content);
} else if (key.equals("priority")) {
String prioString = val.getAsString().trim();
if (prioString.equals("L") && t.getPriority() != -1) {
t.setPriority(-2);
} else if (prioString.equals("M")) {
t.setPriority(1);
} else if (prioString.equals("H")) {
t.setPriority(2);
} else if (!prioString.equals("L")) {
t.setPriority(val.getAsInt());
}
} else if(key.equals("progress")) {
int progress=(int) val.getAsDouble();
t.setProgress(progress);
} else if (key.equals("list_id")) {
ListMirakel list = ListMirakel.getList(val.getAsInt());
if (list == null) {
list = SpecialList.firstSpecial().getDefaultList();
}
t.setList(list, true);
} else if (key.equals("project")) {
ListMirakel list = ListMirakel.findByName(val.getAsString(),
account);
if (list == null
|| list.getAccount().getId() != account.getId()) {
list = ListMirakel.newList(val.getAsString(),
ListMirakel.SORT_BY_OPT, account);
}
t.setList(list, true);
} else if (key.equals("created_at")) {
t.setCreatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("updated_at")) {
t.setUpdatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("entry")) {
t.setCreatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
- } else if (key.equals("modification")) {
+ } else if (key.equals("modification") || key.equals("modified")) {
t.setUpdatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
- } else if (key.equals("modified")) {
- Calendar modification = new GregorianCalendar();
- modification
- .setTimeInMillis(Long.parseLong(val.getAsString()) * 1000);
- t.setUpdatedAt(modification);
} else if (key.equals("done")) {
t.setDone(val.getAsBoolean());
} else if (key.equals("status")) {
String status = val.getAsString();
if (status.equals("pending")) {
t.setDone(false);
} else if (status.equals("deleted")) {
t.setSyncState(SYNC_STATE.DELETE);
} else {
t.setDone(true);
}
t.addAdditionalEntry(key, "\"" + val.getAsString() + "\"");
// TODO don't ignore waiting and recurring!!!
} else if (key.equals("due")) {
Calendar due = parseDate(val.getAsString(), "yyyy-MM-dd");
if (due == null) {
due = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
// try to workaround timezone-bug
if (due != null) {
due.setTimeInMillis(due.getTimeInMillis()
+ TimeZone.getDefault().getRawOffset());
}
}
t.setDue(due);
} else if (key.equals("reminder")) {
Calendar reminder = parseDate(val.getAsString(), "yyyy-MM-dd");
if (reminder == null) {
reminder = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
}
t.setReminder(reminder);
} else if (key.equals("annotations")) {
String content = "";
try {
JsonArray annotations = val.getAsJsonArray();
boolean first = true;
for (JsonElement a : annotations) {
if (first) {
first = false;
} else {
content += "\n";
}
content += a.getAsJsonObject().get("description")
.getAsString();
}
} catch (Exception e) {
Log.e(TAG, "cannot parse json");
}
t.setContent(content);
} else if (key.equals("content")) {
t.setContent(val.getAsString());
} else if (key.equals("sync_state")) {
t.setSyncState(SYNC_STATE.parseInt(val.getAsInt()));
} else if (key.equals("depends")) {
t.setDependencies(val.getAsString().split(","));
} else {
if (val.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) val;
if (p.isBoolean()) {
t.addAdditionalEntry(key, val.getAsBoolean() + "");
} else if (p.isNumber()) {
t.addAdditionalEntry(key, val.getAsInt() + "");
} else if (p.isJsonNull()) {
t.addAdditionalEntry(key, "null");
} else if (p.isString()) {
t.addAdditionalEntry(key, "\"" + val.getAsString()
+ "\"");
} else {
Log.w(TAG, "unkown json-type");
}
} else if (val.isJsonArray()) {
JsonArray a = (JsonArray) val;
String s = "[";
boolean first = true;
for (JsonElement e : a) {
if (e.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) e;
String add;
if (p.isBoolean()) {
add = p.getAsBoolean() + "";
} else if (p.isNumber()) {
add = p.getAsInt() + "";
} else if (p.isString()) {
add = "\"" + p.getAsString() + "\"";
} else if (p.isJsonNull()) {
add = "null";
} else {
Log.w(TAG, "unkown json-type");
break;
}
s += (first ? "" : ",") + add;
first = false;
} else {
Log.w(TAG, "unkown json-type");
}
}
t.addAdditionalEntry(key, s + "]");
} else {
Log.w(TAG, "unkown json-type");
}
}
}
return t;
}
/**
* Parse a JSON–String to a List of Tasks
*
* @param result
* @return
*/
public static List<Task> parse_json(String result, AccountMirakel account) {
try {
List<Task> tasks = new ArrayList<Task>();
Iterator<JsonElement> i = new JsonParser().parse(result)
.getAsJsonArray().iterator();
while (i.hasNext()) {
JsonObject el = (JsonObject) i.next();
Task t = parse_json(el, account);
tasks.add(t);
}
return tasks;
} catch (Exception e) {
Log.e(TAG, "Cannot parse response");
Log.e(TAG, result);
Log.d(TAG, Log.getStackTraceString(e));
}
return new ArrayList<Task>();
}
private static Calendar parseDate(String date, String format) {
GregorianCalendar temp = new GregorianCalendar();
try {
temp.setTime(new SimpleDateFormat(format, Locale.getDefault())
.parse(date));
return temp;
} catch (ParseException e) {
return null;
}
}
public static List<Task> rawQuery(String generateQuery) {
Cursor c = database.rawQuery(generateQuery, null);
List<Task> ret = cursorToTaskList(c);
c.close();
return ret;
}
public static void resetSyncState(List<Task> tasks) {
if (tasks.size() == 0) return;
for (Task t : tasks) {
if (t.getSyncState() != SYNC_STATE.DELETE) {
t.setSyncState(SYNC_STATE.NOTHING);
try {
database.update(TABLE, t.getContentValues(),
DatabaseHelper.ID + " = " + t.getId(), null);
} catch (NoSuchListException e) {
Log.d(TAG, "List did vanish");
} catch (Exception e) {
t.destroy(false);
Log.d(TAG, "destroy: " + t.getName());
Log.w(TAG, Log.getStackTraceString(e));
}
} else {
Log.d(TAG, "destroy: " + t.getName());
t.destroy(true);
}
}
}
public static List<Task> search(String query) {
Cursor cursor = database.query(TABLE, allColumns, query, null, null,
null, null);
return cursorToTaskList(cursor);
}
/**
* Search Tasks
*
* @param id
* @return
*/
public static List<Task> searchName(String query) {
String[] args = { "%" + query + "%" };
Cursor cursor = database.query(TABLE, allColumns, DatabaseHelper.NAME
+ " LIKE ?", args, null, null, null);
return cursorToTaskList(cursor);
}
private String dependencies[];
Task() {
super();
}
public Task(long id, String uuid, ListMirakel list, String name, String content, boolean done, Calendar due, Calendar reminder, int priority, Calendar created_at, Calendar updated_at, SYNC_STATE sync_state, String additionalEntriesString, int recurring, int recurring_reminder, int progress) {
super(id, uuid, list, name, content, done, due, reminder, priority,
created_at, updated_at, sync_state, additionalEntriesString,
recurring, recurring_reminder, progress);
}
public Task(String name) {
super(name);
}
public FileMirakel addFile(Context ctx, String path) {
return FileMirakel.newFile(ctx, this, path);
}
public void addSubtask(Task t) {
if (checkIfParent(t)) return;
ContentValues cv = new ContentValues();
cv.put("parent_id", getId());
cv.put("child_id", t.getId());
database.beginTransaction();
database.insert(SUBTASK_TABLE, null, cv);
database.setTransactionSuccessful();
database.endTransaction();
}
public boolean checkIfParent(Task t) {
return isChildRec(t);
}
public Task create() throws NoSuchListException {
return create(true);
}
public Task create(boolean addFlag) throws NoSuchListException {
ContentValues values = new ContentValues();
values.put(UUID, getUUID());
values.put(DatabaseHelper.NAME, getName());
if (getList() == null) throw new NoSuchListException();
values.put(LIST_ID, getList().getId());
values.put(CONTENT, getContent());
values.put(DONE, isDone());
values.put(DUE,
getDue() == null ? null : DateTimeHelper.formatDBDateTime(getDue()));
values.put(PRIORITY, getPriority());
values.put(DatabaseHelper.SYNC_STATE_FIELD, addFlag ? SYNC_STATE.ADD.toInt()
: SYNC_STATE.NOTHING.toInt());
values.put(DatabaseHelper.CREATED_AT,
DateTimeHelper.formatDateTime(getCreatedAt()));
if (getUpdatedAt() == null) {
setUpdatedAt(new GregorianCalendar());
}
values.put(DatabaseHelper.UPDATED_AT,
DateTimeHelper.formatDateTime(getUpdatedAt()));
values.put(PROGRESS, getProgress());
values.put("additional_entries", getAdditionalEntriesString());
database.beginTransaction();
long insertId = database.insertOrThrow(TABLE, null, values);
database.setTransactionSuccessful();
database.endTransaction();
Cursor cursor = database.query(TABLE, allColumns, DatabaseHelper.ID
+ " = " + insertId, null, null, null, null);
cursor.moveToFirst();
Task newTask = cursorToTask(cursor);
cursor.close();
UndoHistory.logCreate(newTask, context);
return newTask;
}
public void deleteSubtask(Task s) {
database.beginTransaction();
database.delete(SUBTASK_TABLE, "parent_id=" + getId()
+ " and child_id=" + s.getId(), null);
database.setTransactionSuccessful();
database.endTransaction();
}
/**
* Delete a task
*
* @param task
*/
public void destroy() {
destroy(false);
}
public void destroy(boolean force) {
if (!force) {
UndoHistory.updateLog(this, context);
}
long id = getId();
if (getSyncState() == SYNC_STATE.ADD || force) {
database.delete(TABLE, DatabaseHelper.ID + " = " + id, null);
FileMirakel.destroyForTask(this);
database.delete(SUBTASK_TABLE, "parent_id=" + id + " or child_id="
+ id, null);
} else {
ContentValues values = new ContentValues();
values.put(DatabaseHelper.SYNC_STATE_FIELD, SYNC_STATE.DELETE.toInt());
database.update(TABLE, values, DatabaseHelper.ID + "=" + id, null);
}
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Task)) return false;
Task t = (Task) o;
// Id
if (getId() != t.getId()) return false;
// List
if (t.getList() != null && getList() != null) {
if (t.getList().getId() != getList().getId()) return false;
} else if (t.getList() != null || getList() != null) return false;
// Name
if (t.getName() != null && getName() != null) {
if (!t.getName().equals(getName())) return false;
} else if (getName() != null || t.getName() != null) return false;
// Content
if (t.getContent() != null && getContent() != null) {
if (!t.getContent().equals(getContent())) return false;
} else if (getContent() != null || t.getContent() != null)
return false;
// Done
if (t.isDone() != isDone()) return false;
// Due
if (t.getDue() != null && getDue() != null) {
if (t.getDue().compareTo(getDue()) != 0) return false;
} else if (t.getDue() != null || getDue() != null) return false;
// Priority
if (t.getPriority() != getPriority()) return false;
// Additional Entries
if (t.getAdditionalEntries() != null && getAdditionalEntries() != null) {
if (!t.getAdditionalEntries().equals(getAdditionalEntries()))
return false;
} else if (t.getAdditionalEntries() != null
|| getAdditionalEntries() != null) return false;
// Reminder
if (t.getReminder() != null && getReminder() != null) {
if (t.getReminder().compareTo(getReminder()) != 0) return false;
} else if (getReminder() != null || t.getReminder() != null)
return false;
// progress
if (t.getProgress() != getProgress()) return false;
return true;
}
public String[] getDependencies() {
return this.dependencies;
}
public List<FileMirakel> getFiles() {
return FileMirakel.getForTask(this);
}
public int getSubtaskCount() {
Cursor c = database.rawQuery("Select count(_id) from " + SUBTASK_TABLE
+ " where parent_id=" + getId(), null);
c.moveToFirst();
int count = c.getInt(0);
c.close();
return count;
}
public List<Task> getSubtasks() {
Cursor c = Task.getTasksCursor(this);
List<Task> subTasks = new ArrayList<Task>();
c.moveToFirst();
while (!c.isAfterLast()) {
subTasks.add(cursorToTask(c));
c.moveToNext();
}
c.close();
return subTasks;
}
private boolean isChildRec(Task t) {
List<Task> subtasks = getSubtasks();
for (Task s : subtasks) {
if (s.getId() == t.getId() || s.isChildRec(t)) return true;
}
return false;
}
public boolean isSubtaskOf(Task otherTask) {
Cursor c = database.rawQuery("Select count(_id) from " + SUBTASK_TABLE
+ " where parent_id=" + otherTask.getId() + " AND child_id="
+ getId(), null);
c.moveToFirst();
int count = c.getInt(0);
c.close();
return count > 0;
}
public void safeSave() {
safeSave(true);
}
/**
* Save a Task
*
* @param task
*/
public void safeSave(boolean log) {
try {
save(log);
} catch (NoSuchListException e) {
Log.w(TAG, "List did vanish");
}
}
private void save(boolean log) throws NoSuchListException {
if (!isEdited()) {
Log.d(TAG, "new Task equals old, didnt need to save it");
return;
}
if (isEdited(DONE) && isDone()) {
setSubTasksDone();
}
setSyncState(getSyncState() == SYNC_STATE.ADD
|| getSyncState() == SYNC_STATE.IS_SYNCED ? getSyncState()
: SYNC_STATE.NEED_SYNC);
if (context != null) {
setUpdatedAt(new GregorianCalendar());
}
ContentValues values = getContentValues();
if (log) {
Task old = Task.get(getId());
UndoHistory.updateLog(old, context);
}
database.beginTransaction();
database.update(TABLE, values, DatabaseHelper.ID + " = " + getId(),
null);
database.setTransactionSuccessful();
database.endTransaction();
if (isEdited(REMINDER) || isEdited(RECURRING_REMINDER)) {
ReminderAlarm.updateAlarms(context);
}
clearEdited();
NotificationService.updateNotificationAndWidget(context);
}
private void setDependencies(String[] dep) {
this.dependencies = dep;
}
private void setSubTasksDone() {
List<Task> subTasks = getSubtasks();
for (Task t : subTasks) {
t.setDone(true);
try {
t.save(true);
} catch (NoSuchListException e) {
Log.d(TAG, "List did vanish");
}
}
}
public String toJson() {
String json = "{";
json += "\"id\":" + getId() + ",";
json += "\"name\":\"" + getName() + "\",";
json += "\"content\":\"" + getContent() + "\",";
json += "\"done\":" + (isDone() ? "true" : "false") + ",";
json += "\"priority\":" + getPriority() + ",";
json += "\"list_id\":" + getList().getId() + ",";
String s = "";
if (getDue() != null) {
s = DateTimeHelper.formatDate(getDue());
}
json += "\"due\":\"" + s + "\",";
s = "";
if (getReminder() != null) {
s = DateTimeHelper.formatDateTime(getReminder());
}
json += "\"reminder\":\"" + s + "\",";
json += "\"sync_state\":" + getSyncState() + ",";
json += "\"created_at\":\""
+ DateTimeHelper.formatDateTime(getCreatedAt()) + "\",";
json += "\"updated_at\":\""
+ DateTimeHelper.formatDateTime(getUpdatedAt()) + "\"}";
return json;
}
}
| false | true | public static Task parse_json(JsonObject el, AccountMirakel account) {
Task t = null;
JsonElement id = el.get("id");
if (id != null) {
t = Task.get(id.getAsLong());
} else {
id = el.get("uuid");
if (id != null) {
t = Task.getByUUID(id.getAsString());
}
}
if (t == null) {
t = new Task();
}
// Name
Set<Entry<String, JsonElement>> entries = el.entrySet();
for (Entry<String, JsonElement> entry : entries) {
String key = entry.getKey();
JsonElement val = entry.getValue();
if (key == null || key.equals("id")) {
continue;
}
if (key.equals("uuid")) {
t.setUUID(val.getAsString());
} else if (key.equals("name") || key.equals("description")) {
t.setName(val.getAsString());
} else if (key.equals("content")) {
String content = val.getAsString();
if (content == null) {
content = "";
}
t.setContent(content);
} else if (key.equals("priority")) {
String prioString = val.getAsString().trim();
if (prioString.equals("L") && t.getPriority() != -1) {
t.setPriority(-2);
} else if (prioString.equals("M")) {
t.setPriority(1);
} else if (prioString.equals("H")) {
t.setPriority(2);
} else if (!prioString.equals("L")) {
t.setPriority(val.getAsInt());
}
} else if(key.equals("progress")) {
int progress=(int) val.getAsDouble();
t.setProgress(progress);
} else if (key.equals("list_id")) {
ListMirakel list = ListMirakel.getList(val.getAsInt());
if (list == null) {
list = SpecialList.firstSpecial().getDefaultList();
}
t.setList(list, true);
} else if (key.equals("project")) {
ListMirakel list = ListMirakel.findByName(val.getAsString(),
account);
if (list == null
|| list.getAccount().getId() != account.getId()) {
list = ListMirakel.newList(val.getAsString(),
ListMirakel.SORT_BY_OPT, account);
}
t.setList(list, true);
} else if (key.equals("created_at")) {
t.setCreatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("updated_at")) {
t.setUpdatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("entry")) {
t.setCreatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
} else if (key.equals("modification")) {
t.setUpdatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
} else if (key.equals("modified")) {
Calendar modification = new GregorianCalendar();
modification
.setTimeInMillis(Long.parseLong(val.getAsString()) * 1000);
t.setUpdatedAt(modification);
} else if (key.equals("done")) {
t.setDone(val.getAsBoolean());
} else if (key.equals("status")) {
String status = val.getAsString();
if (status.equals("pending")) {
t.setDone(false);
} else if (status.equals("deleted")) {
t.setSyncState(SYNC_STATE.DELETE);
} else {
t.setDone(true);
}
t.addAdditionalEntry(key, "\"" + val.getAsString() + "\"");
// TODO don't ignore waiting and recurring!!!
} else if (key.equals("due")) {
Calendar due = parseDate(val.getAsString(), "yyyy-MM-dd");
if (due == null) {
due = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
// try to workaround timezone-bug
if (due != null) {
due.setTimeInMillis(due.getTimeInMillis()
+ TimeZone.getDefault().getRawOffset());
}
}
t.setDue(due);
} else if (key.equals("reminder")) {
Calendar reminder = parseDate(val.getAsString(), "yyyy-MM-dd");
if (reminder == null) {
reminder = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
}
t.setReminder(reminder);
} else if (key.equals("annotations")) {
String content = "";
try {
JsonArray annotations = val.getAsJsonArray();
boolean first = true;
for (JsonElement a : annotations) {
if (first) {
first = false;
} else {
content += "\n";
}
content += a.getAsJsonObject().get("description")
.getAsString();
}
} catch (Exception e) {
Log.e(TAG, "cannot parse json");
}
t.setContent(content);
} else if (key.equals("content")) {
t.setContent(val.getAsString());
} else if (key.equals("sync_state")) {
t.setSyncState(SYNC_STATE.parseInt(val.getAsInt()));
} else if (key.equals("depends")) {
t.setDependencies(val.getAsString().split(","));
} else {
if (val.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) val;
if (p.isBoolean()) {
t.addAdditionalEntry(key, val.getAsBoolean() + "");
} else if (p.isNumber()) {
t.addAdditionalEntry(key, val.getAsInt() + "");
} else if (p.isJsonNull()) {
t.addAdditionalEntry(key, "null");
} else if (p.isString()) {
t.addAdditionalEntry(key, "\"" + val.getAsString()
+ "\"");
} else {
Log.w(TAG, "unkown json-type");
}
} else if (val.isJsonArray()) {
JsonArray a = (JsonArray) val;
String s = "[";
boolean first = true;
for (JsonElement e : a) {
if (e.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) e;
String add;
if (p.isBoolean()) {
add = p.getAsBoolean() + "";
} else if (p.isNumber()) {
add = p.getAsInt() + "";
} else if (p.isString()) {
add = "\"" + p.getAsString() + "\"";
} else if (p.isJsonNull()) {
add = "null";
} else {
Log.w(TAG, "unkown json-type");
break;
}
s += (first ? "" : ",") + add;
first = false;
} else {
Log.w(TAG, "unkown json-type");
}
}
t.addAdditionalEntry(key, s + "]");
} else {
Log.w(TAG, "unkown json-type");
}
}
}
return t;
}
| public static Task parse_json(JsonObject el, AccountMirakel account) {
Task t = null;
JsonElement id = el.get("id");
if (id != null) {
t = Task.get(id.getAsLong());
} else {
id = el.get("uuid");
if (id != null) {
t = Task.getByUUID(id.getAsString());
}
}
if (t == null) {
t = new Task();
}
// Name
Set<Entry<String, JsonElement>> entries = el.entrySet();
for (Entry<String, JsonElement> entry : entries) {
String key = entry.getKey();
JsonElement val = entry.getValue();
if (key == null || key.equals("id")) {
continue;
}
if (key.equals("uuid")) {
t.setUUID(val.getAsString());
} else if (key.equals("name") || key.equals("description")) {
t.setName(val.getAsString());
} else if (key.equals("content")) {
String content = val.getAsString();
if (content == null) {
content = "";
}
t.setContent(content);
} else if (key.equals("priority")) {
String prioString = val.getAsString().trim();
if (prioString.equals("L") && t.getPriority() != -1) {
t.setPriority(-2);
} else if (prioString.equals("M")) {
t.setPriority(1);
} else if (prioString.equals("H")) {
t.setPriority(2);
} else if (!prioString.equals("L")) {
t.setPriority(val.getAsInt());
}
} else if(key.equals("progress")) {
int progress=(int) val.getAsDouble();
t.setProgress(progress);
} else if (key.equals("list_id")) {
ListMirakel list = ListMirakel.getList(val.getAsInt());
if (list == null) {
list = SpecialList.firstSpecial().getDefaultList();
}
t.setList(list, true);
} else if (key.equals("project")) {
ListMirakel list = ListMirakel.findByName(val.getAsString(),
account);
if (list == null
|| list.getAccount().getId() != account.getId()) {
list = ListMirakel.newList(val.getAsString(),
ListMirakel.SORT_BY_OPT, account);
}
t.setList(list, true);
} else if (key.equals("created_at")) {
t.setCreatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("updated_at")) {
t.setUpdatedAt(val.getAsString().replace(":", ""));
} else if (key.equals("entry")) {
t.setCreatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
} else if (key.equals("modification") || key.equals("modified")) {
t.setUpdatedAt(parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat)));
} else if (key.equals("done")) {
t.setDone(val.getAsBoolean());
} else if (key.equals("status")) {
String status = val.getAsString();
if (status.equals("pending")) {
t.setDone(false);
} else if (status.equals("deleted")) {
t.setSyncState(SYNC_STATE.DELETE);
} else {
t.setDone(true);
}
t.addAdditionalEntry(key, "\"" + val.getAsString() + "\"");
// TODO don't ignore waiting and recurring!!!
} else if (key.equals("due")) {
Calendar due = parseDate(val.getAsString(), "yyyy-MM-dd");
if (due == null) {
due = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
// try to workaround timezone-bug
if (due != null) {
due.setTimeInMillis(due.getTimeInMillis()
+ TimeZone.getDefault().getRawOffset());
}
}
t.setDue(due);
} else if (key.equals("reminder")) {
Calendar reminder = parseDate(val.getAsString(), "yyyy-MM-dd");
if (reminder == null) {
reminder = parseDate(val.getAsString(),
context.getString(R.string.TWDateFormat));
}
t.setReminder(reminder);
} else if (key.equals("annotations")) {
String content = "";
try {
JsonArray annotations = val.getAsJsonArray();
boolean first = true;
for (JsonElement a : annotations) {
if (first) {
first = false;
} else {
content += "\n";
}
content += a.getAsJsonObject().get("description")
.getAsString();
}
} catch (Exception e) {
Log.e(TAG, "cannot parse json");
}
t.setContent(content);
} else if (key.equals("content")) {
t.setContent(val.getAsString());
} else if (key.equals("sync_state")) {
t.setSyncState(SYNC_STATE.parseInt(val.getAsInt()));
} else if (key.equals("depends")) {
t.setDependencies(val.getAsString().split(","));
} else {
if (val.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) val;
if (p.isBoolean()) {
t.addAdditionalEntry(key, val.getAsBoolean() + "");
} else if (p.isNumber()) {
t.addAdditionalEntry(key, val.getAsInt() + "");
} else if (p.isJsonNull()) {
t.addAdditionalEntry(key, "null");
} else if (p.isString()) {
t.addAdditionalEntry(key, "\"" + val.getAsString()
+ "\"");
} else {
Log.w(TAG, "unkown json-type");
}
} else if (val.isJsonArray()) {
JsonArray a = (JsonArray) val;
String s = "[";
boolean first = true;
for (JsonElement e : a) {
if (e.isJsonPrimitive()) {
JsonPrimitive p = (JsonPrimitive) e;
String add;
if (p.isBoolean()) {
add = p.getAsBoolean() + "";
} else if (p.isNumber()) {
add = p.getAsInt() + "";
} else if (p.isString()) {
add = "\"" + p.getAsString() + "\"";
} else if (p.isJsonNull()) {
add = "null";
} else {
Log.w(TAG, "unkown json-type");
break;
}
s += (first ? "" : ",") + add;
first = false;
} else {
Log.w(TAG, "unkown json-type");
}
}
t.addAdditionalEntry(key, s + "]");
} else {
Log.w(TAG, "unkown json-type");
}
}
}
return t;
}
|
diff --git a/src/jp/thoy/psxlittle/MainActivity.java b/src/jp/thoy/psxlittle/MainActivity.java
index d72ad44..8dd70c4 100644
--- a/src/jp/thoy/psxlittle/MainActivity.java
+++ b/src/jp/thoy/psxlittle/MainActivity.java
@@ -1,267 +1,265 @@
package jp.thoy.psxlittle;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import jp.thoy.psxlittle.R;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements OnItemClickListener, OnItemLongClickListener {
public static final int TAB_NUM = 3;
public final static String K_PAGE = "PAGE";
public final static String K_KEY = "KEY";
private final String CNAME = CommTools.getLastPart(this.getClass().getName(),".");
private final static boolean isDebug = true;
final static Calendar calendar = Calendar.getInstance();
final static int year = calendar.get(Calendar.YEAR);
final static int month = calendar.get(Calendar.MONTH);
final static int day = calendar.get(Calendar.DAY_OF_MONTH);
final static int hour = calendar.get(Calendar.HOUR_OF_DAY);
final static int min = calendar.get(Calendar.MINUTE);
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
PagerAdapter mPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
Thread.setDefaultUncaughtExceptionHandler(new TraceLog(context));
PackageManager mPackageManager = getPackageManager();
try{
DataObject mDataObject = new DataObject(context);
SQLiteDatabase mdb = mDataObject.dbOpen();
mDataObject.dbClose(mdb);
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.setPackageManager(mPackageManager);
mViewPager = (ViewPager)findViewById(R.id.viewPager);
mViewPager.setAdapter(mPagerAdapter);
} catch (Exception ex){
TraceLog saveTrace = new TraceLog(context);
String mname = ":" + Thread.currentThread().getStackTrace()[2].getMethodName();
saveTrace.saveLog(ex,CNAME + mname);
Log.e(CNAME,ex.getMessage());
ex.printStackTrace();
}
}
@Override
protected void onStart() {
// TODO �����������ꂽ���\�b�h�E�X�^�u
super.onStart();
Context context = getApplicationContext();
DataObject mDO = new DataObject(context);
PSXShared pShared = new PSXShared(context);
long before = pShared.getBefore();
if(before == 0L){
if(isDebug){
Log.w(CNAME,"install from main count" + mDO.countTable(DataObject.PREVINFO));
}
PSXAsyncTask aTask = new PSXAsyncTask();
Param mParam = new Param();
ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Activity.ACTIVITY_SERVICE);
mParam.cParam = context;
mParam.aParam = mActivityManager;
mParam.sParam = PSXService.INSTALL;
mParam.clParam = CNAME;
aTask.execute(mParam);
pShared.putBefore(Calendar.getInstance());
}
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_DATE_CHANGED);
iFilter.addAction(Intent.ACTION_LOCALE_CHANGED);
iFilter.addAction(Intent.ACTION_TIME_CHANGED);
iFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
iFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
BootReceiver mReceiver = new BootReceiver();
try{
context.unregisterReceiver(mReceiver);
} catch (IllegalArgumentException ex) {
;
}
try{
context.registerReceiver(mReceiver, iFilter);
} catch (Exception ex){
ex.printStackTrace();
}
RegistTask rTask = new RegistTask(getApplicationContext());
rTask.StartCommand();
if(isDebug){
Log.w(CNAME,"OnStart");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO �����������ꂽ���\�b�h�E�X�^�u
Intent mIntent;
Context context = getApplicationContext();
ArrayList<TempTable> list;
ListAdapter adapter;
ListView mListView;
int ids[] = new int[]{R.id.listCPU,R.id.listMEM};
switch(item.getItemId()){
case R.id.action_reload:
ViewPager vPager = (ViewPager)findViewById(R.id.viewPager);
PackageManager pManager = getPackageManager();
switch(vPager.getCurrentItem()){
case 0:
case 1:
SummarizeData iCalc = new SummarizeData(context);
list = iCalc.calculate(null,vPager.getCurrentItem());
if(list == null){
Toast.makeText(context, getString(R.string.strNoData), Toast.LENGTH_SHORT).show();
return super.onMenuItemSelected(featureId, item);
}
mListView = (ListView)findViewById(ids[vPager.getCurrentItem()]);
adapter = new ListAdapter(this,list,pManager);
- list = iCalc.calculate(null,1);
+ list = iCalc.calculate(null,vPager.getCurrentItem());
if(list == null){
return super.onMenuItemSelected(featureId, item);
}
- mListView = (ListView)findViewById(R.id.listMEM);
- adapter = new ListAdapter(this,list,pManager);
break;
case 2:
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = context.registerReceiver(null, ifilter);
GetBatteryInfo batteryInfo = new GetBatteryInfo();
BatteryInfo bInfo = batteryInfo.getInfo(intent);
TextView tLebel = (TextView)findViewById(R.id.txtBattery);
tLebel.setText(String.valueOf(bInfo.rLevel) + " %");
TextView tTemp = (TextView)findViewById(R.id.txtTemp);
tTemp.setText(String.valueOf(bInfo.temp) + " ");
TextView tPlugged = (TextView)findViewById(R.id.txtPlugged);
tPlugged.setText(bInfo.plugged + " ");
TextView tCharge = (TextView)findViewById(R.id.txtCharge);
tCharge.setText(bInfo.status + " ");
default :
mListView = null;
adapter = null;
}
if(adapter != null && mListView != null){
mListView.setAdapter(adapter);
}
break;
case R.id.action_debug:
mIntent = new Intent(this, DebugActivity.class);
startActivity(mIntent);
break;
case R.id.action_setting:
mIntent = new Intent(this, SettingActivity.class);
startActivity(mIntent);
break;
default:
;
}
return super.onMenuItemSelected(featureId, item);
}
boolean isServiceRunning(String className) {
ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceInfos = am.getRunningServices(Integer.MAX_VALUE);
int serviceNum = serviceInfos.size();
for (int i = 0; i < serviceNum; i++) {
if (serviceInfos.get(i).service.getClassName().equals(className)) {
return true;
}
}
return false;
}
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// TODO �����������ꂽ���\�b�h�E�X�^�u
TextView tView = (TextView)view.findViewById(R.id.textKey);
ViewPager vPager = (ViewPager)findViewById(R.id.viewPager);
Intent mIntent;
if(isDebug) Log.w(CNAME,"getText=" + tView.getText());
if(!tView.getText().equals("root") && !tView.getText().equals("system")){
mIntent = new Intent(view.getContext(),ChartActivity.class);
mIntent.putExtra("PAGE",String.valueOf(vPager.getCurrentItem()));
mIntent.putExtra("KEY",tView.getText());
startActivity(mIntent);
} else {
mIntent = new Intent(view.getContext(),DetailActivity.class);
mIntent.putExtra("PAGE",String.valueOf(vPager.getCurrentItem()));
mIntent.putExtra("KEY",tView.getText());
startActivity(mIntent);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
// TODO �����������ꂽ���\�b�h�E�X�^�u
PackageManager pManager = getPackageManager();
TextView tView = (TextView)view.findViewById(R.id.textSysName);
Intent intent = pManager.getLaunchIntentForPackage((tView.getText()).toString());
try{
startActivity(intent);
} catch (Exception ex) {
Toast.makeText(view.getContext(), getString(R.string.strDontExec), Toast.LENGTH_SHORT).show();
}
return false;
}
}
| false | true | public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO �����������ꂽ���\�b�h�E�X�^�u
Intent mIntent;
Context context = getApplicationContext();
ArrayList<TempTable> list;
ListAdapter adapter;
ListView mListView;
int ids[] = new int[]{R.id.listCPU,R.id.listMEM};
switch(item.getItemId()){
case R.id.action_reload:
ViewPager vPager = (ViewPager)findViewById(R.id.viewPager);
PackageManager pManager = getPackageManager();
switch(vPager.getCurrentItem()){
case 0:
case 1:
SummarizeData iCalc = new SummarizeData(context);
list = iCalc.calculate(null,vPager.getCurrentItem());
if(list == null){
Toast.makeText(context, getString(R.string.strNoData), Toast.LENGTH_SHORT).show();
return super.onMenuItemSelected(featureId, item);
}
mListView = (ListView)findViewById(ids[vPager.getCurrentItem()]);
adapter = new ListAdapter(this,list,pManager);
list = iCalc.calculate(null,1);
if(list == null){
return super.onMenuItemSelected(featureId, item);
}
mListView = (ListView)findViewById(R.id.listMEM);
adapter = new ListAdapter(this,list,pManager);
break;
case 2:
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = context.registerReceiver(null, ifilter);
GetBatteryInfo batteryInfo = new GetBatteryInfo();
BatteryInfo bInfo = batteryInfo.getInfo(intent);
TextView tLebel = (TextView)findViewById(R.id.txtBattery);
tLebel.setText(String.valueOf(bInfo.rLevel) + " %");
TextView tTemp = (TextView)findViewById(R.id.txtTemp);
tTemp.setText(String.valueOf(bInfo.temp) + " ");
TextView tPlugged = (TextView)findViewById(R.id.txtPlugged);
tPlugged.setText(bInfo.plugged + " ");
TextView tCharge = (TextView)findViewById(R.id.txtCharge);
tCharge.setText(bInfo.status + " ");
default :
mListView = null;
adapter = null;
}
if(adapter != null && mListView != null){
mListView.setAdapter(adapter);
}
break;
case R.id.action_debug:
mIntent = new Intent(this, DebugActivity.class);
startActivity(mIntent);
break;
case R.id.action_setting:
mIntent = new Intent(this, SettingActivity.class);
startActivity(mIntent);
break;
default:
;
}
return super.onMenuItemSelected(featureId, item);
}
| public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO �����������ꂽ���\�b�h�E�X�^�u
Intent mIntent;
Context context = getApplicationContext();
ArrayList<TempTable> list;
ListAdapter adapter;
ListView mListView;
int ids[] = new int[]{R.id.listCPU,R.id.listMEM};
switch(item.getItemId()){
case R.id.action_reload:
ViewPager vPager = (ViewPager)findViewById(R.id.viewPager);
PackageManager pManager = getPackageManager();
switch(vPager.getCurrentItem()){
case 0:
case 1:
SummarizeData iCalc = new SummarizeData(context);
list = iCalc.calculate(null,vPager.getCurrentItem());
if(list == null){
Toast.makeText(context, getString(R.string.strNoData), Toast.LENGTH_SHORT).show();
return super.onMenuItemSelected(featureId, item);
}
mListView = (ListView)findViewById(ids[vPager.getCurrentItem()]);
adapter = new ListAdapter(this,list,pManager);
list = iCalc.calculate(null,vPager.getCurrentItem());
if(list == null){
return super.onMenuItemSelected(featureId, item);
}
break;
case 2:
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent intent = context.registerReceiver(null, ifilter);
GetBatteryInfo batteryInfo = new GetBatteryInfo();
BatteryInfo bInfo = batteryInfo.getInfo(intent);
TextView tLebel = (TextView)findViewById(R.id.txtBattery);
tLebel.setText(String.valueOf(bInfo.rLevel) + " %");
TextView tTemp = (TextView)findViewById(R.id.txtTemp);
tTemp.setText(String.valueOf(bInfo.temp) + " ");
TextView tPlugged = (TextView)findViewById(R.id.txtPlugged);
tPlugged.setText(bInfo.plugged + " ");
TextView tCharge = (TextView)findViewById(R.id.txtCharge);
tCharge.setText(bInfo.status + " ");
default :
mListView = null;
adapter = null;
}
if(adapter != null && mListView != null){
mListView.setAdapter(adapter);
}
break;
case R.id.action_debug:
mIntent = new Intent(this, DebugActivity.class);
startActivity(mIntent);
break;
case R.id.action_setting:
mIntent = new Intent(this, SettingActivity.class);
startActivity(mIntent);
break;
default:
;
}
return super.onMenuItemSelected(featureId, item);
}
|
diff --git a/changes/haeberling/qooxdoo_0-8_integration/src/xmlvm/org/xmlvm/Main.java b/changes/haeberling/qooxdoo_0-8_integration/src/xmlvm/org/xmlvm/Main.java
index b96d1fa3..5212515f 100644
--- a/changes/haeberling/qooxdoo_0-8_integration/src/xmlvm/org/xmlvm/Main.java
+++ b/changes/haeberling/qooxdoo_0-8_integration/src/xmlvm/org/xmlvm/Main.java
@@ -1,646 +1,646 @@
/*
* Copyright (c) 2004-2008 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at
* http://www.xmlvm.org
*/
package org.xmlvm;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.List;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.bcel.classfile.JavaClass;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.transform.JDOMResult;
import org.jdom.transform.JDOMSource;
import org.xmlvm.dep.Import;
import org.xmlvm.dep.Recursion;
import org.xmlvm.util.FileSet;
import edu.arizona.cs.mbel.mbel.ClassParser;
import edu.arizona.cs.mbel.mbel.Module;
public class Main {
private JavaClass jvm_class;
private Module cil_class;
private String class_name;
private boolean _isXMLVM = false;
public Main(JavaClass clazz) {
jvm_class = clazz;
cil_class = null;
class_name = null;
setSaxonEngine();
}
public Main(File inputFile) {
jvm_class = null;
cil_class = null;
setSaxonEngine();
String inputFileName = inputFile.getPath().toLowerCase();
try {
if (inputFileName.endsWith(".exe")) {
FileInputStream fin = new FileInputStream(inputFile);
ClassParser parser = new ClassParser(fin);
cil_class = parser.parseModule();
class_name = inputFile.getName();
class_name = class_name.substring(0, class_name.length() - 4);
} else if (inputFileName.endsWith(".class")) {
org.apache.bcel.classfile.ClassParser parser = new org.apache.bcel.classfile.ClassParser(
inputFileName);
jvm_class = parser.parse();
// new BCELifier(jvm_class, System.out).start();
// System.exit(0);
class_name = jvm_class.getClassName();
} else if (inputFileName.endsWith(".xmlvm")) {
_isXMLVM = true;
}
/*
* else { jvm_class = org.apache.bcel.Repository .lookupClass(inputFile);
* class_name = jvm_class.getClassName(); }
*/
} catch (Exception ex) {
System.err.println("Could not file '" + inputFileName + "'");
System.exit(-1);
}
}
private void setSaxonEngine() {
System.setProperty("javax.xml.transform.TransformerFactory",
"net.sf.saxon.TransformerFactoryImpl");
}
/**
* Returns an output stream created based on the given options.
*
*/
public OutputStream getOutputStream(XmlvmArguments args)/*boolean option_console,
String option_out, boolean option_js, boolean option_cpp,
boolean option_objc, boolean option_python, boolean option_exe*/ {
OutputStream out = null;
try {
if (args.option_console()) {
out = System.out;
} else if (args.option_exe()) {
// TODO Should check that option_out is set
out = new FileOutputStream(args.option_out());
} else if (args.option_js()) {
String suffix = ".js";
String path = args.option_out() != null ? args.option_out() : "";
class_name = class_name.replace('.', '_');
String outputFileName = path + File.separatorChar + class_name + suffix;
out = new FileOutputStream(outputFileName);
System.out.println("Generate JS " + outputFileName);
} else {
int index = class_name.lastIndexOf('.');
String path = class_name.substring(0, index + 1).replace('.',
File.separatorChar);
if (args.option_out() != null) {
path = args.option_out() + File.separatorChar + path;
}
class_name = class_name.substring(index + 1);
if (!path.equals("")) {
File f = new File(path);
f.mkdirs();
}
String suffix = ".xmlvm";
if (args.option_js())
suffix = ".js";
if (args.option_cpp())
suffix = ".cpp";
if (args.option_objc())
suffix = ".m";
if (args.option_python())
suffix = ".py";
out = new FileOutputStream(path + class_name + suffix);
System.out.println("Generate " + path + class_name + suffix);
}
} catch (Exception ex) {
System.err.println("Could not create file");
System.exit(-1);
}
return out;
}
public Document genXMLVM() {
if (jvm_class != null)
return new ParseJVM(jvm_class).genXMLVM();
return new ParseCIL(cil_class).genXMLVM();
}
/**
* Generates a JavaScript file from the given Document. The JavaScript file is
* created based on the given OutputStream.
*
* @param doc
* The XML document from which to generate a JavaScript file.
* @param out
* The output stream to use for the creation of the JavaScript file.
*/
public void genJS(Document doc, OutputStream out) {
Document jvmDoc = null;
if (cil_class == null) {
jvmDoc = doc;
} else {
try {
System.out.println("Switch CS to JVM");
jvmDoc = genJVM(doc);
} catch (Exception ex) {
System.err.println(ex);
System.exit(-1);
}
}
InputStream xslt = this.getClass().getResourceAsStream("/xmlvm2js.xsl");
runXSLT(xslt, jvmDoc, out);
}
public void genCPP(Document doc, OutputStream out) {
InputStream xslt = this.getClass().getResourceAsStream("/xmlvm2cpp.xsl");
runXSLT(xslt, doc, out, null);
}
public void genObjC(Document doc, String path, String headerFileName,
boolean option_console) {
try {
// The filename will be the name of the first class
Namespace nsXMLVM = Namespace.getNamespace("vm", "http://xmlvm.org");
String className = doc.getRootElement().getChild("class", nsXMLVM)
.getAttributeValue("name");
if (headerFileName == null)
headerFileName = className + ".h";
String final_path = path + File.separatorChar + className;
OutputStream header;
header = option_console ? System.out : new FileOutputStream(final_path
+ ".h");
System.out.println("Creating Objective-C header: " + final_path + ".h");
InputStream xslt = this.getClass().getResourceAsStream("/xmlvm2objc.xsl");
runXSLT(xslt, doc, header, new String[][] { { "pass", "emitHeader" },
{ "header", headerFileName } });
if (!option_console)
header.close();
OutputStream impl = option_console ? System.out : new FileOutputStream(
final_path + ".m");
System.out.println("Creating Objective-C implementation: " + final_path
+ ".m");
xslt = this.getClass().getResourceAsStream("/xmlvm2objc.xsl");
if (headerFileName == null)
headerFileName = className + ".h";
runXSLT(xslt, doc, impl, new String[][] {
{ "pass", "emitImplementation" }, { "header", headerFileName } });
if (!option_console)
impl.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void genObjC(Document doc, OutputStream out) {
InputStream xslt = this.getClass().getResourceAsStream("/xmlvm2objc.xsl");
runXSLT(xslt, doc, out);
}
public void genPython(Document doc, OutputStream out) {
InputStream xslt = this.getClass().getResourceAsStream("/xmlvm2py.xsl");
runXSLT(xslt, doc, out, null);
}
/**
* Performs a DFA (Data Flow Analysis) of the given XMLVM(CLR) document and
* returns an XMLVM(CLR-DFA) document.
*
* @param doc
* An XMLVM(CLR) document.
* @return An XMLVM(CLR-DFA) document created from the given XMLVM(DFA)
* document.
*/
public Document genDFA(Document doc) throws Exception {
JDOMResult out = new JDOMResult();
JDOMSource in = new JDOMSource(doc);
CustomUriResolver myResolver = new CustomUriResolver();
TransformerFactory transFactory = TransformerFactory.newInstance();
// because we don't get includes off the file system
transFactory.setURIResolver(myResolver);
String stageOneResourceName = "stage1.xsl";
String stageTwoResourceName = "stage2.xsl";
if (_isXMLVM) {
stageOneResourceName = "stageOne4avm.xsl";
stageTwoResourceName = "stageTwo4avm.xsl";
}
System.out.println("Preparing dfa...");
Transformer stage1 = transFactory.newTransformer(myResolver.resolve(
stageOneResourceName, ""));
stage1.transform(in, out);
in = iterateTransform(new JDOMSource(out.getDocument()), myResolver,
transFactory);
System.out.println("Preparing boxing...");
Transformer stage2 = transFactory.newTransformer(myResolver.resolve(
stageTwoResourceName, ""));
stage2.transform(in, out);
in = iterateTransform(new JDOMSource(out.getDocument()), myResolver,
transFactory);
return in.getDocument();
// TODO: Eventually this pipeline path will only go through
// the avm2jvm xslt documents. Adjust build.xml so that
// only avm2jvm is used (not clr2jvm)
// Then the resourceName should always be "/dfa.xsl"
// The file in src/avm2jvm/avm_dfa.xsl should be renamed to dfa.xsl
/*
* String resourceName = "/dfa.xsl";
*
* if (_isXMLVM) { resourceName = "/dfa4avm.xsl"; }
*
* InputStream xslt = this.getClass().getResourceAsStream(resourceName);
* return runXSLT(xslt, doc);
*/
}
private JDOMSource iterateTransform(JDOMSource in,
CustomUriResolver myResolver, TransformerFactory transFactory)
throws Exception {
String iterateFileName = "iterateUntilNoChange.xsl";
if (_isXMLVM) {
iterateFileName = "iterateUntilNoChange4avm.xsl";
}
Transformer iter = transFactory.newTransformer(myResolver.resolve(
iterateFileName, ""));
System.out.println("Applying transform until no change");
int x = 0;
in.getDocument().getRootElement().setAttribute("iters", "");
while (true) {
JDOMResult out = new JDOMResult();
System.out.print(".");
if (in.getDocument().getRootElement().getAttributeValue("iters") != null
&& in.getDocument().getRootElement().getAttributeValue("iters")
.equals("done")) {
break;
}
iter.transform(in, out);
in = new JDOMSource(out.getDocument());
if (++x % 80 == 0) {
System.out.println();
}
}
System.out.println("\nDone after " + x + " transforms");
return in;
}
/*
* This thing turns xsl:import or xsl:includes into streams that saxon can
* use. The streams come out of java resources (eg things in jars) rather than
* off the file system.
*/
class CustomUriResolver implements javax.xml.transform.URIResolver {
public Source resolve(String href, String base) throws TransformerException {
// System.out.println("href " + href + " base " + base);
StreamSource ss = new StreamSource(this.getClass().getResourceAsStream(
"/" + href));
return ss;
}
}
/**
* Returns an XMLVM(JVM) document based on the given XMLVM(CLR).
*
* @param doc
* An XMLVM(CLR) document.
* @return An XMLVM(JVM) document created from the given XMLVM(CLR) document.
*/
public Document genJVM(Document doc) {
Document jvmDoc = null;
try {
Document dfaDoc = genDFA(doc);
// TODO: Eventually this pipeline path will only go through
// the avm2jvm xslt documents. Adjust build.xml so that
// only avm2jvm is used (not clr2jvm)
// Then the resourceName should always be "/avm2jvm.xsl"
String resourceName = "/clr2jvm.xsl";
if (_isXMLVM) {
resourceName = "/avm2jvm.xsl";
}
InputStream xsltJVM = this.getClass().getResourceAsStream(resourceName);
jvmDoc = runXSLT(xsltJVM, dfaDoc);
} catch (Exception ex) {
System.err.println(ex);
System.exit(-1);
}
return jvmDoc;
}
/**
* Returns an XMLVM(CLR) document based on the given XMLVM(JVM).
*
* @param doc
* An XMLVM(JVM) document.
* @return An XMLVM(CLR) document created from the given XMLVM(JVM) document.
*/
public Document genCLR(Document doc) {
Document clrDoc = null;
Document clrAPIDoc = null;
try {
InputStream xslt = this.getClass().getResourceAsStream("/jvm2clr.xsl");
clrDoc = runXSLT(xslt, doc);
xslt = this.getClass().getResourceAsStream("/clr-api.xsl");
clrAPIDoc = runXSLT(xslt, clrDoc);
} catch (Exception ex) {
System.err.println(ex);
System.exit(-1);
}
return clrAPIDoc;
}
public void genExe(Document doc, OutputStream out) {
try {
Document clrDoc = genCLR(doc);
new GenCIL(clrDoc).create(out, class_name);
} catch (Exception ex) {
ex.printStackTrace();
System.exit(-1);
}
}
public Document genAPI(Document doc) {
Document apiDoc = null;
try {
Document jvmDoc = genJVM(doc);
// TODO: Eventually this pipeline path will only go through
// the avm2jvm xslt documents. Adjust build.xml so that
// only avm2jvm is used (not clr2jvm)
// Then the resourceName should always be "/api.xsl"
// The file in src/avm2jvm/api4avm.xsl should be renamed to api.xsl
String resourceName = "/api.xsl";
if (_isXMLVM) {
resourceName = "/api4avm.xsl";
}
InputStream xsltJVM = this.getClass().getResourceAsStream(resourceName);
apiDoc = runXSLT(xsltJVM, jvmDoc);
} catch (Exception ex) {
System.err.println(ex);
System.exit(-1);
}
return apiDoc;
}
/**
* Generates Java class files based on the given XMLVM(CLR) document. The root
* for the generated class files is determined by the given string path.
*
* @param doc
* An XMLVM(CLR) document.
* @param path
* The root path for the Java class files. Can be the empty string.
*/
public void genJava(Document doc, String path) {
try {
Document jvmDoc = genAPI(doc);
new GenJava(jvmDoc).create(path);
} catch (Exception ex) {
System.err.println(ex);
System.exit(-1);
}
}
/**
* Generates an XML document.
*
* @param doc
* A jdom document from which we want to output an actual XML
* document.
* @param out
* The output stream specifying the location of the generated XML
* document.
*/
public void genXML(Document doc, OutputStream out) {
try {
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, out);
} catch (Exception ex) {
System.err.println(ex);
}
}
private void runXSLT(InputStream xsltFile, Document doc, OutputStream out) {
runXSLT(xsltFile, doc, out, null);
}
private void runXSLT(InputStream xsltFile, Document doc, OutputStream out,
String[][] xsltParams) {
try {
OutputStream xmlvm_out = new ByteArrayOutputStream();
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, xmlvm_out);
xmlvm_out.close();
StringReader xmlvmReader = new StringReader(xmlvm_out.toString());
Source xmlvmSource = new StreamSource(xmlvmReader);
Source xsltSource = new StreamSource(xsltFile);
Result result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer(xsltSource);
if (xsltParams != null) {
for (int i = 0; i < xsltParams.length; i++)
trans.setParameter(xsltParams[i][0], xsltParams[i][1]);
}
trans.transform(xmlvmSource, result);
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
/**
* Performs an XSLT transformation on the Document 'doc', using the stream
* 'xsltFile' for the transform rules. Returns the resulting transformed
* document
*
* @param xsltFile
* The xslt file with rules for the transformation
* @param doc
* A document representing an xml file to be transformed
* @return The resulting transformed document.
*/
private Document runXSLT(InputStream xsltFile, Document doc) {
Document returnDoc = null;
try {
JDOMResult out = new JDOMResult();
JDOMSource in = new JDOMSource(doc);
Source xsltSource = new StreamSource(xsltFile);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer trans = transFactory.newTransformer(xsltSource);
trans.transform(in, out);
returnDoc = out.getDocument();
} catch (Exception ex) {
ex.printStackTrace(System.err);
}
return returnDoc;
}
public static void main(String[] argv) throws Exception {
XmlvmArguments args = new XmlvmArguments(argv);
if (args.option_class() == null) {
System.out.println("Opt class : " + args.option_class());
}
for (File f : new FileSet(args.option_class())) {
System.out.println("Processing: " + f);
Main main = new Main(f);
// String inputFileName = f.getPath().toLowerCase();
Document doc = null;
// If the document does not end with .xmlvm,
// then it is a module that needs to be parsed
// into XMLVM, else we need to create the document
// file for working with the XMLVM byte code in memory
// if (!inputFileName.endsWith(".xmlvm")) {
if (!main._isXMLVM) {
doc = main.genXMLVM();
} else {
SAXBuilder builder = new SAXBuilder();
try {
FileInputStream in = new FileInputStream(f);
doc = builder.build(in);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (args.option_import()) {
Import imp = new Import();
imp.genImport(doc);
}
if (args.option_recursive()) {
Recursion rec = new Recursion();
rec.startRecursion(doc);
}
OutputStream out = null;
if (!(args.option_java() || args.option_objc() || args.option_js())) {
out = main.getOutputStream(args);
}
if (args.option_js()) {
// This chunk of code generates 1 JS file per class so we can maintain 1
// class per file
// which makes dependency resolution easier.
- out.close(); // Don't use this...
+// out.close(); // Don't use this...
List<Element> clazzes = doc.getRootElement().getChildren("class",
Namespace.getNamespace("vm", "http://xmlvm.org"));
for (Element clazz : clazzes) {
//main.class_name = clazz.getAttributeValue("name");
out = main.getOutputStream(args);
Document newDoc = new Document();
Element newRoot = new Element(doc.getRootElement().getName(), doc
.getRootElement().getNamespace());
for (Namespace ns : (List<Namespace>) doc.getRootElement()
.getAdditionalNamespaces()) {
newRoot.addNamespaceDeclaration(ns);
}
for (Element i : (List<Element>) doc.getRootElement().getAttributes()) {
newRoot.addContent((Element) i.clone());
}
newRoot.addContent((Element) clazz.clone());
newDoc.setRootElement(newRoot);
main.genJS(newDoc, out);
}
} else if (args.option_cpp()) {
main.genCPP(doc, out);
} else if (args.option_objc()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genObjC(doc, path, args.option_objc_header(), args
.option_console());
} else if (args.option_python()) {
main.genPython(doc, out);
} else if (args.option_jvm()) {
Document jvmDoc = main.genJVM(doc);
main.genXML(jvmDoc, out);
} else if (args.option_dfa()) {
Document dfaDoc = main.genDFA(doc);
main.genXML(dfaDoc, out);
} else if (args.option_api()) {
Document apiDoc = main.genAPI(doc);
main.genXML(apiDoc, out);
} else if (args.option_java()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genJava(doc, path);
} else if (args.option_clr()) {
Document clrDoc = main.genCLR(doc);
main.genXML(clrDoc, out);
} else if (args.option_exe()) {
main.genExe(doc, out);
} else {
main.genXML(doc, out);
}
// the output stream will not be opened if
// the java option is chosen.
if (!(args.option_java() || args.option_objc())) {
try {
out.close();
} catch (Exception ex) {
System.err.println("Error closing output file.");
}
}
}
}
}
| true | true | public static void main(String[] argv) throws Exception {
XmlvmArguments args = new XmlvmArguments(argv);
if (args.option_class() == null) {
System.out.println("Opt class : " + args.option_class());
}
for (File f : new FileSet(args.option_class())) {
System.out.println("Processing: " + f);
Main main = new Main(f);
// String inputFileName = f.getPath().toLowerCase();
Document doc = null;
// If the document does not end with .xmlvm,
// then it is a module that needs to be parsed
// into XMLVM, else we need to create the document
// file for working with the XMLVM byte code in memory
// if (!inputFileName.endsWith(".xmlvm")) {
if (!main._isXMLVM) {
doc = main.genXMLVM();
} else {
SAXBuilder builder = new SAXBuilder();
try {
FileInputStream in = new FileInputStream(f);
doc = builder.build(in);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (args.option_import()) {
Import imp = new Import();
imp.genImport(doc);
}
if (args.option_recursive()) {
Recursion rec = new Recursion();
rec.startRecursion(doc);
}
OutputStream out = null;
if (!(args.option_java() || args.option_objc() || args.option_js())) {
out = main.getOutputStream(args);
}
if (args.option_js()) {
// This chunk of code generates 1 JS file per class so we can maintain 1
// class per file
// which makes dependency resolution easier.
out.close(); // Don't use this...
List<Element> clazzes = doc.getRootElement().getChildren("class",
Namespace.getNamespace("vm", "http://xmlvm.org"));
for (Element clazz : clazzes) {
//main.class_name = clazz.getAttributeValue("name");
out = main.getOutputStream(args);
Document newDoc = new Document();
Element newRoot = new Element(doc.getRootElement().getName(), doc
.getRootElement().getNamespace());
for (Namespace ns : (List<Namespace>) doc.getRootElement()
.getAdditionalNamespaces()) {
newRoot.addNamespaceDeclaration(ns);
}
for (Element i : (List<Element>) doc.getRootElement().getAttributes()) {
newRoot.addContent((Element) i.clone());
}
newRoot.addContent((Element) clazz.clone());
newDoc.setRootElement(newRoot);
main.genJS(newDoc, out);
}
} else if (args.option_cpp()) {
main.genCPP(doc, out);
} else if (args.option_objc()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genObjC(doc, path, args.option_objc_header(), args
.option_console());
} else if (args.option_python()) {
main.genPython(doc, out);
} else if (args.option_jvm()) {
Document jvmDoc = main.genJVM(doc);
main.genXML(jvmDoc, out);
} else if (args.option_dfa()) {
Document dfaDoc = main.genDFA(doc);
main.genXML(dfaDoc, out);
} else if (args.option_api()) {
Document apiDoc = main.genAPI(doc);
main.genXML(apiDoc, out);
} else if (args.option_java()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genJava(doc, path);
} else if (args.option_clr()) {
Document clrDoc = main.genCLR(doc);
main.genXML(clrDoc, out);
} else if (args.option_exe()) {
main.genExe(doc, out);
} else {
main.genXML(doc, out);
}
// the output stream will not be opened if
// the java option is chosen.
if (!(args.option_java() || args.option_objc())) {
try {
out.close();
} catch (Exception ex) {
System.err.println("Error closing output file.");
}
}
}
}
| public static void main(String[] argv) throws Exception {
XmlvmArguments args = new XmlvmArguments(argv);
if (args.option_class() == null) {
System.out.println("Opt class : " + args.option_class());
}
for (File f : new FileSet(args.option_class())) {
System.out.println("Processing: " + f);
Main main = new Main(f);
// String inputFileName = f.getPath().toLowerCase();
Document doc = null;
// If the document does not end with .xmlvm,
// then it is a module that needs to be parsed
// into XMLVM, else we need to create the document
// file for working with the XMLVM byte code in memory
// if (!inputFileName.endsWith(".xmlvm")) {
if (!main._isXMLVM) {
doc = main.genXMLVM();
} else {
SAXBuilder builder = new SAXBuilder();
try {
FileInputStream in = new FileInputStream(f);
doc = builder.build(in);
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (args.option_import()) {
Import imp = new Import();
imp.genImport(doc);
}
if (args.option_recursive()) {
Recursion rec = new Recursion();
rec.startRecursion(doc);
}
OutputStream out = null;
if (!(args.option_java() || args.option_objc() || args.option_js())) {
out = main.getOutputStream(args);
}
if (args.option_js()) {
// This chunk of code generates 1 JS file per class so we can maintain 1
// class per file
// which makes dependency resolution easier.
// out.close(); // Don't use this...
List<Element> clazzes = doc.getRootElement().getChildren("class",
Namespace.getNamespace("vm", "http://xmlvm.org"));
for (Element clazz : clazzes) {
//main.class_name = clazz.getAttributeValue("name");
out = main.getOutputStream(args);
Document newDoc = new Document();
Element newRoot = new Element(doc.getRootElement().getName(), doc
.getRootElement().getNamespace());
for (Namespace ns : (List<Namespace>) doc.getRootElement()
.getAdditionalNamespaces()) {
newRoot.addNamespaceDeclaration(ns);
}
for (Element i : (List<Element>) doc.getRootElement().getAttributes()) {
newRoot.addContent((Element) i.clone());
}
newRoot.addContent((Element) clazz.clone());
newDoc.setRootElement(newRoot);
main.genJS(newDoc, out);
}
} else if (args.option_cpp()) {
main.genCPP(doc, out);
} else if (args.option_objc()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genObjC(doc, path, args.option_objc_header(), args
.option_console());
} else if (args.option_python()) {
main.genPython(doc, out);
} else if (args.option_jvm()) {
Document jvmDoc = main.genJVM(doc);
main.genXML(jvmDoc, out);
} else if (args.option_dfa()) {
Document dfaDoc = main.genDFA(doc);
main.genXML(dfaDoc, out);
} else if (args.option_api()) {
Document apiDoc = main.genAPI(doc);
main.genXML(apiDoc, out);
} else if (args.option_java()) {
String path = "";
if (args.option_out() != null)
path = args.option_out();
main.genJava(doc, path);
} else if (args.option_clr()) {
Document clrDoc = main.genCLR(doc);
main.genXML(clrDoc, out);
} else if (args.option_exe()) {
main.genExe(doc, out);
} else {
main.genXML(doc, out);
}
// the output stream will not be opened if
// the java option is chosen.
if (!(args.option_java() || args.option_objc())) {
try {
out.close();
} catch (Exception ex) {
System.err.println("Error closing output file.");
}
}
}
}
|
diff --git a/src/com/android/ex/photo/PhotoViewActivity.java b/src/com/android/ex/photo/PhotoViewActivity.java
index aa8029e..1ba81a8 100644
--- a/src/com/android/ex/photo/PhotoViewActivity.java
+++ b/src/com/android/ex/photo/PhotoViewActivity.java
@@ -1,543 +1,541 @@
/*
* Copyright (C) 2011 Google Inc.
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ex.photo;
import android.app.ActionBar;
import android.app.ActionBar.OnMenuVisibilityListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import com.android.ex.photo.PhotoViewPager.InterceptType;
import com.android.ex.photo.PhotoViewPager.OnInterceptTouchListener;
import com.android.ex.photo.adapters.BaseFragmentPagerAdapter.OnFragmentPagerListener;
import com.android.ex.photo.adapters.PhotoPagerAdapter;
import com.android.ex.photo.fragments.PhotoViewFragment;
import com.android.ex.photo.loaders.PhotoPagerLoader;
import com.android.ex.photo.provider.PhotoContract;
import java.util.HashSet;
import java.util.Set;
/**
* Activity to view the contents of an album.
*/
public class PhotoViewActivity extends Activity implements
LoaderCallbacks<Cursor>, OnPageChangeListener, OnInterceptTouchListener,
OnFragmentPagerListener, OnMenuVisibilityListener {
/**
* Listener to be invoked for screen events.
*/
public static interface OnScreenListener {
/**
* The full screen state has changed.
*/
public void onFullScreenChanged(boolean fullScreen);
/**
* A new view has been activated and the previous view de-activated.
*/
public void onViewActivated();
/**
* Called when a right-to-left touch move intercept is about to occur.
*
* @param origX the raw x coordinate of the initial touch
* @param origY the raw y coordinate of the initial touch
* @return {@code true} if the touch should be intercepted.
*/
public boolean onInterceptMoveLeft(float origX, float origY);
/**
* Called when a left-to-right touch move intercept is about to occur.
*
* @param origX the raw x coordinate of the initial touch
* @param origY the raw y coordinate of the initial touch
* @return {@code true} if the touch should be intercepted.
*/
public boolean onInterceptMoveRight(float origX, float origY);
}
public static interface CursorChangedListener {
/**
* Called when the cursor that contains the photo list data
* is updated. Note that there is no guarantee that the cursor
* will be at the proper position.
* @param cursor the cursor containing the photo list data
*/
public void onCursorChanged(Cursor cursor);
}
private final static String STATE_ITEM_KEY =
"com.google.android.apps.plus.PhotoViewFragment.ITEM";
private final static String STATE_FULLSCREEN_KEY =
"com.google.android.apps.plus.PhotoViewFragment.FULLSCREEN";
private static final int LOADER_PHOTO_LIST = 1;
/** Count used when the real photo count is unknown [but, may be determined] */
public static final int ALBUM_COUNT_UNKNOWN = -1;
/** Argument key for the dialog message */
public static final String KEY_MESSAGE = "dialog_message";
public static int sMemoryClass;
/** The URI of the photos we're viewing; may be {@code null} */
private String mPhotosUri;
/** The index of the currently viewed photo */
private int mPhotoIndex;
/** The query projection to use; may be {@code null} */
private String[] mProjection;
/** The name of the particular photo being viewed. */
private String mPhotoName;
/** The total number of photos; only valid if {@link #mIsEmpty} is {@code false}. */
private int mAlbumCount = ALBUM_COUNT_UNKNOWN;
/** {@code true} if the view is empty. Otherwise, {@code false}. */
private boolean mIsEmpty;
/** The main pager; provides left/right swipe between photos */
private PhotoViewPager mViewPager;
/** Adapter to create pager views */
private PhotoPagerAdapter mAdapter;
/** Whether or not we're in "full screen" mode */
private boolean mFullScreen;
/** The set of listeners wanting full screen state */
private Set<OnScreenListener> mScreenListeners = new HashSet<OnScreenListener>();
/** The set of listeners wanting full screen state */
private Set<CursorChangedListener> mCursorListeners = new HashSet<CursorChangedListener>();
/** When {@code true}, restart the loader when the activity becomes active */
private boolean mRestartLoader;
/** Whether or not this activity is paused */
private boolean mIsPaused = true;
private Handler mActionBarHideHandler;
// TODO Find a better way to do this. We basically want the activity to display the
// "loading..." progress until the fragment takes over and shows it's own "loading..."
// progress [located in photo_header_view.xml]. We could potentially have all status displayed
// by the activity, but, that gets tricky when it comes to screen rotation. For now, we
// track the loading by this variable which is fragile and may cause phantom "loading..."
// text.
private long mActionBarHideDelayTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
- } else {
- mPhotoName = getResources().getString(R.string.photo_view_default_title);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
@Override
protected void onResume() {
super.onResume();
setFullScreen(mFullScreen, false);
mIsPaused = false;
if (mRestartLoader) {
mRestartLoader = false;
getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this);
}
}
@Override
protected void onPause() {
mIsPaused = true;
super.onPause();
}
@Override
public void onBackPressed() {
// If in full screen mode, toggle mode & eat the 'back'
if (mFullScreen) {
toggleFullScreen();
} else {
super.onBackPressed();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_ITEM_KEY, mViewPager.getCurrentItem());
outState.putBoolean(STATE_FULLSCREEN_KEY, mFullScreen);
}
public void addScreenListener(OnScreenListener listener) {
mScreenListeners.add(listener);
}
public void removeScreenListener(OnScreenListener listener) {
mScreenListeners.remove(listener);
}
public synchronized void addCursorListener(CursorChangedListener listener) {
mCursorListeners.add(listener);
}
public synchronized void removeCursorListener(CursorChangedListener listener) {
mCursorListeners.remove(listener);
}
public boolean isFragmentFullScreen(Fragment fragment) {
if (mViewPager == null || mAdapter == null || mAdapter.getCount() == 0) {
return mFullScreen;
}
return mFullScreen || (mViewPager.getCurrentItem() != mAdapter.getItemPosition(fragment));
}
public void toggleFullScreen() {
setFullScreen(!mFullScreen, true);
}
public void onPhotoRemoved(long photoId) {
final Cursor data = mAdapter.getCursor();
if (data == null) {
// Huh?! How would this happen?
return;
}
final int dataCount = data.getCount();
if (dataCount <= 1) {
finish();
return;
}
getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == LOADER_PHOTO_LIST) {
return new PhotoPagerLoader(this, Uri.parse(mPhotosUri), mProjection);
}
return null;
}
@Override
public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) {
final int id = loader.getId();
if (id == LOADER_PHOTO_LIST) {
if (data == null || data.getCount() == 0) {
mIsEmpty = true;
} else {
mAlbumCount = data.getCount();
// Cannot do this directly; need to be out of the loader
new Handler().post(new Runnable() {
@Override
public void run() {
// We're paused; don't do anything now, we'll get re-invoked
// when the activity becomes active again
if (mIsPaused) {
mRestartLoader = true;
return;
}
mIsEmpty = false;
// set the selected photo
int itemIndex = mPhotoIndex;
// Use an index of 0 if the index wasn't specified or couldn't be found
if (itemIndex < 0) {
itemIndex = 0;
}
mAdapter.swapCursor(data);
notifyCursorListeners(data);
mViewPager.setCurrentItem(itemIndex, false);
setViewActivated();
}
});
}
}
}
private synchronized void notifyCursorListeners(Cursor data) {
// tell all of the objects listening for cursor changes
// that the cursor has changed
for (CursorChangedListener listener : mCursorListeners) {
listener.onCursorChanged(data);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPhotoIndex = position;
setViewActivated();
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageActivated(Fragment fragment) {
setViewActivated();
}
public boolean isFragmentActive(Fragment fragment) {
if (mViewPager == null || mAdapter == null) {
return false;
}
return mViewPager.getCurrentItem() == mAdapter.getItemPosition(fragment);
}
public void onFragmentVisible(PhotoViewFragment fragment) {
updateActionBar(fragment);
}
@Override
public InterceptType onTouchIntercept(float origX, float origY) {
boolean interceptLeft = false;
boolean interceptRight = false;
for (OnScreenListener listener : mScreenListeners) {
if (!interceptLeft) {
interceptLeft = listener.onInterceptMoveLeft(origX, origY);
}
if (!interceptRight) {
interceptRight = listener.onInterceptMoveRight(origX, origY);
}
listener.onViewActivated();
}
if (interceptLeft) {
if (interceptRight) {
return InterceptType.BOTH;
}
return InterceptType.LEFT;
} else if (interceptRight) {
return InterceptType.RIGHT;
}
return InterceptType.NONE;
}
/**
* Updates the title bar according to the value of {@link #mFullScreen}.
*/
private void setFullScreen(boolean fullScreen, boolean setDelayedRunnable) {
final boolean fullScreenChanged = (fullScreen != mFullScreen);
mFullScreen = fullScreen;
if (mFullScreen) {
setLightsOutMode(true);
cancelActionBarHideRunnable();
} else {
setLightsOutMode(false);
if (setDelayedRunnable) {
postActionBarHideRunnableWithDelay();
}
}
if (fullScreenChanged) {
for (OnScreenListener listener : mScreenListeners) {
listener.onFullScreenChanged(mFullScreen);
}
}
}
private void postActionBarHideRunnableWithDelay() {
mActionBarHideHandler.postDelayed(mActionBarHideRunnable,
mActionBarHideDelayTime);
}
private void cancelActionBarHideRunnable() {
mActionBarHideHandler.removeCallbacks(mActionBarHideRunnable);
}
private void setLightsOutMode(boolean enabled) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int flags = enabled
? View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
: View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
// using mViewPager since we have it and we need a view
mViewPager.setSystemUiVisibility(flags);
} else {
final ActionBar actionBar = getActionBar();
if (enabled) {
actionBar.hide();
} else {
actionBar.show();
}
int flags = enabled
? View.SYSTEM_UI_FLAG_LOW_PROFILE
: View.SYSTEM_UI_FLAG_VISIBLE;
mViewPager.setSystemUiVisibility(flags);
}
}
private Runnable mActionBarHideRunnable = new Runnable() {
@Override
public void run() {
PhotoViewActivity.this.setLightsOutMode(true);
}
};
public void setViewActivated() {
for (OnScreenListener listener : mScreenListeners) {
listener.onViewActivated();
}
}
/**
* Adjusts the activity title and subtitle to reflect the photo name and count.
*/
protected void updateActionBar(PhotoViewFragment fragment) {
final int position = mViewPager.getCurrentItem() + 1;
final String subtitle;
final boolean hasAlbumCount = mAlbumCount >= 0;
final Cursor cursor = getCursorAtProperPosition();
if (cursor != null) {
final int photoNameIndex = cursor.getColumnIndex(PhotoContract.PhotoViewColumns.NAME);
mPhotoName = cursor.getString(photoNameIndex);
}
if (mIsEmpty || !hasAlbumCount || position <= 0) {
subtitle = null;
} else {
subtitle = getResources().getString(R.string.photo_view_count, position, mAlbumCount);
}
final ActionBar actionBar = getActionBar();
actionBar.setTitle(mPhotoName);
actionBar.setSubtitle(subtitle);
}
/**
* Utility method that will return the cursor that contains the data
* at the current position so that it refers to the current image on screen.
* @return the cursor at the current position or
* null if no cursor exists or if the {@link PhotoViewPager} is null.
*/
public Cursor getCursorAtProperPosition() {
if (mViewPager == null) {
return null;
}
final int position = mViewPager.getCurrentItem();
final Cursor cursor = mAdapter.getCursor();
if (cursor == null) {
return null;
}
cursor.moveToPosition(position);
return cursor;
}
public Cursor getCursor() {
return (mAdapter == null) ? null : mAdapter.getCursor();
}
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
if (isVisible) {
cancelActionBarHideRunnable();
} else {
postActionBarHideRunnableWithDelay();
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
} else {
mPhotoName = getResources().getString(R.string.photo_view_default_title);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActivityManager mgr = (ActivityManager) getApplicationContext().
getSystemService(Activity.ACTIVITY_SERVICE);
sMemoryClass = mgr.getMemoryClass();
Intent mIntent = getIntent();
int currentItem = -1;
if (savedInstanceState != null) {
currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1);
mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false);
}
// album name; if not set, use a default name
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) {
mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME);
}
// uri of the photos to view; optional
if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) {
mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI);
}
// projection for the query; optional
// I.f not set, the default projection is used.
// This projection must include the columns from the default projection.
if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) {
mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION);
} else {
mProjection = null;
}
// Set the current item from the intent if wasn't in the saved instance
if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) {
currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1);
}
mPhotoIndex = currentItem;
setContentView(R.layout.photo_activity_view);
// Create the adapter and add the view pager
mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null);
mAdapter.setFragmentPagerListener(this);
mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(this);
mViewPager.setOnInterceptTouchListener(this);
// Kick off the loader
getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mActionBarHideDelayTime = getResources().getInteger(
R.integer.action_bar_delay_time_in_millis);
actionBar.addOnMenuVisibilityListener(this);
mActionBarHideHandler = new Handler();
}
|
diff --git a/src/logicrepository/plugins/srs/PatternMatchAutomaton.java b/src/logicrepository/plugins/srs/PatternMatchAutomaton.java
index 01a5b07..16eb322 100644
--- a/src/logicrepository/plugins/srs/PatternMatchAutomaton.java
+++ b/src/logicrepository/plugins/srs/PatternMatchAutomaton.java
@@ -1,362 +1,367 @@
/// TODO : consider symbols that don't appear in the SRS?
package logicrepository.plugins.srs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Set;
//This uses a slightly modified Aho-Corasick automaton
public class PatternMatchAutomaton extends LinkedHashMap<State, HashMap<Symbol, ActionState>> {
private State s0 = new State(0);
private ArrayList<Set<State>> depthMap = new ArrayList<Set<State>>();
private HashMap<State, State> fail;
private int longestLhsSize;
public PatternMatchAutomaton(SRS srs){
longestLhsSize = srs.getLongestLhsSize();
mkGotoMachine(srs);
addFailureTransitions(srs.getTerminals());
}
private void mkGotoMachine(SRS srs){
State currentState;
put(s0, new HashMap<Symbol, ActionState>());
Set<State> depthStates = new HashSet<State>();
depthStates.add(s0);
depthMap.add(depthStates);
//compute one path through the tree for each lhs
for(Rule r : srs){
currentState = s0;
Sequence pattern = r.getLhs();
int patternRemaining = pattern.size() - 1;
for(Symbol s : pattern){
HashMap<Symbol, ActionState> transition = get(currentState);
ActionState nextActionState = transition.get(s);
State nextState;
if(nextActionState == null){
int nextDepth = currentState.getDepth() + 1;
nextState =
new State(nextDepth);
nextActionState = new ActionState(0, nextState);
transition.put(s, nextActionState);
put(nextState, new HashMap<Symbol, ActionState>());
if(nextDepth == depthMap.size()){
depthStates = new HashSet<State>();
depthMap.add(depthStates);
}
else{
depthStates = depthMap.get(nextDepth);
}
depthStates.add(nextState);
}
else{
nextState = nextActionState.getState();
}
if(patternRemaining == 0){
nextState.setMatch(r);
}
currentState = nextState;
--patternRemaining;
}
}
//now add self transitions on s0 for any symbols that don't
//exit from s0 already
HashMap<Symbol, ActionState> s0transition = get(s0);
for(Symbol s : srs.getTerminals()){
if(!s0transition.containsKey(s)){
s0transition.put(s, new ActionState(0, s0));
}
}
}
private void addFailureTransitions(Set<Symbol> terminals){
fail = new HashMap<State, State>();
if(depthMap.size() == 1) return;
//handle all depth 1
for(State state : depthMap.get(1)){
HashMap<Symbol, ActionState> transition = get(state);
fail.put(state, s0);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
transition.put(symbol, new ActionState(1, s0));
}
}
}
if(depthMap.size() == 2) return;
//handle depth d > 1
for(int i = 2; i < depthMap.size(); ++i){
for(State state : depthMap.get(i)){
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
State failState = findState(state, depthMap.get(i - 1), fail,
terminals);
transition.put(symbol,
new ActionState(state.getDepth() - failState.getDepth(),
failState));
fail.put(state, failState);
}
}
}
}
//System.out.println("!!!!!!!!!!");
//System.out.println(fail);
//System.out.println("!!!!!!!!!!");
}
private State findState(State state, Set<State> shallowerStates,
HashMap<State, State> fail, Set<Symbol> terminals){
for(State shallowerState : shallowerStates){
HashMap<Symbol, ActionState> transition = get(shallowerState);
for(Symbol symbol : terminals){
ActionState destination = transition.get(symbol);
if(destination.getState() == state){
// System.out.println(state + " " + destination.getState());
State failState = fail.get(shallowerState);
while(failState != s0 && get(failState).get(symbol).getAction() != 0){
failState = fail.get(failState);
}
return get(failState).get(symbol).getState();
}
}
}
return s0;
}
public void rewrite(SinglyLinkedList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.size() == 0) return;
Iterator<Symbol> first = l.iterator();
first.next(); //make sure first points to an element
Iterator<Symbol> second = l.iterator();
Iterator<Symbol> lastRepl;
State currentState = s0;
ActionState as;
Symbol symbol = second.next();
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.hasNext()) break;
first.next();
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
l.nonDestructiveReplace(first, second, (Sequence) repl);
if(l.isEmpty()) break;
first = l.iterator();
System.out.println("out: " + l);
System.out.println("out: " + first);
//lastRepl = l.iterator(second);
//System.out.println("lastRepl: " + lastRepl);
symbol = first.next();
second = l.iterator(first);
//System.out.println("first: " + first);
//System.out.println("second: " + second);
currentState = s0;
continue;
}
}
if(!second.hasNext()) break;
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
symbol = second.next();
}
//fail transition, need to reconsider he same symbol in next state
}
System.out.println("substituted form = " + l.toString());
}
public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
+ boolean firstIteration = true;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
- System.out.println("******************outer");
+ System.out.println("******************outer*****" + firstIteration);
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
+ atOrPastLastChange = false;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
- if(!changed && second.equals(lastRepl)){
- atOrPastLastChange = true;
- }
- if(atOrPastLastChange && currentState == s0){
- System.out.println("early exit at symbol " + second);
- break DONE;
+ if(!firstIteration){
+ if(second.equals(lastRepl)){
+ atOrPastLastChange = true;
+ }
+ if(atOrPastLastChange && currentState == s0){
+ System.out.println("early exit at symbol " + second);
+ break DONE;
+ }
}
symbol = second.get();
}
//fail transition, need to reconsider he same symbol in next state
}
+ firstIteration = false;
} while(changed);
System.out.println("substituted form = " + l.toString());
}
@Override public String toString(){
StringBuilder sb = new StringBuilder();
for(State state : keySet()){
sb.append(state);
sb.append("\n[");
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : transition.keySet()){
sb.append(" ");
sb.append(symbol);
sb.append(" -> ");
sb.append(transition.get(symbol));
sb.append("\n");
}
sb.append("]\n");
}
return sb.toString();
}
}
class ActionState {
private int action;
private State state;
public int getAction(){
return action;
}
public State getState(){
return state;
}
public ActionState(int action, State state){
this.action = action;
this.state = state;
}
@Override public String toString(){
return "[" + action + "] " + state.toString();
}
}
class State {
private static int counter = 0;
private int number;
private int depth;
private Rule matchedRule = null;
public State(int depth){
number = counter++;
this.depth = depth;
}
public int getNumber(){
return number;
}
public int getDepth(){
return depth;
}
public Rule getMatch(){
return matchedRule;
}
public void setMatch(Rule r){
matchedRule = r;
}
@Override
public String toString(){
return "<" + number
+ " @ "
+ depth
+ ((matchedRule == null)?
""
: " matches " + matchedRule.toString()
)
+ ">";
}
}
| false | true | public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
System.out.println("******************outer");
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
if(!changed && second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
System.out.println("early exit at symbol " + second);
break DONE;
}
symbol = second.get();
}
//fail transition, need to reconsider he same symbol in next state
}
} while(changed);
System.out.println("substituted form = " + l.toString());
}
| public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
boolean firstIteration = true;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
System.out.println("******************outer*****" + firstIteration);
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + " -- " + as);
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
atOrPastLastChange = false;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
if(!firstIteration){
if(second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
System.out.println("early exit at symbol " + second);
break DONE;
}
}
symbol = second.get();
}
//fail transition, need to reconsider he same symbol in next state
}
firstIteration = false;
} while(changed);
System.out.println("substituted form = " + l.toString());
}
|
diff --git a/src/net/sourcewalker/garanbot/api/ItemService.java b/src/net/sourcewalker/garanbot/api/ItemService.java
index 5ddd809..3232b87 100644
--- a/src/net/sourcewalker/garanbot/api/ItemService.java
+++ b/src/net/sourcewalker/garanbot/api/ItemService.java
@@ -1,195 +1,205 @@
package net.sourcewalker.garanbot.api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.content.ContentUris;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Base64;
import android.util.Base64InputStream;
public class ItemService {
private static final String LAST_MODIFIED_HEADER = "Last-Modified";
private final GaranboClient client;
ItemService(GaranboClient client) {
this.client = client;
}
public List<Integer> list() throws ClientException {
List<Integer> result = new ArrayList<Integer>();
try {
HttpResponse response = client.get("/item");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String content = client.readEntity(response);
JSONObject jsonContent = (JSONObject) new JSONTokener(content)
.nextValue();
- JSONArray refArray = jsonContent.getJSONArray("ref");
- for (int i = 0; i < refArray.length(); i++) {
- String refString = refArray.getString(i);
- int refId = Integer.parseInt(refString.split("/")[1]);
- result.add(refId);
+ JSONArray refArray = jsonContent.optJSONArray("ref");
+ if (refArray == null) {
+ String ref = jsonContent.optString("ref");
+ if (ref == null) {
+ throw new ClientException(
+ "No valid ref element found: " + content);
+ } else {
+ result.add(Integer.parseInt(ref.split("/")[1]));
+ }
+ } else {
+ for (int i = 0; i < refArray.length(); i++) {
+ String refString = refArray.getString(i);
+ int refId = Integer.parseInt(refString.split("/")[1]);
+ result.add(refId);
+ }
}
} else if (statusCode == HttpStatus.SC_NOT_FOUND) {
// No items on server.
} else {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
} catch (JSONException e) {
throw new ClientException("JSON Parser error: " + e.getMessage(), e);
} catch (NumberFormatException e) {
throw new ClientException("Error parsing id: " + e.getMessage(), e);
}
return result;
}
public Item get(int id) throws ClientException {
try {
HttpResponse response = client.get("/item/" + id);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return getItemFromResponse(response);
} else {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
} catch (NumberFormatException e) {
throw new ClientException("Error parsing id: " + e.getMessage(), e);
}
}
/**
* Create an Item object from a HTTP response.
*
* @param response
* Response to parse.
* @return Item object parsed from response.
* @throws ClientException
* If there was an error parsing the Item.
*/
private Item getItemFromResponse(final HttpResponse response)
throws ClientException {
final String content = client.readEntity(response);
final Header lastModifiedHeader = response
.getFirstHeader(LAST_MODIFIED_HEADER);
return Item.fromJSON(content, lastModifiedHeader.getValue());
}
public Item getIfNewer(final int itemId, final Date modifiedDate)
throws ClientException {
try {
Header[] headers = new Header[] { new BasicHeader(
"If-Modified-Since",
ApiConstants.HTTP_DATE_FORMAT.format(modifiedDate)) };
HttpResponse response = client.get("/item/" + itemId, headers);
switch (response.getStatusLine().getStatusCode()) {
case HttpStatus.SC_OK:
return getItemFromResponse(response);
case HttpStatus.SC_NOT_MODIFIED:
return null;
default:
throw new ClientException("Got HTTP status: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
}
}
public Bitmap getPicture(int id) throws ClientException {
try {
HttpResponse response = client.get("/item/" + id + "/picture");
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case HttpStatus.SC_OK:
Base64InputStream stream = new Base64InputStream(response
.getEntity().getContent(), Base64.DEFAULT);
Bitmap result = BitmapFactory.decodeStream(stream);
if (result == null) {
throw new ClientException("Picture could not be decoded!");
}
return result;
case HttpStatus.SC_NOT_FOUND:
return null;
default:
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
}
}
public void delete(int id) throws ClientException {
try {
HttpResponse response = client.delete("/item/" + id);
if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT)) {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
}
}
public int create(Item itemData) throws ClientException {
try {
if (itemData.getServerId() != Item.UNKNOWN_ID) {
throw new ClientException(
"Can't create Item which already has an ID!");
}
String jsonData = itemData.json().toString();
HttpResponse response = client.put("/item", jsonData);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
Header locationHeader = response.getFirstHeader("Location");
Uri itemUri = Uri.parse(locationHeader.getValue());
return (int) ContentUris.parseId(itemUri);
} else {
throw new ClientException("Got HTTP status: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
} catch (NumberFormatException e) {
throw new ClientException("Error parsing new item id: "
+ e.getMessage(), e);
}
}
public void update(Item itemData) throws ClientException {
try {
if (itemData.getServerId() == Item.UNKNOWN_ID) {
throw new ClientException("Can't update Item with no ID!");
}
String jsonData = itemData.json().toString();
HttpResponse response = client.put("/item", jsonData);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
}
}
}
| true | true | public List<Integer> list() throws ClientException {
List<Integer> result = new ArrayList<Integer>();
try {
HttpResponse response = client.get("/item");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String content = client.readEntity(response);
JSONObject jsonContent = (JSONObject) new JSONTokener(content)
.nextValue();
JSONArray refArray = jsonContent.getJSONArray("ref");
for (int i = 0; i < refArray.length(); i++) {
String refString = refArray.getString(i);
int refId = Integer.parseInt(refString.split("/")[1]);
result.add(refId);
}
} else if (statusCode == HttpStatus.SC_NOT_FOUND) {
// No items on server.
} else {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
} catch (JSONException e) {
throw new ClientException("JSON Parser error: " + e.getMessage(), e);
} catch (NumberFormatException e) {
throw new ClientException("Error parsing id: " + e.getMessage(), e);
}
return result;
}
| public List<Integer> list() throws ClientException {
List<Integer> result = new ArrayList<Integer>();
try {
HttpResponse response = client.get("/item");
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
String content = client.readEntity(response);
JSONObject jsonContent = (JSONObject) new JSONTokener(content)
.nextValue();
JSONArray refArray = jsonContent.optJSONArray("ref");
if (refArray == null) {
String ref = jsonContent.optString("ref");
if (ref == null) {
throw new ClientException(
"No valid ref element found: " + content);
} else {
result.add(Integer.parseInt(ref.split("/")[1]));
}
} else {
for (int i = 0; i < refArray.length(); i++) {
String refString = refArray.getString(i);
int refId = Integer.parseInt(refString.split("/")[1]);
result.add(refId);
}
}
} else if (statusCode == HttpStatus.SC_NOT_FOUND) {
// No items on server.
} else {
throw new ClientException("Got HTTP error: "
+ response.getStatusLine().toString());
}
} catch (IOException e) {
throw new ClientException("IO error: " + e.getMessage(), e);
} catch (JSONException e) {
throw new ClientException("JSON Parser error: " + e.getMessage(), e);
} catch (NumberFormatException e) {
throw new ClientException("Error parsing id: " + e.getMessage(), e);
}
return result;
}
|
diff --git a/core/plugins/org.eclipse.dltk.debug/src/org/eclipse/dltk/internal/debug/core/model/ScriptVariable.java b/core/plugins/org.eclipse.dltk.debug/src/org/eclipse/dltk/internal/debug/core/model/ScriptVariable.java
index eeea4f909..84d6c47e3 100644
--- a/core/plugins/org.eclipse.dltk.debug/src/org/eclipse/dltk/internal/debug/core/model/ScriptVariable.java
+++ b/core/plugins/org.eclipse.dltk.debug/src/org/eclipse/dltk/internal/debug/core/model/ScriptVariable.java
@@ -1,169 +1,169 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.internal.debug.core.model;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.debug.core.model.IVariable;
import org.eclipse.dltk.dbgp.IDbgpProperty;
import org.eclipse.dltk.dbgp.commands.IDbgpCoreCommands;
import org.eclipse.dltk.dbgp.exceptions.DbgpException;
import org.eclipse.dltk.debug.core.model.IRefreshableScriptVariable;
import org.eclipse.dltk.debug.core.model.IScriptStackFrame;
import org.eclipse.dltk.debug.core.model.IScriptThread;
import org.eclipse.dltk.debug.core.model.IScriptVariable;
public class ScriptVariable extends ScriptDebugElement implements
IScriptVariable, IRefreshableScriptVariable {
private final IScriptStackFrame frame;
private final String name;
private IDbgpProperty property;
private IValue value;
private boolean isValueChanged = false;
public ScriptVariable(IScriptStackFrame frame, String name,
IDbgpProperty property) {
this.frame = frame;
this.name = name;
this.property = property;
}
public IDebugTarget getDebugTarget() {
return frame.getDebugTarget();
}
public synchronized IValue getValue() throws DebugException {
if (value == null) {
value = ScriptValue.createValue(frame, property);
}
return value;
}
public String getName() {
return name;
}
public String getReferenceTypeName() throws DebugException {
return property.getType();
}
public boolean hasValueChanged() throws DebugException {
return isValueChanged;
}
public synchronized void setValue(String expression) throws DebugException {
try {
if (("String".equals(property.getType())) && //$NON-NLS-1$
(!expression.startsWith("'") || !expression.endsWith("'")) && //$NON-NLS-1$ //$NON-NLS-2$
(!expression.startsWith("\"") || !expression.endsWith("\""))) //$NON-NLS-1$ //$NON-NLS-2$
expression = "\"" + expression.replaceAll("\\\"", "\\\\\"") + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
if (getCoreCommands().setProperty(property.getEvalName(),
frame.getLevel(), expression)) {
clearEvaluationManagerCache();
update();
}
} catch (DbgpException e) {
// TODO: localize
throw wrapDbgpException(Messages.ScriptVariable_cantAssignVariable,
e);
}
}
private IDbgpCoreCommands getCoreCommands() {
return ((IScriptThread) frame.getThread()).getDbgpSession()
.getCoreCommands();
}
private void clearEvaluationManagerCache() {
ScriptThread thread = (ScriptThread) frame.getThread();
thread.notifyModified();
}
private void update() throws DbgpException {
this.value = null;
// String key = property.getKey();
String name = property.getEvalName();
// TODO: Use key if provided
this.property = getCoreCommands().getProperty(name, frame.getLevel());
DebugEventHelper.fireChangeEvent(this);
}
public void setValue(IValue value) throws DebugException {
setValue(value.getValueString());
}
public boolean supportsValueModification() {
return !property.isConstant();
}
public boolean verifyValue(String expression) throws DebugException {
// TODO: perform more smart verification
return expression != null;
}
public boolean verifyValue(IValue value) throws DebugException {
return verifyValue(value.getValueString());
}
public boolean isConstant() {
return property.isConstant();
}
public String toString() {
return getName();
}
public String getId() {
return property.getKey();
}
/**
* @param newVariable
* @return
* @throws DebugException
*/
public IVariable refreshVariable(IVariable newVariable)
throws DebugException {
if (newVariable instanceof ScriptVariable) {
final ScriptVariable v = (ScriptVariable) newVariable;
isValueChanged = !equals(property, v.property);
if (!isValueChanged) {
- if (property.getChildrenCount() != 0
- && v.property.getChildrenCount() != 0) {
+ if (property.getAvailableChildren().length != 0
+ && v.property.getAvailableChildren().length != 0) {
ScriptStackFrame.refreshVariables(v.getValue()
.getVariables(), getValue().getVariables());
}
}
value = v.value;
property = v.property;
return this;
} else {
return newVariable;
}
}
private static boolean equals(IDbgpProperty p1, IDbgpProperty p2) {
if (StrUtils.equals(p1.getType(), p2.getType())) {
if (!StrUtils.equals(p1.getValue(), p2.getValue())) {
return false;
}
}
if (StrUtils.isNotEmpty(p1.getKey())
&& StrUtils.isNotEmpty(p2.getKey())) {
return p1.getKey().equals(p2.getKey());
}
return true;
}
}
| true | true | public IVariable refreshVariable(IVariable newVariable)
throws DebugException {
if (newVariable instanceof ScriptVariable) {
final ScriptVariable v = (ScriptVariable) newVariable;
isValueChanged = !equals(property, v.property);
if (!isValueChanged) {
if (property.getChildrenCount() != 0
&& v.property.getChildrenCount() != 0) {
ScriptStackFrame.refreshVariables(v.getValue()
.getVariables(), getValue().getVariables());
}
}
value = v.value;
property = v.property;
return this;
} else {
return newVariable;
}
}
| public IVariable refreshVariable(IVariable newVariable)
throws DebugException {
if (newVariable instanceof ScriptVariable) {
final ScriptVariable v = (ScriptVariable) newVariable;
isValueChanged = !equals(property, v.property);
if (!isValueChanged) {
if (property.getAvailableChildren().length != 0
&& v.property.getAvailableChildren().length != 0) {
ScriptStackFrame.refreshVariables(v.getValue()
.getVariables(), getValue().getVariables());
}
}
value = v.value;
property = v.property;
return this;
} else {
return newVariable;
}
}
|
diff --git a/src/com/mojang/mojam/entity/building/Building.java b/src/com/mojang/mojam/entity/building/Building.java
index f64501a5..8db4d969 100644
--- a/src/com/mojang/mojam/entity/building/Building.java
+++ b/src/com/mojang/mojam/entity/building/Building.java
@@ -1,153 +1,153 @@
package com.mojang.mojam.entity.building;
import com.mojang.mojam.MojamComponent;
import com.mojang.mojam.entity.*;
import com.mojang.mojam.entity.mob.Mob;
import com.mojang.mojam.gui.Notifications;
import com.mojang.mojam.math.BB;
import com.mojang.mojam.network.TurnSynchronizer;
import com.mojang.mojam.screen.*;
public class Building extends Mob implements IUsable {
public static final int SPAWN_INTERVAL = 60;
public static final int MIN_BUILDING_DISTANCE = 1700; // Sqr
public static final int HEALING_INTERVAL = 15;
public int spawnTime = 0;
public boolean highlight = false;
private int healingTime = HEALING_INTERVAL;
public Building(double x, double y, int team) {
super(x, y, team);
setStartHealth(20);
freezeTime = 10;
spawnTime = TurnSynchronizer.synchedRandom.nextInt(SPAWN_INTERVAL);
}
@Override
public void render(Screen screen) {
super.render(screen);
renderMarker(screen);
}
protected void renderMarker(Screen screen) {
if (highlight) {
BB bb = getBB();
bb = bb.grow((getSprite().w - (bb.x1 - bb.x0)) / (3 + Math.sin(System.currentTimeMillis() * .01)));
int width = (int) (bb.x1 - bb.x0);
int height = (int) (bb.y1 - bb.y0);
Bitmap marker = new Bitmap(width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if ((x < 2 || x > width - 3 || y < 2 || y > height - 3) && (x < 5 || x > width - 6) && (y < 5 || y > height - 6)) {
int i = x + y * width;
marker.pixels[i] = 0xffffffff;
}
}
}
screen.blit(marker, bb.x0, bb.y0 - 4);
}
}
public void tick() {
super.tick();
if (freezeTime > 0) {
return;
}
if (hurtTime <= 0) {
if (health < maxHealth) {
if (--healingTime <= 0) {
++health;
healingTime = HEALING_INTERVAL;
}
}
}
xd = 0.0;
yd = 0.0;
}
@Override
public void hurt(Bullet bullet) {
super.hurt(bullet);
healingTime = HEALING_INTERVAL;
}
@Override
public void hurt(Entity source, float damage) {
super.hurt(source, damage);
healingTime = HEALING_INTERVAL;
}
public Bitmap getSprite() {
return Art.floorTiles[3][2];
}
public boolean move(double xBump, double yBump) {
return false;
}
public void slideMove(double xa, double ya) {
super.move(xa, ya);
}
//
// Upgrade
//
protected void upgradeComplete() {
}
protected int upgradeLevel = 0;
private int maxUpgradeLevel = 0;
private int[] upgradeCosts = null;
public boolean upgrade(Player p) {
if (upgradeLevel >= maxUpgradeLevel) {
Notifications.getInstance().add("Fully upgraded already");
return false;
}
final int cost = upgradeCosts[upgradeLevel];
if (cost > p.getScore()) {
- Notifications.getInstance().add("You dont have enough money");
+ Notifications.getInstance().add("You dont have enough money (" + cost + ")");
return false;
}
MojamComponent.soundPlayer.playSound("/sound/Upgrade.wav", (float) pos.x, (float) pos.y, true);
++upgradeLevel;
p.useMoney(cost);
upgradeComplete();
- Notifications.getInstance().add("Upgraded to level " + upgradeLevel);
+ Notifications.getInstance().add("Upgraded to level " + (upgradeLevel+1));
return true;
}
void makeUpgradeableWithCosts(int[] costs) {
maxUpgradeLevel = 0;
if (costs == null)
return;
upgradeCosts = costs;
maxUpgradeLevel = costs.length - 1;
upgradeComplete();
}
public void use(Entity user) {
if (user instanceof Player) {
((Player) user).pickup(this);
}
}
public boolean isHighlightable() {
return true;
}
public void setHighlighted(boolean hl) {
highlight = hl;
}
public boolean isAllowedToCancel() {
return true;
}
}
| false | true | public boolean upgrade(Player p) {
if (upgradeLevel >= maxUpgradeLevel) {
Notifications.getInstance().add("Fully upgraded already");
return false;
}
final int cost = upgradeCosts[upgradeLevel];
if (cost > p.getScore()) {
Notifications.getInstance().add("You dont have enough money");
return false;
}
MojamComponent.soundPlayer.playSound("/sound/Upgrade.wav", (float) pos.x, (float) pos.y, true);
++upgradeLevel;
p.useMoney(cost);
upgradeComplete();
Notifications.getInstance().add("Upgraded to level " + upgradeLevel);
return true;
}
| public boolean upgrade(Player p) {
if (upgradeLevel >= maxUpgradeLevel) {
Notifications.getInstance().add("Fully upgraded already");
return false;
}
final int cost = upgradeCosts[upgradeLevel];
if (cost > p.getScore()) {
Notifications.getInstance().add("You dont have enough money (" + cost + ")");
return false;
}
MojamComponent.soundPlayer.playSound("/sound/Upgrade.wav", (float) pos.x, (float) pos.y, true);
++upgradeLevel;
p.useMoney(cost);
upgradeComplete();
Notifications.getInstance().add("Upgraded to level " + (upgradeLevel+1));
return true;
}
|
diff --git a/src/jvm/backtype/storm/utils/Time.java b/src/jvm/backtype/storm/utils/Time.java
index b3abe0e7..d5610b85 100644
--- a/src/jvm/backtype/storm/utils/Time.java
+++ b/src/jvm/backtype/storm/utils/Time.java
@@ -1,78 +1,81 @@
package backtype.storm.utils;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.log4j.Logger;
public class Time {
public static Logger LOG = Logger.getLogger(Time.class);
private static AtomicBoolean simulating = new AtomicBoolean(false);
//TODO: should probably use weak references here or something
private static Map<Thread, AtomicLong> threadSleepTimes;
private static final Object sleepTimesLock = new Object();
private static AtomicLong simulatedCurrTimeMs; //should this be a thread local that's allowed to keep advancing?
public static void startSimulating() {
simulating.set(true);
simulatedCurrTimeMs = new AtomicLong(0);
threadSleepTimes = new ConcurrentHashMap<Thread, AtomicLong>();
}
public static void stopSimulating() {
simulating.set(false);
threadSleepTimes = null;
}
public static boolean isSimulating() {
return simulating.get();
}
public static void sleepUntil(long targetTimeMs) throws InterruptedException {
if(simulating.get()) {
- synchronized(sleepTimesLock) {
- threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
- }
- while(simulatedCurrTimeMs.get() < targetTimeMs) {
- Thread.sleep(10);
- }
- synchronized(sleepTimesLock) {
- threadSleepTimes.remove(Thread.currentThread());
+ try {
+ synchronized(sleepTimesLock) {
+ threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
+ }
+ while(simulatedCurrTimeMs.get() < targetTimeMs) {
+ Thread.sleep(10);
+ }
+ } finally {
+ synchronized(sleepTimesLock) {
+ threadSleepTimes.remove(Thread.currentThread());
+ }
}
} else {
long sleepTime = targetTimeMs-currentTimeMillis();
if(sleepTime>0)
Thread.sleep(sleepTime);
}
}
public static void sleep(long ms) throws InterruptedException {
sleepUntil(currentTimeMillis()+ms);
}
public static long currentTimeMillis() {
if(simulating.get()) {
return simulatedCurrTimeMs.get();
} else {
return System.currentTimeMillis();
}
}
public static void advanceTime(long ms) {
if(!simulating.get()) throw new IllegalStateException("Cannot simulate time unless in simulation mode");
simulatedCurrTimeMs.set(simulatedCurrTimeMs.get() + ms);
}
public static boolean isThreadWaiting(Thread t) {
if(!simulating.get()) throw new IllegalStateException("Must be in simulation mode");
AtomicLong time;
synchronized(sleepTimesLock) {
time = threadSleepTimes.get(t);
}
return time!=null && currentTimeMillis() < time.longValue();
}
}
| true | true | public static void sleepUntil(long targetTimeMs) throws InterruptedException {
if(simulating.get()) {
synchronized(sleepTimesLock) {
threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
}
while(simulatedCurrTimeMs.get() < targetTimeMs) {
Thread.sleep(10);
}
synchronized(sleepTimesLock) {
threadSleepTimes.remove(Thread.currentThread());
}
} else {
long sleepTime = targetTimeMs-currentTimeMillis();
if(sleepTime>0)
Thread.sleep(sleepTime);
}
}
| public static void sleepUntil(long targetTimeMs) throws InterruptedException {
if(simulating.get()) {
try {
synchronized(sleepTimesLock) {
threadSleepTimes.put(Thread.currentThread(), new AtomicLong(targetTimeMs));
}
while(simulatedCurrTimeMs.get() < targetTimeMs) {
Thread.sleep(10);
}
} finally {
synchronized(sleepTimesLock) {
threadSleepTimes.remove(Thread.currentThread());
}
}
} else {
long sleepTime = targetTimeMs-currentTimeMillis();
if(sleepTime>0)
Thread.sleep(sleepTime);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.